In this post we are going to cover type checking inside a VARIANT in Snowflake: TYPEOF, the IS_ family and the AS_ family.
A VARIANT column does not have one type. Every row in it can hold something different, so before you read a value out of one you need a way to ask what is actually in there. These three families are the three ways to ask. TYPEOF gives you a name, the IS_ functions give you a boolean, and the AS_ functions give you the value itself.
We will start with one value of every type and build it up step by step. On the way we will find the safe numeric read that Episode 89 went looking for and could not find, and then we will find out what it costs.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back, including the three that failed.
Episode 94 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's set up the data to work with
- Let's start with TYPEOF
- Now let's separate a JSON null from a SQL NULL
- Now let's ask the IS_ family about a number
- What happens when the value is a string that looks like a number?
- Now let's ask about a key that is not there
- Let's take the IS_ family to a real column of numbers
- Now let's try the AS_ family
- Here is the safe cast Episode 89 could not find
- Now let's run the AS_ family over the real column
- So let's use IS_ as a guard and then cast
- Can we check the shape before we reach into it?
- Three ways to ask about one value
- Let's put all three families into one validator
- One last thing: a type report for a whole column
Let's set up the data to work with
Two tables on this page, and both of them are from earlier in this level. EVENTS_JSON holds four documents in a VARIANT column. JSON_TEXT_RAW holds eleven pieces of JSON that have never been parsed at all. Copy this into a worksheet and run it once.
-- Two tables on this page, both of them from earlier in this level.
-- EVENTS_JSON - four documents already parsed, in a VARIANT column.
-- JSON_TEXT_RAW - eleven pieces of JSON stored as plain text, nothing parsed.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE EVENTS_JSON (
EVENT_ID INT,
PAYLOAD VARIANT
);
INSERT INTO EVENTS_JSON (EVENT_ID, PAYLOAD)
SELECT 1, PARSE_JSON('{
"event": "purchase",
"amount": 4200,
"device": { "os": "windows", "type": "desktop" },
"user": { "id": 101, "name": "Northwind Traders" },
"items": [ { "sku": "A-100", "qty": 8, "price": 300 },
{ "sku": "B-220", "qty": 4, "price": 450 } ],
"tags": [ "priority", "repeat" ]
}')
UNION ALL SELECT 2, PARSE_JSON('{
"event": "purchase",
"amount": 890.5,
"device": { "os": "ios", "type": "mobile" },
"user": { "id": 102, "name": "Blue Ridge Supply" },
"items": [ { "sku": "C-310", "qty": 3, "price": 296.83 } ],
"tags": [ "new" ]
}')
UNION ALL SELECT 3, PARSE_JSON('{
"event": "refund",
"amount": "1500.00",
"user": { "id": 103, "name": "Kestrel Analytics" },
"items": [ { "sku": "A-100", "qty": 5, "price": 300 } ],
"tags": []
}')
UNION ALL SELECT 4, PARSE_JSON('{
"event": "purchase",
"amount": 9250,
"device": { "os": "android", "type": "tablet" },
"user": { "id": 107, "name": "Meridian Health" },
"items": [ { "sku": "D-400", "qty": 12, "price": 500 },
{ "sku": "A-100", "qty": 10, "price": 300 },
{ "sku": "E-505", "qty": 8, "price": 156.25 } ],
"tags": [ "priority", "enterprise", "repeat" ]
}');
-- The raw text table. Note what is in rows 9, 10 and 11: a SQL NULL, an
-- empty string, and the four characters null. They are three different things.
CREATE OR REPLACE TABLE JSON_TEXT_RAW (
ROW_ID INT,
WHAT_IT_IS VARCHAR,
RAW_TEXT VARCHAR
);
INSERT INTO JSON_TEXT_RAW VALUES
( 1, 'valid object', '{"sku":"A-100","qty":8,"price":300.00}'),
( 2, 'valid, other shape', '{"sku":"B-220","price":450.00,"note":"back-ordered"}'),
( 3, 'trailing comma', '{"sku":"C-310","qty":3,}'),
( 4, 'single quotes', '{''sku'':''D-400'',''qty'':12}'),
( 5, 'unquoted key', '{sku:"E-505","qty":8}'),
( 6, 'truncated', '{"sku":"F-600","qty":'),
( 7, 'valid array', '[1,2,3]'),
( 8, 'valid bare scalar', '42'),
( 9, 'NULL, no text', NULL),
(10, 'empty string', ''),
(11, 'the text null', 'null');Before we touch either table, let's make ourselves one value of every type a VARIANT can hold.
SELECT PARSE_JSON('42') AS AN_INTEGER,
PARSE_JSON('42.5') AS A_DECIMAL,
PARSE_JSON('"hello"') AS A_VARCHAR,
PARSE_JSON('true') AS A_BOOLEAN,
PARSE_JSON('[1,2]') AS AN_ARRAY,
PARSE_JSON('{"a":1}') AS AN_OBJECT,
PARSE_JSON('null') AS A_JSON_NULL;| AN_INTEGER | A_DECIMAL | A_VARCHAR | A_BOOLEAN | AN_ARRAY | AN_OBJECT | A_JSON_NULL |
|---|---|---|---|---|---|---|
| 42 | 42.5 | "hello" | true | [ 1, 2 ] | { "a": 1 } | null |
An integer, a decimal, a string, a boolean, an array, an object, and the JSON word null. That is seven values, and every one of them is a VARIANT.
Look at the last column. It prints as the four characters null, in lower case, as ordinary text in the cell. It is not a grey NULL. That is Snowflake showing us a JSON null, which is a value, and we are going to spend the next two sections on the difference.
Let's start with TYPEOF
TYPEOF takes a VARIANT and gives back the name of what is inside it, as text. Let's put it round each of those same seven values.
SELECT TYPEOF(PARSE_JSON('42')) AS AN_INTEGER,
TYPEOF(PARSE_JSON('42.5')) AS A_DECIMAL,
TYPEOF(PARSE_JSON('"hello"')) AS A_VARCHAR,
TYPEOF(PARSE_JSON('true')) AS A_BOOLEAN,
TYPEOF(PARSE_JSON('[1,2]')) AS AN_ARRAY,
TYPEOF(PARSE_JSON('{"a":1}')) AS AN_OBJECT,
TYPEOF(PARSE_JSON('null')) AS A_JSON_NULL;| AN_INTEGER | A_DECIMAL | A_VARCHAR | A_BOOLEAN | AN_ARRAY | AN_OBJECT | A_JSON_NULL |
|---|---|---|---|---|---|---|
| INTEGER | DECIMAL | VARCHAR | BOOLEAN | ARRAY | OBJECT | NULL_VALUE |
Seven names for seven values: INTEGER, DECIMAL, VARCHAR, BOOLEAN, ARRAY, OBJECT and NULL_VALUE.
The last one is the one to hold on to. The JSON word null did not come back as nothing. It came back as NULL_VALUE, which is a piece of text like all the others in that row.
Now let's separate a JSON null from a SQL NULL
Episode 87 left a problem open. A NULL coming out of a VARIANT could mean three different things and nothing on the page could tell them apart. It could be a real SQL NULL, it could be a key that is not in the document, or it could be the JSON word null.
Let's ask TYPEOF about all three at once, and ask IS NULL about each answer as well.
SELECT TYPEOF(NULL::VARIANT) AS TYPEOF_SQL_NULL,
TYPEOF(NULL::VARIANT) IS NULL AS IT_IS_A_SQL_NULL,
TYPEOF(PARSE_JSON('null')) AS TYPEOF_JSON_NULL,
TYPEOF(PARSE_JSON('null')) IS NULL AS THAT_ONE_IS_A_SQL_NULL,
TYPEOF(PAYLOAD:nothing_here) AS TYPEOF_A_MISSING_KEY,
TYPEOF(PAYLOAD:nothing_here) IS NULL AS MISSING_IS_A_SQL_NULL
FROM EVENTS_JSON
WHERE EVENT_ID = 1;| TYPEOF_SQL_NULL | IT_IS_A_SQL_NULL | TYPEOF_JSON_NULL | THAT_ONE_IS_A_SQL_NULL | TYPEOF_A_MISSING_KEY | MISSING_IS_A_SQL_NULL |
|---|---|---|---|---|---|
| NULL | TRUE | NULL_VALUE | FALSE | NULL | TRUE |
Read that grid in pairs. A SQL NULL cast to VARIANT gives TYPEOF of NULL, and IS NULL on that answer is TRUE. A key that is not in the document does exactly the same thing.
The JSON word null does not. TYPEOF gives NULL_VALUE, and IS NULL on that answer is FALSE, because NULL_VALUE is a string and a string is not nothing.
Have a look at how those two print. The first and fifth columns are a grey NULL, which is this page's way of showing a real SQL NULL. The third column is the plain text NULL_VALUE. One of the three meanings is now separable, and the other two still are not. That is one more than we had before.
Now let's ask the IS_ family about a number
The IS_ family asks a yes-or-no question. There is one for each type: IS_INTEGER, IS_DECIMAL, IS_DOUBLE, IS_VARCHAR, IS_BOOLEAN, IS_ARRAY, IS_OBJECT and IS_NULL_VALUE.
Let's point all of them at the number 42.
SELECT IS_INTEGER(PARSE_JSON('42')) AS IS_INTEGER_,
IS_DECIMAL(PARSE_JSON('42')) AS IS_DECIMAL_,
IS_DOUBLE(PARSE_JSON('42')) AS IS_DOUBLE_,
IS_VARCHAR(PARSE_JSON('42')) AS IS_VARCHAR_,
IS_BOOLEAN(PARSE_JSON('42')) AS IS_BOOLEAN_,
IS_ARRAY(PARSE_JSON('42')) AS IS_ARRAY_,
IS_OBJECT(PARSE_JSON('42')) AS IS_OBJECT_,
IS_NULL_VALUE(PARSE_JSON('42')) AS IS_NULL_VALUE_;| IS_INTEGER_ | IS_DECIMAL_ | IS_DOUBLE_ | IS_VARCHAR_ | IS_BOOLEAN_ | IS_ARRAY_ | IS_OBJECT_ | IS_NULL_VALUE_ |
|---|---|---|---|---|---|---|---|
| TRUE | TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE |
Eight columns, and three of them are TRUE. IS_INTEGER is TRUE, which is no surprise. But IS_DECIMAL is also TRUE, and so is IS_DOUBLE.
So these functions are not exclusive. 42 is an integer and a decimal and a double, all at the same time. Let's try the same eight questions on 42.5 and see which answer moves.
SELECT IS_INTEGER(PARSE_JSON('42.5')) AS IS_INTEGER_,
IS_DECIMAL(PARSE_JSON('42.5')) AS IS_DECIMAL_,
IS_DOUBLE(PARSE_JSON('42.5')) AS IS_DOUBLE_,
IS_VARCHAR(PARSE_JSON('42.5')) AS IS_VARCHAR_,
IS_BOOLEAN(PARSE_JSON('42.5')) AS IS_BOOLEAN_,
IS_ARRAY(PARSE_JSON('42.5')) AS IS_ARRAY_,
IS_OBJECT(PARSE_JSON('42.5')) AS IS_OBJECT_,
IS_NULL_VALUE(PARSE_JSON('42.5')) AS IS_NULL_VALUE_;| IS_INTEGER_ | IS_DECIMAL_ | IS_DOUBLE_ | IS_VARCHAR_ | IS_BOOLEAN_ | IS_ARRAY_ | IS_OBJECT_ | IS_NULL_VALUE_ |
|---|---|---|---|---|---|---|---|
| FALSE | TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE |
Only IS_INTEGER changed. It went from TRUE to FALSE, and IS_DECIMAL and IS_DOUBLE stayed TRUE. So IS_INTEGER is the only one of the three that actually narrows anything down.
What happens when the value is a string that looks like a number?
This is the question that catches people. Let's ask IS_INTEGER about the text "42", and ask IS_BOOLEAN about the text "true".
SELECT IS_VARCHAR(PARSE_JSON('"hello"')) AS IS_VARCHAR_,
IS_CHAR(PARSE_JSON('"hello"')) AS IS_CHAR_,
IS_INTEGER(PARSE_JSON('"42"')) AS IS_INTEGER_ON_A_NUMERIC_STRING,
IS_VARCHAR(PARSE_JSON('"42"')) AS IS_VARCHAR_ON_THE_SAME,
IS_BOOLEAN(PARSE_JSON('"true"')) AS IS_BOOLEAN_ON_THE_WORD_TRUE,
IS_VARCHAR(PARSE_JSON('"true"')) AS IS_VARCHAR_ON_THE_SAME;| IS_VARCHAR_ | IS_CHAR_ | IS_INTEGER_ON_A_NUMERIC_STRING | IS_VARCHAR_ON_THE_SAME | IS_BOOLEAN_ON_THE_WORD_TRUE | IS_VARCHAR_ON_THE_SAME |
|---|---|---|---|---|---|
| TRUE | TRUE | FALSE | TRUE | FALSE | TRUE |
IS_INTEGER on the text "42" is FALSE, and IS_VARCHAR on the same value is TRUE. Same story for the word "true": IS_BOOLEAN says FALSE and IS_VARCHAR says TRUE.
So the IS_ family asks what a value is. It never asks what the value could be read as. A number written as text is text, and that is the end of it.
Let's do the containers as well, because there is one small thing worth confirming there.
SELECT IS_ARRAY(PARSE_JSON('[1,2]')) AS ARRAY_IS_ARRAY,
IS_OBJECT(PARSE_JSON('[1,2]')) AS ARRAY_IS_OBJECT,
IS_ARRAY(PARSE_JSON('{"a":1}')) AS OBJECT_IS_ARRAY,
IS_OBJECT(PARSE_JSON('{"a":1}')) AS OBJECT_IS_OBJECT,
IS_ARRAY(PARSE_JSON('[]')) AS EMPTY_ARRAY_IS_ARRAY,
IS_OBJECT(PARSE_JSON('{}')) AS EMPTY_OBJECT_IS_OBJECT;| ARRAY_IS_ARRAY | ARRAY_IS_OBJECT | OBJECT_IS_ARRAY | OBJECT_IS_OBJECT | EMPTY_ARRAY_IS_ARRAY | EMPTY_OBJECT_IS_OBJECT |
|---|---|---|---|---|---|
| TRUE | FALSE | FALSE | TRUE | TRUE | TRUE |
An array is not an object and an object is not an array, which is what we would hope. And an empty array is still an array, and an empty object is still an object. Being empty does not change what something is.
Now let's ask about a key that is not there
Up to here every answer has been TRUE or FALSE. Now let's run IS_OBJECT over the real table. Three of the four documents have a device key and one of them does not.
SELECT EVENT_ID,
PAYLOAD:device IS NULL AS THE_KEY_IS_ABSENT,
IS_OBJECT(PAYLOAD:device) AS IS_OBJECT_,
IS_OBJECT(PAYLOAD:device) IS NULL AS IS_OBJECT_ANSWERED_NULL,
IS_ARRAY(PAYLOAD:device) AS IS_ARRAY_,
IS_ARRAY(PAYLOAD:device) IS NULL AS IS_ARRAY_ANSWERED_NULL,
IS_NULL_VALUE(PAYLOAD:device) AS IS_NULL_VALUE_
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | THE_KEY_IS_ABSENT | IS_OBJECT_ | IS_OBJECT_ANSWERED_NULL | IS_ARRAY_ | IS_ARRAY_ANSWERED_NULL | IS_NULL_VALUE_ |
|---|---|---|---|---|---|---|
| 1 | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE |
| 2 | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE |
| 3 | TRUE | NULL | TRUE | NULL | TRUE | NULL |
| 4 | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE |
Event 3 is the row to look at. THE_KEY_IS_ABSENT is TRUE on that row, and IS_OBJECT_ beside it is not FALSE. It is NULL. So is IS_ARRAY_, and so is IS_NULL_VALUE_.
That is a third answer, and it is the one that breaks filters. Let's count the rows and see what it does to the arithmetic.
SELECT COUNT(*) AS EVENTS_TOTAL,
COUNT_IF(IS_OBJECT(PAYLOAD:device)) AS IS_OBJECT_TRUE,
COUNT_IF(NOT IS_OBJECT(PAYLOAD:device)) AS IS_OBJECT_FALSE,
COUNT_IF(IS_OBJECT(PAYLOAD:device) IS NULL) AS IS_OBJECT_NULL,
COUNT_IF(IS_OBJECT(PAYLOAD:device))
+ COUNT_IF(NOT IS_OBJECT(PAYLOAD:device)) AS THE_TWO_ADDED_UP
FROM EVENTS_JSON;| EVENTS_TOTAL | IS_OBJECT_TRUE | IS_OBJECT_FALSE | IS_OBJECT_NULL | THE_TWO_ADDED_UP |
|---|---|---|---|---|
| 4 | 3 | 0 | 1 | 3 |
IS_OBJECT_TRUE is 3. IS_OBJECT_FALSE is 0. IS_OBJECT_NULL is 1. And the two booleans added together come to 3, over a table of 4 rows.
Think about what that does to a filter. If you write WHERE NOT IS_OBJECT(PAYLOAD:device) to find the bad row, you will find nothing at all. The row you are looking for answers NULL to the question, and NOT NULL is NULL, which is not TRUE, so the row is not returned. The query runs, returns no rows, and tells you everything is fine.
So whenever you count with an IS_ function, count the NULLs as well and check that your three numbers add up to your row count.
Let's take the IS_ family to a real column of numbers
The amount key is the interesting one in this table, because it was not loaded consistently. Let's print each amount, ask TYPEOF what it is, and then ask three of the IS_ questions about it.
SELECT EVENT_ID,
PAYLOAD:amount AS AMOUNT_RAW,
TYPEOF(PAYLOAD:amount) AS ITS_TYPE,
IS_INTEGER(PAYLOAD:amount) AS IS_INTEGER_,
IS_DECIMAL(PAYLOAD:amount) AS IS_DECIMAL_,
IS_VARCHAR(PAYLOAD:amount) AS IS_VARCHAR_
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | AMOUNT_RAW | ITS_TYPE | IS_INTEGER_ | IS_DECIMAL_ | IS_VARCHAR_ |
|---|---|---|---|---|---|
| 1 | 4200 | DECIMAL | FALSE | TRUE | FALSE |
| 2 | 890.5 | DECIMAL | FALSE | TRUE | FALSE |
| 3 | "1500.00" | VARCHAR | FALSE | FALSE | TRUE |
| 4 | 9250 | INTEGER | TRUE | TRUE | FALSE |
Three different types in one column of four rows. Events 1 and 2 are DECIMAL, event 4 is INTEGER, and event 3 is VARCHAR because its amount was written into the document with quotes round it.
That one row is the whole problem of this post. "1500.00" is a perfectly good number. It is just stored as text, and the IS_ family reports it as text, which is the truthful answer.
Now let's try the AS_ family
The AS_ family has the same names and does a different job. Instead of a boolean it gives you back the value. Let's run each one on a value of the type it is asking about.
SELECT AS_INTEGER(PARSE_JSON('42')) AS AS_INTEGER_,
AS_DECIMAL(PARSE_JSON('42.5')) AS AS_DECIMAL_,
AS_VARCHAR(PARSE_JSON('"hello"')) AS AS_VARCHAR_,
AS_BOOLEAN(PARSE_JSON('true')) AS AS_BOOLEAN_,
AS_ARRAY(PARSE_JSON('[1,2]')) AS AS_ARRAY_,
AS_OBJECT(PARSE_JSON('{"a":1}')) AS AS_OBJECT_;| AS_INTEGER_ | AS_DECIMAL_ | AS_VARCHAR_ | AS_BOOLEAN_ | AS_ARRAY_ | AS_OBJECT_ |
|---|---|---|---|---|---|
| 42 | 43 | hello | TRUE | [ 1, 2 ] | { "a": 1 } |
AS_INTEGER of 42 gives 42, AS_VARCHAR of "hello" gives hello with the quotes taken off, and the array and the object come back as themselves.
Now look at AS_DECIMAL_. We gave it 42.5 and it gave us back 43.
AS_DECIMAL rounds. There is no scale argument to pass it, so it behaves as though you asked for scale zero, and your decimal places are gone without a word. This is the same defect Episode 89 found in TRY_TO_NUMBER, wearing a different name. If the fractional part matters, do not use AS_DECIMAL to read it.
Now let's ask each of them for a type the value is not.
SELECT AS_INTEGER(PARSE_JSON('"42"')) AS INTEGER_OF_A_STRING,
AS_INTEGER(PARSE_JSON('"42"')) IS NULL AS IT_GAVE_NULL,
AS_VARCHAR(PARSE_JSON('42')) AS VARCHAR_OF_A_NUMBER,
AS_VARCHAR(PARSE_JSON('42')) IS NULL AS THAT_GAVE_NULL_TOO,
AS_ARRAY(PARSE_JSON('{"a":1}')) AS ARRAY_OF_AN_OBJECT,
AS_ARRAY(PARSE_JSON('{"a":1}')) IS NULL AS AND_THAT_ONE;| INTEGER_OF_A_STRING | IT_GAVE_NULL | VARCHAR_OF_A_NUMBER | THAT_GAVE_NULL_TOO | ARRAY_OF_AN_OBJECT | AND_THAT_ONE |
|---|---|---|---|---|---|
| NULL | TRUE | NULL | TRUE | NULL | TRUE |
AS_INTEGER on the text "42" gives NULL. AS_VARCHAR on the number 42 gives NULL. AS_ARRAY on an object gives NULL. Every IS NULL column beside them is TRUE.
So the AS_ family does not convert. It checks, and if the type is wrong it hands back a NULL rather than trying to be helpful.
Here is the safe cast Episode 89 could not find
Episode 89 ended on a complaint. Casting out of a VARIANT raises as soon as one value is not convertible, and there was no safe version of it. Let's run that failure again so we have it in front of us.
SELECT PARSE_JSON('"N/A"')::INT AS SHOULD_NOT_GET_THIS_FAR;100071 (22000): Failed to cast variant value "N/A" to FIXED
One unconvertible value and the whole statement is gone. In any other situation the fix for this is TRY_CAST, so let's try that.
SELECT TRY_CAST(PARSE_JSON('42') AS INT) AS SHOULD_NOT_GET_THIS_FAR;001065 (22023): SQL compilation error: Function TRY_CAST cannot be used with arguments of types VARIANT and NUMBER(38,0)
That is not a data error, it is a compile error. And notice what we handed it: a VARIANT holding the number 42, which would convert without any trouble at all. TRY_CAST is not refusing the value. It is refusing the VARIANT type, so there is nothing you can feed it that will work.
Now let's ask AS_INTEGER for the same value the cast died on.
SELECT PARSE_JSON('"N/A"') AS THE_VALUE,
AS_INTEGER(PARSE_JSON('"N/A"')) AS AS_INTEGER_GIVES,
AS_INTEGER(PARSE_JSON('"N/A"')) IS NULL AS IT_IS_NULL,
TRY_TO_NUMBER(PARSE_JSON('"N/A"')::VARCHAR) AS TRY_TO_NUMBER_GIVES;| THE_VALUE | AS_INTEGER_GIVES | IT_IS_NULL | TRY_TO_NUMBER_GIVES |
|---|---|---|---|
| "N/A" | NULL | TRUE | NULL |
NULL, and IT_IS_NULL is TRUE. No error, no failed statement. That is the safe read we were looking for: AS_INTEGER is parse-or-NULL for a VARIANT, which is exactly what TRY_CAST would have been if it had let us use it.
Now let's run the AS_ family over the real column
That is the good news. Let's find the cost. Same four amounts as before, read three ways.
SELECT EVENT_ID,
PAYLOAD:amount AS AMOUNT_RAW,
TYPEOF(PAYLOAD:amount) AS ITS_TYPE,
AS_DECIMAL(PAYLOAD:amount) AS AS_DECIMAL_,
AS_INTEGER(PAYLOAD:amount) AS AS_INTEGER_,
AS_VARCHAR(PAYLOAD:amount) AS AS_VARCHAR_
FROM EVENTS_JSON
ORDER BY EVENT_ID;| EVENT_ID | AMOUNT_RAW | ITS_TYPE | AS_DECIMAL_ | AS_INTEGER_ | AS_VARCHAR_ |
|---|---|---|---|---|---|
| 1 | 4200 | DECIMAL | 4200 | 4200 | NULL |
| 2 | 890.5 | DECIMAL | 891 | 891 | NULL |
| 3 | "1500.00" | VARCHAR | NULL | NULL | 1500.00 |
| 4 | 9250 | INTEGER | 9250 | 9250 | NULL |
Event 1 comes back as 4200 from both numeric readers, which is what we want. Event 2 was 890.5 and comes back 891 from AS_DECIMAL_ as well as from AS_INTEGER_, which is the rounding we were warned about.
And event 3 is NULL in both numeric columns. The string "1500.00" is the wrong type, so AS_DECIMAL will not touch it. It is the only row where AS_VARCHAR_ has anything in it, and the only row the numeric readers throw away.
Let's count what each reader kept.
SELECT COUNT(*) AS EVENTS_TOTAL,
COUNT(AS_DECIMAL(PAYLOAD:amount)) AS AS_DECIMAL_KEPT,
COUNT(AS_INTEGER(PAYLOAD:amount)) AS AS_INTEGER_KEPT,
COUNT(AS_VARCHAR(PAYLOAD:amount)) AS AS_VARCHAR_KEPT,
COUNT(PAYLOAD:amount::NUMBER(12,2)) AS THE_CAST_KEPT
FROM EVENTS_JSON;| EVENTS_TOTAL | AS_DECIMAL_KEPT | AS_INTEGER_KEPT | AS_VARCHAR_KEPT | THE_CAST_KEPT |
|---|---|---|---|---|
| 4 | 3 | 3 | 1 | 4 |
Out of 4 rows, AS_DECIMAL kept 3 and AS_INTEGER kept 3. AS_VARCHAR kept 1. And the plain cast, the one that raises on "N/A", kept 4.
Read those last two numbers together, because this is the honest version of the whole episode. The plain cast raises on "N/A" and converts "1500.00" without complaining, because "1500.00" really is a number written as text. The AS_ family never raises and silently drops that same row. Neither one of them is correct on its own. One blows up on garbage, the other throws away good data quietly, and quietly is worse.
So let's use IS_ as a guard and then cast
If the cast is the one that keeps everything and the AS_ family is the one that never raises, the thing we actually want is the IS_ family deciding which rows the cast is allowed near.
Let's count how many amounts look numeric, count how many are text, and then sum the column twice: once behind the guard and once without it.
SELECT COUNT(*) AS EVENTS_TOTAL,
COUNT_IF(IS_INTEGER(PAYLOAD:amount)
OR IS_DECIMAL(PAYLOAD:amount)
OR IS_DOUBLE(PAYLOAD:amount)) AS LOOKS_NUMERIC,
COUNT_IF(IS_VARCHAR(PAYLOAD:amount)) AS IS_TEXT,
SUM(CASE WHEN IS_INTEGER(PAYLOAD:amount)
OR IS_DECIMAL(PAYLOAD:amount)
THEN PAYLOAD:amount::NUMBER(12,2) END) AS SUM_OF_THE_SAFE_ONES,
SUM(PAYLOAD:amount::NUMBER(12,2)) AS SUM_OF_EVERYTHING
FROM EVENTS_JSON;| EVENTS_TOTAL | LOOKS_NUMERIC | IS_TEXT | SUM_OF_THE_SAFE_ONES | SUM_OF_EVERYTHING |
|---|---|---|---|---|
| 4 | 3 | 1 | 14340.50 | 15840.50 |
LOOKS_NUMERIC is 3 and IS_TEXT is 1, which accounts for all 4 rows with nothing left over. The guard is correct, and it is poorer: the two sums are 1500.00 apart, and that gap is event 3.
There is no free version of this. Either you go and look at the text rows and decide what they mean, or you do not count them. What you must not do is report the guarded sum as the total and say nothing about the difference. Put both numbers on the page, the way this query does.
Can we check the shape before we reach into it?
Here is the same lesson in a smaller shape. OBJECT_KEYS wants an object. Let's hand it an array instead.
SELECT OBJECT_KEYS(PARSE_JSON('[1,2,3]')) AS SHOULD_NOT_GET_THIS_FAR;100071 (22000): Failed to cast variant value [1,2,3] to OBJECT
It raises, and it raises for the same reason the cast did: it was asked to turn one thing into another and it could not. Now let's ask about the same value instead of reaching into it.
SELECT IS_OBJECT(PARSE_JSON('[1,2,3]')) AS IS_OBJECT_ON_AN_ARRAY,
IS_ARRAY(PARSE_JSON('[1,2,3]')) AS IS_ARRAY_ON_AN_ARRAY,
AS_OBJECT(PARSE_JSON('[1,2,3]')) AS AS_OBJECT_ON_AN_ARRAY,
AS_OBJECT(PARSE_JSON('[1,2,3]')) IS NULL AS AS_OBJECT_GAVE_NULL;| IS_OBJECT_ON_AN_ARRAY | IS_ARRAY_ON_AN_ARRAY | AS_OBJECT_ON_AN_ARRAY | AS_OBJECT_GAVE_NULL |
|---|---|---|---|
| FALSE | TRUE | NULL | TRUE |
IS_OBJECT says FALSE, IS_ARRAY says TRUE, and AS_OBJECT hands back a NULL. Three answers and no error anywhere.
So the pattern is: ask first, reach second. Put IS_OBJECT in front of OBJECT_KEYS and the statement stops being something that can fail on a row you have not seen yet.
Three ways to ask about one value
Before we build anything, let's put all three families on one value and compare what comes back. The value is the string "1500.00", which has been the troublemaker all the way through this post.
SELECT PARSE_JSON('"1500.00"') AS THE_VALUE,
TYPEOF(PARSE_JSON('"1500.00"')) AS TYPEOF_GIVES_A_STRING,
IS_VARCHAR(PARSE_JSON('"1500.00"')) AS IS_GIVES_A_BOOLEAN,
AS_VARCHAR(PARSE_JSON('"1500.00"')) AS AS_GIVES_THE_VALUE,
IS_DECIMAL(PARSE_JSON('"1500.00"')) AS IS_DECIMAL_SAYS,
AS_DECIMAL(PARSE_JSON('"1500.00"')) AS AS_DECIMAL_SAYS;| THE_VALUE | TYPEOF_GIVES_A_STRING | IS_GIVES_A_BOOLEAN | AS_GIVES_THE_VALUE | IS_DECIMAL_SAYS | AS_DECIMAL_SAYS |
|---|---|---|---|---|---|
| "1500.00" | VARCHAR | TRUE | 1500.00 | FALSE | NULL |
TYPEOF gives a name, VARCHAR. IS_VARCHAR gives a boolean, TRUE. AS_VARCHAR gives the value itself, 1500.00. Three different return types from three questions about one value.
And the last two columns agree with each other. IS_DECIMAL says FALSE and AS_DECIMAL gives NULL. They are the same answer in two different shapes, which is useful: you can test with one and read with the other and know they will not disagree.
Let's put all three families into one validator
Now we can build the thing this level has been working towards. Let's go back to the eleven rows of raw text from Episode 87 and ask, for each one: does CHECK_JSON accept it, does it parse, what did it parse to, is that an object, and does the object have a sku key.
SELECT ROW_ID, WHAT_IT_IS,
CHECK_JSON(RAW_TEXT) IS NULL AS CHECK_JSON_HAPPY,
TRY_PARSE_JSON(RAW_TEXT) IS NOT NULL AS IT_PARSED,
TYPEOF(TRY_PARSE_JSON(RAW_TEXT)) AS WHAT_IT_PARSED_TO,
IS_OBJECT(TRY_PARSE_JSON(RAW_TEXT)) AS IS_OBJECT_,
CASE WHEN IS_OBJECT(TRY_PARSE_JSON(RAW_TEXT))
THEN ARRAY_CONTAINS('sku'::VARIANT,
OBJECT_KEYS(TRY_PARSE_JSON(RAW_TEXT)))
ELSE FALSE END AS HAS_SKU
FROM JSON_TEXT_RAW
ORDER BY ROW_ID;| ROW_ID | WHAT_IT_IS | CHECK_JSON_HAPPY | IT_PARSED | WHAT_IT_PARSED_TO | IS_OBJECT_ | HAS_SKU |
|---|---|---|---|---|---|---|
| 1 | valid object | TRUE | TRUE | OBJECT | TRUE | TRUE |
| 2 | valid, other shape | TRUE | TRUE | OBJECT | TRUE | TRUE |
| 3 | trailing comma | TRUE | TRUE | OBJECT | TRUE | TRUE |
| 4 | single quotes | TRUE | TRUE | OBJECT | TRUE | TRUE |
| 5 | unquoted key | TRUE | TRUE | OBJECT | TRUE | TRUE |
| 6 | truncated | FALSE | FALSE | NULL | NULL | FALSE |
| 7 | valid array | TRUE | TRUE | ARRAY | FALSE | FALSE |
| 8 | valid bare scalar | TRUE | TRUE | INTEGER | FALSE | FALSE |
| 9 | NULL, no text | TRUE | FALSE | NULL | NULL | FALSE |
| 10 | empty string | TRUE | FALSE | NULL | NULL | FALSE |
| 11 | the text null | TRUE | TRUE | NULL_VALUE | FALSE | FALSE |
Rows 1 to 5 are objects with a sku, and those are the rows you can use. Rows 7 and 8 are the ones worth stopping on. The array and the bare number both parse perfectly well, WHAT_IT_PARSED_TO says ARRAY and INTEGER, and IS_OBJECT_ says FALSE for both. Valid JSON, and no use to a query that wants a sku.
Row 11 is the text null, and it parsed to NULL_VALUE. Compare that cell with the WHAT_IT_PARSED_TO cell on rows 6, 9 and 10, which are grey NULLs. The text null parsed to something. The other three parsed to nothing.
Let's count the funnel.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(CHECK_JSON(RAW_TEXT) IS NULL) AS CHECK_JSON_SAYS_OK,
COUNT_IF(TRY_PARSE_JSON(RAW_TEXT) IS NOT NULL) AS ACTUALLY_PARSED,
COUNT_IF(IS_OBJECT(TRY_PARSE_JSON(RAW_TEXT))) AS GAVE_AN_OBJECT,
COUNT_IF(IS_OBJECT(TRY_PARSE_JSON(RAW_TEXT))
AND ARRAY_CONTAINS('sku'::VARIANT,
OBJECT_KEYS(TRY_PARSE_JSON(RAW_TEXT))))
AS USABLE_ROWS
FROM JSON_TEXT_RAW;| ROWS_TOTAL | CHECK_JSON_SAYS_OK | ACTUALLY_PARSED | GAVE_AN_OBJECT | USABLE_ROWS |
|---|---|---|---|---|
| 11 | 10 | 8 | 5 | 5 |
11 rows in. CHECK_JSON is happy with 10 of them. 8 actually parse. 5 give an object. And 5 are usable, because every object here happens to have a sku.
The step from 10 to 8 is worth naming, because it is not obvious from the counts alone. Row 6 is the truncated document, and that is the one CHECK_JSON rejects. Rows 9 and 10 are the SQL NULL and the empty string, and CHECK_JSON has no complaint about either of them. They just do not parse to anything.
That is the funnel finished, and it is the number worth remembering out of this whole level. Of the rows that went in, fewer than half came out the other end as something a query could read. CHECK_JSON on its own would have told you almost everything was fine.
One last thing: a type report for a whole column
One query to finish with, and it is the one to run first on any VARIANT column you have not seen before. Group the column by TYPEOF and count.
SELECT TYPEOF(PAYLOAD:amount) AS ITS_TYPE,
COUNT(*) AS HOW_MANY,
COUNT_IF(IS_INTEGER(PAYLOAD:amount)
OR IS_DECIMAL(PAYLOAD:amount)) AS NUMERIC_,
COUNT_IF(IS_VARCHAR(PAYLOAD:amount)) AS TEXT_
FROM EVENTS_JSON
GROUP BY TYPEOF(PAYLOAD:amount)
ORDER BY HOW_MANY DESC;| ITS_TYPE | HOW_MANY | NUMERIC_ | TEXT_ |
|---|---|---|---|
| DECIMAL | 2 | 2 | 0 |
| VARCHAR | 1 | 0 | 1 |
| INTEGER | 1 | 1 | 0 |
DECIMAL 2, VARCHAR 1, INTEGER 1. Three rows, one per type that is actually in there.
That is the whole picture before you write a single cast. If the report comes back with one row you can read the column straight. If it comes back with a VARCHAR row like this one, you know there is a decision to make and roughly how big it is.
Key points
TYPEOFgives you a name, theIS_family gives you a boolean, and theAS_family gives you the value.TYPEOFof the JSON word null is the textNULL_VALUE, which is not a SQLNULL. A SQLNULLand a missing key both give a SQLNULL, so one of Episode 87's three meanings is now separable and the other two are not.- The
IS_functions are not exclusive.IS_INTEGER,IS_DECIMALandIS_DOUBLEare allTRUEof42. - They ask what a value is, never what it could be read as.
IS_INTEGERon the text"42"isFALSE. - On a missing key an
IS_function answersNULL, notFALSE. SoWHERE NOT IS_OBJECT(...)finds nothing, andTRUEplusFALSEdoes not add up to your row count. Count theNULLs too. - The
AS_family checks rather than converts. Wrong type,NULLback, no error. AS_INTEGERis the parse-or-NULLread thatTRY_CASTrefuses to give you, becauseTRY_CASTrejects aVARIANTat compile time whatever is inside it.AS_DECIMALrounds.42.5comes back as43.- Safety costs rows. The plain cast kept all
4amounts,AS_DECIMALkept3, and the row it dropped was a good number stored as text. - Guard with
IS_and then cast, and report what the guard left out beside what it kept. OBJECT_KEYSraises on an array whileIS_OBJECTandAS_OBJECTanswer. Ask first, reach second.GROUP BY TYPEOF(...)is a one-query type report, and it is the first thing to run on aVARIANTcolumn you do not know.
Episode 95 — structured types. ARRAY(INT), OBJECT(...) and MAP(...), where the column itself carries the type and does the checking, so none of this guarding is left for you to remember.
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, including the three statements that failed. The EVENTS_JSON and JSON_TEXT_RAW rows are invented demo data, and the quoted amount on event 3 is there on purpose. Every count in the text above was read off one of the grids on this page rather than worked out here. Nothing is timed and no performance claims are made anywhere in this series. Function behaviour follows the Snowflake semi-structured function documentation.



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