Snowflake SQL Tutorial 85 - GENERATOR, SEQ4, Date Spine - Making Rows From Nothing

Snowflake SQL · Episode 85

In this post we are going to cover GENERATOR and the sequence functions in Snowflake: SEQ1, SEQ2, SEQ4 and SEQ8.

Every query in this course so far has read from a table. GENERATOR does not. You tell it how many rows you want and it manufactures them, and then the SEQ functions number them for you.

That sounds like a toy until you need a row for something that has no row. A day with no sales, a product with no orders, a position in a string. Those are the cases where the data cannot answer the question, because the thing you are asking about is not in it.

We will start with ten rows out of nothing and build it up step by step. On the way we will look at a daily sales report that looks finished and leaves out most of the calendar, a sequence function that silently starts repeating itself, and a query I named wrongly and then left the name on.

This is the last post in Level 7.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 85 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

Most of this post needs no table at all, which is rather the point. The date-spine section joins onto the ORDERS table, the same one the rest of the course uses.

Sample data
-- ORDERS comes from the setup script this course uses throughout.
-- Run it once; every episode works on the same tables.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

Nothing else to set up. Let's start generating.

Let's start with ten rows out of nothing

GENERATOR is a table function, so it goes inside TABLE(...) in the FROM clause. Give it a ROWCOUNT and it gives you that many rows.

The rows have no columns of their own, so we ask SEQ4 for a number to put in them.

Query
SELECT SEQ4() AS N
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY N;
Result10 rows · 1 column
N
0
1
2
3
4
5
6
7
8
9

Ten rows, numbered 0 to 9. And there is no table named anywhere in that query.

GENERATOR made the rows. SEQ4 numbered them. Those are two separate jobs and it is worth keeping them separate in your head.

Now let's look at the four SEQ functions

There are four of them, and at this size they look identical. Let's put them next to each other and check.

Query
SELECT SEQ1() AS SEQ1_, SEQ2() AS SEQ2_, SEQ4() AS SEQ4_, SEQ8() AS SEQ8_
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY SEQ8_;
Result10 rows · 4 columns
SEQ1_SEQ2_SEQ4_SEQ8_
0000
1111
2222
3333
4444
5555
6666
7777
8888
9999

All four counted 0 to 9. No difference at all.

The difference is in the name. The number is a count of bytes. SEQ1 is one byte, SEQ2 is two, SEQ4 is four and SEQ8 is eight. A one-byte signed number cannot go past 127.

Which means the grid above only looks reassuring because we asked for ten rows. Let's ask for 300 instead.

Query
SELECT MIN(SEQ1()) AS SEQ1_MIN, MAX(SEQ1()) AS SEQ1_MAX,
       MIN(SEQ4()) AS SEQ4_MIN, MAX(SEQ4()) AS SEQ4_MAX,
       COUNT(*) AS ROWS_GENERATED,
       COUNT(DISTINCT SEQ1()) AS DISTINCT_SEQ1_VALUES,
       COUNT(DISTINCT SEQ4()) AS DISTINCT_SEQ4_VALUES
FROM TABLE(GENERATOR(ROWCOUNT => 300));
Result1 row · 7 columns · scroll →
SEQ1_MINSEQ1_MAXSEQ4_MINSEQ4_MAXROWS_GENERATEDDISTINCT_SEQ1_VALUESDISTINCT_SEQ4_VALUES
01270299300128300

SEQ4 ran from 0 to 299, with 300 distinct values. One value per row, as you would expect.

SEQ1 stopped at 127 and produced 128 distinct values across those same 300 rows. It filled up and started over.

This is the one that catches people

No error. No warning. Just the same numbers again, quietly, from the hundred and twenty-ninth row onwards. If you had used SEQ1 to number rows, every id from there on is a duplicate of one you already issued.
Use SEQ4 or SEQ8. There is no reason to reach for the small ones.

Now let's put SEQ4 next to ROW_NUMBER

ROW_NUMBER also numbers rows, and the two do not start in the same place. Let's see them together.

