Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate_series() equivalent in snowflake

I'm trying to find the snowflake equivalent of generate_series() (the PostgreSQL syntax).

SELECT generate_series(timestamp '2017-11-01', CURRENT_DATE, '1 day')
like image 428
Tarik Avatar asked Jan 24 '19 14:01

Tarik


People also ask

How do you make a sequence number in a snowflake?

To simplify nested-query syntax, Snowflake provides an additional method to generate sequences using the table function GETNEXTVAL, as in the following example: CREATE OR REPLACE SEQUENCE seq1; CREATE OR REPLACE TABLE foo (n NUMBER); INSERT INTO foo VALUES (100), (101), (102); SELECT n, s.

What is generator in Snowflake?

Creates rows of data based either on a specified number of rows, a specified generation period (in seconds), or both. This system-defined table function enables synthetic row generation. Note that it is possible to generate virtual tables with 0 columns but possibly many rows.


2 Answers

Just wanted to expand on Marcin Zukowski's comment to say that these gaps started to show up almost immediately after using a date range generated this way in a JOIN.

We ultimately ended up doing this instead!

select
  dateadd(
    day,
    '-' || row_number() over (order by null),
    dateadd(day, '+1', current_date())
  ) as date
from table (generator(rowcount => 90))
like image 130
bcrowell Avatar answered Oct 13 '22 01:10

bcrowell


I had a similar problem and found an approach, which avoids the issue of a generator requiring a constant value by using a session variable in addition to the already great answers here. This is closest to the requirement of the OP to my mind.

-- set parameter to be used as generator "constant" including the start day
set num_days =  (Select datediff(day, TO_DATE('2017-11-01','YYYY-MM-DD'), current_date()+1));
-- use parameter in bcrowell's answer now
select
  dateadd(
    day,
    '-' || row_number() over (order by null),
    dateadd(day, '+1', current_date())
  ) as date
from table (generator(rowcount => ($num_days)));
-- clean up previously set variable
unset num_days;
like image 35
kf06925 Avatar answered Oct 13 '22 02:10

kf06925