Snowflake SQL Tutorial 96 - XML - PARSE_XML, CHECK_XML and XMLGET - Level 8 Finale

Snowflake SQL · Episode 96

In this post we are going to cover XML in Snowflake: PARSE_XML to turn text into a document, CHECK_XML to find out whether it will, and XMLGET to read inside it.

XML works the way JSON did in this level. The text sits in an ordinary VARCHAR column, a function parses it, and from then on you reach into it with accessors. The functions have different names and there is one fewer of them than you expect.

This is the last post of Level 8. It is also the one the author got wrong the first time round, on the belief that PARSE_XML returns NULL for a bad document. It does not. That mistake is in here too, because what actually happens is more useful than the guess.

We will start with four documents in a text column and build it up step by step.

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

Let's create some sample data

We need a few documents to work on, and one of them has to be broken, because half of this post is about what Snowflake does with a broken one.

Copy this into a Snowflake worksheet and run it once.

Sample data
-- Sample data for this post. Four XML documents in an ordinary text column.
-- Three of them are well formed. The fourth closes the wrong tag, and it is
-- there on purpose.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE DOCS_XML (
    DOC_ID      INT,
    WHAT_IT_IS  VARCHAR,
    RAW_XML     VARCHAR
);

INSERT INTO DOCS_XML VALUES
    (1, 'two children',
     '<order id="1001"><customer>Northwind Traders</customer>'
     || '<item sku="A-100"><qty>8</qty></item>'
     || '<item sku="B-220"><qty>4</qty></item></order>'),
    (2, 'attributes and text',
     '<order id="1002" status="SHIPPED">'
     || '<customer country="USA">Blue Ridge Supply</customer>'
     || '<item sku="C-310"><qty>3</qty></item></order>'),
    (3, 'repeated and empty tags',
     '<order id="1003"><customer>Kestrel Analytics</customer>'
     || '<note/><tag>priority</tag><tag>repeat</tag></order>'),
    (4, 'not well formed',
     '<order id="1004"><customer>Harbour Foods</order>');

Now let's look at what we just created.

Query
SELECT * FROM DOCS_XML ORDER BY DOC_ID;
Result4 rows · 3 columns
DOC_IDWHAT_IT_ISRAW_XML
1two children<order id="1001"><customer>Northwind Traders</customer><item sku="A-100"><qty>8</qty></item><item sku="B-220"><qty>4</qty></item></order>
2attributes and text<order id="1002" status="SHIPPED"><customer country="USA">Blue Ridge Supply</customer><item sku="C-310"><qty>3</qty></item></order>
3repeated and empty tags<order id="1003"><customer>Kestrel Analytics</customer><note/><tag>priority</tag><tag>repeat</tag></order>
4not well formed<order id="1004"><customer>Harbour Foods</order>

Four documents. The first has two children of the same name. The second has attributes on the root and on a child, and some text. The third has a repeated tag and an empty one. The fourth opens a customer element and then closes order, so it is not well formed.

And let's be clear that the column really is text, not some XML type that has done work for us already.

Query
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'DOCS_XML'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
COLUMN_NAMEDATA_TYPE
DOC_IDNUMBER
WHAT_IT_ISTEXT
RAW_XMLTEXT

NUMBER and then two TEXT columns. Nothing has been parsed yet.

Let's parse all four documents

The obvious first query. Parse the column over the whole table.

Query — refused
SELECT DOC_ID, PARSE_XML(RAW_XML) AS SHOULD_NOT_GET_THIS_FAR
FROM DOCS_XML
ORDER BY DOC_ID;
Query failed — Snowflake returned an error
100100 (22P02): Error parsing XML: missing closing tags: </customer>, pos 48

Error parsing XML: missing closing tags: </customer>, pos 48.

This is the bit worth slowing down for. We did not get three documents and a NULL. We got no rows at all. One bad document in the column, and the whole statement failed.

PARSE_XML raises, exactly like PARSE_JSON in Episode 87. Here is PARSE_JSON on a broken piece of JSON for comparison, so you can see the same shape of refusal.

PARSE_JSON on bad JSON — refused
SELECT PARSE_JSON('{"a":') AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
100069 (22P02): Error parsing JSON: incomplete object value, pos 6
About that heading

That capture's name says the opposite of what this post has just shown you, and the reason is in the introduction: the demo script was written on the belief that PARSE_XML returns NULL. The query under the name only runs PARSE_JSON, which does raise, so that is all it is being used for here.

Let's count what the failure cost us.

Query
SELECT COUNT(*)                                       AS ROWS_IN_TABLE,
       COUNT_IF(CHECK_XML(RAW_XML) IS NULL)           AS WELL_FORMED,
       COUNT_IF(CHECK_XML(RAW_XML) IS NOT NULL)       AS NOT_WELL_FORMED,
       COUNT_IF(CHECK_XML(RAW_XML) IS NULL)           AS ROWS_YOU_COULD_HAVE_HAD
FROM DOCS_XML;
Result1 row · 4 columns
ROWS_IN_TABLEWELL_FORMEDNOT_WELL_FORMEDROWS_YOU_COULD_HAVE_HAD
4313

Four rows in the table, three of them well formed. Three rows we could have had, and we got none of them.

So what exactly does PARSE_XML refuse?

Three faults, three different messages. First an unclosed tag.

