Snowflake SQL Tutorial 88 - Navigating JSON - Colon, Dots, Brackets, GET and GET_PATH

Snowflake SQL · Episode 88

In this post we are going to cover how to read inside a JSON document in Snowflake: the colon, the dot, the second colon, square brackets, GET and GET_PATH.

A VARIANT column holds a whole document in one cell. To get at a value inside it you write a path. You start at the column, step into a key, and keep stepping until you reach the value you want.

We will start with one step and build it up to arrays and nested objects. The important part of this post is not the syntax though. It is what happens when the path is wrong, because a wrong path does not raise an error. It returns NULL, and a report full of NULL is a report that ran and is completely wrong.

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

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

Let's create some sample data

Everything on this page runs against one table of four documents. They have nested objects and arrays inside them, which is exactly what we need.

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;

-- EVENTS_JSON has two columns: EVENT_ID, and PAYLOAD, which is a VARIANT
-- holding one JSON document per row.

Let's look at the documents.

Query
SELECT EVENT_ID, PAYLOAD FROM EVENTS_JSON ORDER BY EVENT_ID;
Result4 rows · 2 columns
EVENT_IDPAYLOAD
1{ "amount": 4200, "device": { "os": "windows", "type": "desktop" }, "event": "purchase", "items": [ { "price": 300, "qty": 8, "sku": "A-100" }, { "price": 450, "qty": 4, "sku": "B-220" } ], "tags": [ "priority", "repeat" ], "user": { "id": 101, "name": "Northwind Traders" } }
2{ "amount": 890.5, "device": { "os": "ios", "type": "mobile" }, "event": "purchase", "items": [ { "price": 296.83, "qty": 3, "sku": "C-310" } ], "tags": [ "new" ], "user": { "id": 102, "name": "Blue Ridge Supply" } }
3{ "amount": "1500.00", "event": "refund", "items": [ { "price": 300, "qty": 5, "sku": "A-100" } ], "tags": [], "user": { "id": 103, "name": "Kestrel Analytics" } }
4{ "amount": 9250, "device": { "os": "android", "type": "tablet" }, "event": "purchase", "items": [ { "price": 500, "qty": 12, "sku": "D-400" }, { "price": 300, "qty": 10, "sku": "A-100" }, { "price": 156.25, "qty": 8, "sku": "E-505" } ], "tags": [ "priority", "enterprise", "repeat" ], "user": { "id": 107, "name": "Meridian Health" } }

Four rows, and each PAYLOAD cell holds a whole document. The grid shows the start of each one and they are wider than the column, so take the shapes on trust for now. Every key we use below is read out of the document by a query rather than assumed.

Let's start with the colon and the dot

To go inside the document you write the column name, a colon, and the key you want. To go deeper than one level you add a dot and the next key.

Let's take the user object, then the id inside it, then the same id cast to an integer, then the name.

Query
SELECT EVENT_ID,
       PAYLOAD:user                 AS THE_USER_OBJECT,
       PAYLOAD:user.id              AS ID_AS_VARIANT,
       PAYLOAD:user.id::INT         AS ID_AS_INT,
       PAYLOAD:user.name::VARCHAR   AS NAME_
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 5 columns
EVENT_IDTHE_USER_OBJECTID_AS_VARIANTID_AS_INTNAME_
1{ "id": 101, "name": "Northwind Traders" }101101Northwind Traders
2{ "id": 102, "name": "Blue Ridge Supply" }102102Blue Ridge Supply
3{ "id": 103, "name": "Kestrel Analytics" }103103Kestrel Analytics
4{ "id": 107, "name": "Meridian Health" }107107Meridian Health

The first column gave us back the user object itself. It is still a VARIANT, so we could keep going into it. The second column went one step further and reached the id.

Look at the third column. That is the same value with ::INT on the end, and now it is a number we can do arithmetic on. A path on its own gives you a VARIANT. The cast is what turns it into a normal SQL value, and that is the whole subject of the next post.

Now let's write the same path five different ways

There is more than one way to spell a path, and this will matter later in the post. Let's write the same journey — into user, then into name — five ways in one query.

