Querying JSON Objects & Arrays (->, ->>, #>, @>, jsonb_each, jsonb_array_elements)
Extract and unnest JSON fields with operators and set-returning functions.
In plain words
Arrows pick fields out of JSON, and special functions turn lists inside JSON into rows you can count and sum.
Think of it like…
A filing cabinet of folders: -> opens a drawer and gives you the folder, ->> reads the label on the folder as plain text, and jsonb_array_elements tips a folder's sheets out onto the desk so you can count them.
Where you’ve seen it
A payments provider's webhooks are stored in events(payload jsonb). Revenue per product: SELECT item->>'sku' AS sku, SUM((item->>'quantity')::int * (item->>'unit_price')::numeric) AS revenue FROM events e CROSS JOIN LATERAL jsonb_array_elements(e.payload->'line_items') AS item WHERE e.payload->>'type' = 'payment.succeeded' GROUP BY 1 ORDER BY 2 DESC;
Words you’ll hear
- -> / ->>
- Get a field as jsonb / as text: payload->'customer' vs payload->>'email'.
- #> / #>>
- Follow a path: payload #>> '{shipping,city}'.
- jsonb_array_elements
- Expands a JSON array into one row per element.
- jsonb_each / jsonb_to_recordset
- Object to key-value rows / array of objects to typed columns.
Visual diagram
Theory & example queries
Picking values out
payload->'customer' returns the customer object as jsonb, which you can keep navigating: payload->'customer'->>'email'. ->> returns text, so numbers and booleans must be cast: (payload->>'amount')::numeric. Array elements are addressed by zero-based index: payload->'line_items'->0. For deep paths, payload #>> '{shipping,address,city}' is shorter than a chain of arrows.
Missing keys return NULL rather than an error, which is convenient but hides typos, so compare counts of non-NULL values when exploring. ? tests whether a key exists, and @> tests containment: payload @> '{"type": "payment.succeeded"}'. For complex conditions, jsonpath (PostgreSQL 12+) with @? and jsonb_path_query filters inside arrays, such as payload @? '$.line_items[*] ? (@.quantity > 5)'.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
SELECT payload ->> 'id' AS event_id, payload -> 'customer' ->> 'email' AS email, payload #>> '{shipping,city}' AS city, (payload ->> 'amount')::numeric / 100 AS amountFROM eventsWHERE payload ->> 'type' = 'payment.succeeded';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative payment events2 sample rows
| event_id | city | amount | |
|---|---|---|---|
| evt_1042 | asha@example.com | Pune | 249.99 |
| evt_1048 | ravi@example.com | Bengaluru | 1200 |
Note: The sample assumes the payloads are payment.succeeded events with customer, shipping.city and minor-unit amount fields. Missing keys would produce NULL and a nonnumeric amount would make the cast fail.
Key takeaway: -> keeps jsonb, ->> gives text; cast before comparing numbers.
Turning arrays and objects into rows
Set-returning functions in FROM with LATERAL expand each document: CROSS JOIN LATERAL jsonb_array_elements(payload->'line_items') AS item produces a row per line item, and WITH ORDINALITY adds the position. CROSS JOIN drops events with empty or missing arrays; use LEFT JOIN LATERAL … ON true to keep them. jsonb_each(payload->'metadata') gives key and value rows for free-form objects.
When array elements share a shape, jsonb_to_recordset(payload->'line_items') AS li(sku text, quantity int, unit_price numeric) returns typed columns directly, with no casts. PostgreSQL 17's JSON_TABLE does the same with standard syntax, and MySQL 8.0 has JSON_TABLE too, with -> and ->> operators that take paths like '$.customer.email'.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
SELECT e.payload ->> 'id' AS event_id, li.*FROM events e CROSS JOIN LATERAL jsonb_to_recordset(e.payload -> 'line_items') AS li ( sku text, quantity int, unit_price numeric );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative line-item rows3 sample rows
| event_id | sku | quantity | unit_price |
|---|---|---|---|
| evt_1042 | SKU-41 | 2 | 99.99 |
| evt_1042 | SKU-56 | 1 | 50.01 |
| evt_1048 | SKU-41 | 4 | 300 |
Note: The sample assumes each event has a line_items JSON array matching the declared record fields. Invalid numeric JSON would fail conversion to int or numeric.
Key takeaway: LATERAL + jsonb_array_elements or jsonb_to_recordset turns arrays into rows.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Explore the shape
Look at a few documents and list their keys with jsonb_object_keys to see what's present.
SELECT DISTINCT jsonb_object_keys(payload)FROM eventsWhen to use it & trade-offs
What it is
PostgreSQL's JSON operators pull values out of jsonb documents: -> returns a jsonb value, ->> returns text, #> and #>> follow a path such as '{shipping,city}', and @> tests containment. To turn nested data into rows, set-returning functions expand it: jsonb_array_elements gives one row per array element, jsonb_each one row per key, and jsonb_to_recordset turns an array of objects into typed columns. PostgreSQL 17 adds the standard JSON_TABLE.
Why it matters: Webhooks, event payloads and API responses arrive as JSON, and analysts need to report on the line items, tags and nested fields inside them. Knowing which operator returns text, how to unnest arrays with LATERAL, and how to cast values safely is the difference between a quick query and an afternoon of string parsing.
When to reach for it
- Reporting on webhook and event payloads
- Line items, tags and attributes stored as JSON
- Exploring API responses loaded into a table
When to avoid or be careful
- Comparing ->> results with numbers without casting
- CROSS JOIN LATERAL when documents without the array must stay
- Parsing JSON with string functions like substring
Ways to read nested JSON in SQL
Strengths: Short; works in filters and SELECT.
Watch out: Text results need casts; missing keys become silent NULLs.
Strengths: Turns nested data into rows for aggregation.
Watch out: Element fields still need ->> and casts.
Strengths: Typed columns in one step; JSON_TABLE is standard.
Watch out: JSON_TABLE needs PostgreSQL 17+ or MySQL 8.0+.
Interview signals & numbers to know
When this topic comes up
- “Sum the line items inside each webhook”
- “Extract the customer email from the payload”
- “Count events that have a given tag”
- jsonb operators
- Unnesting arrays
Benchmarks & rules of thumb
- 0
- index of the first JSON array element
- PostgreSQL 17
- JSON_TABLE support
- PostgreSQL 12
- jsonpath (@?, jsonb_path_query)
Common mistakes & follow-ups
Common interview mistakes
- Writing payload->'amount' > 100, comparing jsonb with a number, instead of (payload->>'amount')::numeric > 100.
- Using CROSS JOIN LATERAL jsonb_array_elements and silently losing orders with no line items from the order count.
- Mistyping a key ('emial') and getting NULL for every row without any error.
Likely interviewer follow-ups
- What's the difference between -> and ->>?
- How do you turn an array inside a JSON column into rows?
- How would you keep documents whose array is empty?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Querying JSON Objects & Arrays (->, ->>, #>, @>, jsonb_each, jsonb_array_elements) with hands-on SQL practice and interview Q&A.