Query
SELECT SEQ4()                               AS SEQ4_,
       ROW_NUMBER() OVER (ORDER BY SEQ4())  AS ROW_NUMBER_,
       ROW_NUMBER() OVER (ORDER BY SEQ4()) - 1 AS ROW_NUMBER_ZERO_BASED
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY SEQ4_;
Result10 rows · 3 columns
SEQ4_ROW_NUMBER_ROW_NUMBER_ZERO_BASED
010
121
232
343
454
565
676
787
898
9109

SEQ4 starts at 0. ROW_NUMBER starts at 1. Subtract one from ROW_NUMBER and they line up, which is what the third column does.

Mind that off-by-one. It is the single most common mistake with these functions, and it shows up as dates one day out or arrays indexed one element short.

There is a second difference, and it is more important. Let's generate 10,000 rows and check for gaps and duplicates.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       MIN(SEQ4()) AS SEQ_MIN, MAX(SEQ4()) AS SEQ_MAX,
       MAX(SEQ4()) - MIN(SEQ4()) + 1 AS SPAN_IF_GAP_FREE,
       COUNT(DISTINCT SEQ4()) AS DISTINCT_VALUES,
       COUNT(DISTINCT SEQ4()) = COUNT(*) AS NO_DUPLICATES
FROM TABLE(GENERATOR(ROWCOUNT => 10000));
Result1 row · 6 columns · scroll →
ROWS_TOTALSEQ_MINSEQ_MAXSPAN_IF_GAP_FREEDISTINCT_VALUESNO_DUPLICATES
10000099991000010000TRUE

10000 rows, running 0 to 9999, with 10000 distinct values and no duplicates. The span works out the same as the count, so on this run there were no gaps either.

What that grid does not prove

On this run. Snowflake's documentation is explicit that these functions “do not necessarily produce a gap-free sequence”, and that “if a fully ordered, gap-free sequence is required, consider using the ROW_NUMBER window function”.
So the grid says gap-free and the documentation refuses to promise it. Believe the documentation. One run on one warehouse is not a guarantee.
Use SEQ4 to make rows exist. Use ROW_NUMBER when the number itself matters.

What are the edge cases?

A few things worth knowing before we build anything real on this. First, GENERATOR with no arguments at all.

Query
SELECT COUNT(*) AS ROWS_RETURNED FROM TABLE(GENERATOR());
Result1 row · 1 column
ROWS_RETURNED
0

Zero rows. No error.

And asking for zero explicitly.

Query
SELECT COUNT(*) AS ROWS_RETURNED FROM TABLE(GENERATOR(ROWCOUNT => 0));
Result1 row · 1 column
ROWS_RETURNED
0

Also zero rows, also fine. So an empty generator is a legal thing and not something you have to guard against.

There is also a TIMELIMIT option instead of ROWCOUNT, which generates rows for a number of seconds rather than to a count. That gives a different answer every time it runs, so there is no row count worth showing you.

Query
SELECT COUNT(*) > 0        AS IT_MADE_SOME_ROWS,
       COUNT(*) IS NOT NULL AS THE_COUNT_IS_A_NUMBER
FROM TABLE(GENERATOR(TIMELIMIT => 1));
Result1 row · 2 columns
IT_MADE_SOME_ROWSTHE_COUNT_IS_A_NUMBER
TRUETRUE

It made some rows. That is the whole claim, and nothing on this page is timed.

And a negative row count?

The query that fails
SELECT COUNT(*) FROM TABLE(GENERATOR(ROWCOUNT => -5));
Query failed — Snowflake returned an error
001046 (22023): SQL compilation error:
Invalid value [-5] for function 'GENERATOR', parameter ROWCOUNT:  must be non-negative.

Refused, and the message says why: it must be non-negative.

Now the real reason GENERATOR exists

Watch this one carefully, because it is the thing I most want you to take away from the post.

The ORDERS table has one row per order. Let's ask it how many distinct order dates it holds, and how wide its date range actually is.