Query
SELECT PAYLOAD:user.name::VARCHAR              AS COLON_DOT,
       PAYLOAD:user:name::VARCHAR              AS COLON_COLON,
       PAYLOAD['user']['name']::VARCHAR        AS BRACKETS,
       GET_PATH(PAYLOAD, 'user.name')::VARCHAR AS GET_PATH_,
       GET(GET(PAYLOAD, 'user'), 'name')::VARCHAR AS GET_NESTED
FROM EVENTS_JSON
WHERE EVENT_ID = 1;
Result1 row · 5 columns
COLON_DOTCOLON_COLONBRACKETSGET_PATH_GET_NESTED
Northwind TradersNorthwind TradersNorthwind TradersNorthwind TradersNorthwind Traders

Dot, second colon, brackets, GET_PATH with the whole path as text, and GET inside GET. Five columns and the same answer in every one of them.

One row is not proof though. Let's compare them properly across the whole table, using EQUAL_NULL so that two NULLs count as agreeing.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(EQUAL_NULL(PAYLOAD:user.name::VARCHAR,
                           PAYLOAD['user']['name']::VARCHAR))     AS DOT_EQUALS_BRACKET,
       COUNT_IF(EQUAL_NULL(PAYLOAD:user.name::VARCHAR,
                           GET_PATH(PAYLOAD, 'user.name')::VARCHAR)) AS DOT_EQUALS_GET_PATH,
       COUNT_IF(EQUAL_NULL(PAYLOAD:user.name::VARCHAR,
                           PAYLOAD:user:name::VARCHAR))           AS DOT_EQUALS_COLON
FROM EVENTS_JSON;
Result1 row · 4 columns
ROWS_TOTALDOT_EQUALS_BRACKETDOT_EQUALS_GET_PATHDOT_EQUALS_COLON
4444

Four rows in the table, and three comparisons that each agree on four rows out of four. So the dot, the brackets, GET_PATH and the second colon are interchangeable here.

Pick whichever one you find easiest to read. Mostly. There is one document later in this post where they stop agreeing and both answers are correct.

So what is the difference between GET and GET_PATH?

They look like the same function with two names. They are not. GET takes exactly one step. GET_PATH takes a whole path, and it will take an array index inside that path.

Let's put both of them next to a few deliberately wrong paths.

Query
SELECT GET(PAYLOAD, 'amount')                       AS GET_ONE_STEP,
       GET_PATH(PAYLOAD, 'user.name')               AS GET_PATH_TWO_STEPS,
       GET_PATH(PAYLOAD, 'items[0].sku')            AS GET_PATH_WITH_INDEX,
       GET_PATH(PAYLOAD, 'User.name')               AS GET_PATH_WRONG_CASE,
       GET_PATH(PAYLOAD, 'user.nombre')             AS GET_PATH_WRONG_KEY,
       GET(PAYLOAD, 'Amount')                       AS GET_WRONG_CASE
FROM EVENTS_JSON
WHERE EVENT_ID = 1;
Result1 row · 6 columns · scroll →
GET_ONE_STEPGET_PATH_TWO_STEPSGET_PATH_WITH_INDEXGET_PATH_WRONG_CASEGET_PATH_WRONG_KEYGET_WRONG_CASE
4200"Northwind Traders""A-100"NULLNULLNULL

GET took one step and gave us the amount. GET_PATH took two steps in one go, and took a path with [0] in it as well.

Have a look at how the strings print. "Northwind Traders" comes back with its JSON quotes still on, because we did not cast it. The quotes are part of being a JSON string.

Now the last three columns, which are the reason this post exists. A path with the wrong case gave NULL. A path with a key that does not exist gave NULL. GET with the wrong case gave NULL. No errors anywhere.

Now let's spell a key in the wrong case on purpose

Here is the thing that catches everybody. JSON keys are case sensitive. SQL identifiers are not. So SELECT amount and SELECT AMOUNT from a normal table are the same query, and PAYLOAD:amount and PAYLOAD:Amount are not.

Let's spell the same key four ways and run it over all four rows.

Query
SELECT EVENT_ID,
       PAYLOAD:amount     AS LOWER_CASE,
       PAYLOAD:Amount     AS TITLE_CASE,
       PAYLOAD:AMOUNT     AS UPPER_CASE,
       PAYLOAD:aMoUnT     AS NONSENSE_CASE
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 5 columns
EVENT_IDLOWER_CASETITLE_CASEUPPER_CASENONSENSE_CASE
14200NULLNULLNULL
2890.5NULLNULLNULL
3"1500.00"NULLNULLNULL
49250NULLNULLNULL

