In this post we are going to cover LATERAL FLATTEN in Snowflake.
FLATTEN takes an array inside a document and gives you one row per element. That is it. It is the function that turns a nested document into something the rest of SQL can group, join and aggregate, and it is the centre of everything else in this level.
We will start by predicting how many rows we should get, then run it and check. After that we will look at the two things FLATTEN does that nobody warns you about: it repeats the parent on every child row, so a SUM over a parent column more than doubles, and it quietly drops parents whose array is empty.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 90 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's predict the row count before we run anything
- Now let's flatten the items
- There is a second spelling of the same thing
- Now let's add the parent amount to that result
- So what happens when somebody sums that column?
- So how do we fix it?
- Now let's flatten the tags instead
- Let's get that row back with OUTER
- Same thing for a key that is missing entirely
- What happens if we flatten something that is not an array?
- Now let's look at all six columns FLATTEN gives us
- Is that reliable, or did we get lucky?
- Now let's check a document against itself
- One last thing: the report you will actually be asked for
Let's create some sample data
We are still on the same four event documents. This time what matters about them is the arrays inside, so let's look at those first.
-- EVENTS_JSON comes from the setup script this course uses throughout.
-- Run it once and every post in this level works against the same data.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
-- Each PAYLOAD holds one event document with two arrays inside it:
-- items - one object per line item, with sku, qty and price
-- tags - one string per tagLet's ask how big each array is on each row.
SELECT EVENT_ID,
PAYLOAD:event::VARCHAR AS EVENT_,
PAYLOAD:amount AS AMOUNT_RAW,
ARRAY_SIZE(PAYLOAD:items) AS ITEM_COUNT,
ARRAY_SIZE(PAYLOAD:tags) AS TAG_COUNT,
PAYLOAD:device IS NULL AS DEVICE_MISSING
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | EVENT_ | AMOUNT_RAW | ITEM_COUNT | TAG_COUNT | DEVICE_MISSING |
|---|---|---|---|---|---|
| 1 | purchase | 4200 | 2 | 2 | FALSE |
| 2 | purchase | 890.5 | 1 | 1 | FALSE |
| 3 | refund | "1500.00" | 1 | 0 | TRUE |
| 4 | purchase | 9250 | 3 | 3 | FALSE |
Four events. The items arrays hold two, one, one and three elements. The tags arrays hold two, one, none and three.
Event three is the awkward one and it is awkward in two ways. Its tags array is empty, and it has no device key at all. Both of those matter later in the post.
Let's predict the row count before we run anything
This is a habit worth building. Before you flatten anything, work out how many rows you should get, so that you have something to check the answer against.
One row per element means the answer is the sum of the array sizes. Let's ask for that.
SELECT COUNT(*) AS EVENTS,
SUM(ARRAY_SIZE(PAYLOAD:items)) AS TOTAL_ITEMS,
SUM(ARRAY_SIZE(PAYLOAD:tags)) AS TOTAL_TAGS,
COUNT_IF(ARRAY_SIZE(PAYLOAD:tags) = 0) AS EVENTS_WITH_NO_TAGS
FROM EVENTS_JSON;| EVENTS | TOTAL_ITEMS | TOTAL_TAGS | EVENTS_WITH_NO_TAGS |
|---|---|---|---|
| 4 | 7 | 6 | 1 |
Four events, seven items between them, six tags, and one event with no tags at all.
So flattening the items should give us seven rows. Hold on to that number.
Now let's flatten the items
The syntax is a comma and then LATERAL FLATTEN(INPUT => ...) with the path to the array. Inside the flattened result, VALUE holds the element, so VALUE:sku reads a key out of it.
SELECT E.EVENT_ID,
I.INDEX AS ITEM_INDEX,
I.VALUE:sku::VARCHAR AS SKU,
I.VALUE:qty::INT AS QTY,
I.VALUE:price::NUMBER(10,2) AS PRICE
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
ORDER BY E.EVENT_ID, I.INDEX;| EVENT_ID | ITEM_INDEX | SKU | QTY | PRICE |
|---|---|---|---|---|
| 1 | 0 | A-100 | 8 | 300.00 |
| 1 | 1 | B-220 | 4 | 450.00 |
| 2 | 0 | C-310 | 3 | 296.83 |
| 3 | 0 | A-100 | 5 | 300.00 |
| 4 | 0 | D-400 | 12 | 500.00 |
| 4 | 1 | A-100 | 10 | 300.00 |
| 4 | 2 | E-505 | 8 | 156.25 |
One row per element. Event one has two items so it has index zero and index one. Events two and three have index zero only. Event four has zero, one and two.
Count the rows and compare them to what we predicted.
SELECT COUNT(*) AS FLATTENED_ROWS,
(SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON) AS SUM_OF_SIZES,
COUNT(*) = (SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON)
AS IT_MATCHES
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I;| FLATTENED_ROWS | EVENTS | SUM_OF_SIZES | IT_MATCHES |
|---|---|---|---|
| 7 | 4 | 7 | TRUE |
Seven flattened rows out of four events, the sum of the sizes is seven, and IT_MATCHES is TRUE. Predict, run, check. It costs one extra query and it is the only way you find out that a flatten silently lost something.
There is a second spelling of the same thing
You will see TABLE(FLATTEN(...)) in other people's code. Let's run it.
SELECT E.EVENT_ID, I.INDEX AS ITEM_INDEX, I.VALUE:sku::VARCHAR AS SKU
FROM EVENTS_JSON E, TABLE(FLATTEN(INPUT => E.PAYLOAD:items)) I
ORDER BY E.EVENT_ID, I.INDEX;| EVENT_ID | ITEM_INDEX | SKU |
|---|---|---|
| 1 | 0 | A-100 |
| 1 | 1 | B-220 |
| 2 | 0 | C-310 |
| 3 | 0 | A-100 |
| 4 | 0 | D-400 |
| 4 | 1 | A-100 |
| 4 | 2 | E-505 |
Same rows, same indexes, same SKUs. Let's count both forms in one query so there is no doubt.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS LATERAL_ROWS,
(SELECT COUNT(*) FROM EVENTS_JSON E,
TABLE(FLATTEN(INPUT => E.PAYLOAD:items)) I) AS TABLE_ROWS,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I)
= (SELECT COUNT(*) FROM EVENTS_JSON E,
TABLE(FLATTEN(INPUT => E.PAYLOAD:items)) I) AS THEY_AGREE;| LATERAL_ROWS | TABLE_ROWS | THEY_AGREE |
|---|---|---|
| 7 | 7 | TRUE |
They agree. Use whichever one you read more easily. The rest of this post uses LATERAL FLATTEN.
Now let's add the parent amount to that result
This is the section to remember. We are going to put the event's own amount next to each item, which is a completely normal thing to want.
SELECT E.EVENT_ID,
E.PAYLOAD:amount::NUMBER(12,2) AS EVENT_AMOUNT,
I.INDEX AS ITEM_INDEX,
I.VALUE:sku::VARCHAR AS SKU,
I.VALUE:qty::INT AS QTY
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
ORDER BY E.EVENT_ID, I.INDEX;| EVENT_ID | EVENT_AMOUNT | ITEM_INDEX | SKU | QTY |
|---|---|---|---|---|
| 1 | 4200.00 | 0 | A-100 | 8 |
| 1 | 4200.00 | 1 | B-220 | 4 |
| 2 | 890.50 | 0 | C-310 | 3 |
| 3 | 1500.00 | 0 | A-100 | 5 |
| 4 | 9250.00 | 0 | D-400 | 12 |
| 4 | 9250.00 | 1 | A-100 | 10 |
| 4 | 9250.00 | 2 | E-505 | 8 |
Read down the EVENT_AMOUNT column. Event one's amount appears twice, once for each of its items. Event four's appears three times.
That is correct. It is a join, and the parent row is joined to each of its children, so the parent's columns repeat. Nothing has gone wrong here.
The problem is that the amount is now sitting right there in the result, where anybody can total it.
So what happens when somebody sums that column?
Let's total the amount two ways in one query: once off the event table on its own, and once off the flattened result.
SELECT (SELECT SUM(PAYLOAD:amount::NUMBER(12,2)) FROM EVENTS_JSON)
AS CORRECT_TOTAL,
(SELECT SUM(E.PAYLOAD:amount::NUMBER(12,2))
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I)
AS TOTAL_AFTER_FLATTENING,
(SELECT COUNT(*) FROM EVENTS_JSON) AS EVENT_ROWS,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS FLATTENED_ROWS;| CORRECT_TOTAL | TOTAL_AFTER_FLATTENING | EVENT_ROWS | FLATTENED_ROWS |
|---|---|---|---|
| 15840.50 | 38540.50 | 4 | 7 |
The correct total is 15840.50. After flattening it is 38540.50. More than double, from the same four rows of data, with no error and no warning in between.
Let's see exactly where the extra came from, event by event.
SELECT E.EVENT_ID,
E.PAYLOAD:amount::NUMBER(12,2) AS EVENT_AMOUNT,
ARRAY_SIZE(E.PAYLOAD:items) AS TIMES_REPEATED,
E.PAYLOAD:amount::NUMBER(12,2) * ARRAY_SIZE(E.PAYLOAD:items)
AS WHAT_THE_SUM_COUNTS,
E.PAYLOAD:amount::NUMBER(12,2) * ARRAY_SIZE(E.PAYLOAD:items)
- E.PAYLOAD:amount::NUMBER(12,2) AS OVERCOUNTED_BY
FROM EVENTS_JSON E
ORDER BY E.EVENT_ID;| EVENT_ID | EVENT_AMOUNT | TIMES_REPEATED | WHAT_THE_SUM_COUNTS | OVERCOUNTED_BY |
|---|---|---|---|---|
| 1 | 4200.00 | 2 | 8400.00 | 4200.00 |
| 2 | 890.50 | 1 | 890.50 | 0.00 |
| 3 | 1500.00 | 1 | 1500.00 | 0.00 |
| 4 | 9250.00 | 3 | 27750.00 | 18500.00 |
Event one's amount was counted twice, so it contributed 8400.00 instead of 4200.00. Event four's was counted three times, which is an overcount of 18500.00 out of a single row.
Now look at events two and three. Their arrays hold one element each, so their amounts were counted once and their overcount is 0.00.
Those two rows are why this bug survives. Any event with exactly one child is unaffected, so a test built on single-item orders passes, a spot check on one row passes, and the total is still wrong. The rows that break it are the ones with the most children, which are usually the biggest numbers you have.
So how do we fix it?
Group first, then aggregate. Take the amount once per event, and only then add the amounts up. Let's put the correct total, the grouped version and SUM(DISTINCT ...) side by side.
SELECT (SELECT SUM(PAYLOAD:amount::NUMBER(12,2)) FROM EVENTS_JSON)
AS CORRECT_TOTAL,
(SELECT SUM(X.AMT) FROM (
SELECT E.EVENT_ID, MAX(E.PAYLOAD:amount::NUMBER(12,2)) AS AMT
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
GROUP BY E.EVENT_ID) X)
AS GROUPED_THEN_SUMMED,
(SELECT SUM(DISTINCT E.PAYLOAD:amount::NUMBER(12,2))
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I)
AS SUM_DISTINCT,
(SELECT COUNT(DISTINCT PAYLOAD:amount::NUMBER(12,2)) FROM EVENTS_JSON)
AS DISTINCT_AMOUNTS,
(SELECT COUNT(*) FROM EVENTS_JSON)
AS EVENTS_TOTAL;| CORRECT_TOTAL | GROUPED_THEN_SUMMED | SUM_DISTINCT | DISTINCT_AMOUNTS | EVENTS_TOTAL |
|---|---|---|---|---|
| 15840.50 | 15840.50 | 15840.50 | 4 | 4 |
The grouped version matches the correct total exactly. Group by the event, take the amount with MAX because it is the same on every child row, then sum the result of that.
SUM(DISTINCT ...) also gives the right answer here, and please do not trust it. The last two columns say why: there are four distinct amounts across four events, so no two events share an amount.
Give two events the same amount and SUM(DISTINCT ...) counts it once and your total is short. It is not a fix, it is a coincidence that looks like one.
Now let's flatten the tags instead
Second thing FLATTEN does that nobody warns you about. Same query shape, different array.
SELECT E.EVENT_ID, T.INDEX AS TAG_INDEX, T.VALUE::VARCHAR AS TAG
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T
ORDER BY E.EVENT_ID, T.INDEX;| EVENT_ID | TAG_INDEX | TAG |
|---|---|---|
| 1 | 0 | priority |
| 1 | 1 | repeat |
| 2 | 0 | new |
| 4 | 0 | priority |
| 4 | 1 | enterprise |
| 4 | 2 | repeat |
Six rows. Event one appears twice, event two once, event four three times. Now read the EVENT_ID column again and look for event three.
It is not there. Its tags array was empty, so it has no children to join to, so the row is gone.
Let's count that properly rather than noticing it by eye.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_IN,
COUNT(DISTINCT E.EVENT_ID) AS EVENTS_OUT,
COUNT(*) AS TAG_ROWS,
(SELECT COUNT(*) FROM EVENTS_JSON) - COUNT(DISTINCT E.EVENT_ID)
AS EVENTS_LOST
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T;| EVENTS_IN | EVENTS_OUT | TAG_ROWS | EVENTS_LOST |
|---|---|---|---|
| 4 | 3 | 6 | 1 |
Four events went in, three came out, six tag rows, one event lost. Not filtered by us, not warned about, just absent.
That is an inner join doing what an inner join does. An empty array joins to nothing, so the parent disappears with it.
Let's get that row back with OUTER
The fix is one argument. OUTER => TRUE keeps the parent row even when the array has nothing in it.
SELECT E.EVENT_ID,
ARRAY_SIZE(E.PAYLOAD:tags) AS ITS_TAG_COUNT,
T.INDEX AS TAG_INDEX,
T.VALUE::VARCHAR AS TAG,
T.VALUE IS NULL AS TAG_IS_NULL
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags, OUTER => TRUE) T
ORDER BY E.EVENT_ID, T.INDEX;| EVENT_ID | ITS_TAG_COUNT | TAG_INDEX | TAG | TAG_IS_NULL |
|---|---|---|---|---|
| 1 | 2 | 0 | priority | FALSE |
| 1 | 2 | 1 | repeat | FALSE |
| 2 | 1 | 0 | new | FALSE |
| 3 | 0 | NULL | NULL | TRUE |
| 4 | 3 | 0 | priority | FALSE |
| 4 | 3 | 1 | enterprise | FALSE |
| 4 | 3 | 2 | repeat | FALSE |
Seven rows now, and event three is back. Look along that row. Its tag count is zero, its index is NULL and its tag is NULL. The row exists with nothing in it, which is exactly what an outer join gives you.
Let's count the two versions together.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T) AS INNER_ROWS,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags, OUTER => TRUE) T) AS OUTER_ROWS,
(SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags) T) AS INNER_EVENTS,
(SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:tags, OUTER => TRUE) T) AS OUTER_EVENTS,
(SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_TOTAL;| INNER_ROWS | OUTER_ROWS | INNER_EVENTS | OUTER_EVENTS | EVENTS_TOTAL |
|---|---|---|---|---|
| 6 | 7 | 3 | 4 | 4 |
Inner gave six rows across three events. Outer gave seven rows across four, which is every event in the table. That is what the extra argument buys you.
Same thing for a key that is missing entirely
An empty array is one way to lose a parent. A missing key is the other. Event three has no device key, so let's flatten the device object and count.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:device) D) AS INNER_ROWS,
(SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:device) D) AS INNER_EVENTS,
(SELECT COUNT(DISTINCT E.EVENT_ID) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:device, OUTER => TRUE) D)
AS OUTER_EVENTS,
(SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_TOTAL;| INNER_ROWS | INNER_EVENTS | OUTER_EVENTS | EVENTS_TOTAL |
|---|---|---|---|
| 6 | 3 | 4 | 4 |
Inner gave six rows across three events. With OUTER => TRUE all four events come back.
Have a look at what was flattened there, though. device is an object, not an array, and FLATTEN handled it. An object gives you one row per key, and we will look at that properly in a couple of sections.
What happens if we flatten something that is not an array?
This is the one that should worry you most. amount is a number, not an array and not an object. Let's flatten it and count the rows.
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:amount) A;| ROWS_RETURNED |
|---|
| 0 |
Zero rows. For the whole table. Not an error, not a warning, not one row with a NULL in it. Zero.
And with the outer argument the rows come back.
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:amount, OUTER => TRUE) A;| ROWS_RETURNED |
|---|
| 4 |
So one wrong path inside a FLATTEN empties your whole result set and says nothing about it. A typo in a key name gives you a scalar or a NULL instead of an array, and either way the query succeeds with no rows. This is why the predict-then-check habit from the top of the post is worth the extra query.
Now let's look at all six columns FLATTEN gives us
A flatten produces six columns and most people only ever use VALUE. Let's see all of them on one event's items array.
SELECT E.EVENT_ID,
I.SEQ, I.KEY, I.PATH, I.INDEX,
I.VALUE:sku::VARCHAR AS VALUE_SKU,
TYPEOF(I.THIS) AS THIS_TYPE
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
WHERE E.EVENT_ID = 4
ORDER BY I.INDEX;| EVENT_ID | SEQ | KEY | PATH | INDEX | VALUE_SKU | THIS_TYPE |
|---|---|---|---|---|---|---|
| 4 | 1 | NULL | [0] | 0 | D-400 | ARRAY |
| 4 | 1 | NULL | [1] | 1 | A-100 | ARRAY |
| 4 | 1 | NULL | [2] | 2 | E-505 | ARRAY |
SEQ is the same on all three rows, because all three came from one input row. KEY is NULL on every row, because an array has no keys. INDEX counts zero, one, two, and PATH spells out where each element came from.
The last column is the one worth noticing. We asked TYPEOF of THIS and it says ARRAY. So THIS is the whole container, not the element, and it repeats on every row. VALUE is the element.
Now the same six columns over an object instead of an array.
SELECT E.EVENT_ID,
D.SEQ, D.KEY, D.PATH, D.INDEX,
D.VALUE::VARCHAR AS VALUE_,
TYPEOF(D.THIS) AS THIS_TYPE
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:device) D
WHERE E.EVENT_ID = 1
ORDER BY D.KEY;| EVENT_ID | SEQ | KEY | PATH | INDEX | VALUE_ | THIS_TYPE |
|---|---|---|---|---|---|---|
| 1 | 1 | os | os | NULL | windows | OBJECT |
| 1 | 1 | type | type | NULL | desktop | OBJECT |
Two rows, one per key. KEY holds the key name and so does PATH. INDEX is NULL, and THIS is an OBJECT.
So the two swap over. An array gives you an index and no keys. An object gives you keys and no index.
Is that reliable, or did we get lucky?
Worth checking rather than assuming, because it is a test you might want to lean on. Let's count the NULLs in both columns, over the array and over the object.
SELECT (SELECT COUNT_IF(I.KEY IS NULL) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS ARRAY_KEY_NULLS,
(SELECT COUNT_IF(I.INDEX IS NULL) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS ARRAY_INDEX_NULLS,
(SELECT COUNT_IF(D.KEY IS NULL) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:device) D) AS OBJECT_KEY_NULLS,
(SELECT COUNT_IF(D.INDEX IS NULL) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:device) D) AS OBJECT_INDEX_NULLS;| ARRAY_KEY_NULLS | ARRAY_INDEX_NULLS | OBJECT_KEY_NULLS | OBJECT_INDEX_NULLS |
|---|---|---|---|
| 7 | 0 | 0 | 6 |
Over the items array, KEY was NULL on every row and INDEX was never NULL. Over the device object it is the other way round, with no NULL keys and every index NULL.
So KEY IS NULL is a usable test for “this was an array”, and on this data it did not get a single row wrong.
Now let's check a document against itself
Here is why you flatten in the first place. These documents state an amount at the top level and then list their line items underneath. Nothing makes those two agree. Let's find out whether they do.
Group the items back up per event, count them, total the quantities, and work out the line item total from quantity times price.
SELECT E.EVENT_ID,
E.PAYLOAD:amount::NUMBER(12,2) AS EVENT_AMOUNT,
COUNT(*) AS ITEMS,
SUM(I.VALUE:qty::INT) AS TOTAL_QTY,
ROUND(SUM(I.VALUE:qty::INT * I.VALUE:price::NUMBER(10,2)), 2)
AS LINE_ITEM_TOTAL
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
GROUP BY E.EVENT_ID, E.PAYLOAD:amount
ORDER BY E.EVENT_ID;| EVENT_ID | EVENT_AMOUNT | ITEMS | TOTAL_QTY | LINE_ITEM_TOTAL |
|---|---|---|---|---|
| 1 | 4200.00 | 2 | 12 | 4200.00 |
| 2 | 890.50 | 1 | 3 | 890.49 |
| 3 | 1500.00 | 1 | 5 | 1500.00 |
| 4 | 9250.00 | 3 | 30 | 10250.00 |
Event one: two items, twelve units, line item total 4200.00, and the stated amount is also 4200.00. They agree.
Event two: one item, three units, and a line item total of 890.49 against a stated 890.50. A penny out, because the single item is three units at 296.83.
Event four: three items, thirty units, line item total 10250.00, stated amount 9250.00. That is a thousand apart.
Let's put the gap in a column of its own so there is no arithmetic to do by eye.
SELECT E.EVENT_ID,
E.PAYLOAD:amount::NUMBER(12,2) AS STATED,
ROUND(SUM(I.VALUE:qty::INT * I.VALUE:price::NUMBER(10,2)), 2) AS LINE_TOTAL,
ROUND(SUM(I.VALUE:qty::INT * I.VALUE:price::NUMBER(10,2))
- E.PAYLOAD:amount::NUMBER(12,2), 2) AS GAP
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
GROUP BY E.EVENT_ID, E.PAYLOAD:amount
ORDER BY E.EVENT_ID;| EVENT_ID | STATED | LINE_TOTAL | GAP |
|---|---|---|---|
| 1 | 4200.00 | 4200.00 | 0.00 |
| 2 | 890.50 | 890.49 | -0.01 |
| 3 | 1500.00 | 1500.00 | 0.00 |
| 4 | 9250.00 | 10250.00 | 1000.00 |
Zero, minus a penny, zero, and plus a thousand. Now as a single check you could run on a schedule.
SELECT COUNT(*) AS EVENTS_CHECKED,
COUNT_IF(ABS(X.LINE_TOTAL - X.STATED) < 0.01) AS THEY_MATCH,
COUNT_IF(ABS(X.LINE_TOTAL - X.STATED) >= 0.01) AS THEY_DIFFER,
MAX(ABS(X.LINE_TOTAL - X.STATED)) AS BIGGEST_GAP
FROM (SELECT E.EVENT_ID,
E.PAYLOAD:amount::NUMBER(12,2) AS STATED,
SUM(I.VALUE:qty::INT * I.VALUE:price::NUMBER(10,2)) AS LINE_TOTAL
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
GROUP BY E.EVENT_ID, E.PAYLOAD:amount) X;| EVENTS_CHECKED | THEY_MATCH | THEY_DIFFER | BIGGEST_GAP |
|---|---|---|---|
| 4 | 2 | 2 | 1000.00 |
Four events checked, two match, two differ, and the biggest gap is 1000.00.
That check calls a row a mismatch when the gap is a penny or more, so event two's rounding difference counts as one of the two. One of those two differences is a penny and the other is a thousand, and a real check would want to treat those differently. The point stands either way: the document with the thousand-pound gap parses perfectly and every key in it is present. It simply disagrees with itself, and there is no way to find that without a flatten.
One last thing: the report you will actually be asked for
Totals by SKU across every event. Once the items are rows, this is an ordinary GROUP BY and there is nothing JSON about it any more.
SELECT I.VALUE:sku::VARCHAR AS SKU,
COUNT(*) AS TIMES_ORDERED,
SUM(I.VALUE:qty::INT) AS TOTAL_QTY,
ROUND(SUM(I.VALUE:qty::INT * I.VALUE:price::NUMBER(10,2)), 2) AS TOTAL_VALUE,
COUNT(DISTINCT E.EVENT_ID) AS DISTINCT_EVENTS
FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
GROUP BY I.VALUE:sku
ORDER BY TOTAL_VALUE DESC;| SKU | TIMES_ORDERED | TOTAL_QTY | TOTAL_VALUE | DISTINCT_EVENTS |
|---|---|---|---|---|
| A-100 | 3 | 23 | 6900.00 | 3 |
| D-400 | 1 | 12 | 6000.00 | 1 |
| B-220 | 1 | 4 | 1800.00 | 1 |
| E-505 | 1 | 8 | 1250.00 | 1 |
| C-310 | 1 | 3 | 890.49 | 1 |
A-100 was ordered three times, for twenty three units in total, across three different events. The other SKUs appear once each.
And because we are grouping a flattened result, let's reconcile it rather than hope.
SELECT (SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON) AS ITEMS_EXPECTED,
(SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS ITEM_ROWS,
(SELECT SUM(TIMES) FROM (
SELECT COUNT(*) AS TIMES
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I
GROUP BY I.VALUE:sku)) AS REPORT_ROWS_SUMMED,
(SELECT SUM(ARRAY_SIZE(PAYLOAD:items)) FROM EVENTS_JSON)
= (SELECT COUNT(*) FROM EVENTS_JSON E,
LATERAL FLATTEN(INPUT => E.PAYLOAD:items) I) AS NOTHING_LOST;| ITEMS_EXPECTED | ITEM_ROWS | REPORT_ROWS_SUMMED | NOTHING_LOST |
|---|---|---|---|
| 7 | 7 | 7 | TRUE |
Seven items expected from the array sizes, seven rows out of the flatten, and seven when you add up the counts in the report. NOTHING_LOST is TRUE.
That is the whole habit in one line. Predict the number, flatten, then prove the number still matches. Do it on the way in and you never have to wonder later whether a row went missing.
Key points
FLATTENturns one array into one row per element, andVALUEholds the element, soVALUE:keyworks inside it.- Predict the row count first. It is the sum of the array sizes. Here four events with arrays of two, one, one and three gave seven rows, exactly as predicted.
LATERAL FLATTEN(...)andTABLE(FLATTEN(...))are two spellings of the same thing and returned identical results.- The parent repeats on every child row. That is correct join behaviour, and it is why a
SUMover a parent column went from15840.50to38540.50. - Events with a single child are unaffected by that double count, which is exactly why the bug passes testing.
- Group first, then aggregate.
SUM(DISTINCT ...)gave the right answer here only because all four amounts happened to differ. - An inner flatten deletes parents whose array is empty. Four events in, three out, one lost, and nothing said so.
OUTER => TRUEkeeps them, withINDEXandVALUEbothNULL. The same applies to a key that is missing entirely.FLATTENover a scalar returns no rows at all, for the whole table, without an error. One wrong path empties your result set silently.- The six columns are
SEQ,KEY,PATH,INDEX,VALUEandTHIS.THISis the container, not the element. KEYandINDEXare mutually exclusive, soKEY IS NULLtells you the input was an array.- Flattening is what lets a document be checked against itself. Here it found a stated amount a thousand out from its own line items, in a document that parses perfectly.
Episode 91 — FLATTEN, part two. The RECURSIVE argument, the PATH column, and flattening more than one array in the same query.
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 EVENTS_JSON data is invented demo data created by that script, and the discrepancy the last section finds was put there on purpose. Every count in the text above was read off the grid beside it rather than worked out here. Nothing on this page is timed and no performance or benchmark claims are made anywhere in this series. Function behaviour follows the Snowflake FLATTEN documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.