Query
SELECT COUNT(DISTINCT ORDER_DATE) AS DAYS_WITH_AT_LEAST_ONE_ORDER,
       DATEDIFF('day', MIN(ORDER_DATE), MAX(ORDER_DATE)) + 1 AS CALENDAR_DAYS_IN_RANGE,
       DATEDIFF('day', MIN(ORDER_DATE), MAX(ORDER_DATE)) + 1
         - COUNT(DISTINCT ORDER_DATE) AS DAYS_WITH_NO_ORDERS
FROM ORDERS;
Result1 row · 3 columns
DAYS_WITH_AT_LEAST_ONE_ORDERCALENDAR_DAYS_IN_RANGEDAYS_WITH_NO_ORDERS
41664623

41 days have at least one order on them. The range from the first order to the last is 664 days. Which leaves 623 days inside that range with no orders at all.

Now think about what GROUP BY ORDER_DATE would give you on that table. 41 tidy rows. One line per day, sorted, with a count and a total on each one. It looks like a finished daily sales report.

And it leaves out 623 days, because a day with no orders has no row to group.

Why this is worse than a wrong number

A missing row cannot be counted. It cannot be summed, it cannot be averaged, and it cannot be noticed. Nothing in that report says a single day is missing, and no amount of staring at it will tell you.
This is not a reporting problem you can fix in the chart. The rows have to exist before you group.

So let's generate the calendar ourselves

The fix is to make the days exist. Generate a row per day with GENERATOR, turn the sequence number into a date with DATEADD, and you have a calendar.

That is called a date spine. Here is a fortnight of one.

Query
SELECT DATEADD('day', SEQ4(), DATE '2024-01-01') AS THE_DATE,
       DAYNAME(DATEADD('day', SEQ4(), DATE '2024-01-01')) AS DAY_NAME,
       DATE_TRUNC('month', DATEADD('day', SEQ4(), DATE '2024-01-01')) AS MONTH_START
FROM TABLE(GENERATOR(ROWCOUNT => 14))
ORDER BY THE_DATE;
Result14 rows · 3 columns
THE_DATEDAY_NAMEMONTH_START
2024-01-01Mon2024-01-01
2024-01-02Tue2024-01-01
2024-01-03Wed2024-01-01
2024-01-04Thu2024-01-01
2024-01-05Fri2024-01-01
2024-01-06Sat2024-01-01
2024-01-07Sun2024-01-01
2024-01-08Mon2024-01-01
2024-01-09Tue2024-01-01
2024-01-10Wed2024-01-01
2024-01-11Thu2024-01-01
2024-01-12Fri2024-01-01
2024-01-13Sat2024-01-01
2024-01-14Sun2024-01-01

One row per day, with the day name and the start of its month beside it. SEQ4 starts at 0, which is why the first row is the start date itself rather than the day after it.

These rows came from nothing. There is no calendar table in the database.

Now let's join the orders onto the spine

Here is the whole technique. Generate the days, LEFT JOIN the orders onto them, and group by the spine's date rather than the order's date.

Let's do January 2024 — 31 generated days, with whatever orders exist falling into them.

Query
SELECT D.THE_DATE,
       COUNT(O.ORDER_ID) AS ORDERS_,
       ROUND(NVL(SUM(O.AMOUNT), 0), 2) AS TOTAL
FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-01-01') AS THE_DATE
      FROM TABLE(GENERATOR(ROWCOUNT => 31))) D