The lower-case spelling gave us a value on every row. The other three gave NULL on every row.

No error. No warning. Nothing in the output that says a key was misspelled rather than missing. The query simply ran.

Now let's put that in a report

A grid of NULLs is easy to spot. This is how you actually meet the problem. Let's total that column with both spellings and count the rows each one found.

Query
SELECT COUNT(*)                                   AS ROWS_IN_TABLE,
       SUM(PAYLOAD:amount::NUMBER(12,2))          AS TOTAL_CORRECT_SPELLING,
       SUM(PAYLOAD:Amount::NUMBER(12,2))          AS TOTAL_WRONG_SPELLING,
       COUNT(PAYLOAD:amount)                      AS ROWS_WITH_LOWER,
       COUNT(PAYLOAD:Amount)                      AS ROWS_WITH_TITLE
FROM EVENTS_JSON;
Result1 row · 5 columns
ROWS_IN_TABLETOTAL_CORRECT_SPELLINGTOTAL_WRONG_SPELLINGROWS_WITH_LOWERROWS_WITH_TITLE
415840.50NULL40

The correct spelling totals 15840.50 over four rows. The misspelling returns NULL for the total and counts zero rows.

That is a report that ran, returned a row, and is completely wrong. In a dashboard it would be a blank tile. In a nightly job it would be a NULL written into a table nobody looks at.

Nothing here fails

A SUM over a path that does not exist returns NULL, not zero and not an error. COUNT of it returns zero. Neither of those is a failure your pipeline will notice on its own, so the check has to be something you write.

Can we debug it from the NULL?

No, and this is worth seeing rather than being told. Let's put my misspelled key next to a key that genuinely is missing. The device key is absent from one of the four documents.

Query
SELECT EVENT_ID,
       PAYLOAD:Amount                           AS MY_TYPO,
       PAYLOAD:Amount IS NULL                   AS TYPO_IS_NULL,
       PAYLOAD:device                           AS SOMETIMES_MISSING,
       PAYLOAD:device IS NULL                   AS MISSING_IS_NULL,
       IS_NULL_VALUE(PAYLOAD:device)            AS MISSING_IS_JSON_NULL
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 6 columns · scroll →
EVENT_IDMY_TYPOTYPO_IS_NULLSOMETIMES_MISSINGMISSING_IS_NULLMISSING_IS_JSON_NULL
1NULLTRUE{ "os": "windows", "type": "desktop" }FALSEFALSE
2NULLTRUE{ "os": "ios", "type": "mobile" }FALSEFALSE
3NULLTRUENULLTRUENULL
4NULLTRUE{ "os": "android", "type": "tablet" }FALSEFALSE

Look along the row for event three. The typo column says NULL and TRUE. The missing-key column says NULL and TRUE. Identical answers from two completely different causes.

On the other three rows the device column has a real object in it, so you can see the difference there. But if the key had been missing everywhere, the two columns would read the same all the way down and there would be nothing to compare.

The last column is interesting for a different reason. IS_NULL_VALUE is meant to tell a JSON null from a SQL NULL, and on event three it comes back NULL itself. So it cannot help you either.

And you can go as deep as you like into nothing

Let's try a path that is wrong at the first step and then keeps going anyway.

Query
SELECT EVENT_ID,
       PAYLOAD:device.os::VARCHAR                   AS DEVICE_OS,
       PAYLOAD:device.os.vendor::VARCHAR            AS TWO_LEVELS_PAST_NOTHING,
       PAYLOAD:nothing.at.all.here::VARCHAR         AS FOUR_LEVELS_OF_NOTHING,
       PAYLOAD:device.os IS NULL                    AS IS_IT_NULL
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 5 columns
EVENT_IDDEVICE_OSTWO_LEVELS_PAST_NOTHINGFOUR_LEVELS_OF_NOTHINGIS_IT_NULL
1windowsNULLNULLFALSE
2iosNULLNULLFALSE
3NULLNULLNULLTRUE
4androidNULLNULLFALSE

The first column reads device.os, which works on three rows and is NULL on the one with no device. The second column goes two levels past something that does not exist. The third goes four levels into a key that was never there.