Query — refused
SELECT PARSE_XML('<a><b>unclosed</a>') AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
100100 (22P02): Error parsing XML: missing closing tags: </b>, pos 18

It names the tag it wanted and the position it gave up at.

Now text with no root element at all.

Query — refused
SELECT PARSE_XML('just some text') AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
100100 (22P02): Error parsing XML: not an XML element, pos 1

Not an XML element, pos 1. It did not get as far as the first character being useful.

And now two root elements in one string.

Query — refused
SELECT PARSE_XML('<a>1</a><b>2</b>') AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
100100 (22P02): Error parsing XML: more than one document in the input

More than one document in the input. One string, one document. Good messages, all three of them, which raises the obvious question.

Is there a CHECK_XML?

JSON had three functions: PARSE_JSON, TRY_PARSE_JSON and CHECK_JSON. Let's find out which of those XML has, starting with the checker.

Query
SELECT CHECK_XML('<a><b>unclosed</a>') AS SHOULD_NOT_GET_THIS_FAR;
Result1 row · 1 column
SHOULD_NOT_GET_THIS_FAR
missing closing tags: </b>, pos 18

It exists, and it hands back the complaint as a string rather than raising. Same message as the error pane above, only now it is a value we can use.

Another leftover heading

The column heading on that grid says SHOULD_NOT_GET_THIS_FAR, which is left over from the first version of the demo script, where every probe was expected to fail. This one does not fail. Read the heading as the author's old guess and the value under it as the answer.

Let's put it over every row of the table, which is the way you would actually use it.

Query
SELECT DOC_ID, WHAT_IT_IS,
       CHECK_XML(RAW_XML)              AS THE_COMPLAINT,
       CHECK_XML(RAW_XML) IS NULL      AS IT_IS_WELL_FORMED,
       LENGTH(RAW_XML)                 AS TEXT_LENGTH
FROM DOCS_XML
ORDER BY DOC_ID;
Result4 rows · 5 columns
DOC_IDWHAT_IT_ISTHE_COMPLAINTIT_IS_WELL_FORMEDTEXT_LENGTH
1two childrenNULLTRUE137
2attributes and textNULLTRUE131
3repeated and empty tagsNULLTRUE106
4not well formedmissing closing tags: </customer>, pos 48FALSE48

One complaint in four documents. IT_IS_WELL_FORMED is TRUE, TRUE, TRUE, FALSE, and the bad row carries its position. Have a look at the last column while you are there: the position the parser gave up at is the whole length of document 4, because the document ends before the tag it was waiting for.

Notice the shape of the answer. CHECK_XML returns NULL when the document is fine. No news is good news, so the test for a good document is IS NULL.

Now let's look for TRY_PARSE_XML

CHECK_XML tells us whether a document is parseable. What we actually want is the one that parses it or gives us a NULL, the way TRY_PARSE_JSON does.

Query — refused
SELECT TRY_PARSE_XML('<a><b>unclosed</a>') AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
002139 (02000): SQL compilation error:
Unknown function TRY_PARSE_XML.

Unknown function TRY_PARSE_XML. It does not exist. So let's try the other way of asking, a TRY_CAST.

Query — refused
SELECT TRY_CAST('<a><b>unclosed</a>' AS XML) AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
002040 (42601): SQL compilation error:
Unsupported data type 'XML'.

Unsupported data type 'XML'. Also no. There is no parse-or-NULL form of this function anywhere.

Let's see the two families side by side, because this is the fact to take away from the post.

Query
SELECT CHECK_JSON('{"a":')                       AS CHECK_JSON_DESCRIBES,
       TRY_PARSE_JSON('{"a":') IS NULL           AS TRY_PARSE_JSON_GIVES_NULL,
       CHECK_XML('<a><b>1</a>')                  AS CHECK_XML_DESCRIBES,
       CHECK_XML('<a><b>1</a>') IS NOT NULL      AS XML_FAULT_IS_DESCRIBABLE,
       CHECK_JSON('{"a":1}') IS NULL             AS GOOD_JSON_IS_QUIET,
       CHECK_XML('<a>1</a>') IS NULL             AS GOOD_XML_IS_QUIET;
Result1 row · 6 columns · scroll →
CHECK_JSON_DESCRIBESTRY_PARSE_JSON_GIVES_NULLCHECK_XML_DESCRIBESXML_FAULT_IS_DESCRIBABLEGOOD_JSON_IS_QUIETGOOD_XML_IS_QUIET
incomplete object value, pos 6TRUEmissing closing tags: </b>, pos 11TRUETRUETRUE

Both checkers describe their fault with a position. Both are quiet on good input. The difference is the middle column: TRY_PARSE_JSON gives a NULL, and XML has no equivalent at all.

What you wantJSONXML
Parse it, raise on bad inputPARSE_JSONPARSE_XML
Parse it, NULL on bad inputTRY_PARSE_JSONnothing
Describe the faultCHECK_JSONCHECK_XML

JSON has three tools and XML has two. The guard in the middle row is yours to write.

Here is what writing it yourself looks like next to the one-expression JSON version.

Query
SELECT TRY_PARSE_JSON('{"a":1}')                                     AS JSON_ONE_EXPRESSION,
       TRY_PARSE_JSON('{"a":')                                        AS JSON_BAD_IS_NULL,
       CASE WHEN CHECK_XML('<a>1</a>') IS NULL
            THEN PARSE_XML('<a>1</a>') END                            AS XML_TWO_EXPRESSIONS,
       CASE WHEN CHECK_XML('<a><b>1</a>') IS NULL
            THEN PARSE_XML('<a><b>1</a>') END                         AS XML_BAD_IS_NULL;