LEFT JOIN ORDERS O ON O.ORDER_DATE = D.THE_DATE
GROUP BY D.THE_DATE
ORDER BY D.THE_DATE;
Result31 rows · 3 columns
THE_DATEORDERS_TOTAL
2024-01-0100.00
2024-01-0200.00
2024-01-0300.00
2024-01-0400.00
2024-01-0500.00
2024-01-0600.00
2024-01-0700.00
2024-01-0800.00
2024-01-0900.00
2024-01-1000.00
2024-01-1100.00
2024-01-1200.00
2024-01-1300.00
2024-01-1400.00
2024-01-1513910.00
2024-01-1600.00
2024-01-1700.00
2024-01-1800.00
2024-01-1900.00
2024-01-2000.00
2024-01-2100.00
2024-01-2200.00
2024-01-2300.00
2024-01-2400.00
2024-01-2500.00
2024-01-2600.00
2024-01-2700.00
2024-01-2800.00
2024-01-2900.00
2024-01-3000.00
2024-01-31111200.00

31 rows, because that is how many days we asked for. Read down the ORDERS_ column: the 15th has one order for 3910.00 and the 31st has one order for 11200.00, and every other day in the month reads 0 and 0.00.

Let's count that rather than trust my reading of it.

Query
SELECT COUNT(*) AS DAYS_IN_THE_SPINE,
       COUNT_IF(X.ORDERS_ = 0) AS EMPTY_DAYS,
       COUNT_IF(X.ORDERS_ > 0) AS DAYS_WITH_ORDERS
FROM (SELECT D.THE_DATE, COUNT(O.ORDER_ID) AS ORDERS_
      FROM (SELECT DATEADD('day', SEQ4(), DATE '2024-01-01') AS THE_DATE
            FROM TABLE(GENERATOR(ROWCOUNT => 31))) D
      LEFT JOIN ORDERS O ON O.ORDER_DATE = D.THE_DATE
      GROUP BY D.THE_DATE) X;
Result1 row · 3 columns
DAYS_IN_THE_SPINEEMPTY_DAYSDAYS_WITH_ORDERS
31292

31 days in the spine, 29 of them empty, 2 with orders.

Now compare that with what GROUP BY ORDER_DATE would have given you for the same month: two rows, next to each other.

Chart those two rows and you have drawn 3910.00 beside 11200.00 as though they were consecutive days. Count down the dates in the grid above and they are 16 days apart.

That is the entire reason a date spine exists, and it is the main reason to use GENERATOR at all.

Can we size the spine from the data?

Hardcoding a start date and a row count works, but it goes stale. Better to take the range from the data: start at the first order, generate plenty of days, and throw away the ones past the last order.

Query
SELECT COUNT(*) AS DAYS_IN_THE_SPINE,
       MIN(D.THE_DATE) AS SPINE_START,
       MAX(D.THE_DATE) AS SPINE_END,
       (SELECT MIN(ORDER_DATE) FROM ORDERS) AS FIRST_ORDER,
       (SELECT MAX(ORDER_DATE) FROM ORDERS) AS LAST_ORDER
FROM (SELECT DATEADD('day', SEQ4(),
                     (SELECT MIN(ORDER_DATE) FROM ORDERS)) AS THE_DATE
      FROM TABLE(GENERATOR(ROWCOUNT => 10000))) D
WHERE D.THE_DATE <= (SELECT MAX(ORDER_DATE) FROM ORDERS);
Result1 row · 5 columns
DAYS_IN_THE_SPINESPINE_STARTSPINE_ENDFIRST_ORDERLAST_ORDER
6642023-01-122024-11-052023-01-122024-11-05

664 days in the spine, which is the same 664 the earlier grid reported as the calendar range. The spine start and end match the first and last order exactly.

Generating 10,000 days and filtering is a blunt way to do it, and it is fine. The generator is cheap and the WHERE clause does the thinking.

Let's cycle through a list

Another thing generated rows are good for. MOD the sequence number and feed it to DECODE, and you get a repeating pattern of values.

Query
SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS ID,
       DECODE(MOD(SEQ4(), 3), 0, 'Shipped', 1, 'Pending', 'Cancelled') AS STATUS,
       DECODE(MOD(SEQ4(), 2), 0, 'Enterprise', 'SMB')                  AS SEGMENT