All of them come back NULL, on every row, without a word of complaint.

So let's ask the document instead of guessing

If the path will not tell us anything, we ask the document directly. OBJECT_KEYS returns the keys of an object as an array, and ARRAY_CONTAINS turns that into a yes or no question.

Query
SELECT EVENT_ID,
       OBJECT_KEYS(PAYLOAD)                           AS ITS_KEYS,
       ARRAY_SIZE(OBJECT_KEYS(PAYLOAD))               AS HOW_MANY,
       ARRAY_CONTAINS('amount'::VARIANT, OBJECT_KEYS(PAYLOAD)) AS HAS_AMOUNT,
       ARRAY_CONTAINS('Amount'::VARIANT, OBJECT_KEYS(PAYLOAD)) AS HAS_TITLE_AMOUNT,
       ARRAY_CONTAINS('device'::VARIANT, OBJECT_KEYS(PAYLOAD)) AS HAS_DEVICE
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 6 columns · scroll →
EVENT_IDITS_KEYSHOW_MANYHAS_AMOUNTHAS_TITLE_AMOUNTHAS_DEVICE
1[ "amount", "device", "event", "items", "tags", "user" ]6TRUEFALSETRUE
2[ "amount", "device", "event", "items", "tags", "user" ]6TRUEFALSETRUE
3[ "amount", "event", "items", "tags", "user" ]5TRUEFALSEFALSE
4[ "amount", "device", "event", "items", "tags", "user" ]6TRUEFALSETRUE

Read the HOW_MANY column. Events one, two and four have six keys each and event three has five. There is the missing device key, visible at last.

And the three questions beside it answer themselves. Every row has amount. No row has Amount. Three rows have device.

Let's roll that into one line, which is the form you would actually run.

Query
SELECT COUNT(*)                                                       AS ROWS_TOTAL,
       COUNT_IF(ARRAY_CONTAINS('amount'::VARIANT, OBJECT_KEYS(PAYLOAD))) AS HAVE_AMOUNT,
       COUNT_IF(ARRAY_CONTAINS('Amount'::VARIANT, OBJECT_KEYS(PAYLOAD))) AS HAVE_TITLE_AMOUNT,
       COUNT_IF(ARRAY_CONTAINS('device'::VARIANT, OBJECT_KEYS(PAYLOAD))) AS HAVE_DEVICE,
       COUNT(DISTINCT ARRAY_SIZE(OBJECT_KEYS(PAYLOAD)))               AS DISTINCT_SHAPES
FROM EVENTS_JSON;
Result1 row · 5 columns
ROWS_TOTALHAVE_AMOUNTHAVE_TITLE_AMOUNTHAVE_DEVICEDISTINCT_SHAPES
44032

Four rows, all four have the key I meant, none has the key I typed, three have the device key. And the last column counts how many different key counts there are across the four documents. It comes back as two.

So these four documents do not all have the same shape, and nothing in the table definition says so. That is the normal state of a JSON column, and that one query is how you find out.

Now let's check every path the query actually uses

One key at a time is fine for debugging. Before you trust a query, check every path in it at once. COUNT of a path counts the rows where it is not NULL, so one SELECT does the lot.

Query
SELECT COUNT(*)                                          AS ROWS_TOTAL,
       COUNT(PAYLOAD:event)                              AS EVENT_PRESENT,
       COUNT(PAYLOAD:user.id)                            AS USER_ID_PRESENT,
       COUNT(PAYLOAD:user.name)                          AS USER_NAME_PRESENT,
       COUNT(PAYLOAD:amount)                             AS AMOUNT_PRESENT,
       COUNT(PAYLOAD:device.os)                          AS DEVICE_OS_PRESENT,
       COUNT(PAYLOAD:items[0].sku)                       AS FIRST_SKU_PRESENT,
       COUNT(PAYLOAD:tags[0])                            AS FIRST_TAG_PRESENT
FROM EVENTS_JSON;
Result1 row · 8 columns · scroll →
ROWS_TOTALEVENT_PRESENTUSER_ID_PRESENTUSER_NAME_PRESENTAMOUNT_PRESENTDEVICE_OS_PRESENTFIRST_SKU_PRESENTFIRST_TAG_PRESENT
44444343

Out of four rows: event, user.id, user.name, amount and the first item's sku are present on all four. device.os and the first tag are present on three.