Result1 row · 4 columns
JSON_ONE_EXPRESSIONJSON_BAD_IS_NULLXML_TWO_EXPRESSIONSXML_BAD_IS_NULL
{ "a": 1 }NULL<a>1</a>NULL

One expression on the JSON side, two on the XML side, and the bad input ends as a NULL either way. The XML version has to name the document twice, once in the check and once in the parse.

One warning about CHECK_XML first

Before we build the guard on it, we should find out what CHECK_XML says about input that is not really a document at all.

Query
SELECT CHECK_XML('') IS NULL                   AS EMPTY_CALLED_VALID,
       CHECK_XML('')                           AS EMPTY_COMPLAINT,
       CHECK_XML(NULL::VARCHAR) IS NULL        AS NULL_CALLED_VALID,
       CHECK_XML('   ') IS NULL                AS SPACES_CALLED_VALID,
       CHECK_XML('   ')                        AS SPACES_COMPLAINT,
       CHECK_JSON('') IS NULL                  AS JSON_SAYS_EMPTY_IS_VALID;
Result1 row · 6 columns · scroll →
EMPTY_CALLED_VALIDEMPTY_COMPLAINTNULL_CALLED_VALIDSPACES_CALLED_VALIDSPACES_COMPLAINTJSON_SAYS_EMPTY_IS_VALID
TRUENULLTRUETRUENULLTRUE

An empty string is called valid. A SQL NULL is called valid. A string of spaces is called valid. And the last column says CHECK_JSON does the same thing with an empty string.

Valid is not the same as present

CHECK_XML answers is this well formed, not is there a document here. Those are two different questions and only one of them is being asked. If a blank row has to be a problem in your pipeline, test for it yourself.

Now let's write the guard, and watch where we put it

The guard is CHECK_XML(RAW_XML) IS NULL. The obvious place for it is the WHERE clause, so let's start there.

Query
SELECT DOC_ID, WHAT_IT_IS,
       PARSE_XML(RAW_XML)                                     AS PARSED,
       TYPEOF(PARSE_XML(RAW_XML))                             AS ITS_TYPE
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;
Result3 rows · 4 columns
DOC_IDWHAT_IT_ISPARSEDITS_TYPE
1two children<order id="1001"> <customer>Northwind Traders</customer> <item sku="A-100"> <qty>8</qty> </item> <item sku="B-220"> <qty>4</qty> </item> </order>XML
2attributes and text<order id="1002" status="SHIPPED"> <customer country="USA">Blue Ridge Supply</customer> <item sku="C-310"> <qty>3</qty> </item> </order>XML
3repeated and empty tags<order id="1003"> <customer>Kestrel Analytics</customer> <note></note> <tag>priority</tag> <tag>repeat</tag> </order>XML

Three rows, all parsed, all of type XML. The statement runs now. But look at what we have: the broken document is gone, and nothing on this result says it ever existed.

Now the same guard written as a CASE expression in the select list instead.

Query
SELECT DOC_ID, WHAT_IT_IS,
       CASE WHEN CHECK_XML(RAW_XML) IS NULL THEN PARSE_XML(RAW_XML) END
         AS PARSED_OR_NULL,
       CASE WHEN CHECK_XML(RAW_XML) IS NULL THEN 'parsed'
            ELSE 'REJECTED: ' || CHECK_XML(RAW_XML) END       AS WHAT_HAPPENED
FROM DOCS_XML
ORDER BY DOC_ID;
Result4 rows · 4 columns
DOC_IDWHAT_IT_ISPARSED_OR_NULLWHAT_HAPPENED
1two children<order id="1001"> <customer>Northwind Traders</customer> <item sku="A-100"> <qty>8</qty> </item> <item sku="B-220"> <qty>4</qty> </item> </order>parsed
2attributes and text<order id="1002" status="SHIPPED"> <customer country="USA">Blue Ridge Supply</customer> <item sku="C-310"> <qty>3</qty> </item> </order>parsed
3repeated and empty tags<order id="1003"> <customer>Kestrel Analytics</customer> <note></note> <tag>priority</tag> <tag>repeat</tag> </order>parsed
4not well formedNULLREJECTED: missing closing tags: </customer>, pos 48

Four rows. The broken one is still here, its parsed value is NULL, and the last column carries the reason why. That is the only form that lets you report on what failed.

Let's count the difference rather than eyeball it.

Query
SELECT (SELECT COUNT(*) FROM DOCS_XML)                        AS DOCUMENTS_IN,
       (SELECT COUNT(*) FROM DOCS_XML WHERE CHECK_XML(RAW_XML) IS NULL)
         AS WHERE_FORM_KEEPS,
       (SELECT COUNT(*) FROM DOCS_XML)                        AS CASE_FORM_KEEPS,
       (SELECT COUNT(*) FROM DOCS_XML)
         - (SELECT COUNT(*) FROM DOCS_XML WHERE CHECK_XML(RAW_XML) IS NULL)
         AS WHAT_THE_WHERE_DROPPED;
Result1 row · 4 columns
DOCUMENTS_INWHERE_FORM_KEEPSCASE_FORM_KEEPSWHAT_THE_WHERE_DROPPED
4341

