JSONB and Arrays
Document and array columns with operators and functions. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Busque em todas as páginas da documentação
Document and array columns with operators and functions. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
-> json, ->> text extraction.
SELECT body -> 'user' ->> 'id' AS user_id
FROM events;
-- user_id as textContainment for queries and GIN.
SELECT id FROM docs
WHERE body @> '{"type":"invoice"}'::jsonb;
-- docs with type invoiceSet a path to a new value.
SELECT jsonb_set('{"a":1}'::jsonb, '{a}', '2', false);
-- {"a": 2}&& true if arrays share elements.
SELECT ARRAY[1,2,3] && ARRAY[3,4];
-- tExpand array to rows.
SELECT unnest(ARRAY['a','b']) AS x;
--
-- x
-- a
-- bExpand object keys to rows.
SELECT * FROM jsonb_each('{"a":1,"b":2}'::jsonb);
-- key | valueExpand JSON arrays.
SELECT * FROM jsonb_array_elements('[1,2,3]'::jsonb) AS t(val);
-- val: 1,2,3 as jsonbjsonb_build_object / array.
SELECT jsonb_build_object('id', 1, 'ok', true);
-- {"id": 1, "ok": true}jsonpath existence (PG 12+).
SELECT body @? '$.items[*] ? (@.qty > 0)'
FROM carts;
-- t if any positive qtyarray_append / ||.
SELECT array_append(ARRAY[1,2], 3);
-- {1,2,3}Match any array element.
SELECT id FROM posts WHERE 'sql' = ANY (tags);
-- posts tagged sqlRemove null keys.
SELECT jsonb_strip_nulls('{"a":1,"b":null}'::jsonb);
-- {"a": 1}jsonb_agg builds arrays of objects.
SELECT user_id, jsonb_agg(jsonb_build_object('id', id)) AS orders
FROM orders GROUP BY user_id;Set key in UPDATE.
UPDATE docs
SET body = body || '{"status":"done"}'::jsonb
WHERE id = 1;
-- merges keysCardinality of arrays.
SELECT cardinality(ARRAY[1,2,3]);
-- 3Stack versions: PostgreSQL 18.4 (stable 18, maintenance 17) · pgvector 0.8+
Revisado por Chris St. John·Última atualização: 18 de jul. de 2026