jsonb
- Version
- 19
- Since
- 9.4
- Review
- Draft
Summary#
jsonb stores JSON in a parsed binary form that supports operators and indexes. It does not preserve white space, object key order or duplicate keys.
Syntax#
document -> 'key'
document ->> 'key'
document #>> '{outer,inner}'
document @> '{"key": "value"}'
document ? 'key'
document @? '$.key ? (@ > 1)'
jsonb_set(document, '{outer,inner}', new_value)
UPDATE table_name SET document['outer']['inner'] = new_value WHERE condition;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE devices (
device_id integer PRIMARY KEY,
info jsonb NOT NULL
);
INSERT INTO devices VALUES
(1, '{"name": "probe", "tags": ["lab", "usb"], "limits": {"max": 40}}'),
(2, '{"name": "relay", "tags": ["field"], "limits": {"max": 75}}');
CREATE INDEX devices_info_idx ON devices USING gin (info);
SELECT device_id,
info ->> 'name' AS name,
info -> 'tags' ->> 0 AS first_tag,
(info #>> '{limits,max}')::integer AS max_limit
FROM devices
ORDER BY device_id;
-- Containment, key existence and a jsonpath predicate.
SELECT device_id
FROM devices
WHERE info @> '{"tags": ["lab"]}'
AND info ? 'limits'
AND info @? '$.limits.max ? (@ < 50)'
ORDER BY device_id;
UPDATE devices
SET info['limits']['max'] = '55'
WHERE device_id = 1;
UPDATE devices
SET info = jsonb_set(info, '{limits,min}', '5') || '{"active": true}'
WHERE device_id = 1;
SELECT jsonb_pretty(info) AS info FROM devices WHERE device_id = 1;
SELECT d.device_id, t.tag
FROM devices AS d
CROSS JOIN LATERAL jsonb_array_elements_text(d.info -> 'tags') AS t(tag)
ORDER BY d.device_id, t.tag;
ROLLBACK;
Expected output#
device_id|name|first_tag|max_limit
1|probe|lab|40
2|relay|field|75
(2 rows)
device_id
1
(1 row)
info
{
"name": "probe",
"tags": [
"lab",
"usb"
],
"active": true,
"limits": {
"max": 55,
"min": 5
}
}
(1 row)
device_id|tag
1|lab
1|usb
2|field
(3 rows)
Common mistakes#
jsonb_set returns SQL null when the new value is SQL null, which can overwrite the whole column with null. Pass 'null'::jsonb to store a JSON null. Every parent in the path must exist for jsonb_set to change the final key. Use a GIN index for containment with @> and a matching expression index for equality on info ->> 'name'.
Version applicability#
PostgreSQL 9.4 added jsonb. The example needs 9.5 for jsonb_set, jsonb_pretty and the || operator, 12 for the jsonpath operator @?, and 14 for subscripting such as info['limits'].
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0