Four documents in. The WHERE form keeps three and the CASE form keeps four, so the WHERE form dropped one. On four rows that is easy to spot. On a load of four million it is a silent shortfall.

The pattern to take away

Write the guard as a CASE, not a WHERE, and keep CHECK_XML's complaint in a column beside it. Then a bad document is a row you can report on rather than a row that was never there.

Let's parse the good ones and read the root tag

With the guard in place we can parse safely. Let's do that and ask what the parsed value actually is.

Query
SELECT DOC_ID, WHAT_IT_IS,
       PARSE_XML(RAW_XML)              AS PARSED,
       TYPEOF(PARSE_XML(RAW_XML))      AS ITS_TYPE,
       PARSE_XML(RAW_XML):"@"::VARCHAR AS THE_ROOT_TAG
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;
Result3 rows · 5 columns
DOC_IDWHAT_IT_ISPARSEDITS_TYPETHE_ROOT_TAG
1two children<order id="1001"> <customer>Northwind Traders</customer> <item sku="A-100"> <qty>8</qty> </item> <item sku="B-220"> <qty>4</qty> </item> </order>XMLorder
2attributes and text<order id="1002" status="SHIPPED"> <customer country="USA">Blue Ridge Supply</customer> <item sku="C-310"> <qty>3</qty> </item> </order>XMLorder
3repeated and empty tags<order id="1003"> <customer>Kestrel Analytics</customer> <note></note> <tag>priority</tag> <tag>repeat</tag> </order>XMLorder

TYPEOF says XML. Not OBJECT, not ARRAY. XML gets its own type name, unlike everything else in this level.

And the last column is the first accessor: :"@" on its own gives the name of the root tag. order, three times.

Now let's reach inside with XMLGET

XMLGET takes a parsed document and the name of a child element. Let's ask for the customer.

Query
SELECT DOC_ID,
       XMLGET(PARSE_XML(RAW_XML), 'customer')                  AS THE_ELEMENT,
       TYPEOF(XMLGET(PARSE_XML(RAW_XML), 'customer'))           AS ELEMENT_TYPE,
       XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"               AS THE_CONTENT,
       XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR      AS AS_TEXT
FROM DOCS_XML
WHERE DOC_ID IN (1, 2)
ORDER BY DOC_ID;
Result2 rows · 5 columns
DOC_IDTHE_ELEMENTELEMENT_TYPETHE_CONTENTAS_TEXT
1<customer>Northwind Traders</customer>XML"Northwind Traders"Northwind Traders
2<customer country="USA">Blue Ridge Supply</customer>XML"Blue Ridge Supply"Blue Ridge Supply

Look carefully at the second column. We did not get Northwind Traders. We got <customer>Northwind Traders</customer>, tags and all, and TYPEOF on it says XML. XMLGET returns an element, not its text.

To get the text inside, add :"$". The third column does that and the fourth casts the result to VARCHAR.

Let's measure the difference, because this is the accessor people leave out.

Query
SELECT XMLGET(PARSE_XML(RAW_XML), 'customer')::VARCHAR          AS ELEMENT_AS_VARCHAR,
       XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR      AS CONTENT_AS_VARCHAR,
       LENGTH(XMLGET(PARSE_XML(RAW_XML), 'customer')::VARCHAR)  AS ELEMENT_LENGTH,
       LENGTH(XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR) AS CONTENT_LENGTH
FROM DOCS_XML
WHERE DOC_ID = 1;
Result1 row · 4 columns
ELEMENT_AS_VARCHARCONTENT_AS_VARCHARELEMENT_LENGTHCONTENT_LENGTH
<customer>Northwind Traders</customer>Northwind Traders3817

The element is thirty-eight characters and the content is seventeen. That is twenty-one characters of tags you would be carrying around in a report column. :"$" is not optional.

Now let's read the attributes

An attribute is :"@" with the name after it, inside the quotes. Let's read the id and the status off the root, the tag name, and one attribute from inside a child.

Query
SELECT DOC_ID,
       PARSE_XML(RAW_XML):"@id"::VARCHAR                         AS THE_ID_ATTRIBUTE,
       PARSE_XML(RAW_XML):"@status"::VARCHAR                      AS THE_STATUS_ATTRIBUTE,
       PARSE_XML(RAW_XML):"@"::VARCHAR                            AS THE_TAG_NAME,
       XMLGET(PARSE_XML(RAW_XML), 'customer'):"@country"::VARCHAR  AS A_NESTED_ATTRIBUTE
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;
Result3 rows · 5 columns
DOC_IDTHE_ID_ATTRIBUTETHE_STATUS_ATTRIBUTETHE_TAG_NAMEA_NESTED_ATTRIBUTE
11001NULLorderNULL
21002SHIPPEDorderUSA
31003NULLorderNULL

Every document has an id, so that column is filled in. Only document 2 has a status, so the other two rows are NULL there. The tag name is order on all three.

The last column is the one to notice. XMLGET(..., 'customer'):"@country" is an attribute on a child element, and it works the same way. Attributes nest.

So there are three accessors, and they do three different jobs.

AccessorWhat it gives you
:"$"The content inside the element
:"@"The name of the element's tag
:"@name"The attribute called name

What happens if we use the wrong accessor?

That table is three things that look very alike, so the next question is what Snowflake does when we pick the wrong one. Let's ask for an attribute as if it were a child, and a child as if it were an attribute.

