So far every ShopKart table had neat columns. Real data engineering isn't always like that. The mobile app sends events as JSON, payment providers send webhooks as JSON, and APIs answer in JSON. Each event can have different fields, nested objects and lists. This kind of data is called semi-structured: it has a shape, but not a fixed table shape.
Every query below ran on PostgreSQL 18 against the same ShopKart database as the rest of the course, and you're seeing the real results. At the end we show the same ideas in Databricks and Snowflake.
The data: raw app events
We save each event exactly as the app sent it, in a JSONB column. Notice how different they are: searches have a query, checkouts have an items list, the web visit has no app_version, and only some checkouts have a coupon.
-- Raw events from the ShopKart app, saved exactly as the app sent them (JSON).
CREATE TABLE app_events (
event_id INT PRIMARY KEY,
received TIMESTAMP NOT NULL,
payload JSONB NOT NULL
);
INSERT INTO app_events VALUES
(1, '2026-06-01 09:12', '{"type": "checkout", "customer_id": 1, "device": {"os": "android", "app_version": "5.2.1"},
"items": [{"product_id": 1, "qty": 1}, {"product_id": 2, "qty": 2}], "coupon": "MONSOON10"}'),
(2, '2026-06-01 09:40', '{"type": "search", "customer_id": 3, "device": {"os": "ios", "app_version": "5.3.0"},
"query": "smartwatch"}'),
(3, '2026-06-01 10:05', '{"type": "checkout", "customer_id": 3, "device": {"os": "ios", "app_version": "5.3.0"},
"items": [{"product_id": 3, "qty": 1}]}'),
(4, '2026-06-01 11:30', '{"type": "checkout", "customer_id": 4, "device": {"os": "web"},
"items": [{"product_id": 4, "qty": 3}, {"product_id": 6, "qty": 1}], "coupon": "MONSOON10"}'),
(5, '2026-06-01 12:02', '{"type": "app_open", "customer_id": 2, "device": {"os": "android", "app_version": "5.1.0"}}');Read a field: -> and ->>
-- -> keeps JSON, ->> gives text. Chain them to go deeper.
SELECT event_id,
payload -> 'device' AS device_json,
payload ->> 'type' AS type,
payload -> 'device' ->> 'os' AS os
FROM app_events
ORDER BY event_id;| event_id | device_json | type | os |
|---|---|---|---|
| 1 | {"os": "android", "app_version": "5.2.1"} | checkout | android |
| 2 | {"os": "ios", "app_version": "5.3.0"} | search | ios |
| 3 | {"os": "ios", "app_version": "5.3.0"} | checkout | ios |
| 4 | {"os": "web"} | checkout | web |
| 5 | {"os": "android", "app_version": "5.1.0"} | app_open | android |
->returns JSON:device_jsonis still an object you could dig into.->>returns text: ready to compare, display or cast.- Chain them to go deeper: into
device, then reados.
Text isn't always what you want. Cast numbers, use a path for deep fields, and give missing keys a default:
-- ->> always returns text: cast it to the type you need
SELECT event_id,
(payload ->> 'customer_id')::INT AS customer_id,
payload #>> '{device,app_version}' AS app_version,
COALESCE(payload ->> 'coupon', 'none') AS coupon
FROM app_events
ORDER BY event_id;| event_id | customer_id | app_version | coupon |
|---|---|---|---|
| 1 | 1 | 5.2.1 | MONSOON10 |
| 2 | 3 | 5.3.0 | none |
| 3 | 3 | 5.3.0 | none |
| 4 | 4 | NULL | MONSOON10 |
| 5 | 2 | 5.1.0 | none |
Event 4 (the web visit) has no app_version, so it's NULL, not an error. Missing keys are normal in JSON; COALESCE turns them into a sensible default.
Try it on one event. Click any line of the JSON:
Click any part of the event
{}
PostgreSQL
payload -> 'device' ->> 'os'Databricks SQL
payload:device.osSnowflake
payload:device.os::STRINGResult for event 1
'android' (text)
Same question, three dialects. The idea is identical: follow the path, then cast to the type you need.
Filter on JSON
-- Checkouts that used a coupon
SELECT event_id, payload ->> 'coupon' AS coupon
FROM app_events
WHERE payload ->> 'type' = 'checkout'
AND payload ? 'coupon' -- ? means "has this key"
ORDER BY event_id;| event_id | coupon |
|---|---|
| 1 | MONSOON10 |
| 4 | MONSOON10 |
payload ? 'coupon' means “has a coupon key”. For matching a whole piece of JSON, @> (“contains”) is clearer and can use an index:
-- @> means "contains this JSON": events from iOS devices
SELECT event_id, payload ->> 'type' AS type
FROM app_events
WHERE payload @> '{"device": {"os": "ios"}}'
ORDER BY event_id;| event_id | type |
|---|---|
| 2 | search |
| 3 | checkout |
Explode arrays into rows
Checkouts carry a list of items. A list is many values squeezed into one row, and SQL can't sum or join what it can't see. jsonb_array_elements unpacks the list: one row per item, next to its event:
-- One row per item in each checkout's "items" array
SELECT e.event_id,
item ->> 'product_id' AS product_id,
item ->> 'qty' AS qty
FROM app_events e,
jsonb_array_elements(e.payload -> 'items') AS item
ORDER BY e.event_id, product_id;| event_id | product_id | qty |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 3 | 3 | 1 |
| 4 | 4 | 3 |
| 4 | 6 | 1 |
🧾Event 1
items: [headphones ×1, phone case ×2]
💥jsonb_array_elements
one row per element
📄2 rows
(1, product 1, qty 1) and (1, product 2, qty 2)
Search and app-open events have no items, so they simply produce no rows. Once items are rows, they're normal data: join them to products and add up revenue per checkout.
-- Join the items to products to get revenue per checkout
SELECT e.event_id,
(e.payload ->> 'customer_id')::INT AS customer_id,
COUNT(*) AS lines,
SUM((item ->> 'qty')::INT * p.price) AS revenue
FROM app_events e
CROSS JOIN LATERAL jsonb_array_elements(e.payload -> 'items') AS item
JOIN products p ON p.product_id = (item ->> 'product_id')::INT
WHERE e.payload ->> 'type' = 'checkout'
GROUP BY e.event_id, customer_id
ORDER BY e.event_id;| event_id | customer_id | lines | revenue |
|---|---|---|---|
| 1 | 1 | 2 | 2597.00 |
| 3 | 3 | 1 | 4999.00 |
| 4 | 4 | 2 | 3996.00 |
CROSS JOIN LATERAL means “for each event, run jsonb_array_elements on that event's items”. The comma in the previous query does the same thing; LATERAL just says it out loud. Event 1: one headphones (₹1,999) plus two phone cases (2 × ₹299) = ₹2,597.
Explore messy JSON: which keys exist?
When you get a new feed and don't know its shape, list the keys and count how often each appears:
-- What keys appear in the events, and how often? (Great for exploring messy data)
SELECT key, COUNT(*) AS events
FROM app_events, jsonb_object_keys(payload) AS key
GROUP BY key
ORDER BY events DESC, key;| key | events |
|---|---|
| customer_id | 5 |
| device | 5 |
| type | 5 |
| items | 3 |
| coupon | 2 |
| query | 1 |
Now you know: every event has type, customer_id and device; only 3 have items; coupon is optional. That's your schema, discovered from the data.
Build JSON in SQL
The other direction is just as useful: shaping rows into JSON, for example an API response with each customer's orders inside.
-- Build JSON for an API: one object per customer with their orders inside
SELECT jsonb_build_object(
'customer', c.name,
'orders', jsonb_agg(jsonb_build_object('order_id', o.order_id, 'status', o.status) ORDER BY o.order_id)
) AS api_response
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id IN (1, 2)
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;| api_response |
|---|
| {"orders": [{"status": "DELIVERED", "order_id": 101}, {"status": "DELIVERED", "order_id": 103}, {"status": "DELIVERED", "order_id": 109}], "customer": "Asha"} |
| {"orders": [{"status": "DELIVERED", "order_id": 102}, {"status": "DELIVERED", "order_id": 106}, {"status": "RETURNED", "order_id": 112}], "customer": "Rahul"} |
jsonb_agg collects many rows into one JSON array; jsonb_build_object makes an object from key–value pairs. Notice orders comes before customer in the output: JSONB doesn't keep key order, so never rely on it.
The pipeline move: flatten once
Writing ->> and casts in every report is slow and easy to get wrong. The standard data-engineering approach: keep the raw JSON (bronze), and flatten the fields you need into a typed table (silver) once.
-- The data-engineering move: turn raw JSON into a clean, typed table once,
-- so every report after this uses normal columns.
CREATE TABLE checkout_items AS
SELECT e.event_id,
e.received::DATE AS event_date,
(e.payload ->> 'customer_id')::INT AS customer_id,
e.payload -> 'device' ->> 'os' AS os,
e.payload ->> 'coupon' AS coupon,
(item ->> 'product_id')::INT AS product_id,
(item ->> 'qty')::INT AS qty
FROM app_events e
CROSS JOIN LATERAL jsonb_array_elements(e.payload -> 'items') AS item
WHERE e.payload ->> 'type' = 'checkout';SELECT * FROM checkout_items ORDER BY event_id, product_id;| event_id | event_date | customer_id | os | coupon | product_id | qty |
|---|---|---|---|---|---|---|
| 1 | 2026-06-01 | 1 | android | MONSOON10 | 1 | 1 |
| 1 | 2026-06-01 | 1 | android | MONSOON10 | 2 | 2 |
| 3 | 2026-06-01 | 3 | ios | NULL | 3 | 1 |
| 4 | 2026-06-01 | 4 | web | MONSOON10 | 4 | 3 |
| 4 | 2026-06-01 | 4 | web | MONSOON10 | 6 | 1 |
From here on, analysts query checkout_items with plain SQL. If the app later adds a field, the raw JSON still has it, and you can add a column. This is the same idea as the medallion architecture.
-- Casting text that isn't a number fails loudly
SELECT ('{"qty": "two"}'::jsonb ->> 'qty')::INT AS qty;SQL arrays (without JSON)
Databases also have real array columns. You'll meet them as lists of tags, and you'll create them with ARRAY_AGG, which collects a group's values into one array:
-- SQL arrays: collect values into one array per group
SELECT c.name, ARRAY_AGG(o.order_id ORDER BY o.order_id) AS order_ids
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id
LIMIT 4;| name | order_ids |
|---|---|
| Asha | {101,103,109} |
| Rahul | {102,106,112} |
| Priya | {104,110} |
| Imran | {105,111} |
-- A column that holds a list: tags on each product
CREATE TABLE product_tags (product_id INT PRIMARY KEY, tags TEXT[] NOT NULL);
INSERT INTO product_tags VALUES
(1, ARRAY['audio', 'wireless', 'bestseller']),
(2, ARRAY['mobile', 'budget']),
(3, ARRAY['wearable', 'fitness', 'bestseller']),
(4, ARRAY['mobile', 'budget', 'fast-charge']),
(5, ARRAY['desk']),
(6, ARRAY['audio', 'wireless']);= ANY(array) checks if a value is in the list, and cardinality counts its elements:
-- Products tagged "bestseller", and how many tags each has
SELECT p.name, t.tags, cardinality(t.tags) AS n_tags
FROM product_tags t
JOIN products p USING (product_id)
WHERE 'bestseller' = ANY (t.tags)
ORDER BY p.name;| name | tags | n_tags |
|---|---|---|
| Headphones | {audio,wireless,bestseller} | 3 |
| Smartwatch | {wearable,fitness,bestseller} | 3 |
unnest is the array version of exploding: one row per element. Then it's a normal GROUP BY:
-- unnest turns an array into rows: count products per tag
SELECT tag, COUNT(*) AS products
FROM product_tags, unnest(tags) AS tag
GROUP BY tag
ORDER BY products DESC, tag;| tag | products |
|---|---|
| audio | 2 |
| bestseller | 2 |
| budget | 2 |
| mobile | 2 |
| wireless | 2 |
| desk | 1 |
| fast-charge | 1 |
| fitness | 1 |
| wearable | 1 |
Make JSON searches fast
On millions of events, filters like @> and ? need an index. A GIN index indexes every key and value inside the JSON (see indexes):
-- A GIN index makes @> and ? searches fast on big tables
CREATE INDEX app_events_payload_gin ON app_events USING GIN (payload);If you always filter on one field, an index on that expression is smaller: CREATE INDEX ON app_events ((payload ->> 'type'));
The same ideas in Databricks and Snowflake
The syntax changes, the ideas don't: follow a path, cast, explode.
-- Databricks SQL: the same questions on a STRING column of JSON
SELECT payload:device.os AS os, -- colon path syntax
payload:customer_id::INT AS customer_id,
item.product_id, item.qty
FROM app_events
LATERAL VIEW explode(
from_json(payload:items, 'ARRAY<STRUCT<product_id: INT, qty: INT>>')
) AS item
WHERE payload:type = 'checkout';-- Snowflake: payload is a VARIANT column
SELECT payload:device.os::STRING AS os,
payload:customer_id::INT AS customer_id,
item.value:product_id::INT AS product_id,
item.value:qty::INT AS qty
FROM app_events,
LATERAL FLATTEN(input => payload:items) item
WHERE payload:type::STRING = 'checkout';| Task | PostgreSQL | Databricks SQL | Snowflake | BigQuery |
|---|---|---|---|---|
| Column type | JSONB | STRING or VARIANT | VARIANT | JSON |
| Read a field | payload ->> 'type' | payload:type | payload:type::STRING | JSON_VALUE(payload, '$.type') |
| Nested field | payload #>> '{device,os}' | payload:device.os | payload:device.os | JSON_VALUE(payload, '$.device.os') |
| Array → rows | jsonb_array_elements | explode | LATERAL FLATTEN | UNNEST(JSON_QUERY_ARRAY(...)) |
| Build JSON | jsonb_build_object | to_json(named_struct(...)) | OBJECT_CONSTRUCT | TO_JSON(STRUCT(...)) |
Common mistakes
| Mistake | What goes wrong | Do this instead |
|---|---|---|
| Comparing ->> text to a number | '10' > '9' is false for text | Cast first: (payload ->> 'qty')::INT |
| Using -> where you need text | You compare JSON to text | -> to go deeper, ->> for the final value |
| LIKE on the JSON text | Slow, and matches the wrong things | @> or ? with a GIN index |
| Forgetting missing keys | NULLs break sums and joins | COALESCE, and count missing keys when exploring |
| Querying raw JSON in every report | Slow, repeated casting logic | Flatten into a typed table once |
| Relying on key order | JSONB reorders keys | Read keys by name |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you extract a nested field from JSON in SQL?Fresher+
Q2Each order event has an array of items. How do you compute revenue per product?1–3 yrs+
Q3How would you handle a JSON feed whose fields change over time?1–3 yrs+
Q4JSON queries on a 500-million-row events table are slow. What do you do?3+ yrs+
Key takeaways
- ✓Semi-structured data has nested objects, optional keys and arrays; SQL can read all of it.
- ✓Follow a path to a field, cast it, and treat missing keys as NULL.
- ✓Explode arrays to rows before you join or aggregate them.
- ✓Flatten raw JSON into a typed table once; keep the raw copy too.
- ✓The same ideas work in PostgreSQL, Databricks, Snowflake and BigQuery with different syntax.
Next: put everything from this course to the test with the SQL interview questions.
Frequently asked questions
Can SQL databases store JSON?
Yes. PostgreSQL has JSON and JSONB column types, Snowflake has VARIANT, BigQuery has JSON, and Databricks can query JSON stored as text with a colon path syntax (and has a VARIANT type too). You can pull out fields, filter on them, and turn arrays into rows, all in SQL.
What is the difference between JSON and JSONB in PostgreSQL?
JSON stores the text exactly as given. JSONB stores a parsed binary version: slightly slower to insert, much faster to query, supports indexes (GIN) and operators like @> and ?. It also removes duplicate keys and doesn't keep key order. Use JSONB unless you need the exact original text.
What does -> vs ->> mean?
Both read a key from JSON. -> returns JSON (so you can keep going deeper), ->> returns text (so you can compare it or cast it). payload -> 'device' ->> 'os' goes into device, then reads os as text.
How do I turn a JSON array into rows?
Explode it. In PostgreSQL use jsonb_array_elements in the FROM clause (with CROSS JOIN LATERAL or a comma); in Databricks use explode; in Snowflake use LATERAL FLATTEN; in BigQuery use UNNEST. Each element becomes its own row next to the columns of its parent row.
Should I keep data as JSON or turn it into columns?
Keep the raw JSON in your bronze or staging layer, so nothing is lost when the app adds fields. Then flatten the fields you actually use into typed columns in silver. Reports on typed columns are faster, simpler and catch bad data early.
🧠 Quick check: JSON and arrays in SQL
1. payload ->> 'customer_id' returns...
2. A checkout has 3 items in an array. After jsonb_array_elements, how many rows does it become?
3. Which finds events whose device os is "ios" using a GIN index?
4. The web event has no app_version. payload #>> '{device,app_version}' gives...
Checking your access…