That is the whole defence, and it costs one query. The paths that come back short are the ones you cannot write a plain SUM over and expect to be right.

Now the case where the five spellings stop agreeing

Earlier we proved the notations agree. Here is the document where they do not, and it is worth going slowly.

This document has two keys. One of them is literally called user.name, with a dot in the key name. The other is called user and holds an object with a name inside it. Both of those exist at the same time.

So what should :user.name give us?

Query
SELECT PARSE_JSON('{"user.name":"Northwind","user":{"name":"Blue Ridge"}}')
         AS THE_DOCUMENT,
       PARSE_JSON('{"user.name":"Northwind","user":{"name":"Blue Ridge"}}'):user.name::VARCHAR
         AS DOT_NOTATION_GIVES,
       PARSE_JSON('{"user.name":"Northwind","user":{"name":"Blue Ridge"}}')['user.name']::VARCHAR
         AS BRACKETS_GIVE,
       GET(PARSE_JSON('{"user.name":"Northwind","user":{"name":"Blue Ridge"}}'), 'user.name')::VARCHAR
         AS GET_GIVES;
Result1 row · 4 columns
THE_DOCUMENTDOT_NOTATION_GIVESBRACKETS_GIVEGET_GIVES
{ "user": { "name": "Blue Ridge" }, "user.name": "Northwind" }Blue RidgeNorthwindNorthwind

The dot notation gave Blue Ridge. It treated the dot as a step, went into user, and found name inside it.

The brackets gave Northwind. They read the key whose name is literally user.name, dot and all. GET with the same string agreed with the brackets.

Two different values out of the same document, and both are right.

The difference in one line

The dot is not a path separator. It is a guess that you meant to descend. Brackets say exactly what you mean, and so does GET. When a key name could contain a dot, that difference stops being trivia.

Which keys need brackets?

Brackets are not only for awkward cases like that one. For some key names they are the only thing that works. Let's try a key with a space in it, a key called select, and a key that is a number.

Query
SELECT PARSE_JSON('{"order id":1001,"select":"x","2024":"a year"}')['order id']::INT
         AS A_KEY_WITH_A_SPACE,
       PARSE_JSON('{"order id":1001,"select":"x","2024":"a year"}')['select']::VARCHAR
         AS A_KEYWORD_KEY,
       PARSE_JSON('{"order id":1001,"select":"x","2024":"a year"}')['2024']::VARCHAR
         AS A_NUMERIC_KEY,
       PARSE_JSON('{"order id":1001,"select":"x","2024":"a year"}'):"order id"::INT
         AS QUOTED_AFTER_COLON;
Result1 row · 4 columns
A_KEY_WITH_A_SPACEA_KEYWORD_KEYA_NUMERIC_KEYQUOTED_AFTER_COLON
1001xa year1001

All three read fine through brackets. And the last column shows that a space works after a colon too, as long as you put the key in double quotes.

Without the quotes it is not even valid SQL. Let's see what Snowflake says.

Query
SELECT PARSE_JSON('{"order id":1001}'):order id::INT AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
001003 (42000): SQL compilation error:
syntax error line 1 at position 47 unexpected '::'.

A compilation error, and the position it complains about is the cast rather than the space. So this one fails loudly, which honestly makes it the friendliest mistake in the whole post.

Now let's index into an array

Arrays use square brackets and a number, and the number starts at zero. Let's ask for the first three items of each document, with the array size beside them so we know what to expect.

Query
SELECT EVENT_ID,
       ARRAY_SIZE(PAYLOAD:items)            AS HOW_MANY_ITEMS,
       PAYLOAD:items[0].sku::VARCHAR        AS FIRST_SKU,
       PAYLOAD:items[1].sku::VARCHAR        AS SECOND_SKU,
       PAYLOAD:items[2].sku::VARCHAR        AS THIRD_SKU,
       PAYLOAD:tags[0]::VARCHAR             AS FIRST_TAG
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 6 columns · scroll →
EVENT_IDHOW_MANY_ITEMSFIRST_SKUSECOND_SKUTHIRD_SKUFIRST_TAG
12A-100B-220NULLpriority
21C-310NULLNULLnew
31A-100NULLNULLNULL
43D-400A-100E-505priority

Event four has three items, so all three columns fill up. The other rows have fewer items than that, and the columns past the end of their arrays are NULL.