Query
SELECT PARSE_XML(RAW_XML):"@id"::VARCHAR                 AS ATTRIBUTE_CORRECTLY,
       XMLGET(PARSE_XML(RAW_XML), 'id')                  AS ATTRIBUTE_AS_A_CHILD,
       XMLGET(PARSE_XML(RAW_XML), 'id') IS NULL          AS THAT_IS_NULL,
       PARSE_XML(RAW_XML):"@customer"::VARCHAR           AS CHILD_AS_AN_ATTRIBUTE,
       PARSE_XML(RAW_XML):"@customer" IS NULL            AS THAT_IS_NULL_TOO
FROM DOCS_XML
WHERE DOC_ID = 2;
Result1 row · 5 columns
ATTRIBUTE_CORRECTLYATTRIBUTE_AS_A_CHILDTHAT_IS_NULLCHILD_AS_AN_ATTRIBUTETHAT_IS_NULL_TOO
1002NULLTRUENULLTRUE

The first column reads the id correctly. Then XMLGET(..., 'id') looks for a child element called id, and there is no such child, so it is NULL. And :"@customer" looks for an attribute called customer, and there is no such attribute, so that is NULL too.

No error either time. Let's count it over all three good documents, so the scale of it is clear.

Query
SELECT COUNT(*)                                       AS GOOD_DOCUMENTS,
       COUNT(PARSE_XML(RAW_XML):"@id")                AS ID_AS_ATTRIBUTE,
       COUNT(XMLGET(PARSE_XML(RAW_XML), 'id'))        AS ID_AS_CHILD,
       COUNT(XMLGET(PARSE_XML(RAW_XML), 'customer'))  AS CUSTOMER_AS_CHILD,
       COUNT(PARSE_XML(RAW_XML):"@customer")          AS CUSTOMER_AS_ATTRIBUTE
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL;
Result1 row · 5 columns
GOOD_DOCUMENTSID_AS_ATTRIBUTEID_AS_CHILDCUSTOMER_AS_CHILDCUSTOMER_AS_ATTRIBUTE
33030

The id as an attribute is found on all three. The id as a child is found on none of them. The customer as a child is found on all three, and as an attribute on none.

NULL is not the same as wrong

Those two zero columns are the Level 8 problem one last time. A wrong accessor gives you NULL on every row, and a NULL on every row looks exactly like a column that was never populated. That is the same silent failure as the capital letter in Episode 88.

Now the one that will actually bite you: no index means index 0

Document 1 has two item elements in it, with the same tag name. Let's ask for the item, singular, the way you would write it without thinking.

Query
SELECT DOC_ID,
       XMLGET(PARSE_XML(RAW_XML), 'item')                       AS FIRST_ITEM,
       XMLGET(PARSE_XML(RAW_XML), 'item'):"@sku"::VARCHAR       AS ITS_SKU,
       XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item'), 'qty'):"$"::VARCHAR AS ITS_QTY
FROM DOCS_XML
WHERE DOC_ID = 1;
Result1 row · 4 columns
DOC_IDFIRST_ITEMITS_SKUITS_QTY
1<item sku="A-100"> <qty>8</qty> </item>A-1008

We got one of them: sku A-100, quantity 8. Which one is that, and where did the other one go?

XMLGET has a third argument, an index. Let's use it.

Query
SELECT XMLGET(PARSE_XML(RAW_XML), 'item', 0):"@sku"::VARCHAR    AS ITEM_0_SKU,
       XMLGET(PARSE_XML(RAW_XML), 'item', 1):"@sku"::VARCHAR    AS ITEM_1_SKU,
       XMLGET(PARSE_XML(RAW_XML), 'item', 2):"@sku"::VARCHAR    AS ITEM_2_PAST_THE_END,
       XMLGET(PARSE_XML(RAW_XML), 'item', 2) IS NULL            AS PAST_THE_END_IS_NULL,
       XMLGET(PARSE_XML(RAW_XML), 'item', 0):"@sku"
         = XMLGET(PARSE_XML(RAW_XML), 'item'):"@sku"            AS NO_INDEX_MEANS_ZERO
FROM DOCS_XML
WHERE DOC_ID = 1;
Result1 row · 5 columns
ITEM_0_SKUITEM_1_SKUITEM_2_PAST_THE_ENDPAST_THE_END_IS_NULLNO_INDEX_MEANS_ZERO
A-100B-220NULLTRUETRUE

Index 0 is A-100 and index 1 is B-220. Index 2 is past the end, and it is NULL rather than an error. The last column answers the question we just asked: with no index at all we get the same value as index 0.

Now let's total the quantities on that document, written the obvious way, and put the right answer beside it.

Query
SELECT DOC_ID,
       XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 0), 'qty'):"$"::INT AS QTY_0,
       XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 1), 'qty'):"$"::INT AS QTY_1,
       XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item'), 'qty'):"$"::INT    AS WHAT_NO_INDEX_GIVES,
       COALESCE(XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 0), 'qty'):"$"::INT, 0)
         + COALESCE(XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 1), 'qty'):"$"::INT, 0)
         AS THE_REAL_TOTAL
FROM DOCS_XML
WHERE DOC_ID = 1;
Result1 row · 5 columns
DOC_IDQTY_0QTY_1WHAT_NO_INDEX_GIVESTHE_REAL_TOTAL
184812

Quantity at index 0 is 8 and at index 1 is 4. Written with no index the answer is 8, and the real total is 12.

