Part 14 / Topic 5 of 10
JSON path
For questions deeper than operators comfortably reach, jsonb speaks the SQL/JSON path language — $ is the document, dots step in, filters live in ? (...):
SELECT event_id,
jsonb_path_exists(payload, '$.tags[*] ? (@ == "sale")') AS tagged_sale
FROM events
WHERE payload ? 'tags';
event_id | tagged_sale
----------+-------------
6 | t
(1 row)
SELECT jsonb_path_query(payload, '$.product_id') AS product_ids
FROM events
WHERE event_type = 'view'
ORDER BY event_id;
product_ids
-------------
1
3
2
(3 rows)
jsonb_path_exists filters, jsonb_path_query extracts (one row per match — handy inside arrays). For flat payloads like shopdb's, operators stay shorter; path syntax earns its keep on nested documents ("any line item over 100 inside this stored order?") where chaining -> turns to soup.
🧪 Quick quiz — answer from memory, then check.
- In a JSON path, what are
$and@? - When does path syntax beat the operators?
Show the answers
$the whole document;@the current element inside a filter.- Nested structures and array-element conditions — anywhere
->chains stop reading clearly.
Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.