Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate series in BigQuery Standard SQL

I need to generate table with say 600 consecutive numbers (starting with 51) in each row
How I do this with BigQuery Standard SQL?

like image 567
Mikhail Berlyant Avatar asked Aug 10 '16 22:08

Mikhail Berlyant


People also ask

Is BigQuery standard SQL?

BigQuery supports the Google Standard SQL dialect, but a legacy SQL dialect is also available. If you are new to BigQuery, you should use Google Standard SQL as it supports the broadest range of functionality. For example, features such as DDL and DML statements are only supported using Google Standard SQL.

How do you repeat a query column in BigQuery?

How to Query BigQuery Repeated Fields. To extract information from a repeated field in BigQuery, you must use a more exotic pattern. This is normally done using the UNNEST function, which converts an array of values in a table into rows. These can then be joined to the original table to be queried.

How can I get data from multiple tables in BigQuery?

Notifications Stay organized with collections Save this page to your Developer Profile to get notifications on important updates. Save and categorize content based on your preferences. Wildcard tables enable you to query multiple tables using concise SQL statements.


2 Answers

Try GENERATE_ARRAY in standard SQL:

SELECT num FROM UNNEST(GENERATE_ARRAY(51, 650)) AS num;

Edit: if you want more than about a million elements, you can use multiple calls to GENERATE_ARRAY, although be warned that the query can end up taking a long time if you produce too many elements:

SELECT num1 * num2 AS num
FROM UNNEST(GENERATE_ARRAY(1, 1000000)) AS num1,
  UNNEST(GENERATE_ARRAY(1, 100)) AS num2;
like image 121
Elliott Brossard Avatar answered Sep 18 '22 14:09

Elliott Brossard


BigQuery Standard SQL

SELECT 50 + ROW_NUMBER() OVER() AS num
FROM UNNEST((SELECT SPLIT(FORMAT("%600s", ""),'') AS h FROM (SELECT NULL))) AS pos
ORDER BY num

BigQuery Legacy SQL

SELECT 50 + pos AS pos FROM (
  SELECT ROW_NUMBER() OVER() AS pos, * 
  FROM (FLATTEN((SELECT SPLIT(RPAD('', 600, '.'),'') AS h FROM (SELECT NULL)), h))
) WHERE pos BETWEEN 1 AND 600

From there you can adjust logic for example to get consecutive days and other sequences

like image 27
Mikhail Berlyant Avatar answered Sep 20 '22 14:09

Mikhail Berlyant