In two sentences
APIs, webhooks and event streams send nested documents: an order with a list of lines inside it. To analyse them
you extract fields with JSON functions and turn each list into rows with UNNEST, one row per element, keeping
the parent's columns on each.
See it
Two webhooks:
{"order": {"id": 7, "customer": "c1"}, "amount": 30.5, "lines": [{"sku": "A", "qty": 2}, {"sku": "B", "qty": 1}]}
{"order": {"id": 8, "customer": "c2"}, "total_amount": "12", "lines": []}One row per order line:
| order_id | line_no | sku | qty |
|---|---|---|---|
| 7 | 1 | A | 2 |
| 7 | 2 | B | 1 |
Order 8 has no lines, so CROSS JOIN UNNEST drops it. LEFT JOIN UNNEST … ON true keeps it with NULLs. Its
amount also moved: total_amount, as a string. That's schema drift.
In SQL
Scalar fields, with a path:
SELECT CAST(json_extract_scalar(payload, '$.order.id') AS integer) AS order_id,
json_extract_scalar(payload, '$.order.customer') AS customer_id,
try_cast(coalesce(json_extract_scalar(payload, '$.amount'),
json_extract_scalar(payload, '$.total_amount')) AS decimal(10, 2)) AS amount
FROM webhooks;coalesce absorbs the renamed field; try_cast turns a value that isn't a number into NULL instead of failing the
whole query.
The list, as rows: cast the JSON array to an array of rows, then unnest it.
SELECT CAST(json_extract_scalar(w.payload, '$.order.id') AS integer) AS order_id,
l.line_no, l.sku, l.qty
FROM webhooks w
CROSS JOIN UNNEST(
CAST(json_extract(w.payload, '$.lines') AS array(row(sku varchar, qty integer)))
) WITH ORDINALITY AS l(sku, qty, line_no);WITH ORDINALITY adds each element's position, often the only line number the source has.
To keep parents with empty lists:
LEFT JOIN UNNEST(CAST(json_extract(w.payload, '$.lines') AS array(row(sku varchar, qty integer)))) AS l(sku, qty)
ON trueWhen to use it
| situation | approach |
|---|---|
| landing raw events | keep the raw JSON as it arrived, untouched |
| the cleaned layer | extract the fields people use into typed columns; lists into child tables |
| fields rename or appear over time | coalesce the known names; alert on unknown ones |
| a value sometimes isn't the type you expect | try_cast, and count the NULLs it produced |
| lists | one child table per list, keyed by parent id + position |
Best practices
- Keep the raw payload next to the extracted columns, or in landing. When a field turns out to matter later, you can backfill it.
- Flatten once, in the cleaned layer, not in every report with its own JSON paths.
- Count what
try_castturned into NULL. Silent NULLs are how drift goes unnoticed for weeks. - Test the row counts: lines after unnesting should equal the sum of the arrays' lengths
(
json_array_length).
Common mistakes
CROSS JOIN UNNESTlosing parents. An order with an empty or missing list disappears, and so does its amount from every total. UseLEFT JOIN UNNEST … ON truewhen the parent must stay.- Summing a parent amount after unnesting. Order 7 now has two rows; summing
amountdoubles it. It's fan-out again (see Joins and fan-out). json_extractvsjson_extract_scalar. The first returns a JSON value, so a string keeps its quotes ("c1"); the second returns the varcharc1. Usejson_extract_scalarfor anything you compare, join or group on.- Casting strings that are numbers in one payload and text in another with
CAST: one bad value fails the whole run.try_cast, then check.
What an interviewer asks next
- "A partner renamed a field last week. How would you have noticed?" A test on the share of NULLs in the extracted column, or on unknown keys in the payload.
- "Store JSON or columns?" Both: raw JSON in landing for safety, typed columns in the cleaned layer for everyone.
Go further
Trino's JSON page covers the functions and the casts from JSON to arrays, maps and rows used above.
Practise it
Flatten Nested Order Webhooks and Allocate Discounts to Lines, then Explode and Pivot IoT Sensor Payloads, then Absorb Schema Drift in a Partner's Event Feed.