Have a look at the last column too. Event three has no first tag, and we will come back to why in a moment.

Once you are inside an array element you carry on as normal, because the element is just another document. Let's reach a price inside the first item four different ways.

Query
SELECT PAYLOAD:items[0]                          AS THE_FIRST_ITEM,
       PAYLOAD:items[0].price::NUMBER(10,2)      AS DOT_AFTER_BRACKET,
       PAYLOAD:items[0]:price::NUMBER(10,2)      AS COLON_AFTER_BRACKET,
       PAYLOAD['items'][0]['price']::NUMBER(10,2) AS ALL_BRACKETS,
       GET_PATH(PAYLOAD, 'items[0].price')::NUMBER(10,2) AS GET_PATH_WITH_INDEX
FROM EVENTS_JSON
WHERE EVENT_ID = 1;
Result1 row · 5 columns
THE_FIRST_ITEMDOT_AFTER_BRACKETCOLON_AFTER_BRACKETALL_BRACKETSGET_PATH_WITH_INDEX
{ "price": 300, "qty": 8, "sku": "A-100" }300.00300.00300.00300.00

A dot after the bracket, a colon after the bracket, all brackets, and GET_PATH with the index written inside the path string. Same answer four times.

Is an empty array the same as a missing one?

It is not, and this is the distinction that bites. Let's look at the tags array on every row, with its size, whether the array itself is NULL, and whether the first element is.

Query
SELECT EVENT_ID,
       PAYLOAD:tags                     AS THE_TAGS,
       ARRAY_SIZE(PAYLOAD:tags)         AS ITS_SIZE,
       PAYLOAD:tags IS NULL             AS TAGS_IS_NULL,
       PAYLOAD:tags[0]::VARCHAR         AS FIRST_TAG,
       PAYLOAD:tags[0] IS NULL          AS FIRST_TAG_IS_NULL
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 6 columns · scroll →
EVENT_IDTHE_TAGSITS_SIZETAGS_IS_NULLFIRST_TAGFIRST_TAG_IS_NULL
1[ "priority", "repeat" ]2FALSEpriorityFALSE
2[ "new" ]1FALSEnewFALSE
3[]0FALSENULLTRUE
4[ "priority", "enterprise", "repeat" ]3FALSEpriorityFALSE

Event three has an empty array. You can see it in the THE_TAGS column as a pair of brackets with nothing between them. Its size is zero, and TAGS_IS_NULL is FALSE.

But FIRST_TAG on that row is NULL. So the array exists and the element does not.

That means PAYLOAD:tags[0] IS NULL cannot tell you whether the tags are missing or merely empty. ARRAY_SIZE can. If the difference matters to your logic, ask for the size.

How far past the end of an array can we go?

Let's find out. Event four has three items, so index two is the last one. We will ask for index three, which is one past the end, and index ninety nine, which is a long way past it.

Query
SELECT PAYLOAD:items[0].sku::VARCHAR   AS INDEX_0,
       PAYLOAD:items[2].sku::VARCHAR   AS INDEX_2_LAST_ONE,
       PAYLOAD:items[3].sku::VARCHAR   AS INDEX_3_ONE_PAST,
       PAYLOAD:items[99].sku::VARCHAR  AS INDEX_99,
       PAYLOAD:items[3] IS NULL        AS ONE_PAST_IS_NULL,
       PAYLOAD:items[99] IS NULL       AS FAR_PAST_IS_NULL,
       ARRAY_SIZE(PAYLOAD:items)       AS ACTUAL_SIZE
FROM EVENTS_JSON
WHERE EVENT_ID = 4;
Result1 row · 7 columns · scroll →
INDEX_0INDEX_2_LAST_ONEINDEX_3_ONE_PASTINDEX_99ONE_PAST_IS_NULLFAR_PAST_IS_NULLACTUAL_SIZE
D-400E-505NULLNULLTRUETRUE3

Index zero and index two gave us values. Index three and index ninety nine gave NULL, and both of them are flagged TRUE in the IS NULL columns. The last column confirms the array really does have three elements in it.

Let's push it a lot further and check that the rows themselves still come back.

