Sub topic 12
JSON_VALUE, JSON_QUERY and JSON_TABLE in PostgreSQL 17
This chapter assumes you know the ->, ->> and @> operators and SQL/JSON path expressions from earlier chapters. PostgreSQL 17 added the SQL-standard JSON query functions JSON_EXISTS, JSON_VALUE, JSON_QUERY and JSON_TABLE. They cover work you could already do with operators and jsonb_path_query, but with explicit return types and explicit error handling. JSON_TABLE also turns a document into a relational result in one step.
These functions do not exist in PostgreSQL 16 or earlier. On those versions the examples fail with a syntax error.
Setting up the data
The earlier chapters changed the orders rows with UPDATE statements. To get predictable output, this chapter uses a fresh table.
CREATE TABLE orders17 (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);
INSERT INTO orders17 (customer, details) VALUES
('Ada', '{"status": "paid", "total": 42.50, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}], "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}');How the functions fit together
All four functions take a context item (the document) and a SQL/JSON path expression. They differ in what they return.
| Function | Returns | Typical use |
|---|---|---|
| `JSON_EXISTS` | boolean | Filter rows in `WHERE` |
| `JSON_VALUE` | One scalar, as `text` unless you say otherwise | Pull a single typed value |
| `JSON_QUERY` | An object, an array, or a scalar, as `jsonb` unless you say otherwise | Pull a JSON fragment |
| `JSON_TABLE` | A set of rows | Flatten a document in `FROM` |
JSON_VALUE: one scalar with a type
JSON_VALUE extracts a single scalar (string, number, boolean or null). Without a RETURNING clause the result is text, like ->>. With RETURNING the conversion happens inside the function, so you don't need a ::numeric cast.
SELECT id,
JSON_VALUE(details, '$.status') AS status,
JSON_VALUE(details, '$.total' RETURNING numeric) AS total,
JSON_VALUE(details, '$.shipping.city') AS city
FROM orders17;For the sample data this returns 1 | paid | 42.50 | Oslo and 2 | pending | 10.00 | Bergen.
The full clause order is:
JSON_VALUE(context_item, path
[PASSING value AS name, ...]
[RETURNING type]
[ERROR | NULL | DEFAULT expr ON EMPTY]
[ERROR | NULL | DEFAULT expr ON ERROR])Empty results and errors
Two different situations are handled separately:
- Empty means the path matched nothing, for example a missing key. The default is
NULL ON EMPTY. - Error means something went wrong, such as the path matching an object or array instead of a scalar, matching several values, or a value that can't be cast to the
RETURNINGtype. The default isNULL ON ERROR.
SELECT id,
JSON_VALUE(details, '$.coupon' DEFAULT 'none' ON EMPTY) AS coupon,
JSON_VALUE(details, '$.items') AS items_as_scalar,
JSON_VALUE(details, '$.status' RETURNING int) AS status_as_int
FROM orders17;Here coupon is none because the key is absent. The other two columns are NULL: $.items is an array, and 'paid' is not an integer. Because errors become NULL silently, a typo in a path or a bad cast looks the same as missing data. During development, make failures visible with ERROR ON ERROR:
SELECT JSON_VALUE(details, '$.status' RETURNING int ERROR ON ERROR)
FROM orders17;This statement raises an error instead of returning NULL.
Lax and strict path modes
Path expressions run in lax mode by default. Lax mode turns structural problems, such as a missing key, into empty results. Prefix the path with strict to treat them as errors:
SELECT id,
JSON_VALUE(details, 'strict $.coupon' DEFAULT 'none' ON ERROR) AS coupon
FROM orders17;A missing key under strict is an error, so the ON ERROR branch applies, not ON EMPTY. This is a common source of confusion. If a default doesn't fire, check which of the two clauses the failure belongs to.
JSON_QUERY: objects, arrays and wrappers
JSON_QUERY returns JSON, so use it when the target is an object or an array. The result type is jsonb unless you add RETURNING.
SELECT id,
JSON_QUERY(details, '$.items') AS items,
JSON_QUERY(details, '$.shipping') AS shipping
FROM orders17;The first row returns [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}] for items.
Wrapper clauses
A path can match several values. JSON_QUERY must return one JSON value, so the wrapper clause controls what happens:
WITHOUT WRAPPERis the default. More than one match is an error, which becomesNULLunderNULL ON ERROR.WITH WRAPPER(the same asWITH UNCONDITIONAL WRAPPER) always wraps the matches in an array.WITH CONDITIONAL WRAPPERwraps only when there is not exactly one match that is already an object or array.
SELECT id,
JSON_QUERY(details, '$.items[*].sku') AS no_wrapper,
JSON_QUERY(details, '$.items[*].sku' WITH WRAPPER) AS wrapped,
JSON_QUERY(details, '$.items[*].sku' WITH CONDITIONAL WRAPPER) AS conditional
FROM orders17;For Ada, no_wrapper is NULL because there are two matches. Both wrapped and conditional are ["A1", "B7"]. For Grace there is one match, so no_wrapper is "A1", wrapped is ["A1"] and conditional is "A1".
Quotes
A string result keeps its JSON quotes by default (KEEP QUOTES). To get plain text, ask for it and omit the quotes:
SELECT JSON_QUERY(details, '$.shipping.city' RETURNING text OMIT QUOTES) AS city
FROM orders17;This returns Oslo and Bergen without quotes. OMIT QUOTES applies only to scalar strings, and it is only useful with a non-JSON return type such as text. If you only need a scalar string, JSON_VALUE is simpler.
JSON_EXISTS: testing a path
JSON_EXISTS returns true when the path matches at least one item. A filter expression inside the path makes it a condition. Use PASSING to supply values as path variables instead of building the path with string concatenation.
SELECT id
FROM orders17
WHERE JSON_EXISTS(details, '$.items[*] ? (@.sku == $s && @.qty >= $q)'
PASSING 'A1' AS s, 2 AS q);This returns order 1, the only order with at least 2 units of A1 on one line. The default error behavior is FALSE ON ERROR, which can hide problems the same way NULL ON ERROR does. You can write ERROR ON ERROR here as well.
JSON_TABLE: a document as a table
JSON_TABLE goes in the FROM clause and returns rows. It is implicitly lateral, so it can refer to columns of tables listed before it. Think of it as a combination of many JSON_VALUE, JSON_QUERY and JSON_EXISTS calls, plus row expansion, in one declaration.
SELECT o.id, jt.*
FROM orders17 AS o,
JSON_TABLE(o.details, '$' COLUMNS (
status text PATH '$.status',
total numeric PATH '$.total',
city text PATH '$.shipping.city',
NESTED PATH '$.items[*]' COLUMNS (
line FOR ORDINALITY,
sku text PATH '$.sku',
qty int PATH '$.qty'
)
)) AS jt;The result has three rows, one per order line:
| id | status | total | city | line | sku | qty |
|---|---|---|---|---|---|---|
| 1 | paid | 42.50 | Oslo | 1 | A1 | 2 |
| 1 | paid | 42.50 | Oslo | 2 | B7 | 1 |
| 2 | pending | 10.00 | Bergen | 1 | A1 | 1 |
The pieces work like this:
- The first path (
'$') is the row pattern. It selects the items that become rows. Each column path is evaluated relative to one such item. - A regular column such as
status text PATH '$.status'behaves likeJSON_VALUE. It accepts the sameON EMPTYandON ERRORclauses and defaults toNULLfor both. If you leave outPATH, it defaults to'$.'followed by the column name, sostatus textalone reads$.status. NESTED PATHexpands an array into child rows. The parent's columns repeat on every child row. A parent with an empty or missing array still produces one row, withNULLin the nested columns.FOR ORDINALITYnumbers rows starting at 1, within its ownCOLUMNSlevel.
Other column kinds
SELECT o.id, jt.*
FROM orders17 AS o,
JSON_TABLE(o.details, '$' COLUMNS (
items jsonb FORMAT JSON PATH '$.items',
has_bulk boolean EXISTS PATH '$.items[*] ? (@.qty > 1)',
first_sku text PATH '$.items[0].sku'
)) AS jt;FORMAT JSON PATHbehaves likeJSON_QUERYand returns a fragment. It accepts wrapper and quote clauses.EXISTS PATHbehaves likeJSON_EXISTSand returns a boolean.
Several arrays at the same level
Two NESTED PATH clauses at the same level are siblings. PostgreSQL does not cross-join them. Each parent row gets the rows of the first array, then the rows of the second, with NULL filling the columns of the other sibling. Nest one NESTED PATH inside another if you need a parent-child relationship.
JSON_TABLE compared with jsonb_array_elements
| Need | Earlier approach | PostgreSQL 17 approach |
|---|---|---|
| One row per array element | `CROSS JOIN LATERAL jsonb_array_elements(...)` | `NESTED PATH '$.items[*]'` |
| Typed columns | `(i ->> 'qty')::int` in the select list | `qty int PATH '$.qty'` |
| Defaults for missing keys | `COALESCE(...)` | `DEFAULT ... ON EMPTY` |
| Several levels | Several lateral joins | Nested `COLUMNS` |
JSON_TABLE puts the whole mapping in one place, which makes it easier to review and reuse. For a single simple array, jsonb_array_elements is still shorter.
Indexing and performance
The planner does not translate JSON_VALUE, JSON_QUERY or JSON_EXISTS into the GIN operator classes from the indexing chapter. When a query needs an index, keep a form the index supports: @> for a GIN index, or an expression index on details ->> 'status' paired with a matching WHERE clause. Confirm the plan with EXPLAIN. The new functions suit extraction in the select list and reporting queries, and JSON_TABLE suits joins against documents you have already filtered.
Common mistakes
- Expecting
JSON_VALUEto return an object. It returnsNULL(or an error underERROR ON ERROR) for an object or array. UseJSON_QUERY. - Forgetting the wrapper. A
JSON_QUERYover[*]with several matches returnsNULLunless you addWITH WRAPPER. - Putting
RETURNINGbeforePASSING. The clause order is fixed:PASSING,RETURNING,ON EMPTY,ON ERROR. - Trusting
NULL. ANULLcan mean a missing key, a wrong type or a bad path. Test withERROR ON ERRORfirst. - Using these functions on PostgreSQL 16 or older. Fall back to
->>,jsonb_path_queryandjsonb_array_elements.
Exercise
Write a query on orders17 that returns one row per order with the id and the number-of-lines-independent list of all SKUs as one JSON array, even when an order has only one item. Which function and clause do you use, and why not JSON_VALUE?
Show answer
Use JSONQUERY with WITH WRAPPER: SELECT id, JSONQUERY(details, '$.items[*].sku' WITH WRAPPER) AS skus FROM orders17; WITH WRAPPER always wraps the matches in an array, so Grace's single item returns ["A1"] and Ada's two items return ["A1","B7"]. JSON_VALUE cannot be used because it returns only one scalar, and several matches would be an error that becomes NULL.
Exercise
Using JSON_TABLE on orders17, return one row per item with columns id, sku and qty (integer), but only for lines where qty is greater than 1. Which approach gives the filter without a WHERE clause on the result?
Show answer
Put the filter in the NESTED PATH: SELECT o.id, jt.sku, jt.qty FROM orders17 o, JSON_TABLE(o.details, '$.items[?(@.qty > 1)]' COLUMNS (sku text PATH '$.sku', qty int PATH '$.qty')) AS jt; The row pattern selects only items with qty above 1, so only Ada's A1 line (qty 2) is returned. A WHERE jt.qty > 1 on the result also works, but the path filter removes rows before they are produced.