shuffleet
Home
Practice
Problems
Lessons
Plans
Compete
Challenges
Interviews
Leaderboard
Progress
Skills
Analytics
Submissions
Account
Settings

Nested data: JSON and UNNEST

Intermediate · 4 min read

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:

json
{"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_idline_noskuqty
71A2
72B1

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.

A JSON document with a nested list becomes one row per element; an empty list disappears with CROSS JOIN and stays with LEFT JOIN

In SQL

Scalar fields, with a path:

SQL
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.

SQL
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:

SQL
LEFT JOIN UNNEST(CAST(json_extract(w.payload, '$.lines') AS array(row(sku varchar, qty integer)))) AS l(sku, qty)
  ON true

When to use it

situationapproach
landing raw eventskeep the raw JSON as it arrived, untouched
the cleaned layerextract the fields people use into typed columns; lists into child tables
fields rename or appear over timecoalesce the known names; alert on unknown ones
a value sometimes isn't the type you expecttry_cast, and count the NULLs it produced
listsone 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_cast turned 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 UNNEST losing parents. An order with an empty or missing list disappears, and so does its amount from every total. Use LEFT JOIN UNNEST … ON true when the parent must stay.
  • Summing a parent amount after unnesting. Order 7 now has two rows; summing amount doubles it. It's fan-out again (see Joins and fan-out).
  • json_extract vs json_extract_scalar. The first returns a JSON value, so a string keeps its quotes ("c1"); the second returns the varchar c1. Use json_extract_scalar for 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.