FROM TABLE(GENERATOR(ROWCOUNT => 12))
ORDER BY ID;
Result12 rows · 3 columns
IDSTATUSSEGMENT
1ShippedEnterprise
2PendingSMB
3CancelledEnterprise
4ShippedSMB
5PendingEnterprise
6CancelledSMB
7ShippedEnterprise
8PendingSMB
9CancelledEnterprise
10ShippedSMB
11PendingEnterprise
12CancelledSMB

MOD(SEQ4(), 3) cycles the status through three values and MOD(SEQ4(), 2) cycles the segment through two, so the pair repeats every sixth row.

Did every row get one? Let's check over a bigger run rather than eyeballing twelve rows.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(DECODE(MOD(SEQ4(), 3), 0, 'Shipped', 1, 'Pending', 'Cancelled'))
         AS STATUS_ASSIGNED,
       COUNT(DISTINCT DECODE(MOD(SEQ4(), 3), 0, 'Shipped', 1, 'Pending', 'Cancelled'))
         AS DISTINCT_STATUSES
FROM TABLE(GENERATOR(ROWCOUNT => 300));
Result1 row · 3 columns
ROWS_TOTALSTATUS_ASSIGNEDDISTINCT_STATUSES
3003003

300 rows, 300 statuses assigned, 3 distinct ones. Nothing fell through the DECODE.

Now let's make a numbers table

Put ROW_NUMBER over the generated rows instead of SEQ4 and you get a one-based count, which is what a numbers table wants.

Query
SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS N
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY N;
Result10 rows · 1 column
N
1
2
3
4
5
6
7
8
9
10

1 to 10. That is a numbers table, and the classic use for one is splitting a delimited string into rows.

Join the string to the numbers and use the number as the position for SPLIT_PART.

Query
SELECT N.N AS PART_NUMBER,
       SPLIT_PART('alpha,beta,gamma,delta', ',', N.N) AS THE_PART
FROM (SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS N
      FROM TABLE(GENERATOR(ROWCOUNT => 4))) N
ORDER BY N.N;
Result4 rows · 2 columns
PART_NUMBERTHE_PART
1alpha
2beta
3gamma
4delta

Four rows, one part each. That works.

It also means you had to know there were four parts before you wrote the query, which is the weakness of the trick. FLATTEN does not need that.

Query
SELECT F.INDEX + 1 AS PART_NUMBER, F.VALUE::VARCHAR AS THE_PART
FROM TABLE(FLATTEN(INPUT => SPLIT('alpha,beta,gamma,delta', ','))) F
ORDER BY F.INDEX;
Result4 rows · 2 columns
PART_NUMBERTHE_PART
1alpha
2beta
3gamma
4delta

Same four parts, and the query never mentions how many there are. SPLIT turns the string into an array and FLATTEN turns the array into rows.

Notice the INDEX + 1. FLATTEN's index starts at 0, the same as SEQ4. Everything in this post is zero-based except ROW_NUMBER.

Let's confirm the two methods agree, and ask the array itself as a third opinion.

Query
SELECT (SELECT COUNT(*) FROM TABLE(FLATTEN(INPUT => SPLIT('alpha,beta,gamma,delta', ','))))
         AS FLATTEN_ROWS,
       (SELECT COUNT(*) FROM (SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS N
                              FROM TABLE(GENERATOR(ROWCOUNT => 4)))) AS GENERATOR_ROWS,
       ARRAY_SIZE(SPLIT('alpha,beta,gamma,delta', ',')) AS SPLIT_SAYS;
Result1 row · 3 columns
FLATTEN_ROWSGENERATOR_ROWSSPLIT_SAYS
444

4, 4 and 4. So use FLATTEN for splitting. The numbers table still has its uses, and this is not one of them.

Now let's generate some test data, and get it wrong

Last thing generated rows are good for, and the one I misunderstood first time. Test data.

I wanted a random amount on each row, between 100 and 5000. So I reached for UNIFORM with RANDOM, seeded from the row's own sequence number, thinking that would give me a different value per row.

