Sub topic 9
Querying nested data with SQL/JSON path
This chapter assumes you know the ->, ->> and @> operators from earlier chapters, can read JSON syntax, and run PostgreSQL 12 or later. The examples use the orders table from the storing chapter, with its two original rows (Ada and Grace). If you ran the UPDATE examples on order 1, recreate the table first.
Why a path language
The arrow operators walk one key at a time. They are awkward when you need to look inside an array, filter its elements, and return a part of the matching ones. Expanding with jsonb_array_elements works, but it needs a LATERAL join and a cast for every field.
SQL/JSON path is a small expression language that does this in one string. It is part of the SQL standard, and PostgreSQL has supported it since version 12. You write the path, and PostgreSQL evaluates it against a jsonb value.
Anatomy of a path
A path is a string that starts at $, the whole document. You add steps after it:
| Step | Meaning |
|---|---|
| `.key` | Member access: the value of `key` in an object |
| `[0]`, `[1 to 2]`, `[last]` | Array element by position (zero-based), a range, or the final element |
| `[*]` | Every element of an array |
| `.*` | Every value of an object |
| `? (condition)` | Filter: keep only items for which the condition is true |
| `@` | Inside a filter, the item being tested |
| `$name` | A variable passed in from SQL |
Inside a path, strings use double quotes, such as "B7". The path itself is a SQL string literal in single quotes, so the two quoting styles do not clash.
The following diagram shows how the path from the spine, $.items[*] ? (@.qty > 1).sku, is evaluated step by step.
Each step receives a sequence of values and passes a sequence on. A path can therefore produce zero, one, or many results. That is why the main function is called jsonb_path_query and returns a set of rows.
The path functions and operators
PostgreSQL provides several entry points. They all take a jsonb value and a path.
| Function | Returns | Use it for |
|---|---|---|
| `jsonb_path_exists` | boolean | Does the path match anything? |
| `jsonb_path_match` | boolean | Does a predicate path evaluate to true? |
| `jsonb_path_query` | set of jsonb | One row per matched value |
| `jsonb_path_query_array` | jsonb | All matches wrapped in one array |
| `jsonb_path_query_first` | jsonb | The first match, or null |
Two operators are shorthand for the boolean functions. @? is jsonb_path_exists, and @@ is jsonb_path_match.
Start with the simplest query, which reads a nested value:
SELECT id, jsonb_path_query(details, '$.shipping.city') AS city
FROM orders;The result is "Oslo" for order 1 and "Bergen" for order 2. These are jsonb values, so the strings keep their quotes. To get SQL text, wrap the call with #>> '{}' or cast through ->>. For example, jsonb_path_query_first(...) #>> '{}' returns plain text.
Filtering array elements
Filters are where the path language pays off. This query returns the SKU of every item with a quantity above one:
SELECT id,
jsonb_path_query(details, '$.items[*] ? (@.qty > 1).sku') AS sku
FROM orders;Only order 1 returns a row, with "A1". Order 2 has no item matching the filter, so it produces no rows. A set-returning function that yields nothing removes the order from the output, just as an inner join would.
To keep orders that have no match, use the array variant, which always returns exactly one value per row:
SELECT id,
jsonb_path_query_array(details, '$.items[*] ? (@.qty > 1).sku') AS skus
FROM orders;Here order 1 gives ["A1"] and order 2 gives [].
Conditions you can use in a filter
Inside ? ( ... ) you can use these:
- Comparisons:
==,!=,<,<=,>,>=. Note that equality is==, not=. - Boolean logic:
&&,||,!. starts with "text"for prefix tests.like_regex "pattern"for regular expressions, with an optionalflag "i"for case-insensitive matching.exists(path)to test whether a sub-path matches.(condition) is unknownto detect comparisons that could not be evaluated.
Conditions combine as you would expect. This query finds orders with a specific SKU at a specific quantity:
SELECT id
FROM orders
WHERE details @? '$.items[*] ? (@.sku == "A1" && @.qty == 1)';It returns order 2. Order 1 has SKU A1 but with quantity 2, so the combined condition fails for every element.
Prefix and nested tests work the same way:
SELECT id
FROM orders
WHERE jsonb_path_exists(details, '$.shipping ? (@.city starts with "Os")');Passing variables
Do not build a path by concatenating user input into the string. Pass values through the vars argument, a jsonb object whose keys become $name variables:
SELECT id,
jsonb_path_query_array(
details,
'$.items[*] ? (@.qty >= $min).sku',
'{"min": 2}'
) AS skus
FROM orders;The variable keeps its JSON type, so $min here is a number and the comparison is numeric. Passing values this way also avoids quoting mistakes and injection.
Predicates in `WHERE`: `@?` versus `@@`
The two operators answer different questions.
-- Does this path return at least one item?
SELECT id FROM orders
WHERE details @? '$.items[*] ? (@.sku == "B7")';
-- Does this predicate evaluate to true?
SELECT id FROM orders
WHERE details @@ '$.total > 20';The first returns order 1. The second also returns order 1, because only its total (42.50) exceeds 20.
A common mistake is mixing them up. @@ needs a path whose result is a single boolean, such as a comparison. A path that returns an item, such as $.total, gives no boolean. @@ then returns null, so WHERE skips the row. When you want "does something matching exist", use @? with a filter.
Lax and strict mode
A path can begin with lax or strict. Lax is the default.
- In lax mode, structural problems are quietly absorbed. A missing key yields no result, and member access on an array automatically unwraps it and applies the step to each element.
- In strict mode, the same problems raise errors.
Compare these two queries:
SELECT jsonb_path_query(details, '$.items.sku') FROM orders;In lax mode, items is an array, but .sku is applied to each element. You get "A1" and "B7" for order 1 and "A1" for order 2. Under strict $.items.sku the same query fails, because the path says .sku on an array. Strict mode would require strict $.items[*].sku.
A missing key shows the difference too:
SELECT jsonb_path_query('{"a": 1}', '$.b'); -- no rows
SELECT jsonb_path_query('{"a": 1}', 'strict $.b'); -- ERROR: JSON object does not contain key "b"Lax mode suits messy data where keys are optional. Strict mode suits cases where a missing key means a bug and you want to hear about it.
Errors inside filters
Lax mode does not apply to everything. If a filter compares incompatible types, for example a string with a number, the comparison evaluates to unknown. A filter keeps only items where the condition is true, so these items are dropped without an error. This is useful but can hide bad data. Compare against the is unknown test when you want to find rows that fail to compare.
Item methods
Paths also have methods that you call after a step:
SELECT id,
jsonb_path_query(details, '$.items.size()') AS item_count,
jsonb_path_query(details, '$.total.type()') AS total_type,
jsonb_path_query(details, '$.total.double()') AS total_double
FROM orders;Order 1 gives 2, "number" and 42.5. The useful methods are size() (array length), type() (the JSON type name), double() (convert a string or number to a number), ceiling(), floor(), abs(), and datetime() (parse a string as a date or timestamp).
Silent errors
The @? and @@ operators suppress errors. If the path fails in strict mode, you get null (or no match), not an exception. The functions accept an optional fourth argument, silent, which defaults to false. Set it to true to get the same behavior:
SELECT jsonb_path_exists(details, 'strict $.missing', '{}', true) FROM orders;This returns null for each row, with no error. Be careful: suppressed errors can make a misspelled key look like an empty result.
Indexing path queries
A GIN index on a jsonb column supports @? and @@, with either operator class (jsonb_ops or jsonb_path_ops). The index helps when the path contains an equality check against a constant:
CREATE INDEX orders_details_gin ON orders USING gin (details jsonb_path_ops);
EXPLAIN SELECT id FROM orders
WHERE details @? '$.items[*] ? (@.sku == "B7")';With only two rows, the planner will probably choose a sequential scan anyway. Load more rows, or run SET enable_seqscan = off; in a test session, to see the index scan.
Three limits apply:
- Only the operators use the index. A call such as
jsonb_path_exists(details, ...)inWHEREis a plain function call and cannot use a GIN index. - Range conditions such as
@.qty > 1do not use the index. Only equality (==) conditions can. - The planner only gets help from the parts of the path it can extract as simple key chains. Complex filters are rechecked on each candidate row.
Choosing between path and other tools
- Use
->and->>for a known, fixed route to a single value. They are shorter and fast. - Use
@>when the question is "does the document contain this shape?" and the shape is a literal. - Use a path when you need to filter inside arrays, compare with
>or<, match patterns, or reach values through arrays without a join. - Use
jsonb_array_elementswhen you need the elements as rows to join or aggregate with other tables.
Common mistakes
- Writing
=instead of==inside a filter. This is a syntax error. - Using single quotes around strings inside the path. Path strings need double quotes.
- Forgetting that lax mode hides missing keys, and then blaming the data for empty results.
- Using
@@with a path that returns values rather than a boolean. - Expecting
jsonb_path_existsinWHEREto use a GIN index.
Exercise
Write a query that returns the id of every order that has at least one item with qty of 1 or less AND whose shipping city starts with "Ber". Use a single path and the @? operator.
Show answer
SELECT id FROM orders WHERE details @? '$ ? (@.shipping.city starts with "Ber") .items[*] ? (@.qty <= 1)'; This returns order 2 (Grace). The first filter keeps the document only if the city starts with "Ber". The path then moves into the items array and keeps elements with qty at most 1. The operator is true if any element survives both filters.
Exercise
What does jsonb_path_query('{"a": [1, 2]}', '$.a.b') return in lax mode, and what happens if you prefix the path with strict?
Show answer
In lax mode, the array under "a" is unwrapped and ".b" is applied to each number. The numbers have no members, so nothing matches and the query returns no rows. In strict mode the same path raises an error, because member access on an array (and then on a number) is a structural error.