Snowflake SQL Tutorial 90 - LATERAL FLATTEN - Arrays into Rows, and the Total That Doubles

Snowflake SQL · Episode 90

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

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.

Sample data
-- 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 tag

Let's ask how big each array is on each row.

Query
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;
Result4 rows · 6 columns · scroll →
EVENT_IDEVENT_AMOUNT_RAWITEM_COUNTTAG_COUNTDEVICE_MISSING
1purchase420022FALSE
2purchase890.511FALSE
3refund"1500.00"10TRUE
4purchase925033FALSE

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.

Query
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;
Result1 row · 4 columns
EVENTSTOTAL_ITEMSTOTAL_TAGSEVENTS_WITH_NO_TAGS
4761

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.

Query
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;
Result7 rows · 5 columns
EVENT_IDITEM_INDEXSKUQTYPRICE
10A-1008300.00
11B-2204450.00
20C-3103296.83
30A-1005300.00
40D-40012500.00
41A-10010300.00
42E-5058156.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.

Query
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;
Result1 row · 4 columns
FLATTENED_ROWSEVENTSSUM_OF_SIZESIT_MATCHES
747TRUE

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.

Query
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;
Result7 rows · 3 columns
EVENT_IDITEM_INDEXSKU
10A-100
11B-220
20C-310
30A-100
40D-400
41A-100
42E-505

Same rows, same indexes, same SKUs. Let's count both forms in one query so there is no doubt.

Query
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;
Result1 row · 3 columns
LATERAL_ROWSTABLE_ROWSTHEY_AGREE
77TRUE

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.

Query
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;
Result7 rows · 5 columns
EVENT_IDEVENT_AMOUNTITEM_INDEXSKUQTY
14200.000A-1008
14200.001B-2204
2890.500C-3103
31500.000A-1005
49250.000D-40012
49250.001A-10010
49250.002E-5058

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.

Query
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;
Result1 row · 4 columns
CORRECT_TOTALTOTAL_AFTER_FLATTENINGEVENT_ROWSFLATTENED_ROWS
15840.5038540.5047

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.

Query
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;
Result4 rows · 5 columns
EVENT_IDEVENT_AMOUNTTIMES_REPEATEDWHAT_THE_SUM_COUNTSOVERCOUNTED_BY
14200.0028400.004200.00
2890.501890.500.00
31500.0011500.000.00
49250.00327750.0018500.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.

Why nobody catches this

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.

Query
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;
Result1 row · 5 columns
CORRECT_TOTALGROUPED_THEN_SUMMEDSUM_DISTINCTDISTINCT_AMOUNTSEVENTS_TOTAL
15840.5015840.5015840.5044

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.

Query
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;
Result6 rows · 3 columns
EVENT_IDTAG_INDEXTAG
10priority
11repeat
20new
40priority
41enterprise
42repeat

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.

Query
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;
Result1 row · 4 columns
EVENTS_INEVENTS_OUTTAG_ROWSEVENTS_LOST
4361

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.

Query
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;
Result7 rows · 5 columns
EVENT_IDITS_TAG_COUNTTAG_INDEXTAGTAG_IS_NULL
120priorityFALSE
121repeatFALSE
210newFALSE
30NULLNULLTRUE
430priorityFALSE
431enterpriseFALSE
432repeatFALSE

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.

Query
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;
Result1 row · 5 columns
INNER_ROWSOUTER_ROWSINNER_EVENTSOUTER_EVENTSEVENTS_TOTAL
67344

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.

Query
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;
Result1 row · 4 columns
INNER_ROWSINNER_EVENTSOUTER_EVENTSEVENTS_TOTAL
6344

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.

Query
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:amount) A;
Result1 row · 1 column
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.

Query
SELECT COUNT(*) AS ROWS_RETURNED
FROM EVENTS_JSON E, LATERAL FLATTEN(INPUT => E.PAYLOAD:amount, OUTER => TRUE) A;
Result1 row · 1 column
ROWS_RETURNED
4
A wrong path returns no rows

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.

Query
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;
Result3 rows · 7 columns · scroll →
EVENT_IDSEQKEYPATHINDEXVALUE_SKUTHIS_TYPE
41NULL[0]0D-400ARRAY
41NULL[1]1A-100ARRAY
41NULL[2]2E-505ARRAY

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.

Query
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;
Result2 rows · 7 columns · scroll →
EVENT_IDSEQKEYPATHINDEXVALUE_THIS_TYPE
11ososNULLwindowsOBJECT
11typetypeNULLdesktopOBJECT

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.

Query
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;
Result1 row · 4 columns
ARRAY_KEY_NULLSARRAY_INDEX_NULLSOBJECT_KEY_NULLSOBJECT_INDEX_NULLS
7006

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.

Query
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;
Result4 rows · 5 columns
EVENT_IDEVENT_AMOUNTITEMSTOTAL_QTYLINE_ITEM_TOTAL
14200.002124200.00
2890.5013890.49
31500.00151500.00
49250.0033010250.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.

Query
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;
Result4 rows · 4 columns
EVENT_IDSTATEDLINE_TOTALGAP
14200.004200.000.00
2890.50890.49-0.01
31500.001500.000.00
49250.0010250.001000.00

Zero, minus a penny, zero, and plus a thousand. Now as a single check you could run on a schedule.

Query
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;
Result1 row · 4 columns
EVENTS_CHECKEDTHEY_MATCHTHEY_DIFFERBIGGEST_GAP
4221000.00

Four events checked, two match, two differ, and the biggest gap is 1000.00.

About that tolerance

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.

Query
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;
Result5 rows · 5 columns
SKUTIMES_ORDEREDTOTAL_QTYTOTAL_VALUEDISTINCT_EVENTS
A-1003236900.003
D-4001126000.001
B-220141800.001
E-505181250.001
C-31013890.491

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.

Query
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;
Result1 row · 4 columns
ITEMS_EXPECTEDITEM_ROWSREPORT_ROWS_SUMMEDNOTHING_LOST
777TRUE

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

  • FLATTEN turns one array into one row per element, and VALUE holds the element, so VALUE:key works 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(...) and TABLE(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 SUM over a parent column went from 15840.50 to 38540.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 => TRUE keeps them, with INDEX and VALUE both NULL. The same applies to a key that is missing entirely.
  • FLATTEN over 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, VALUE and THIS. THIS is the container, not the element.
  • KEY and INDEX are mutually exclusive, so KEY IS NULL tells 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.
Next in this series

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.