Query
SELECT PAYLOAD:items[1000000] IS NULL          AS A_MILLION_IS_NULL,
       PAYLOAD:items[2147483646] IS NULL       AS NEAR_THE_LIMIT_IS_NULL,
       COUNT(*)                                AS ROWS_STILL_RETURNED
FROM EVENTS_JSON
GROUP BY 1, 2;
Result1 row · 3 columns
A_MILLION_IS_NULLNEAR_THE_LIMIT_IS_NULLROWS_STILL_RETURNED
TRUETRUE4

A million is NULL. A number near the signed integer limit is NULL. And the query still returned the rows, so nothing was filtered out on the way.

GET_PATH behaves the same way with an index written inside the path.

Query
SELECT GET_PATH(PAYLOAD, 'items[0].sku')::VARCHAR  AS PATH_0,
       GET_PATH(PAYLOAD, 'items[99].sku')          AS PATH_99,
       GET_PATH(PAYLOAD, 'items[99]') IS NULL      AS PATH_99_IS_NULL
FROM EVENTS_JSON
WHERE EVENT_ID = 4;
Result1 row · 3 columns
PATH_0PATH_99PATH_99_IS_NULL
D-400NULLTRUE

So an index past the end is silent at any distance. There is no error and no warning, which is the same lesson as the misspelled key: a path that does not reach anything returns nothing and says nothing.

Now let's go the other way with index -1

In plenty of languages a negative index counts back from the end. Let's try it on event four's items array.

Query
SELECT PAYLOAD:items[-1].sku::VARCHAR AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON
WHERE EVENT_ID = 4;
Query failed — Snowflake returned an error
001852 (22023): Invalid extraction path '-1': array index -1 is off limits; must be between 0 and 2,147,483,647.

That one is not silent at all. Snowflake rejects the path, names the index, and tells us the allowed range.

Is that a per-row thing, like a bad value in one document? Let's find out by taking the data out of the question and only counting.

Query
SELECT COUNT(PAYLOAD:items[-1]) AS SHOULD_NOT_GET_THIS_FAR FROM EVENTS_JSON;
Query failed — Snowflake returned an error
001852 (22023): Invalid extraction path '-1': array index -1 is off limits; must be between 0 and 2,147,483,647.

Same error, from a COUNT over the whole table. Nothing was being extracted and nothing was being displayed, and it still failed. So it is the path itself that is rejected, before any document is touched.

GET_PATH refuses it too, with a different message.

Query
SELECT GET_PATH(PAYLOAD, 'items[-1].sku') AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON
WHERE EVENT_ID = 4;
Query failed — Snowflake returned an error
001841 (22023): Invalid extraction path 'items[-1].sku': invalid number at position 7.

Here the whole path is a string, so the complaint is about the string: an invalid number at a position inside it. Same refusal, different wording.

One last thing: how do we read the last element?

There is no negative index, so we work the index out ourselves. The last element of an array is at ARRAY_SIZE(...) - 1.

Query
SELECT EVENT_ID,
       ARRAY_SIZE(PAYLOAD:items)                              AS N,
       PAYLOAD:items[ARRAY_SIZE(PAYLOAD:items) - 1].sku::VARCHAR
         AS LAST_SKU_BY_ARITHMETIC,
       ARRAY_SLICE(PAYLOAD:items, -1, ARRAY_SIZE(PAYLOAD:items))
         AS LAST_VIA_ARRAY_SLICE,
       PAYLOAD:items[0].sku::VARCHAR                          AS FIRST_SKU
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 5 columns
EVENT_IDNLAST_SKU_BY_ARITHMETICLAST_VIA_ARRAY_SLICEFIRST_SKU
12B-220[ { "price": 450, "qty": 4, "sku": "B-220" } ]A-100
21C-310[ { "price": 296.83, "qty": 3, "sku": "C-310" } ]C-310
31A-100[ { "price": 300, "qty": 5, "sku": "A-100" } ]A-100
43E-505[ { "price": 156.25, "qty": 8, "sku": "E-505" } ]D-400

That works on all four rows. The second column is the array size, and the third is the last SKU, which is the same as the first one on the two rows whose arrays hold a single item.

The fourth column does the same job with ARRAY_SLICE, and notice the start index it is given. It is -1, and nothing raised.