The query that fails
SELECT UNIFORM(100, 5000, RANDOM(SEQ4())) AS SHOULD_NOT_GET_THIS_FAR
FROM TABLE(GENERATOR(ROWCOUNT => 5));
Query failed — Snowflake returned an error
001015 (22023): SQL compilation error:
argument 1 to function RANDOM needs to be constant, found 'SEQ4()'

Refused at compile time. RANDOM's seed has to be a constant, and SEQ4() is not.

Fair enough. So I gave it a constant, and wrote a follow-up to show what I assumed that would do: give the same value on every row. I named the query that.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(DISTINCT UNIFORM(100, 5000, RANDOM(42))) AS DISTINCT_VALUES_WITH_A_SEED,
       COUNT(DISTINCT UNIFORM(100, 5000, RANDOM()))   AS DISTINCT_VALUES_UNSEEDED
FROM TABLE(GENERATOR(ROWCOUNT => 100));
Result1 row · 3 columns
ROWS_TOTALDISTINCT_VALUES_WITH_A_SEEDDISTINCT_VALUES_UNSEEDED
100100100

100 rows, and 100 distinct values with the seed in place. The same as without it.

So the query disproved its own name, and I am leaving the name on it. A constant seed seeds the generator. It does not freeze the value.

And what it does not do is repeat across runs. Let's be careful about that.

Query
SELECT (SELECT COUNT(DISTINCT UNIFORM(1, 1000000, RANDOM()))
        FROM TABLE(GENERATOR(ROWCOUNT => 100))) > 1 AS IT_VARIES_WITHIN_A_RUN,
       (SELECT COUNT(*) FROM TABLE(GENERATOR(ROWCOUNT => 100)))
         AS ROWS_IT_WAS_ASKED_FOR;
Result1 row · 2 columns
IT_VARIES_WITHIN_A_RUNROWS_IT_WAS_ASKED_FOR
TRUE100

All that grid says is that an unseeded UNIFORM varies within a single run, over the number of rows it was asked for. I never ran the seeded version twice in two separate statements, so I cannot tell you whether it repeats, and I am not going to.

Let's use HASH instead, and prove it repeats

Here is something I can prove. HASH is deterministic, which we established in Episode 83, and it takes a per-row argument quite happily. So hash the sequence number instead of randomising it.

Query
SELECT SEQ4()                                  AS N,
       HASH(SEQ4())                            AS ITS_HASH,
       MOD(ABS(HASH(SEQ4())), 4901) + 100      AS IN_RANGE_100_TO_5000
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY N;
Result10 rows · 3 columns
NITS_HASHIN_RANGE_100_TO_5000
0-6076851061503311999789
1-47301684949648752352544
2-36901317534532052644451
3-7287585996956442977744
4-12853600040045201912603
548018571652824518533058
6-21128981948612331694013
71885958945512144850694
8-39949460213359878984154
9-35590315456299224663428

A different hash on every row, and MOD(ABS(...), 4901) + 100 folds each one into the range I wanted. The ABS is there because HASH returns a signed integer.

Now the question the random version could not answer. Run the same generated data twice and compare the two fingerprints.

Query
SELECT (SELECT HASH_AGG(MOD(ABS(HASH(SEQ4())), 4901) + 100)
        FROM TABLE(GENERATOR(ROWCOUNT => 100))) AS FIRST_RUN,
       (SELECT HASH_AGG(MOD(ABS(HASH(SEQ4())), 4901) + 100)
        FROM TABLE(GENERATOR(ROWCOUNT => 100))) AS SECOND_RUN,
       (SELECT HASH_AGG(MOD(ABS(HASH(SEQ4())), 4901) + 100)
        FROM TABLE(GENERATOR(ROWCOUNT => 100)))
         = (SELECT HASH_AGG(MOD(ABS(HASH(SEQ4())), 4901) + 100)
            FROM TABLE(GENERATOR(ROWCOUNT => 100))) AS IDENTICAL;
Result1 row · 3 columns
FIRST_RUNSECOND_RUNIDENTICAL
-5666859996066187567-5666859996066187567TRUE

