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
- Let's start with the colon and the dot
- Now let's write the same path five different ways
- So what is the difference between GET and GET_PATH?
- Now let's spell a key in the wrong case on purpose
- Now let's put that in a report
- Can we debug it from the NULL?
- So let's ask the document instead of guessing
- Now let's check every path the query actually uses
- Now the case where the five spellings stop agreeing
- Which keys need brackets?
- Now let's index into an array
- Is an empty array the same as a missing one?
- How far past the end of an array can we go?
- Now let's go the other way with index -1
- One last thing: how do we read the last element?
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.
-- 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.
SELECT EVENT_ID, PAYLOAD FROM EVENTS_JSON ORDER BY EVENT_ID;| EVENT_ID | PAYLOAD |
|---|---|
| 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.
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;| EVENT_ID | THE_USER_OBJECT | ID_AS_VARIANT | ID_AS_INT | NAME_ |
|---|---|---|---|---|
| 1 | { "id": 101, "name": "Northwind Traders" } | 101 | 101 | Northwind Traders |
| 2 | { "id": 102, "name": "Blue Ridge Supply" } | 102 | 102 | Blue Ridge Supply |
| 3 | { "id": 103, "name": "Kestrel Analytics" } | 103 | 103 | Kestrel Analytics |
| 4 | { "id": 107, "name": "Meridian Health" } | 107 | 107 | Meridian 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.
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;| COLON_DOT | COLON_COLON | BRACKETS | GET_PATH_ | GET_NESTED |
|---|---|---|---|---|
| Northwind Traders | Northwind Traders | Northwind Traders | Northwind Traders | Northwind 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.
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;| ROWS_TOTAL | DOT_EQUALS_BRACKET | DOT_EQUALS_GET_PATH | DOT_EQUALS_COLON |
|---|---|---|---|
| 4 | 4 | 4 | 4 |
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.
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;| GET_ONE_STEP | GET_PATH_TWO_STEPS | GET_PATH_WITH_INDEX | GET_PATH_WRONG_CASE | GET_PATH_WRONG_KEY | GET_WRONG_CASE |
|---|---|---|---|---|---|
| 4200 | "Northwind Traders" | "A-100" | NULL | NULL | NULL |
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.
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;| EVENT_ID | LOWER_CASE | TITLE_CASE | UPPER_CASE | NONSENSE_CASE |
|---|---|---|---|---|
| 1 | 4200 | NULL | NULL | NULL |
| 2 | 890.5 | NULL | NULL | NULL |
| 3 | "1500.00" | NULL | NULL | NULL |
| 4 | 9250 | NULL | NULL | NULL |
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.
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;| ROWS_IN_TABLE | TOTAL_CORRECT_SPELLING | TOTAL_WRONG_SPELLING | ROWS_WITH_LOWER | ROWS_WITH_TITLE |
|---|---|---|---|---|
| 4 | 15840.50 | NULL | 4 | 0 |
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.
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.
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;| EVENT_ID | MY_TYPO | TYPO_IS_NULL | SOMETIMES_MISSING | MISSING_IS_NULL | MISSING_IS_JSON_NULL |
|---|---|---|---|---|---|
| 1 | NULL | TRUE | { "os": "windows", "type": "desktop" } | FALSE | FALSE |
| 2 | NULL | TRUE | { "os": "ios", "type": "mobile" } | FALSE | FALSE |
| 3 | NULL | TRUE | NULL | TRUE | NULL |
| 4 | NULL | TRUE | { "os": "android", "type": "tablet" } | FALSE | FALSE |
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.
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;| EVENT_ID | DEVICE_OS | TWO_LEVELS_PAST_NOTHING | FOUR_LEVELS_OF_NOTHING | IS_IT_NULL |
|---|---|---|---|---|
| 1 | windows | NULL | NULL | FALSE |
| 2 | ios | NULL | NULL | FALSE |
| 3 | NULL | NULL | NULL | TRUE |
| 4 | android | NULL | NULL | FALSE |
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.
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;| EVENT_ID | ITS_KEYS | HOW_MANY | HAS_AMOUNT | HAS_TITLE_AMOUNT | HAS_DEVICE |
|---|---|---|---|---|---|
| 1 | [ "amount", "device", "event", "items", "tags", "user" ] | 6 | TRUE | FALSE | TRUE |
| 2 | [ "amount", "device", "event", "items", "tags", "user" ] | 6 | TRUE | FALSE | TRUE |
| 3 | [ "amount", "event", "items", "tags", "user" ] | 5 | TRUE | FALSE | FALSE |
| 4 | [ "amount", "device", "event", "items", "tags", "user" ] | 6 | TRUE | FALSE | TRUE |
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.
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;| ROWS_TOTAL | HAVE_AMOUNT | HAVE_TITLE_AMOUNT | HAVE_DEVICE | DISTINCT_SHAPES |
|---|---|---|---|---|
| 4 | 4 | 0 | 3 | 2 |
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.
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;| ROWS_TOTAL | EVENT_PRESENT | USER_ID_PRESENT | USER_NAME_PRESENT | AMOUNT_PRESENT | DEVICE_OS_PRESENT | FIRST_SKU_PRESENT | FIRST_TAG_PRESENT |
|---|---|---|---|---|---|---|---|
| 4 | 4 | 4 | 4 | 4 | 3 | 4 | 3 |
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?
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;| THE_DOCUMENT | DOT_NOTATION_GIVES | BRACKETS_GIVE | GET_GIVES |
|---|---|---|---|
| { "user": { "name": "Blue Ridge" }, "user.name": "Northwind" } | Blue Ridge | Northwind | Northwind |
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 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.
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;| A_KEY_WITH_A_SPACE | A_KEYWORD_KEY | A_NUMERIC_KEY | QUOTED_AFTER_COLON |
|---|---|---|---|
| 1001 | x | a year | 1001 |
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.
SELECT PARSE_JSON('{"order id":1001}'):order id::INT AS SHOULD_NOT_GET_THIS_FAR;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.
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;| EVENT_ID | HOW_MANY_ITEMS | FIRST_SKU | SECOND_SKU | THIRD_SKU | FIRST_TAG |
|---|---|---|---|---|---|
| 1 | 2 | A-100 | B-220 | NULL | priority |
| 2 | 1 | C-310 | NULL | NULL | new |
| 3 | 1 | A-100 | NULL | NULL | NULL |
| 4 | 3 | D-400 | A-100 | E-505 | priority |
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.
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;| THE_FIRST_ITEM | DOT_AFTER_BRACKET | COLON_AFTER_BRACKET | ALL_BRACKETS | GET_PATH_WITH_INDEX |
|---|---|---|---|---|
| { "price": 300, "qty": 8, "sku": "A-100" } | 300.00 | 300.00 | 300.00 | 300.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.
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;| EVENT_ID | THE_TAGS | ITS_SIZE | TAGS_IS_NULL | FIRST_TAG | FIRST_TAG_IS_NULL |
|---|---|---|---|---|---|
| 1 | [ "priority", "repeat" ] | 2 | FALSE | priority | FALSE |
| 2 | [ "new" ] | 1 | FALSE | new | FALSE |
| 3 | [] | 0 | FALSE | NULL | TRUE |
| 4 | [ "priority", "enterprise", "repeat" ] | 3 | FALSE | priority | FALSE |
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.
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;| INDEX_0 | INDEX_2_LAST_ONE | INDEX_3_ONE_PAST | INDEX_99 | ONE_PAST_IS_NULL | FAR_PAST_IS_NULL | ACTUAL_SIZE |
|---|---|---|---|---|---|---|
| D-400 | E-505 | NULL | NULL | TRUE | TRUE | 3 |
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.
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;| A_MILLION_IS_NULL | NEAR_THE_LIMIT_IS_NULL | ROWS_STILL_RETURNED |
|---|---|---|
| TRUE | TRUE | 4 |
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.
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;| PATH_0 | PATH_99 | PATH_99_IS_NULL |
|---|---|---|
| D-400 | NULL | TRUE |
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.
SELECT PAYLOAD:items[-1].sku::VARCHAR AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON
WHERE EVENT_ID = 4;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.
SELECT COUNT(PAYLOAD:items[-1]) AS SHOULD_NOT_GET_THIS_FAR FROM EVENTS_JSON;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.
SELECT GET_PATH(PAYLOAD, 'items[-1].sku') AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON
WHERE EVENT_ID = 4;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.
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;| EVENT_ID | N | LAST_SKU_BY_ARITHMETIC | LAST_VIA_ARRAY_SLICE | FIRST_SKU |
|---|---|---|---|---|
| 1 | 2 | B-220 | [ { "price": 450, "qty": 4, "sku": "B-220" } ] | A-100 |
| 2 | 1 | C-310 | [ { "price": 296.83, "qty": 3, "sku": "C-310" } ] | C-310 |
| 3 | 1 | A-100 | [ { "price": 300, "qty": 5, "sku": "A-100" } ] | A-100 |
| 4 | 3 | E-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.
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;| FIRST_TWO | NEGATIVE_START | END_PAST_THE_END | EMPTY_SLICE | EMPTY_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.
SELECT EVENT_ID,
PAYLOAD:tags[ARRAY_SIZE(PAYLOAD:tags) - 1]::VARCHAR AS SHOULD_NOT_GET_THIS_FAR
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | SHOULD_NOT_GET_THIS_FAR |
|---|---|
| 1 | repeat |
| 2 | new |
| 3 | NULL |
| 4 | repeat |
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.
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.
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;| EVENT_ID | N_TAGS | LAST_TAG_SAFE |
|---|---|---|
| 1 | 2 | repeat |
| 2 | 1 | new |
| 3 | 0 | NULL |
| 4 | 3 | repeat |
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.
GETtakes exactly one step.GET_PATHtakes 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:AmountreturnedNULLon 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
SUMover a misspelled path returnsNULLrather than zero, which is how a report ends up blank instead of broken. OBJECT_KEYSandARRAY_CONTAINSlet you ask the document rather than guess, andCOUNTof 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_SIZEtells them apart. - An index past the end of an array is
NULLat any distance. A literal-1is a hard error, even inside aCOUNT. ARRAY_SLICEdoes accept a negative start, so the restriction belongs to the path notation and not to arrays in general.
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.