Study FAQ
How do I query nested VARIANT arrays in Snowflake without losing track of rows or invalid values?
Also asked as 2
- How can I use LATERAL FLATTEN while handling missing array items and invalid JSON fields?
- How should I track parent and child rows and failed casts when flattening Snowflake VARIANT?
Answer
Use path notation to read scalar values in Snowflake VARIANT, and LATERAL FLATTEN when you need a row per element of an array or object. Decide first whether the result should be at parent or child grain. Each emitted child row repeats its parent, and an input with no expansion normally emits no row.
SELECT
e.event_id,
e.event_payload:customer:id::VARCHAR AS customer_id,
item.index AS item_position,
item.value:sku::VARCHAR AS sku,
item.value:quantity AS raw_quantity,
TRY_TO_DECIMAL(item.value:quantity::VARCHAR, 18, 3) AS quantity
FROM analytics.raw.events AS e,
LATERAL FLATTEN(INPUT => e.event_payload:items, OUTER => TRUE) AS item;
The example assumes the JSON uses these case-sensitive keys and the intended quantity is NUMBER(18,3). Choose precision and scale to fit the contract. OUTER => TRUE emits one row for a zero-row expansion with NULL expansion columns. Test the difference between an empty array, a missing path, a JSON null, and a wrong input type if those states have different business meanings.
A failed tolerant conversion produces SQL NULL. Keep the raw field or a quality flag so malformed values do not disappear into the same bucket as missing values. Compare parent counts and emitted child counts before and after flattening. Keep a stable parent key and use the array index only when position is meaningful.
Query semi-structured data · FLATTEN · TRY_TO_DECIMAL and scale
Full explanation
Working with Structured, Semi-structured, and Unstructured Data
Study guide · COF-C03
Read the full explanation