Part 14 / Topic 3 of 10
Querying JSONB
The operator family, on real event payloads. -> steps into a field (returns jsonb), ->> extracts it as text — the distinction that bites everyone once:
SELECT event_id, event_type,
payload -> 'device' AS device_jsonb,
payload ->> 'device' AS device_text
FROM events
ORDER BY event_id
LIMIT 3;
event_id | event_type | device_jsonb | device_text
----------+------------+--------------+-------------
1 | view | "mobile" | mobile
2 | cart | "mobile" | mobile
3 | purchase | "desktop" | desktop
(3 rows)
Same data, different types: -> keeps you in JSON-land (chainable); ->> lands in SQL-land (comparable, groupable). Deep paths use #>> with a path array — or just chain. The filter operators: @> containment ("does the payload contain this sub-document?") and ? key-existence:
SELECT event_id, event_type, payload ->> 'device' AS device
FROM events
WHERE payload @> '{"device": "mobile"}'
ORDER BY event_id;
event_id | event_type | device
----------+------------+--------
1 | view | mobile
2 | cart | mobile
6 | view | mobile
7 | cart | mobile
(4 rows)
SELECT event_id, payload
FROM events
WHERE payload ? 'tags';
event_id | payload
----------+---------------------------------------------------------
6 | {"tags": ["sale"], "device": "mobile", "product_id": 2}
(1 row)
@> is the one to internalise: it asks structural questions ("mobile events", "orders with this flag") and it is exactly what the GIN index in section 7 accelerates.
🧪 Quick quiz — answer from memory, then check.
payload ->> 'device'returns which type?- What does
payload @> '{"device": "mobile"}'ask?
Show the answers
- text (
->returns jsonb). - Does the payload contain that key/value pair — structural containment, GIN-indexable.
Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.