JSON_VALUE, JSON_EXISTS, And JSON_QUERY
Query JSONB with PostgreSQL 17 JSON_EXISTS, JSON_VALUE, and JSON_QUERY using PASSING variables, RETURNING types, and ON EMPTY/ON ERROR clauses.
Code
CREATE TEMP TABLE order_docs (
id integer PRIMARY KEY,
doc jsonb NOT NULL
);
INSERT INTO order_docs VALUES
(1, '{"total": "49.50", "items": [{"sku": "A1", "qty": 3}, {"sku": "B2", "qty": 1}]}'),
(2, '{"items": [{"sku": "C3", "qty": 1}]}'),
(3, '{"total": [1, 2], "items": []}');
-- PostgreSQL 17 SQL/JSON query functions with typed RETURNING and fallback clauses
SELECT
id,
JSON_EXISTS(doc, '$.items[*] ? (@.qty >= $min)' PASSING 3 AS min) AS has_bulk,
JSON_VALUE(
doc, '$.total'
RETURNING numeric
DEFAULT 0 ON EMPTY
DEFAULT -1 ON ERROR
) AS parsed_total,
JSON_QUERY(
doc, '$.items[*].sku'
WITH UNCONDITIONAL ARRAY WRAPPER
EMPTY ARRAY ON EMPTY
) AS sku_list
FROM order_docs
ORDER BY id;Walkthrough notes — JSON_VALUE, JSON_EXISTS, And JSON_QUERY
What runs here is SELECT / INSERT / CREATE — order_docs are the objects involved.
order_docs establishes transient session-scoped structures directly in this script so no pre-created objects are needed and storage clears on exit.
The SQL constructs in play: an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Using it
Setup is internal: the session-local tables it queries (order_docs) are made by the file, so a single complete run against a scratch database suffices.
Key statements
INSERT INTO order_docs VALUES
(1, '{"total": "49.50", "items": [{"sku": "A1", "qty": 3}, {"sku": "B2", "qty": 1}]}'),
(2, '{"items": [{"sku": "C3", "qty": 1}]}'),
(3, '{"total": [1, 2], "items": []}');
CREATE TEMP TABLE order_docs (
id integer PRIMARY KEY,
doc jsonb NOT NULL
);
Interactive Tools for This Topic
FAQ
- What relations does the SQL touch?
- The references are `order_docs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.