Sub topic 4
Filtering with @>, ? and related operators
This chapter covers the jsonb operators that test a document's shape and contents in a WHERE clause. It assumes you know basic SQL, can read JSON syntax, and have PostgreSQL 12 or later. It also assumes you know the -> and ->> operators from the previous chapter. The examples use the orders table from this tutorial. If you don't have it yet, run this setup once.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);
INSERT INTO orders (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"}}');Why not just use ->>?
You can filter with details ->> 'status' = 'paid'. It works, but it has two drawbacks:
- It extracts text, so you must cast values like numbers and compare them as SQL types.
- A plain B-tree index can't help unless you build an expression index for that exact expression.
The containment and existence operators work on whole jsonb values instead. One GIN index can serve many different conditions, and a single operator can test nested structure. They only work on jsonb. The json type has no @> or ? operators, so a json column needs a cast such as details::jsonb.
Containment: @> and <@
a @> b is true when a contains b. a <@ b means the same thing with the sides reversed. Think of b as a template that a must match.
SELECT id FROM orders WHERE details @> '{"status": "paid"}';This returns id 1. The right-hand literal is an unknown-typed string that PostgreSQL resolves to jsonb. Both sides must be valid JSON.
The rules
Containment is recursive and depends on the type of each value:
- Objects. Every key in the right object must exist in the left object, and each value on the left must contain the corresponding value on the right. The left object may have extra keys.
- Arrays. Every element of the right array must be contained by at least one element of the left array. Order and duplicates are ignored.
- Scalars. Strings, numbers, booleans, and null must be equal. A number never equals a string, so
{"total": "42.5"}does not match a numeric42.5.
Numbers compare by value, not by how they were written. The stored 42.50 matches a pattern written as 42.5:
SELECT id FROM orders WHERE details @> '{"total": 42.5}';This returns id 1.
Containment in nested arrays
Arrays of objects are the most useful case. The pattern states what at least one array element must look like:
SELECT id FROM orders
WHERE details @> '{"items": [{"sku": "A1"}]}';Both orders contain an item with sku A1, so this returns ids 1 and 2. Add qty, and only Ada's order matches:
SELECT id FROM orders
WHERE details @> '{"items": [{"sku": "A1", "qty": 2}]}';Each object in the pattern is matched against one element at a time. Consider this query:
SELECT id FROM orders
WHERE details @> '{"items": [{"sku": "B7", "qty": 2}]}';It returns no rows. Ada's order has a B7 item and also an item with quantity 2, but they are different elements. Compare that with a pattern that uses two separate objects:
SELECT id FROM orders
WHERE details @> '{"items": [{"sku": "B7"}, {"qty": 2}]}';This matches Ada's order. Each pattern element only needs some element that contains it. {"sku": "B7"} is satisfied by the second item and {"qty": 2} by the first. When you need "one element with both properties", put both properties in one pattern object.
Structure must match
Containment does not search at arbitrary depth. A nested value is only found if the pattern has the same nesting:
SELECT '{"shipping": {"city": "Oslo"}}'::jsonb @> '{"city": "Oslo"}';This returns false, because city is not a top-level key. The pattern must be {"shipping": {"city": "Oslo"}}. Arrays work the same way. '[1, 2, [1, 3]]'::jsonb @> '[1, 3]' is false, and '[1, 2, [1, 3]]'::jsonb @> '[[1, 3]]' is true.
There is one special case. A top-level array is allowed to contain a bare scalar:
SELECT '["red", "green"]'::jsonb @> '"red"';This returns true, even though the right side is a string and not an array. This exception exists for convenience, and it applies only at the top level.
Empty patterns and null
An empty object or array in the pattern matches any object or array on the left, because there is nothing to check. details @> '{}' is true for every row whose details is an object. A pattern value of null matches only a key that is present with a JSON null. A missing key does not match:
SELECT '{"a": null}'::jsonb @> '{"a": null}' AS present,
'{}'::jsonb @> '{"a": null}' AS missing;This returns true and false.
Key existence: ?, ?| and ?&
The existence operators test whether strings appear as keys. They take a text value, not JSON.
| Operator | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `?` | The string is a top-level key or top-level string element | `details ? 'status'` | ||
| `?\ | ` | Any string in the text array exists | `details ?\ | array['tracking', 'shipping']` |
| `?&` | All strings in the text array exist | `details ?& array['status', 'total']` |
Existence checks only the top level of the value you apply them to. This query returns no rows, because city is not a top-level key of details:
SELECT id FROM orders WHERE details ? 'city';To test a nested object, navigate to it first:
SELECT id FROM orders WHERE details -> 'shipping' ? 'city';This returns ids 1 and 2.
Some details to remember:
?checks key names, not values.details ? 'paid'is false, becausepaidis a value.- A key whose value is JSON
nullstill exists.'{"a": null}'::jsonb ? 'a'istrue. - On an array,
?matches string elements only.'["a", "b"]'::jsonb ? 'a'istrue.'[1, 2]'::jsonb ? '1'isfalse. - Wrap negations in parentheses:
WHERE NOT (details ? 'tracking')finds orders with no tracking key.
The multi-key forms save you from chains of OR and AND:
SELECT id FROM orders WHERE details ?& array['status', 'total', 'items'];
SELECT id FROM orders WHERE details ?| array['tracking', 'refund'];The first returns ids 1 and 2. The second returns nothing, since neither order has either key.
The question mark and client libraries
Many database drivers treat ? as a parameter placeholder. JDBC is a well-known example. In those drivers, a query containing ? fails or is misread. PostgreSQL provides function equivalents for this case:
| Operator | Function | Column |
|---|---|---|
| `?` | `jsonb_exists(details, 'status')` | |
| `?\ | ` | `jsonb_exists_any(details, array['a', 'b'])` |
| `?&` | `jsonb_exists_all(details, array['a', 'b'])` |
SELECT id FROM orders WHERE jsonb_exists(details, 'status');The functions are equivalent to the operators, but the planner only uses an index through the operator form, which is what GIN indexes are defined on. Prefer the operator in psql and in drivers that allow escaping, and fall back to the function only when the driver gets in the way. Some drivers let you write ?? to send a literal ?.
Choosing an operator
The diagram shows how to pick an operator from what you want to test.
Containment covers only equality. It cannot say "total greater than 20". For that, extract and cast ((details ->> 'total')::numeric > 20) or use a SQL/JSON path, which a later chapter covers. A common pattern is to combine them, using containment for the indexed part and a comparison for the rest:
SELECT id
FROM orders
WHERE details @> '{"status": "paid"}'
AND (details ->> 'total')::numeric > 20;This returns id 1.
How the operators relate to indexes
Without an index, these operators scan the table and test each document. With a GIN index on the column, PostgreSQL can answer them from the index. Which operators are supported depends on the operator class:
| Operator class | Supports `@>` | Supports `?`, `?\ | `, `?&` |
|---|---|---|---|
| `jsonb_ops` (default) | yes | yes | |
| `jsonb_path_ops` | yes | no |
If you use ? heavily, use the default jsonb_ops. If you only use @>, jsonb_path_ops gives a smaller and usually faster index. The indexing chapter explains the trade-offs and how to confirm usage with EXPLAIN.
A condition such as details ->> 'status' = 'paid' does not use a GIN index on details, because it is a different expression. If you rewrite it as details @> '{"status": "paid"}', the GIN index becomes usable. The two forms are equivalent for a top-level string value, with one difference: if status is missing or null, the ->> form yields NULL, and the @> form yields false. Both exclude the row from the result.
Common mistakes
- Searching for a nested key with
?. It only inspects the top level. Navigate with->first. - Quoting the wrong type.
{"qty": "2"}does not match{"qty": 2}. Match the JSON type used in the data. - Expecting array elements to be merged. Each pattern element is matched against one array element.
- Using
@>onjson. Cast tojsonbor change the column type. - Writing invalid JSON in the pattern. Single quotes inside the JSON, or a trailing comma, produce an error. The pattern is a normal JSON text inside a SQL string literal.
Exercise
Write a query that returns the ids of orders whose items array contains an element with sku "A1" and qty 1, and explain why {"items": [{"sku": "B7", "qty": 2}]} matches neither order in the sample data.
Show answer
Use SELECT id FROM orders WHERE details @> '{"items": [{"sku": "A1", "qty": 1}]}';. It returns id 2 (Grace's order). Ada's A1 item has qty 2, and her qty 1 item is B7. The second pattern matches nothing because containment matches each pattern object against a single array element. No element in either order has both sku B7 and qty 2.
Exercise
Which of these return true? (a) '{"a": {"b": 1}}'::jsonb ? 'b' (b) '["x", "y"]'::jsonb ? 'y' (c) '["x", "y"]'::jsonb @> '"x"' (d) '{"a": 1, "b": 2}'::jsonb @> '{}'
Show answer
(a) is false, because ? checks only the top-level keys and b is nested. (b) is true, because ? matches string elements of a top-level array. (c) is true, because a top-level array may contain a bare scalar. (d) is true, because an empty object is contained in any object.
Exercise
Write a query that returns orders that have both a status key and a shipping key but no tracking key. Why might you choose jsonb_exists over ? in some applications?
Show answer
SELECT id FROM orders WHERE details ?& array['status', 'shipping'] AND NOT (details ? 'tracking');. Some database drivers, such as JDBC, treat ? as a parameter placeholder. jsonb_exists(details, 'tracking') avoids the conflict, though only the operator form can use a GIN index.