JSON and JSONB
Use a jsonb column for documents whose fields vary from row to row: settings, event payloads, API responses, anything you would otherwise spread over many nullable columns. Use json when you need the document back exactly as it was sent. Both take the PostgreSQL operators and functions that applications and ORMs already send.
Declaring a column
CREATE TABLE orders (
id bigint PRIMARY KEY,
doc jsonb NOT NULL DEFAULT '{}',
raw json
);
INSERT INTO orders (id, doc, raw) VALUES
(1, '{"status": "paid", "total": 12.50, "tags": ["new", "vip"], "customer": {"id": 7, "name": "Ann"}}',
'{"b": 1, "a": 2}'),
(2, '{"status": "open", "total": 3, "tags": [], "customer": {"id": 9, "name": "Bob"}}', NULL);A column takes any JSON value: an object, an array, or a bare scalar such as 42, "text", true or null. Text that is not valid JSON is refused with SQLSTATE 22P02.
You can add a document column to an existing table the same way:
ALTER TABLE orders ADD COLUMN IF NOT EXISTS lines jsonb NOT NULL DEFAULT '[]';json or jsonb
jsonb | json | |
|---|---|---|
| Stored as | a binary document | the text as written |
| Whitespace | normalised on output | kept |
| Object key order | canonical: shorter keys first, then by bytes | as written |
| Duplicate keys | the last value wins | all kept; -> finds the last |
| Numbers | every digit and the scale kept (12.50 stays 12.50, 1e2 becomes 100) | kept as written |
@>, <@, ?, ?|, ?& | yes | no |
| GIN index | yes | no |
These are PostgreSQL's rules for both types. Pick jsonb unless you need the original text.
SELECT doc, raw FROM orders WHERE id = 1;{"tags": ["new", "vip"], "total": 12.50, "status": "paid", "customer": {"id": 7, "name": "Ann"}} | {"b": 1, "a": 2}Values are returned with the json or jsonb type on the wire, so typed drivers (sqlx, Npgsql, JDBC, psycopg, node-postgres) decode them as JSON. You can bind a document as a parameter in text or binary form.
Reading fields
| Operator | Right operand | Returns |
|---|---|---|
-> | a key ('status') or an array position (0, -1 counts from the end) | the member as jsonb / json |
->> | a key or a position | the member as text; a JSON string comes back without quotes |
#> | a path: '{customer,name}' or ARRAY['customer', 'name'] | the value at the path as jsonb / json |
#>> | a path | the value at the path as text |
A key that does not exist, a position past the end, and a JSON null read through ->> or #>> are all SQL NULL.
SELECT id,
doc->>'status' AS status,
doc->'customer'->>'name' AS customer,
doc#>>'{tags,0}' AS first_tag,
(doc->>'total')::numeric AS total
FROM orders
ORDER BY id; id | status | customer | first_tag | total
----+--------+----------+-----------+-------
1 | paid | Ann | new | 12.50
2 | open | Bob | | 3The operators work in the select list, in WHERE, GROUP BY and ORDER BY, on a qualified column (o.doc->>'status' in a join or under an alias) and on any expression that yields a document, such as a cast or a function call:
SELECT doc->>'status' AS status, count(*)
FROM orders
WHERE (doc->>'total')::numeric > 5
GROUP BY doc->>'status';
SELECT '{"a": {"b": 1}}'::jsonb -> 'a' ->> 'b';
SELECT coalesce(raw, '{}')->>'a' FROM orders;-> and ->> on a text column are refused with 42883 (operator does not exist), as in PostgreSQL. Cast first: body::jsonb->>'k'.
Searching documents
| Operator | Meaning |
|---|---|
doc @> '{"status": "paid"}' | doc contains the right-hand document |
'{"status": "paid"}' <@ doc | the left-hand document is contained in doc |
doc ? 'tags' | doc has the top-level key tags, or is an array holding the string 'tags' |
doc ?| ARRAY['a', 'b'] | any of the keys exists ('{a,b}' also works) |
doc ?& ARRAY['a', 'b'] | every key exists |
=, <>, <, <=, >, >= | compare whole documents in PostgreSQL's jsonb order |
Containment follows PostgreSQL: numbers compare by value ({"a": 1.0} contains {"a": 1}), and an array contains another when it holds each of its elements, in any order.
SELECT id FROM orders WHERE doc @> '{"customer": {"id": 7}}';
SELECT id FROM orders WHERE doc->'tags' @> '["vip"]';
SELECT id FROM orders WHERE doc ? 'tags' AND doc->>'status' IN ('paid', 'open');
SELECT id FROM orders WHERE doc->>'status' LIKE 'pa%';ORDER BY doc, DISTINCT, GROUP BY, UNION and join keys over jsonb use PostgreSQL's order and equality, so {"a": 1} and {"a": 1.0} are one group. Strings inside a document compare by their bytes (the C collation).
Changing documents
| Expression | Result |
|---|---|
a || b | jsonb concatenation: two objects merge (the right side wins on a shared key); otherwise the two sides become one array ('[1]'::jsonb || '[2, 3]' is [1, 2, 3], '{"o": 1}'::jsonb || '5' is [{"o": 1}, 5]). Two untyped string literals are text concatenation, as in PostgreSQL, so cast one side to jsonb |
jsonb_set(doc, path, value [, create_missing]) | doc with the value at path replaced; create_missing (default true) adds a missing last key |
jsonb_insert(doc, path, value [, insert_after]) | doc with value inserted into an array before the position at path (after it with true), or as a new object key |
jsonb_strip_nulls(doc) | doc with every object member whose value is null removed, at every depth |
UPDATE orders SET doc = jsonb_set(doc, '{status}', '"shipped"') WHERE id = 1;
UPDATE orders SET doc = doc || '{"note": "leave at the door"}' WHERE id = 1;
UPDATE orders SET doc = jsonb_insert(doc, '{tags,0}', '"priority"') WHERE id = 2;jsonb_insert refuses to replace an existing object key ("cannot replace existing key"); use jsonb_set for that. A NULL value makes jsonb_set return NULL, as in PostgreSQL.
Functions
Building documents
| Function | Returns |
|---|---|
jsonb_build_object(key, value, …) | a jsonb object from alternating keys and values (an even number of arguments) |
json_build_object(key, value, …) | the same as json, keys in the order given |
jsonb_build_array(value, …) / json_build_array(value, …) | an array of the arguments |
to_jsonb(value) / to_json(value) | a value as a JSON value |
SELECT jsonb_build_object('id', id, 'status', doc->>'status') FROM orders ORDER BY id;Inspecting documents
| Function | Returns |
|---|---|
jsonb_typeof(doc) / json_typeof(doc) | object, array, string, number, boolean or null |
jsonb_array_length(doc) / json_array_length(doc) | the number of elements of an array |
jsonb_pretty(doc) | the document as indented text |
jsonb_extract_path(doc, key, …), jsonb_extract_path_text(doc, key, …) and their json_ forms, the function spellings of #> and #>>.
Aggregates
| Function | Returns |
|---|---|
jsonb_agg(value) | a jsonb array of every value in the group, NULL as null |
json_agg(value) | the same as json |
Both accept ORDER BY inside the call and DISTINCT:
SELECT doc->>'status' AS status,
jsonb_agg(id ORDER BY id) AS ids,
json_agg(json_build_object('id', id, 'total', doc->'total')) AS orders
FROM orders
GROUP BY doc->>'status';A group's array is limited to 268,435,455 bytes, PostgreSQL's limit; past it the statement fails with 54000.
Expanding documents into rows
These go in FROM, alone or after a table (an implicit LATERAL), and take WITH ORDINALITY:
| Function | Rows |
|---|---|
jsonb_each(doc) | key text, value jsonb, one per member of an object |
jsonb_each_text(doc) | key text, value text |
jsonb_array_elements(doc) | value jsonb, one per element of an array |
jsonb_array_elements_text(doc) | value text |
jsonb_object_keys(doc) | one text row per top-level key |
jsonb_to_record(doc) AS r(col type, …) | one row with the columns you declare |
jsonb_to_recordset(doc) AS r(col type, …) | one row per object of an array |
SELECT o.id, t.value AS tag
FROM orders o, jsonb_array_elements_text(o.doc->'tags') AS t
ORDER BY o.id, tag;
SELECT o.id, m.key
FROM orders o CROSS JOIN LATERAL jsonb_each(o.doc) AS m
WHERE o.id = 1;
SELECT * FROM jsonb_to_recordset('[{"a": 1}, {"a": 2, "b": "z"}]') AS r(a int, b text);
SELECT id FROM orders o
WHERE EXISTS (SELECT 1 FROM jsonb_array_elements_text(o.doc->'tags') AS t(value) WHERE t.value = 'vip');Calling one on the wrong shape fails as in PostgreSQL, for example jsonb_each on an array: "cannot call jsonb_each on a non-object".
The json forms json_each, json_each_text, json_array_elements, json_array_elements_text and json_object_keys, which return members in the order written and keep duplicate keys; and a set-returning function alone in a select list or a subquery (SELECT jsonb_array_elements_text(doc->'tags') FROM orders, 'vip' IN (SELECT jsonb_array_elements_text(o.doc->'tags'))).
Indexing documents
A comparison on a path reads every row unless you index that path. The built-in filter index covers ordinary columns, not paths inside documents, and nothing indexes a path automatically, because a document can hold any number of different keys. Declare an index for each path or operator your queries filter on.
-- One path, as a B-tree over the text ->> reads:
CREATE INDEX orders_status ON orders ((doc->>'status'));
CREATE INDEX orders_customer_name ON orders ((doc->'customer'->>'name'));
CREATE INDEX orders_first_tag ON orders ((doc #>> '{tags,0}'));
-- Every key and value, for @>, ?, ?| and ?&:
CREATE INDEX orders_doc ON orders USING gin (doc);
-- Every leaf path, for @> only (smaller and more selective):
CREATE INDEX orders_doc_paths ON orders USING gin (doc jsonb_path_ops);| Index | Serves |
|---|---|
((doc->>'k')), ((doc->'a'->>'b')), ((doc #>> '{a,b}')) | =, IN / OR of values, and LIKE 'prefix%' on that same path written with ->> or #>> |
USING gin (doc) (jsonb_ops) | @>, ?, ?|, ?& |
USING gin (doc jsonb_path_ops) | @> |
Rules:
- A path index must end in
->>(or be#>>). An index over->is refused, because->yields documents of different types from row to row. - A GIN index takes exactly one
jsonbcolumn. doc @> '{}'matches every object and cannot use an index.- An index never changes an answer, only how many rows are read. A path index works on plain, partitioned and key/value tables alike.
See Indexes for how to check that a query used an index, and for DROP INDEX.
Storage: stored documents or shadow tables
By default a document is stored whole in its row, so a write is always one row write whatever the document holds. This is the right choice for almost every application.
The server can instead take each new document column apart into a hidden table of its own, one column per key (shredding). Start the server with:
rasterizeddb --json-shadow-tables true| Flag | Default | What it does |
|---|---|---|
--json-shadow-tables <BOOL> | off | Columns declared json or jsonb from now on are shredded into a shadow table instead of being stored whole |
Shredding makes a document's fields ordinary typed columns that the filter index prunes on directly, which helps only when every document shares a small, stable set of keys. It is a bad fit when keys are data (a map keyed by user IDs, statistics keyed by column name): each new key adds a column and rewrites the table, so loading slows down sharply as keys accumulate.
The flag decides only what a newly created column becomes. Each column records its own form, so existing columns are never reinterpreted, and both kinds can live in one database. A shredded column cannot be added to a partitioned table. See Configuration for how to set server flags.
Limits
- Not available: the
-and#-delete operators, SQL/JSON path (jsonpath,@?,@@onjsonb,jsonb_path_queryand the otherjsonb_path_*functions),jsonb_object_agg/json_object_agg, and the SQL-standardJSON_TABLE,JSON_VALUE,JSON_QUERY,JSON_EXISTS,JSON_OBJECT,JSON_ARRAY. Usejsonb_setto replace values andjsonb_eachwithjsonb_build_objectorjsonb_aggto rebuild documents. - A comparison on a document path reads every row unless that exact path has an index. A
->comparison (as opposed to->>) is never indexed. - Strings inside documents compare and sort by their bytes; collations do not apply inside documents.
- A path index's name and its path expression are each limited to 128 bytes.
Related pages: Tables and data types, Functions and operators, Querying data, Modifying data, PostgreSQL compatibility.