Lesson 23 of 29Postgres in production
JSON and JSONB in Postgres
Store, query, index and build JSON in Postgres with jsonb, GIN and SQL/JSON, and know when a JSON field should become a real column.
Your payments provider sends webhooks with forty fields, nested three levels deep, and adds new ones every quarter. Product wants laptops to have ram_gb and headphones to have battery_h, without a migration for every category. The front end wants an order with its items as one nested JSON document. All three are jobs for Postgres's jsonb type, and all three can go badly wrong if you treat a JSON column as a schema-free shortcut. This lesson covers the operators you will use every week, how to index them, how to build JSON responses in SQL, and the judgement call that matters most: what belongs in JSON and what belongs in a column. PostgreSQL for Developers gave you one paragraph on jsonb; this is the full version.
json versus jsonb
Postgres has two JSON types, and you almost always want the second.
jsonstores the text exactly as received: whitespace, key order and duplicate keys included. Every query re-parses it. Use it only when you must keep the original bytes, for example to verify a webhook signature later.jsonbparses the input once and stores a binary form. Whitespace is dropped, keys are reordered, and if a key appears twice only the last value is kept. In exchange it is fast to query, supports containment and existence operators, and can be indexed.
CREATE TABLE webhooks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
received_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL
);
SELECT '{"b": 1, "a": 2, "a": 3}'::json; -- {"b": 1, "a": 2, "a": 3}
SELECT '{"b": 1, "a": 2, "a": 3}'::jsonb; -- {"a": 3, "b": 1}A common pattern stores the raw body in a text or bytea column for auditing and signature checks, and the parsed jsonb next to it for querying.
Reading values: the operators
The core operators differ in two ways: whether they take one key or a whole path, and whether they return jsonb or text.
| Operator | Example | Returns |
|---|---|---|
-> | payload -> 'data' | jsonb (a key, or an array index such as -> 0) |
->> | payload -> 'data' ->> 'currency' | text |
#> | payload #> '{data,card}' | jsonb at a path |
#>> | payload #>> '{data,card,brand}' | text at a path |
@> | payload @> '{"type": "charge.failed"}' | true if the left side contains the right |
? | payload ? 'livemode' | true if the top-level key exists |
?|, ?& | attrs ?| array['ram_gb', 'ports'] | any key exists, all keys exist |
Walk through them on one webhook:
payload -> 'data' returns the whole data object, still as jsonb, so you can keep navigating with more operators.
The ->> returning text is the source of a classic bug. WHERE payload ->> 'amount' > '9' compares strings, so '10000' is smaller than '9'. Always cast before comparing numbers or dates.
SQLite has the same -> and ->> operators (since 3.38), plus json_extract, so you can practice on the course dataset. One difference: SQLite's ->> returns a real SQL number for JSON numbers, while Postgres returns text.
Press Run (⌘ Enter) to see what happens.A missing key is not an error: it returns NULL, as the card columns show for rows 2 and 3. That is convenient and dangerous. A typo such as ->> 'ammount' silently returns NULL for every row, and your revenue report reads zero.
Arrays into rows
Arrays inside JSON are where SQL needs help. Postgres turns them into rows with jsonb_array_elements (each element as jsonb) or jsonb_array_elements_text, used as a lateral function in FROM. SQLite's equivalent is json_each:
Press Run (⌘ Enter) to see what happens.In Postgres you would not unnest just to filter. Containment says it directly, and it can use an index:
SELECT name FROM products WHERE attrs @> '{"tags": ["wireless"]}';
SELECT p.name, t.tag
FROM products AS p
CROSS JOIN LATERAL jsonb_array_elements_text(p.attrs -> 'tags') AS t(tag);SQL/JSON path and JSON_TABLE
For anything deeper than a fixed path, Postgres implements the SQL standard's jsonpath language. It has filters, wildcards and comparisons inside the path:
-- Every line item with a quantity above 1.
SELECT jsonb_path_query(payload, '$.data.items[*] ? (@.qty > 1)') FROM webhooks;
-- @? : does the path match anything? @@ : is this predicate true?
SELECT id FROM webhooks WHERE payload @? '$.data.items[*] ? (@.qty > 1)';
SELECT id FROM webhooks WHERE payload @@ '$.data.amount > 100000';Postgres 17 added the standard SQL/JSON query functions. JSON_VALUE extracts a scalar with a declared type, JSON_QUERY extracts a fragment, JSON_EXISTS tests a path, and JSON_TABLE turns a JSON document into a proper relational table you can join:
SELECT w.id, jt.product_id, jt.qty
FROM webhooks AS w,
JSON_TABLE(w.payload, '$.data.items[*]'
COLUMNS (
product_id int PATH '$.product_id',
qty int PATH '$.qty'
)) AS jt;
SELECT JSON_VALUE(payload, '$.data.amount' RETURNING int) FROM webhooks;JSON_TABLE is the cleanest way to load a JSON import into normal tables: one INSERT ... SELECT from it, with types declared once.
Changing JSON
Updating a key in place uses jsonb_set, or since Postgres 14, subscripting. Merging uses ||, and removing uses - for a key or #- for a path:
UPDATE settings SET prefs = jsonb_set(prefs, '{notify,sms}', 'true') WHERE user_id = 1;
UPDATE settings SET prefs['theme'] = '"light"' WHERE user_id = 1; -- Postgres 14+
UPDATE settings SET prefs = prefs - 'beta' WHERE user_id = 1;
UPDATE settings SET prefs = prefs || '{"notify": {"push": true}}' WHERE user_id = 1;Three traps catch people in production:
||is a shallow merge. The last statement does not addpushtonotify. It replaces the wholenotifyobject, and the user'semailandsmspreferences are gone. Usejsonb_seton the exact path for nested changes.jsonb_setwith a NULL value returns NULL. If the new value comes from a parameter that happens to be NULL,SET prefs = jsonb_set(prefs, '{x}', $1)wipes the entire column for that row. Postgres 13 addedjsonb_set_lax, which lets you choose what NULL means.jsonb_setonly creates the last key. Ifnotifyitself is missing, setting{notify,sms}returns the document unchanged, with no error.
SQLite's functions behave a little differently. Its json_patch follows the JSON Merge Patch standard, which merges nested objects instead of replacing them:
Press Run (⌘ Enter) to see what happens.Each update also rewrites the whole value. A jsonb document larger than about 2 kB is compressed and stored out of line (TOAST), and changing one key writes a complete new copy plus a new row version. A 50 kB document that you update ten times a second is a write-amplification problem. Hot counters belong in columns.
Building JSON in SQL
APIs often need nested JSON: a customer with orders, each with items. Building it in application code usually means N+1 queries or a join you regroup by hand. Postgres can build it in one query with jsonb_build_object and jsonb_agg:
SELECT jsonb_build_object(
'id', c.id,
'name', c.name,
'orders', COALESCE(
(SELECT jsonb_agg(jsonb_build_object('id', o.id, 'status', o.status) ORDER BY o.id)
FROM orders AS o WHERE o.customer_id = c.id),
'[]'::jsonb)
) AS doc
FROM customers AS c
WHERE c.id = $1;Note the COALESCE: jsonb_agg over zero rows returns NULL, not an empty array, and your front end crashes on null.map. SQLite spells the same idea json_object and json_group_array:
Press Run (⌘ Enter) to see what happens.This is fast for detail pages and exports. For list endpoints, measure: building large documents in the database moves CPU from your stateless app servers to your one primary, which is the hardest thing to scale.
Indexing JSON
A JSON column without the right index is a sequential scan on every query. There are two tools, for two query shapes.
GIN indexes answer "which rows contain this?" They index every key and value in the document:
CREATE INDEX products_attrs_gin ON products USING GIN (attrs); -- jsonb_ops
CREATE INDEX webhooks_payload_gin ON webhooks USING GIN (payload jsonb_path_ops);The default operator class, jsonb_ops, supports @>, ?, ?|, ?&, @? and @@. jsonb_path_ops supports only @>, @? and @@, but it is usually much smaller and faster, because it hashes whole paths rather than indexing each key separately. If you only query by containment, choose jsonb_path_ops. GIN indexes are slower to update than B-trees, which matters on write-heavy tables.
B-tree expression indexes answer "where is the row whose field equals this, or sorts here?" A GIN index cannot help payload ->> 'email' = $1 or ORDER BY on a field. Index the exact expression your query uses:
CREATE INDEX signups_email_idx ON signups ((profile ->> 'email'));The double parentheses are required for an expression. And the query must use the identical expression: an index on profile ->> 'email' does not help lower(profile ->> 'email'). Here is the same idea in SQLite, including the step most teams eventually take, promoting the field to a generated column:
Press Run (⌘ Enter) to see what happens.One more thing seniors know: the planner keeps little or no statistics about values inside a JSON column, so its row estimates for JSON filters are often guesses, and guesses produce bad join plans. An expression index gets its own statistics after ANALYZE, and CREATE STATISTICS can collect them on an expression without an index (Postgres 14+).
When to use JSON, and when not to
The question is never "can I store this as JSON?" You always can. The question is what you lose: types, NOT NULL, CHECK, foreign keys, cheap single-field updates, planner statistics and readable migrations.
JSON fits well for:
- Third-party payloads you store before you understand them: webhooks, API responses, audit snapshots.
- Sparse or user-defined attributes: per-category product specs, custom fields a customer defines. This is the classic alternative to the entity-attribute-value tables from the data modelling lesson, and it is usually the better one.
- Settings and feature flags read as a whole and rarely filtered.
Promote a field to a real column when you filter, join, sort or aggregate on it often, when it must be required or unique, when another table must reference it, or when it is updated frequently. Promotion is an ordinary expand and contract migration, as covered in Zero-Downtime Migrations: add the column, backfill it from the JSON, switch reads, then stop writing the key.
If you keep data in JSON, validate its shape. Do it in the app (a Pydantic model on the way in), and add a database CHECK for the invariants you cannot afford to lose, such as CHECK (jsonb_typeof(attrs -> 'tags') = 'array'). Without either, after a year the column holds five shapes of the same thing.
Postgres's ->> always returns text. This query imitates that by casting. What does it print?
from shopdb import connect
db = connect()
rows = db.execute("""
SELECT CAST(value ->> '$.qty' AS TEXT) AS qty
FROM json_each('[{"qty": 9}, {"qty": 10}, {"qty": 100}]')
ORDER BY qty
""").fetchall()
print([r[0] for r in rows])products.attrs has CREATE INDEX ... USING GIN (attrs jsonb_path_ops). Which query can use it?prefs is {"notify": {"email": true, "sms": false}}. You run UPDATE settings SET prefs = prefs || '{"notify": {"push": true}}'. What is prefs now?Match each Postgres expression to what it does.
- jsonb
- Postgres's binary JSON type: parsed once, keys deduplicated and reordered, fast to query and indexable.
- containment (@>)
- An operator that is true when the left document includes every key and value of the right one. GIN indexes accelerate it.
- jsonpath
- The SQL standard path language for JSON, with wildcards and filters, used by jsonb_path_query, @? and @@.
- JSON_TABLE
- A Postgres 17 function that turns JSON into typed rows and columns you can join or insert from.
- GIN index
- An inverted index over every key and value in a document. jsonb_ops supports key existence; jsonb_path_ops is smaller but containment-only.
- expression index
- A B-tree index on a computed expression such as
(profile ->> 'email'), used only when a query repeats the exact expression. - TOAST
- Postgres's storage for large values: compressed and out of line. Updating one key rewrites the whole value.