8 where the answer is 12, with no error and nothing missing from the output. The second item is not wrong, it is simply not in the expression. That is the same shape as the silently doubled total in Episode 91, running in the other direction.

When to stop using XMLGET

If a tag can repeat, XMLGET on its own will read the first one and tell you nothing about the rest. Use FLATTEN to get them all as rows, which we do further down this page, and keep XMLGET for the tags you know appear once.

And the other half: an empty element is not a missing one

Document 3 has an empty note tag and a tag element that appears twice. Let's look at the empty one.

Query
SELECT XMLGET(PARSE_XML(RAW_XML), 'note')                       AS THE_EMPTY_ELEMENT,
       XMLGET(PARSE_XML(RAW_XML), 'note') IS NULL               AS EMPTY_ELEMENT_IS_NULL,
       XMLGET(PARSE_XML(RAW_XML), 'note'):"$"                   AS ITS_CONTENT,
       XMLGET(PARSE_XML(RAW_XML), 'note'):"$" IS NULL           AS CONTENT_IS_NULL,
       XMLGET(PARSE_XML(RAW_XML), 'tag', 0):"$"::VARCHAR        AS TAG_0,
       XMLGET(PARSE_XML(RAW_XML), 'tag', 1):"$"::VARCHAR        AS TAG_1
FROM DOCS_XML
WHERE DOC_ID = 3;
Result1 row · 6 columns · scroll →
THE_EMPTY_ELEMENTEMPTY_ELEMENT_IS_NULLITS_CONTENTCONTENT_IS_NULLTAG_0TAG_1
<note></note>FALSE""FALSEpriorityrepeat

The element came back as <note></note> and EMPTY_ELEMENT_IS_NULL is FALSE. Its content is an empty string, printed as two quote characters, and that is not NULL either.

Now let's put that next to a tag that is not in the document at all.

Query
SELECT XMLGET(PARSE_XML(RAW_XML), 'note') IS NOT NULL         AS NOTE_EXISTS,
       XMLGET(PARSE_XML(RAW_XML), 'note'):"$" IS NULL         AS NOTE_HAS_NO_CONTENT,
       XMLGET(PARSE_XML(RAW_XML), 'nothing') IS NULL          AS NOTHING_DOES_NOT_EXIST,
       XMLGET(PARSE_XML(RAW_XML), 'nothing'):"$" IS NULL      AS AND_HAS_NO_CONTENT
FROM DOCS_XML
WHERE DOC_ID = 3;
Result1 row · 4 columns
NOTE_EXISTSNOTE_HAS_NO_CONTENTNOTHING_DOES_NOT_EXISTAND_HAS_NO_CONTENT
TRUEFALSETRUETRUE

The note exists and has content that is not NULL. The tag called nothing does not exist, and both its columns are NULL. Present-but-empty and absent are two different states, and IS NULL is how you tell them apart.

Over all three good documents it looks like this.

Query
SELECT DOC_ID,
       XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR   AS CUSTOMER_,
       XMLGET(PARSE_XML(RAW_XML), 'note')                    AS NOTE_,
       XMLGET(PARSE_XML(RAW_XML), 'never_existed')           AS ABSENT_,
       XMLGET(PARSE_XML(RAW_XML), 'never_existed') IS NULL   AS ABSENT_IS_NULL
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;
Result3 rows · 5 columns
DOC_IDCUSTOMER_NOTE_ABSENT_ABSENT_IS_NULL
1Northwind TradersNULLNULLTRUE
2Blue Ridge SupplyNULLNULLTRUE
3Kestrel Analytics<note></note>NULLTRUE

The customer is on every document. The note is on document 3 only, and on the other two it is NULL, because there is no such element there at all. The tag that never existed is NULL everywhere.

What the grid is showing you

Look at how those two states are printed, because they are easy to read past. The note's content is the two characters "", which is how Snowflake prints an empty string sitting inside a document. The absent element is the grey NULL the grids on this page use for a real SQL NULL. One is a value and the other is the absence of one.

Let's flatten the children into rows

FLATTEN works on XML too, and it is the answer to the repeated tag. The input is the content of the document, which is :"$".

Query
SELECT D.DOC_ID,
       F.INDEX                            AS CHILD_INDEX,
       F.VALUE:"@"::VARCHAR               AS TAG_NAME,
       F.VALUE:"$"                        AS ITS_CONTENT
FROM DOCS_XML D,
     LATERAL FLATTEN(INPUT => PARSE_XML(D.RAW_XML):"$") F
WHERE D.DOC_ID = 1
ORDER BY F.INDEX;
Result3 rows · 4 columns
DOC_IDCHILD_INDEXTAG_NAMEITS_CONTENT
10customer"Northwind Traders"
11item<qty>8</qty>
12item<qty>4</qty>

One row per child, in document order. Index 0 is the customer, and index 1 and index 2 are the two items we lost earlier. The tag name of each one comes from :"@" on the flattened value, which means we can group by it.

Let's do that over every good document.

Query
SELECT D.DOC_ID, D.WHAT_IT_IS,
       COUNT(*)                          AS CHILDREN,
       ARRAY_AGG(F.VALUE:"@"::VARCHAR)   AS TAG_NAMES
FROM DOCS_XML D,
     LATERAL FLATTEN(INPUT => PARSE_XML(D.RAW_XML):"$") F