HASH_AGG over the first run and over the second run gave the same number, and the comparison says TRUE. Same query, same data.

That is what test data needs. Let's build a proper row out of it.

Query
SELECT ROW_NUMBER() OVER (ORDER BY SEQ4())                          AS ID,
       'CUST-' || LPAD(ROW_NUMBER() OVER (ORDER BY SEQ4()), 5, '0') AS REFERENCE,
       MOD(ABS(HASH(SEQ4())), 4901) + 100                           AS AMOUNT,
       DATEADD('day', MOD(ABS(HASH(SEQ4() + 1000)), 365), DATE '2024-01-01') AS THE_DATE,
       DECODE(MOD(ABS(HASH(SEQ4())), 3), 0, 'Shipped', 1, 'Pending', 'Cancelled')
         AS STATUS
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY ID;
Result10 rows · 5 columns
IDREFERENCEAMOUNTTHE_DATESTATUS
1CUST-000017892024-06-07Cancelled
2CUST-0000225442024-12-19Cancelled
3CUST-0000344512024-01-17Shipped
4CUST-000047442024-07-14Cancelled
5CUST-0000526032024-12-14Shipped
6CUST-0000630582024-08-17Cancelled
7CUST-0000740132024-08-10Shipped
8CUST-000086942024-08-21Cancelled
9CUST-0000941542024-08-14Cancelled
10CUST-0001034282024-06-05Cancelled

A reference, an amount, a date and a status, all derived from the sequence number and nothing else.

Now scale it up and look at the properties, including the awkward one.

Query
SELECT COUNT(*) AS ROWS_MADE,
       COUNT(DISTINCT T.ID)                 AS DISTINCT_IDS,
       MIN(T.AMOUNT)                        AS SMALLEST_AMOUNT,
       MAX(T.AMOUNT)                        AS LARGEST_AMOUNT,
       COUNT(DISTINCT T.AMOUNT)             AS DISTINCT_AMOUNTS,
       MIN(T.THE_DATE)                      AS EARLIEST,
       MAX(T.THE_DATE)                      AS LATEST,
       COUNT_IF(T.AMOUNT NOT BETWEEN 100 AND 5000) AS OUT_OF_RANGE
FROM (SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS ID,
             MOD(ABS(HASH(SEQ4())), 4901) + 100 AS AMOUNT,
             DATEADD('day', MOD(ABS(HASH(SEQ4() + 1000)), 365), DATE '2024-01-01')
               AS THE_DATE
      FROM TABLE(GENERATOR(ROWCOUNT => 1000))) T;
Result1 row · 8 columns · scroll →
ROWS_MADEDISTINCT_IDSSMALLEST_AMOUNTLARGEST_AMOUNTDISTINCT_AMOUNTSEARLIESTLATESTOUT_OF_RANGE
1000100010449919042024-01-012024-12-300

1000 rows and 1000 distinct ids. The amounts run from 104 to 4991 and not one of them fell outside the range I asked for. The dates cover the year.

And 904 distinct amounts. Not 1000. So 96 of them collided with another row.

That is MOD of a hash doing exactly what it is for. It buckets values into a range. It does not make them unique, and it never promised to. If you need unique, that is what ROW_NUMBER is for. If you need a plausible spread, this is fine.

One last thing: Level 7 on rows that came from nothing

To close out the level, one query using most of what we have covered in it, on rows that no table supplied.

Query
SELECT ROW_NUMBER() OVER (ORDER BY SEQ4())                           AS ID,
       'cust-' || LPAD(ROW_NUMBER() OVER (ORDER BY SEQ4()), 4, '0')  AS REFERENCE,
       INITCAP(TRIM('  techbrothers it  '))                          AS STRINGS,
       ROUND((MOD(ABS(HASH(SEQ4())), 4901) + 100) / 3.0, 2)          AS NUMBERS,
       DATEADD('day', SEQ4(), DATE '2024-01-01')                     AS DATES,
       DAYNAME(DATEADD('day', SEQ4(), DATE '2024-01-01'))            AS DAY_NAME,
       TO_CHAR(DATEADD('day', SEQ4(), DATE '2024-01-01'), 'DD-MON-YYYY') AS FORMATTED,
       CASE WHEN MOD(SEQ4(), 2) = 0 THEN 'even' ELSE 'odd' END       AS CASE_,
       MD5(TO_VARCHAR(SEQ4()))                                       AS HASHED
