Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 114/ 160
06. Database Design, Normalization & Semi-Structured SQL

Querying JSON Objects & Arrays (->, ->>, #>, @>, jsonb_each, jsonb_array_elements)

Extract and unnest JSON fields with operators and set-returning functions.

Advanced-> / ->> · jsonb_each3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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)'.

Fields from nested objectsQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  payload ->> 'id' AS event_id,3  payload -> 'customer' ->> 'email' AS email,4  payload #>> '{shipping,city}' AS city,5  (payload ->> 'amount')::numeric / 100 AS amount6FROM7  events8WHERE9  payload ->> 'type' = 'payment.succeeded';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative payment events2 sample rows
Representative payment events
event_idemailcityamount
evt_1042asha@example.comPune249.99
evt_1048ravi@example.comBengaluru1200

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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

Typed line itemsQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  e.payload ->> 'id' AS event_id,3  li.*4FROM5  events e6  CROSS JOIN LATERAL jsonb_to_recordset(e.payload -> 'line_items') AS li (7    sku text,8    quantity int,9    unit_price numeric10  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative line-item rows3 sample rows
Representative line-item rows
event_idskuquantityunit_price
evt_1042SKU-41299.99
evt_1042SKU-56150.01
evt_1048SKU-414300

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: LATERAL + jsonb_array_elements or jsonb_to_recordset turns arrays into rows.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Inspect

Explore the shape

Look at a few documents and list their keys with jsonb_object_keys to see what's present.

SQL at this step
1SELECT DISTINCT2  jsonb_object_keys(payload)3FROM4  events
What to watch at this step
Keys
vary by event
Tip: use ← → to move between steps

When 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

-> / ->> / #>> operators
Best for: A few scalar fields per document

Strengths: Short; works in filters and SELECT.

Watch out: Text results need casts; missing keys become silent NULLs.

jsonb_array_elements / jsonb_each with LATERAL
Best for: Arrays and free-form objects

Strengths: Turns nested data into rows for aggregation.

Watch out: Element fields still need ->> and casts.

jsonb_to_recordset / JSON_TABLE
Best for: Arrays of objects with a known shape

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?
Interview tip: Write one query that extracts a scalar with ->> and a cast, and unnests an array with LATERAL. Those two moves cover most JSON interview questions.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Working with JSON & JSONB Data Types
Next topic
Indexing JSONB Columns with GIN Indexes