WHERE CHECK_XML(D.RAW_XML) IS NULL
GROUP BY D.DOC_ID, D.WHAT_IT_IS
ORDER BY D.DOC_ID;
Result3 rows · 4 columns
DOC_IDWHAT_IT_ISCHILDRENTAG_NAMES
1two children3[ "customer", "item", "item" ]
2attributes and text2[ "customer", "item" ]
3repeated and empty tags4[ "customer", "note", "tag", "tag" ]

Three children on document 1, two on document 2 and four on document 3, with the tag names collected into an array beside them. Document 3's array shows the empty note sitting between the customer and the two tags.

And let's account for every row before we move on.

Query
SELECT (SELECT COUNT(*) FROM DOCS_XML)                              AS DOCUMENTS_IN,
       (SELECT COUNT(*) FROM DOCS_XML WHERE CHECK_XML(RAW_XML) IS NULL)
         AS SURVIVED_THE_GUARD,
       COUNT(DISTINCT D.DOC_ID)                                     AS SURVIVED_THE_FLATTEN,
       COUNT(*)                                                     AS CHILD_ROWS
FROM DOCS_XML D,
     LATERAL FLATTEN(INPUT => PARSE_XML(D.RAW_XML):"$") F
WHERE CHECK_XML(D.RAW_XML) IS NULL;
Result1 row · 4 columns
DOCUMENTS_INSURVIVED_THE_GUARDSURVIVED_THE_FLATTENCHILD_ROWS
4339

Four documents in, three survived the guard, three survived the flatten, and nine child rows came out. Nothing unexplained.

Now let's load it properly, keeping the bad row

This is the shape we loaded JSON in, back in Episode 87: the raw text, the parsed document, the complaint, and a flag. Let's build the table.

CREATE TABLE AS SELECT
CREATE OR REPLACE TABLE XML_LOADED AS
SELECT DOC_ID,
       WHAT_IT_IS,
       RAW_XML,
       CASE WHEN CHECK_XML(RAW_XML) IS NULL THEN PARSE_XML(RAW_XML) END AS DOC,
       CHECK_XML(RAW_XML)                                              AS PARSE_COMPLAINT,
       CHECK_XML(RAW_XML) IS NULL                                      AS IS_WELL_FORMED
FROM DOCS_XML;
Result1 row · 1 column
status
Table XML_LOADED successfully created.

The CASE guard is doing the work there, which is why the broken document can come along. Let's read it back.

Query
SELECT DOC_ID, WHAT_IT_IS, IS_WELL_FORMED, PARSE_COMPLAINT,
       TYPEOF(DOC) AS DOC_TYPE,
       XMLGET(DOC, 'customer'):"$"::VARCHAR AS CUSTOMER_
FROM XML_LOADED
ORDER BY DOC_ID;
Result4 rows · 6 columns · scroll →
DOC_IDWHAT_IT_ISIS_WELL_FORMEDPARSE_COMPLAINTDOC_TYPECUSTOMER_
1two childrenTRUENULLXMLNorthwind Traders
2attributes and textTRUENULLXMLBlue Ridge Supply
3repeated and empty tagsTRUENULLXMLKestrel Analytics
4not well formedFALSEmissing closing tags: </customer>, pos 48NULLNULL

Four rows. Three parsed, with DOC_TYPE of XML and the customer read straight out of them. One with a NULL document and the reason it is NULL in the column beside it.

That last row is the whole argument for the CASE form. It is a row somebody can go and fix.

Query
SELECT (SELECT COUNT(*) FROM DOCS_XML)                         AS ROWS_IN,
       (SELECT COUNT(*) FROM XML_LOADED)                       AS ROWS_OUT,
       (SELECT COUNT_IF(IS_WELL_FORMED) FROM XML_LOADED)       AS GOOD_ROWS,
       (SELECT COUNT_IF(NOT IS_WELL_FORMED) FROM XML_LOADED)   AS BAD_ROWS,
       (SELECT COUNT(*) FROM DOCS_XML)
         = (SELECT COUNT(*) FROM XML_LOADED)                   AS NOTHING_LOST;
Result1 row · 5 columns
ROWS_INROWS_OUTGOOD_ROWSBAD_ROWSNOTHING_LOST
4431TRUE

Four in, four out, three good, one bad, and NOTHING_LOST is TRUE.

So how does XML compare with JSON?

We have met both now, so let's put the same data in both shapes side by side.

Query
SELECT PARSE_XML('<order id="1"><customer>Northwind</customer></order>')
         AS AS_XML,
       PARSE_JSON('{"id":1,"customer":"Northwind"}')
         AS AS_JSON,
       TYPEOF(PARSE_XML('<order id="1"><customer>Northwind</customer></order>'))
         AS XML_TYPE,
       TYPEOF(PARSE_JSON('{"id":1,"customer":"Northwind"}'))
         AS JSON_TYPE,
       XMLGET(PARSE_XML('<order id="1"><customer>Northwind</customer></order>'),
              'customer'):"$"::VARCHAR                        AS XML_READ,
       PARSE_JSON('{"id":1,"customer":"Northwind"}'):customer::VARCHAR AS JSON_READ;
Result1 row · 6 columns · scroll →
AS_XMLAS_JSONXML_TYPEJSON_TYPEXML_READJSON_READ
<order id="1"> <customer>Northwind</customer> </order>{ "customer": "Northwind", "id": 1 }XMLOBJECTNorthwindNorthwind

