JSON & JSONB
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
PostgreSQL is one of the few relational databases where semi-structured documents are a first-class, indexable
type. This page covers the two JSON types, the operator and function families that work on them, the standard
SQL/JSON query functions, and the indexing options that make jsonb fast. Everything was run on PostgreSQL 18.6
(postgres:latest) against the shop schema from Getting Started;
the examples use shop.products.attrs, a jsonb column. Large outputs are trimmed where stated. For engine-agnostic
JSON and XML syntax see JSON & XML functions, and for the document-database
alternative see MongoDB.
All snippets assume SET search_path = shop;.
json versus jsonb
PostgreSQL offers two types with the same input syntax:
-
jsonstores the text exactly as received, including whitespace, key order and duplicate keys. It is re-parsed on every operation. -
jsonbstores a decomposed binary representation. Whitespace is dropped, keys are de-duplicated (the last value wins) and keys are stored in an internal order. Operations do not re-parse, andjsonbis the only type that supports indexing and the containment operators.
SELECT '{"a":1, "b":2, "a":3}'::json AS j, '{"a":1, "b":2, "a":3}'::jsonb AS jb;
j | jb
------------------------+------------------
{"a":1, "b":2, "a":3} | {"a": 3, "b": 2}
Storage is not always smaller for jsonb. For a tiny document the binary form carries headers, so it can be larger:
SELECT pg_column_size('{"a": 1, "b": [1,2,3]}'::json) AS json_bytes,
pg_column_size('{"a": 1, "b": [1,2,3]}'::jsonb) AS jsonb_bytes;
json_bytes | jsonb_bytes
------------+-------------
29 | 76
Use jsonb by default. Choose json only when you must preserve the exact text of the input (an audit log of
received payloads, for example) and never query inside it.
A CHECK constraint with the SQL standard IS JSON predicate rejects non-object values at write time:
ALTER TABLE products ADD CONSTRAINT attrs_is_object CHECK (attrs IS JSON OBJECT);
IS JSON also has ARRAY, SCALAR and WITH UNIQUE KEYS forms:
SELECT '{"a":1}' IS JSON AS ok, '{a:1}' IS JSON AS bad, '[1,2]' IS JSON ARRAY AS arr,
'{"a":1,"a":2}' IS JSON WITH UNIQUE KEYS AS uniq;
ok | bad | arr | uniq ----+-----+-----+------ t | f | t | f
Access operators
The two basic operators differ only in the type they return: -> returns jsonb (so it can be chained), and
->> returns text.
SELECT sku, attrs -> 'color' AS color_json, attrs ->> 'color' AS color_text FROM products ORDER BY sku;
sku | color_json | color_text -----+------------+------------ A-1 | "oak" | oak A-2 | "black" | black B-7 | "white" | white C-3 | | C-9 | |
A missing key yields SQL NULL, not an error. #> and #>> follow a path given as a text[]; an integer
operand to -> indexes into an array (negative values count from the end).
SELECT sku, attrs #> '{color}' AS p, attrs #>> '{width_cm}' AS w FROM products WHERE attrs ? 'width_cm';
sku | p | w -----+-------+----- A-1 | "oak" | 160
| Operator | Meaning |
|---|---|
|
Field or element as |
|
Field or element as |
|
Value at a path, as |
|
Left contains right ( |
|
Left is contained in right |
|
Does the top-level key or string element exist |
|
Does any of the keys in the array exist |
|
Do all of the keys in the array exist |
|
Concatenate (merge) two |
|
Delete a key, several keys or an array index |
|
Delete the value at a path |
|
jsonpath predicate operators (see below) |
Containment and key existence
@> tests structural containment and is the operator GIN indexes accelerate best.
SELECT sku FROM products WHERE attrs @> '{"color": "black"}';
SELECT sku FROM products WHERE attrs ? 'watts';
SELECT sku FROM products WHERE attrs ?| ARRAY['mesh','hdr'] ORDER BY sku;
SELECT sku FROM products WHERE attrs ?& ARRAY['color','watts'];
The four queries return A-2 (containment), B-7 (key watts exists), A-2 and C-9 (any of mesh, hdr)
and B-7 (both color and watts).
Values extracted with ->> are text, so cast before comparing numerically:
SELECT sku, (attrs ->> 'watts')::int AS watts FROM products WHERE attrs ? 'watts';
sku | watts -----+------- B-7 | 9
Inline pitfall: attrs ->> 'weight' > '9' compares strings, so '100' < '9'. Always cast, or compare with
@> or a jsonpath.
Modifying jsonb
jsonb values are immutable; every function returns a new value, and an UPDATE rewrites the whole row.
SELECT attrs - 'color' AS no_color, attrs #- '{width_cm}' AS no_w FROM products WHERE sku='A-1';
no_color | no_w
---------------------------------------+--------------------------------------
{"width_cm": 160, "adjustable": true} | {"color": "oak", "adjustable": true}
jsonb_set(target, path, new_value, create_if_missing) replaces a value; jsonb_insert adds into an array at a
position; || merges objects with the right operand winning.
SELECT jsonb_set(attrs, '{color}', '"walnut"') AS s1,
jsonb_set(attrs, '{dims,depth}', '80', true) AS s2
FROM products WHERE sku='A-1';
s1 | s2
----------------------------------------------------------+-------------------------------------------------------
{"color": "walnut", "width_cm": 160, "adjustable": true} | {"color": "oak", "width_cm": 160, "adjustable": true}
s2 shows the main pitfall: jsonb_set creates only the last path element, so a path whose parent (dims) does
not exist leaves the value unchanged. Create the parent first by merging an object. jsonb_set_lax adds a
null_value_treatment argument for SQL NULL input.
SELECT jsonb_insert('{"tags":["a","c"]}', '{tags,1}', '"b"') AS ins,
jsonb_insert('{"tags":["a","c"]}', '{tags,1}', '"b"', true) AS ins_after;
ins | ins_after
---------------------------+---------------------------
{"tags": ["a", "b", "c"]} | {"tags": ["a", "c", "b"]}
A typical in-place update merges a patch object:
UPDATE products SET attrs = attrs || '{"warranty_years": 2}' WHERE sku = 'A-1' RETURNING sku, attrs;
sku | attrs
-----+----------------------------------------------------------------------------
A-1 | {"color": "oak", "width_cm": 160, "adjustable": true, "warranty_years": 2}
jsonpath
jsonpath is the SQL/JSON path language: $ is the document, .key and [*] navigate, and ? (...) filters.
The jsonb_path_* functions evaluate it, and variables are passed as a jsonb object.
SELECT jsonb_path_query('{"items":[{"p":10},{"p":25},{"p":40}]}', '$.items[*] ? (@.p > 20).p');
SELECT jsonb_path_query_array('{"items":[{"p":10},{"p":25},{"p":40}]}',
'$.items[*].p ? (@ > $min)', '{"min": 15}');
SELECT jsonb_path_query_first('{"items":[{"p":10},{"p":25}]}', '$.items[*].p.double()');
The three calls return the rows 25 and 40, the array [25, 40], and the single value 10 respectively.
The predicate operators return a boolean and can use a GIN index:
@? is true when the path yields any item, and @@ evaluates a predicate expression.
SELECT jsonb_path_exists(attrs, '$.watts ? (@ > 5)') AS e,
attrs @? '$.ports ? (@ >= 7)' AS e2,
attrs @@ '$.ports > 5' AS m
FROM products WHERE sku='C-3';
e | e2 | m ---+----+--- f | t | t
Here e is false because C-3 has no watts key. In lax mode (the default) a missing key or a type mismatch makes
the filter evaluate to nothing rather than raising an error; prefix a path with strict to get errors.
Expanding and building JSON
Set-returning functions turn a document into rows:
SELECT key, value FROM products, jsonb_each(attrs) WHERE sku='C-9';
SELECT * FROM jsonb_to_recordset('[{"sku":"X-1","qty":2},{"sku":"X-2","qty":5}]') AS t(sku text, qty int);
SELECT jsonb_array_elements('[1,2,{"x":3}]');
key | value
-------------+-------
diagonal_in | 27
hdr | false
panel | "IPS"
sku | qty
-----+-----
X-1 | 2
X-2 | 5
jsonb_array_elements
----------------------
1
2
{"x": 3}
The reverse direction builds documents from relational data, which is how an API layer can return one JSON document per order straight from a join:
SELECT o.id,
jsonb_build_object('customer', c.name,
'lines', jsonb_agg(jsonb_build_object('sku', i.sku, 'qty', i.qty) ORDER BY i.sku)) AS doc
FROM orders o JOIN customers c ON c.id = o.customer_id
JOIN order_items i ON i.order_id = o.id
WHERE o.id IN (1001, 1004) GROUP BY o.id, c.name ORDER BY o.id;
id | doc
------+---------------------------------------------------------------------------------------------
1001 | {"lines": [{"qty": 1, "sku": "A-1"}, {"qty": 2, "sku": "B-7"}], "customer": "Ada Lovelace"}
1004 | {"lines": [{"qty": 2, "sku": "A-1"}, {"qty": 4, "sku": "A-2"}], "customer": "Grace Hopper"}
Other builders: jsonb_build_array, jsonb_object_agg(key, value), jsonb_pretty for display, and to_jsonb(row)
which serialises a whole row:
SELECT to_jsonb(p) FROM products p WHERE sku='B-7';
{"sku": "B-7", "name": "Desk Lamp", "tags": ["office", "led"], "attrs": {"color": "white", "watts": 9}, "price": 24.99, "stock": 150, "category": "lighting"}
SQL/JSON functions
PostgreSQL 17 added the SQL standard query functions, and they work on 18.6. They take a jsonpath and give more control over the result type and error handling than the operators.
JSON_VALUE extracts one scalar (default result type text; use RETURNING to convert):
SELECT sku, JSON_VALUE(attrs, '$.color') AS color, JSON_VALUE(attrs, '$.watts' RETURNING int) AS watts
FROM products ORDER BY sku;
sku | color | watts -----+-------+------- A-1 | oak | A-2 | black | B-7 | white | 9 C-3 | | C-9 | |
JSON_QUERY returns a JSON fragment, and WITH WRAPPER wraps results in an array. JSON_EXISTS is a boolean test:
SELECT JSON_QUERY('{"a":[1,2]}'::jsonb, '$.a' WITH WRAPPER) AS w,
JSON_QUERY('{"a":[1,2]}'::jsonb, '$.a[*]' WITH ARRAY WRAPPER) AS w2;
SELECT sku FROM products WHERE JSON_EXISTS(attrs, '$.ports ? (@ > 5)');
w | w2 ----------+-------- [[1, 2]] | [1, 2] sku ----- C-3
Error and empty behaviour is explicit, for example DEFAULT ... ON EMPTY:
SELECT JSON_VALUE('{"a":"x"}'::jsonb, '$.b' DEFAULT 'none' ON EMPTY) AS d;
d ------ none
JSON_TABLE projects a document into a relational row set, with FOR ORDINALITY, typed PATH columns and
EXISTS PATH columns. It is the standard replacement for chains of jsonb_array_elements and jsonb_to_recordset:
SELECT p.sku, jt.*
FROM products p,
JSON_TABLE(p.attrs, '$' COLUMNS (
color text PATH '$.color',
watts int PATH '$.watts' DEFAULT 0 ON EMPTY,
ports int PATH '$.ports',
has_hdr bool EXISTS PATH '$.hdr')) AS jt
ORDER BY p.sku;
sku | color | watts | ports | has_hdr -----+-------+-------+-------+--------- A-1 | oak | 0 | | f A-2 | black | 0 | | f B-7 | white | 9 | | f C-3 | | 0 | 7 | f C-9 | | 0 | | t
Note that has_hdr is true only for C-9: EXISTS PATH tests whether the path matches, and hdr exists in
C-9 with the value false; the other rows have no hdr key. Nested arrays use a NESTED PATH clause. Constructors
JSON_OBJECT('k' VALUE v), JSON_ARRAYAGG(x ORDER BY y) and JSON_OBJECTAGG are also available:
SELECT JSON_OBJECT('sku' VALUE sku, 'price' VALUE price) FROM products WHERE sku='B-7';
SELECT JSON_ARRAYAGG(sku ORDER BY sku) FROM products;
json_object
----------------------------------
{"sku" : "B-7", "price" : 24.99}
json_arrayagg
-------------------------------------
["A-1", "A-2", "B-7", "C-3", "C-9"]
These constructors return json, not jsonb, which is why the spacing differs from the jsonb_build_* output.
Indexing jsonb with GIN
A B-tree cannot answer "does this document contain X". A GIN (Generalized Inverted Index) maps each key and value inside the documents to the rows containing it. Two operator classes exist:
| Operator class | Supports | Trade-off |
|---|---|---|
|
|
Indexes every key and value separately; larger |
|
|
Hashes whole paths to values; smaller and faster for containment, but no key-existence operators |
The experiment uses a generated table of 200,000 rows with color, size, weight and a tags array. Without an
index, a containment query scans the table:
Finalize Aggregate (actual rows=1.00 loops=1)
-> Gather (actual rows=3.00 loops=1)
-> Partial Aggregate (actual rows=1.00 loops=3)
-> Parallel Seq Scan on big_products (actual rows=476.00 loops=3)
Filter: (attrs @> '{"size": "XL", "tags": ["t3"], "color": "red"}'::jsonb)
Rows Removed by Filter: 66191
Buffers: shared hit=2304 read=1024
After CREATE INDEX big_attrs_pathops ON big_products USING gin (attrs jsonb_path_ops), the same query becomes a
bitmap scan that touches 1,462 buffers instead of 3,328:
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=1462
-> Bitmap Heap Scan on big_products (actual rows=1428.00 loops=1)
Recheck Cond: (attrs @> '{"size": "XL", "tags": ["t3"], "color": "red"}'::jsonb)
-> Bitmap Index Scan on big_attrs_pathops (actual rows=1428.00 loops=1)
Index Cond: (attrs @> '{"size": "XL", "tags": ["t3"], "color": "red"}'::jsonb)
Buffers: shared hit=34
The default jsonb_ops index answers the same query by reading 199 index buffers (versus 34 for jsonb_path_ops),
and its on-disk size is larger:
SELECT relname, pg_size_pretty(pg_relation_size(oid)) FROM pg_class
WHERE relname IN ('big_products','big_attrs_gin','big_attrs_pathops') ORDER BY relname;
relname | pg_size_pretty -------------------+---------------- big_attrs_gin | 2928 kB big_attrs_pathops | 2032 kB big_products | 26 MB
Key-existence is where the classes differ. On a second table where only 1 row in 1,000 has a recalled key, the
default class supports ?:
-> Bitmap Heap Scan on big_products (actual rows=200.00 loops=1)
Recheck Cond: (attrs ? 'recalled'::text)
-> Bitmap Index Scan on g1 (actual rows=200.00 loops=1)
After replacing it with jsonb_path_ops, the same query falls back to a sequential scan, while the containment form
attrs @> '{"recalled": true}' uses the index again:
Aggregate (actual rows=1.00 loops=1)
-> Seq Scan on big_products (actual rows=200.00 loops=1)
Filter: (attrs ? 'recalled'::text)
Rows Removed by Filter: 199800
A selectivity note: when most rows match, such as attrs ? 'color' on data where every row has that key, the
planner correctly prefers a sequential scan even with a GIN index. Indexes help only for selective predicates.
See Indexing for GIN internals and
Query Planning & EXPLAIN for reading these plans.
Expression indexes and generated columns
When queries always filter on the same extracted field, a B-tree on that expression is smaller and supports range scans and sorting. The query must use the identical expression:
CREATE INDEX big_weight_expr ON big_products (((attrs->>'weight')::int));
With the index, WHERE (attrs->>'weight')::int = 42 uses a Bitmap Index Scan on big_weight_expr (2,000 rows,
four index buffers read). A textually different expression, WHERE attrs->>'weight' = '42', cannot use it and
remains a sequential scan:
Parallel Seq Scan on big_products Filter: ((attrs ->> 'weight'::text) = '42'::text)
A stored generated column is often clearer: it exposes the JSON field as a normal column that can be indexed, constrained and used by ORMs.
ALTER TABLE big_products ADD COLUMN color text GENERATED ALWAYS AS (attrs->>'color') STORED;
CREATE INDEX big_color ON big_products(color);
color | text | generated always as (attrs ->> 'color'::text) stored
Indexes:
"big_color" btree (color)
When to use jsonb, and when not to
| Good fit | Poor fit |
|---|---|
Sparse, per-row attributes that differ by category (the |
Data every row has and every query filters on: make it a column |
Payloads stored and returned as a unit (webhooks, configuration, API responses) |
Relationships: use foreign keys so the database enforces integrity |
Prototyping a schema that is not settled yet |
Frequently updated fields in large documents: every update rewrites the whole value (and TOASTed values are rewritten too) |
Event or audit data read mostly by containment |
Heavy aggregation over inner fields without an expression index or generated column |
A common hybrid is to keep identity, price and stock as columns and put category-specific attributes in attrs,
exactly as the shop.products table does. Statistics are another reason to prefer columns: the planner keeps
per-column statistics, but only coarse ones for values buried in a jsonb document, so it estimates selectivity of
JSON predicates poorly unless an expression index exists.