FROM TABLE(GENERATOR(ROWCOUNT => 8))
ORDER BY ID;
Result8 rows · 9 columns · scroll →
IDREFERENCESTRINGSNUMBERSDATESDAY_NAMEFORMATTEDCASE_HASHED
1cust-0001Techbrothers It263.002024-01-01Mon01-Jan-2024evencfcd208495d565ef66e7dff9f98764da
2cust-0002Techbrothers It848.002024-01-02Tue02-Jan-2024oddc4ca4238a0b923820dcc509a6f75849b
3cust-0003Techbrothers It1483.672024-01-03Wed03-Jan-2024evenc81e728d9d4c2f636f067f89cc14862c
4cust-0004Techbrothers It248.002024-01-04Thu04-Jan-2024oddeccbc87e4b5ce2fe28308fd9f2a7baf3
5cust-0005Techbrothers It867.672024-01-05Fri05-Jan-2024evena87ff679a2f3e71d9181a67b7542122c
6cust-0006Techbrothers It1019.332024-01-06Sat06-Jan-2024odde4da3b7fbbce2345d7772b0674a318d5
7cust-0007Techbrothers It1337.672024-01-07Sun07-Jan-2024even1679091c5a880faf6fb5e6087eb1b2dc
8cust-0008Techbrothers It231.332024-01-08Mon08-Jan-2024odd8f14e45fceea167a5a36dedd4bea2543

LPAD, INITCAP and TRIM on strings. ROUND on a number. DATEADD, DAYNAME and TO_CHAR on dates. A CASE expression and an MD5.

Eight rows, nine columns, and no FROM table anywhere in it.

Key points

  • TABLE(GENERATOR(ROWCOUNT => n)) returns n rows with no table involved. GENERATOR() and ROWCOUNT => 0 both return nothing, and a negative count is an error.
  • The number in SEQ1, SEQ2, SEQ4 and SEQ8 is a count of bytes. SEQ1 stops at 127 and starts over, silently. Use SEQ4 or SEQ8.
  • SEQ4 is zero-based and ROW_NUMBER is one-based.
  • The documentation does not promise a gap-free sequence from the SEQ functions, whatever one run looks like. ROW_NUMBER is what promises that.
  • A day with no orders has no row, so grouping the data alone cannot show it. Here that hid 623 days inside a 664-day range.
  • A date spine is GENERATOR plus DATEADD plus a LEFT JOIN, and you group by the spine's date, not the order's.
  • Size the spine from MIN and MAX of the data rather than hardcoding it.
  • FLATTEN beats a numbers table for splitting a string, because it does not need to know the number of parts in advance. Its INDEX starts at 0.
  • RANDOM's seed must be a constant, and a constant seed does not give you one repeated value — it still varies per row.
  • MOD(ABS(HASH(SEQ4())), n) is per-row and repeatable, which is what test data needs. It also collides, because bucketing is not uniqueness.
Next in this series

Episode 86 — Level 8 begins: semi-structured data. The VARIANT type, TYPEOF and IS_NULL_VALUE, and one column where the total comes out right while the query that looks up the row behind it finds nothing.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The ORDERS data is invented demo data created by that script, and the generated grids come from GENERATOR with fixed row counts and fixed dates rather than the clock. Nothing here is timed, no row count is claimed for TIMELIMIT, and no performance claims are made anywhere in this series. The quoted lines about gap-free sequences are from the SEQ1 / SEQ2 / SEQ4 / SEQ8 documentation; the rest follows the Snowflake GENERATOR documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.