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
- Let's start with ten rows out of nothing
- Now let's look at the four SEQ functions
- Now let's put SEQ4 next to ROW_NUMBER
- What are the edge cases?
- Now the real reason GENERATOR exists
- So let's generate the calendar ourselves
- Now let's join the orders onto the spine
- Can we size the spine from the data?
- Let's cycle through a list
- Now let's make a numbers table
- Now let's generate some test data, and get it wrong
- Let's use HASH instead, and prove it repeats
- One last thing: Level 7 on rows that came from nothing
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.
-- 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.
SELECT SEQ4() AS N
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY N;| 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.
SELECT SEQ1() AS SEQ1_, SEQ2() AS SEQ2_, SEQ4() AS SEQ4_, SEQ8() AS SEQ8_
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY SEQ8_;| SEQ1_ | SEQ2_ | SEQ4_ | SEQ8_ |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | 3 | 3 | 3 |
| 4 | 4 | 4 | 4 |
| 5 | 5 | 5 | 5 |
| 6 | 6 | 6 | 6 |
| 7 | 7 | 7 | 7 |
| 8 | 8 | 8 | 8 |
| 9 | 9 | 9 | 9 |
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.
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));| SEQ1_MIN | SEQ1_MAX | SEQ4_MIN | SEQ4_MAX | ROWS_GENERATED | DISTINCT_SEQ1_VALUES | DISTINCT_SEQ4_VALUES |
|---|---|---|---|---|---|---|
| 0 | 127 | 0 | 299 | 300 | 128 | 300 |
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.
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.
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_;| SEQ4_ | ROW_NUMBER_ | ROW_NUMBER_ZERO_BASED |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 2 | 1 |
| 2 | 3 | 2 |
| 3 | 4 | 3 |
| 4 | 5 | 4 |
| 5 | 6 | 5 |
| 6 | 7 | 6 |
| 7 | 8 | 7 |
| 8 | 9 | 8 |
| 9 | 10 | 9 |
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.
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));| ROWS_TOTAL | SEQ_MIN | SEQ_MAX | SPAN_IF_GAP_FREE | DISTINCT_VALUES | NO_DUPLICATES |
|---|---|---|---|---|---|
| 10000 | 0 | 9999 | 10000 | 10000 | TRUE |
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.
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.
SELECT COUNT(*) AS ROWS_RETURNED FROM TABLE(GENERATOR());| ROWS_RETURNED |
|---|
| 0 |
Zero rows. No error.
And asking for zero explicitly.
SELECT COUNT(*) AS ROWS_RETURNED FROM TABLE(GENERATOR(ROWCOUNT => 0));| 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.
SELECT COUNT(*) > 0 AS IT_MADE_SOME_ROWS,
COUNT(*) IS NOT NULL AS THE_COUNT_IS_A_NUMBER
FROM TABLE(GENERATOR(TIMELIMIT => 1));| IT_MADE_SOME_ROWS | THE_COUNT_IS_A_NUMBER |
|---|---|
| TRUE | TRUE |
It made some rows. That is the whole claim, and nothing on this page is timed.
And a negative row count?
SELECT COUNT(*) FROM TABLE(GENERATOR(ROWCOUNT => -5));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.
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;| DAYS_WITH_AT_LEAST_ONE_ORDER | CALENDAR_DAYS_IN_RANGE | DAYS_WITH_NO_ORDERS |
|---|---|---|
| 41 | 664 | 623 |
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.
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.
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;| THE_DATE | DAY_NAME | MONTH_START |
|---|---|---|
| 2024-01-01 | Mon | 2024-01-01 |
| 2024-01-02 | Tue | 2024-01-01 |
| 2024-01-03 | Wed | 2024-01-01 |
| 2024-01-04 | Thu | 2024-01-01 |
| 2024-01-05 | Fri | 2024-01-01 |
| 2024-01-06 | Sat | 2024-01-01 |
| 2024-01-07 | Sun | 2024-01-01 |
| 2024-01-08 | Mon | 2024-01-01 |
| 2024-01-09 | Tue | 2024-01-01 |
| 2024-01-10 | Wed | 2024-01-01 |
| 2024-01-11 | Thu | 2024-01-01 |
| 2024-01-12 | Fri | 2024-01-01 |
| 2024-01-13 | Sat | 2024-01-01 |
| 2024-01-14 | Sun | 2024-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.
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;| THE_DATE | ORDERS_ | TOTAL |
|---|---|---|
| 2024-01-01 | 0 | 0.00 |
| 2024-01-02 | 0 | 0.00 |
| 2024-01-03 | 0 | 0.00 |
| 2024-01-04 | 0 | 0.00 |
| 2024-01-05 | 0 | 0.00 |
| 2024-01-06 | 0 | 0.00 |
| 2024-01-07 | 0 | 0.00 |
| 2024-01-08 | 0 | 0.00 |
| 2024-01-09 | 0 | 0.00 |
| 2024-01-10 | 0 | 0.00 |
| 2024-01-11 | 0 | 0.00 |
| 2024-01-12 | 0 | 0.00 |
| 2024-01-13 | 0 | 0.00 |
| 2024-01-14 | 0 | 0.00 |
| 2024-01-15 | 1 | 3910.00 |
| 2024-01-16 | 0 | 0.00 |
| 2024-01-17 | 0 | 0.00 |
| 2024-01-18 | 0 | 0.00 |
| 2024-01-19 | 0 | 0.00 |
| 2024-01-20 | 0 | 0.00 |
| 2024-01-21 | 0 | 0.00 |
| 2024-01-22 | 0 | 0.00 |
| 2024-01-23 | 0 | 0.00 |
| 2024-01-24 | 0 | 0.00 |
| 2024-01-25 | 0 | 0.00 |
| 2024-01-26 | 0 | 0.00 |
| 2024-01-27 | 0 | 0.00 |
| 2024-01-28 | 0 | 0.00 |
| 2024-01-29 | 0 | 0.00 |
| 2024-01-30 | 0 | 0.00 |
| 2024-01-31 | 1 | 11200.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.
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;| DAYS_IN_THE_SPINE | EMPTY_DAYS | DAYS_WITH_ORDERS |
|---|---|---|
| 31 | 29 | 2 |
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.
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);| DAYS_IN_THE_SPINE | SPINE_START | SPINE_END | FIRST_ORDER | LAST_ORDER |
|---|---|---|---|---|
| 664 | 2023-01-12 | 2024-11-05 | 2023-01-12 | 2024-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.
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;| ID | STATUS | SEGMENT |
|---|---|---|
| 1 | Shipped | Enterprise |
| 2 | Pending | SMB |
| 3 | Cancelled | Enterprise |
| 4 | Shipped | SMB |
| 5 | Pending | Enterprise |
| 6 | Cancelled | SMB |
| 7 | Shipped | Enterprise |
| 8 | Pending | SMB |
| 9 | Cancelled | Enterprise |
| 10 | Shipped | SMB |
| 11 | Pending | Enterprise |
| 12 | Cancelled | SMB |
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.
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));| ROWS_TOTAL | STATUS_ASSIGNED | DISTINCT_STATUSES |
|---|---|---|
| 300 | 300 | 3 |
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.
SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS N
FROM TABLE(GENERATOR(ROWCOUNT => 10))
ORDER BY N;| 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.
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;| PART_NUMBER | THE_PART |
|---|---|
| 1 | alpha |
| 2 | beta |
| 3 | gamma |
| 4 | delta |
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.
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;| PART_NUMBER | THE_PART |
|---|---|
| 1 | alpha |
| 2 | beta |
| 3 | gamma |
| 4 | delta |
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.
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;| FLATTEN_ROWS | GENERATOR_ROWS | SPLIT_SAYS |
|---|---|---|
| 4 | 4 | 4 |
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.
SELECT UNIFORM(100, 5000, RANDOM(SEQ4())) AS SHOULD_NOT_GET_THIS_FAR
FROM TABLE(GENERATOR(ROWCOUNT => 5));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.
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));| ROWS_TOTAL | DISTINCT_VALUES_WITH_A_SEED | DISTINCT_VALUES_UNSEEDED |
|---|---|---|
| 100 | 100 | 100 |
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.
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;| IT_VARIES_WITHIN_A_RUN | ROWS_IT_WAS_ASKED_FOR |
|---|---|
| TRUE | 100 |
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.
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;| N | ITS_HASH | IN_RANGE_100_TO_5000 |
|---|---|---|
| 0 | -6076851061503311999 | 789 |
| 1 | -4730168494964875235 | 2544 |
| 2 | -3690131753453205264 | 4451 |
| 3 | -7287585996956442977 | 744 |
| 4 | -1285360004004520191 | 2603 |
| 5 | 4801857165282451853 | 3058 |
| 6 | -2112898194861233169 | 4013 |
| 7 | 1885958945512144850 | 694 |
| 8 | -3994946021335987898 | 4154 |
| 9 | -3559031545629922466 | 3428 |
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.
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;| FIRST_RUN | SECOND_RUN | IDENTICAL |
|---|---|---|
| -5666859996066187567 | -5666859996066187567 | TRUE |
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.
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;| ID | REFERENCE | AMOUNT | THE_DATE | STATUS |
|---|---|---|---|---|
| 1 | CUST-00001 | 789 | 2024-06-07 | Cancelled |
| 2 | CUST-00002 | 2544 | 2024-12-19 | Cancelled |
| 3 | CUST-00003 | 4451 | 2024-01-17 | Shipped |
| 4 | CUST-00004 | 744 | 2024-07-14 | Cancelled |
| 5 | CUST-00005 | 2603 | 2024-12-14 | Shipped |
| 6 | CUST-00006 | 3058 | 2024-08-17 | Cancelled |
| 7 | CUST-00007 | 4013 | 2024-08-10 | Shipped |
| 8 | CUST-00008 | 694 | 2024-08-21 | Cancelled |
| 9 | CUST-00009 | 4154 | 2024-08-14 | Cancelled |
| 10 | CUST-00010 | 3428 | 2024-06-05 | Cancelled |
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.
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;| ROWS_MADE | DISTINCT_IDS | SMALLEST_AMOUNT | LARGEST_AMOUNT | DISTINCT_AMOUNTS | EARLIEST | LATEST | OUT_OF_RANGE |
|---|---|---|---|---|---|---|---|
| 1000 | 1000 | 104 | 4991 | 904 | 2024-01-01 | 2024-12-30 | 0 |
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.
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;| ID | REFERENCE | STRINGS | NUMBERS | DATES | DAY_NAME | FORMATTED | CASE_ | HASHED |
|---|---|---|---|---|---|---|---|---|
| 1 | cust-0001 | Techbrothers It | 263.00 | 2024-01-01 | Mon | 01-Jan-2024 | even | cfcd208495d565ef66e7dff9f98764da |
| 2 | cust-0002 | Techbrothers It | 848.00 | 2024-01-02 | Tue | 02-Jan-2024 | odd | c4ca4238a0b923820dcc509a6f75849b |
| 3 | cust-0003 | Techbrothers It | 1483.67 | 2024-01-03 | Wed | 03-Jan-2024 | even | c81e728d9d4c2f636f067f89cc14862c |
| 4 | cust-0004 | Techbrothers It | 248.00 | 2024-01-04 | Thu | 04-Jan-2024 | odd | eccbc87e4b5ce2fe28308fd9f2a7baf3 |
| 5 | cust-0005 | Techbrothers It | 867.67 | 2024-01-05 | Fri | 05-Jan-2024 | even | a87ff679a2f3e71d9181a67b7542122c |
| 6 | cust-0006 | Techbrothers It | 1019.33 | 2024-01-06 | Sat | 06-Jan-2024 | odd | e4da3b7fbbce2345d7772b0674a318d5 |
| 7 | cust-0007 | Techbrothers It | 1337.67 | 2024-01-07 | Sun | 07-Jan-2024 | even | 1679091c5a880faf6fb5e6087eb1b2dc |
| 8 | cust-0008 | Techbrothers It | 231.33 | 2024-01-08 | Mon | 08-Jan-2024 | odd | 8f14e45fceea167a5a36dedd4bea2543 |
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()andROWCOUNT => 0both return nothing, and a negative count is an error.- The number in
SEQ1,SEQ2,SEQ4andSEQ8is a count of bytes.SEQ1stops at 127 and starts over, silently. UseSEQ4orSEQ8. SEQ4is zero-based andROW_NUMBERis one-based.- The documentation does not promise a gap-free sequence from the
SEQfunctions, whatever one run looks like.ROW_NUMBERis 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
GENERATORplusDATEADDplus aLEFT JOIN, and you group by the spine's date, not the order's. - Size the spine from
MINandMAXof the data rather than hardcoding it. FLATTENbeats a numbers table for splitting a string, because it does not need to know the number of parts in advance. ItsINDEXstarts 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.
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.