Query
SELECT ARRAY_SLICE([1,2,3,4,5]::ARRAY, 0, 2)    AS FIRST_TWO,
       ARRAY_SLICE([1,2,3,4,5]::ARRAY, -2, 5)   AS NEGATIVE_START,
       ARRAY_SLICE([1,2,3,4,5]::ARRAY, 3, 99)   AS END_PAST_THE_END,
       ARRAY_SLICE([1,2,3,4,5]::ARRAY, 2, 2)    AS EMPTY_SLICE,
       ARRAY_SIZE(ARRAY_SLICE([1,2,3,4,5]::ARRAY, 2, 2)) AS EMPTY_SLICE_SIZE;
Result1 row · 5 columns
FIRST_TWONEGATIVE_STARTEND_PAST_THE_ENDEMPTY_SLICEEMPTY_SLICE_SIZE
[ 1, 2 ][ 4, 5 ][ 4, 5 ][]0

ARRAY_SLICE takes a negative start and counts back from the end, which is exactly what the path notation refused to do. An end past the end of the array is fine too, and asking for a zero-width slice gives you an empty array rather than NULL.

The computed index and the literal one

Now the pair this episode ends on. Event three has an empty tags array, so ARRAY_SIZE(PAYLOAD:tags) - 1 on that row works out to -1. Let's run the last-element trick over the tags and see what that row does.

Query
SELECT EVENT_ID,
       PAYLOAD:tags[ARRAY_SIZE(PAYLOAD:tags) - 1]::VARCHAR AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 2 columns
EVENT_IDSHOULD_NOT_GET_THIS_FAR
1repeat
2new
3NULL
4repeat

It ran. Four rows came back and event three is NULL. So a -1 that Snowflake works out per row is tolerated, while a -1 we typed into the path was refused before it read anything.

What these captures do and do not prove

The two captures above are not the same query on the same row, so be careful how you remember this. The computed -1 here ran against the tags array over all four rows and returned NULL for the empty one. The literal -1 that failed was written against the items array, and the COUNT version failed over the whole table without extracting anything. What the three results together show is that the literal is checked as part of the path and the computed index is evaluated row by row.

Either way, relying on a computed -1 being tolerated is not something to build on. Guard it instead.

Query
SELECT EVENT_ID,
       ARRAY_SIZE(PAYLOAD:tags)     AS N_TAGS,
       IFF(ARRAY_SIZE(PAYLOAD:tags) > 0,
           PAYLOAD:tags[GREATEST(ARRAY_SIZE(PAYLOAD:tags) - 1, 0)]::VARCHAR,
           NULL)                    AS LAST_TAG_SAFE
FROM EVENTS_JSON
ORDER BY EVENT_ID;
Result4 rows · 3 columns
EVENT_IDN_TAGSLAST_TAG_SAFE
12repeat
21new
30NULL
43repeat

Same answers, and now the index can never go negative. IFF checks the size first and GREATEST keeps the index at zero or above. On this data the unguarded version happened to work. This one works on purpose.

Key points

  • A colon enters the document, and a dot or a second colon goes deeper. Square brackets take an array index, and any key a dot cannot spell.
  • GET takes exactly one step. GET_PATH takes a whole path, and it will take an index inside that path.
  • The notations agreed on every row here, with three comparisons each matching on four rows out of four.
  • JSON keys are case sensitive and SQL identifiers are not. PAYLOAD:Amount returned NULL on every row and nothing complained.
  • A wrong path returns NULL, never an error, so absent, misspelled and a JSON null all come back looking the same.
  • A SUM over a misspelled path returns NULL rather than zero, which is how a report ends up blank instead of broken.
  • OBJECT_KEYS and ARRAY_CONTAINS let you ask the document rather than guess, and COUNT of a path checks every path in one query.
  • A key with a dot in its name is where the notations part company. The dot descends, the brackets read the literal key, and both answers are correct.
  • An empty array is not a missing array. Only ARRAY_SIZE tells them apart.
  • An index past the end of an array is NULL at any distance. A literal -1 is a hard error, even inside a COUNT.
  • ARRAY_SLICE does accept a negative start, so the restriction belongs to the path notation and not to arrays in general.
Next in this series

Episode 89 — getting the value out with a type. The double colon, TRY_TO_NUMBER, and the column whose MAX is not its largest value.

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. 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. Path behaviour follows the Snowflake documentation on querying semi-structured data.

No comments:

Post a Comment

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