Two different types, XML and OBJECT. Both read back Northwind. The XML side needed XMLGET and a :"$" to get there, and the JSON side needed a colon and the key name.

And a few differences worth having in one place.

Query
SELECT PARSE_XML('<a>1</a>') IS NULL                 AS XML_BAD_GIVES_NULL_NOT_ERROR,
       TYPEOF(PARSE_XML('<a>1</a>'))                 AS XML_IS_ALWAYS_ONE_TYPE,
       XMLGET(PARSE_XML('<a><b>1</b></a>'), 'b'):"$"::INT AS XML_NEEDS_A_DOLLAR,
       PARSE_JSON('{"b":1}'):b::INT                  AS JSON_DOES_NOT,
       TYPEOF(PARSE_JSON('{"b":1}'):b)               AS JSON_REMEMBERS_THE_TYPE,
       TYPEOF(XMLGET(PARSE_XML('<a><b>1</b></a>'), 'b'):"$") AS XML_CONTENT_TYPE;
Result1 row · 6 columns · scroll →
XML_BAD_GIVES_NULL_NOT_ERRORXML_IS_ALWAYS_ONE_TYPEXML_NEEDS_A_DOLLARJSON_DOES_NOTJSON_REMEMBERS_THE_TYPEXML_CONTENT_TYPE
FALSEXML11INTEGERINTEGER

Reading across: XML is always one type, XML, where a parsed JSON value takes the type of what it holds. Getting a number out of XML needs the :"$" and out of JSON does not. And on this example both report the content as an INTEGER.

The last leftover heading

The first column of that grid is headed XML_BAD_GIVES_NULL_NOT_ERROR and it is FALSE, which is the third leftover from the first version of the script. The document in that expression is <a>1</a>, which is perfectly well formed, so all the FALSE means is that a good document does not parse to NULL. For what a bad one does, the error panes near the top of this page are the answer.

One last thing: what Level 8 leaves behind

That closes Level 8. Let's count the tables it built, because every one of them turns up again later in the course.

Query
SELECT (SELECT COUNT(*) FROM EVENTS_JSON)   AS EVENTS_JSON,
       (SELECT COUNT(*) FROM JSON_TEXT_RAW) AS JSON_TEXT_RAW,
       (SELECT COUNT(*) FROM DOCS_XML)      AS DOCS_XML,
       (SELECT COUNT(*) FROM TYPED_SHAPES)  AS TYPED_SHAPES;
Result1 row · 4 columns
EVENTS_JSONJSON_TEXT_RAWDOCS_XMLTYPED_SHAPES
41142

The JSON documents from Episode 86 onwards, the raw text table the validator ran over, these four XML documents, and the typed shapes from Episode 95.

And with the loaded XML table added, which we built two sections ago.

Query
SELECT (SELECT COUNT(*) FROM EVENTS_JSON)   AS EVENTS_JSON,
       (SELECT COUNT(*) FROM JSON_TEXT_RAW) AS JSON_TEXT_RAW,
       (SELECT COUNT(*) FROM DOCS_XML)      AS DOCS_XML,
       (SELECT COUNT(*) FROM XML_LOADED)    AS XML_LOADED,
       (SELECT COUNT(*) FROM TYPED_SHAPES)  AS TYPED_SHAPES;
Result1 row · 5 columns
EVENTS_JSONJSON_TEXT_RAWDOCS_XMLXML_LOADEDTYPED_SHAPES
411442

That is semi-structured data, from VARIANT to XML, in eleven posts.

Key points

  • PARSE_XML raises on a malformed document. It does not return NULL. One bad row in the column and the whole statement returns nothing.
  • It refuses three things with three clear messages: an unclosed tag, text with no root element, and two roots in one string.
  • CHECK_XML exists and TRY_PARSE_XML does not, and neither does TRY_CAST(... AS XML). JSON has three tools and XML has two.
  • CHECK_XML returns NULL when the document is fine, so the test for a good document is IS NULL.
  • It calls an empty string, a SQL NULL and a string of spaces all valid. It means well formed, not present.
  • Write the guard as a CASE, not a WHERE. The WHERE form silently deletes the document you most need to report on.
  • TYPEOF of a parsed document is XML, which is its own type.
  • XMLGET returns the whole element, tags included. :"$" is the content, :"@" is the tag name, and :"@name" is an attribute.
  • Use the wrong accessor and you get NULL on every row, which looks exactly like missing data.
  • XMLGET with no index means index 0. On a repeated tag your total is quietly short and nothing says so. Use FLATTEN instead.
  • An empty element is present: XMLGET returns it and its content is an empty string. An absent element is NULL. Those are different states.
  • FLATTEN over :"$" gives one row per child, with :"@" as the tag name, so you can group XML the way you group JSON.
Next in this series

Episode 97 — data types, and which of their names are lies. That is Level 9, which is DDL: building the things our queries have been running against for ninety-six posts.

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, and that includes the seven refusals. Three column and capture headings on this page date from an earlier version of the demo script, written before the author found out that PARSE_XML raises rather than returning NULL, and the page says so at each one rather than letting the heading stand. The DOCS_XML documents are invented demo data and the fourth one is malformed on purpose. Every count in the text above is read off one of the grids on this page. Nothing is timed and no performance claims are made anywhere in this series. Function behaviour follows the Snowflake PARSE_XML documentation.

No comments:

Post a Comment

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