Skip to content

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.

17 min read0/4 questions

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.

  • json stores 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.
  • jsonb parses 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.
schema.sql
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.

OperatorExampleReturns
->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:

A charge webhook as a jsonb tree
payloadjsonb objecttype"charge.succeeded"order_id9amount72700brand"visa"last4"4242"cardobjectdataobjectlivemodetrueroot

payload -> 'data' returns the whole data object, still as jsonb, so you can keep navigating with more operators.

1/5

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.

Pythonwebhooks.py
from shopdb import connect, showdb = connect() # Raw payment-provider webhooks, stored exactly as they arrived.db.executescript("""CREATE TABLE webhooks ( id INTEGER PRIMARY KEY, received_at TEXT NOT NULL, payload TEXT NOT NULL CHECK (json_valid(payload)));INSERT INTO webhooks (received_at, payload) VALUES ('2025-07-01 10:00', '{"type": "charge.succeeded", "data": {"order_id": 9, "amount": 72700, "currency": "usd", "card": {"brand": "visa", "last4": "4242"}}}'), ('2025-07-01 10:05', '{"type": "charge.failed", "data": {"order_id": 10, "amount": 189900, "currency": "usd", "failure": {"code": "card_declined"}}}'), ('2025-07-02 09:30', '{"type": "charge.refunded", "data": {"order_id": 4, "amount": 109900, "currency": "gbp"}, "livemode": true}');""") show(db, """SELECT id, payload -> '$.data.card' AS card_json, payload ->> '$.data.card.brand' AS brand, payload ->> '$.data.amount' AS amount, typeof(payload ->> '$.data.amount') AS amount_typeFROM webhooks""") # Filter and aggregate on fields inside the JSON.show(db, """SELECT payload ->> '$.type' AS type, COUNT(*) AS n, SUM(payload ->> '$.data.amount') AS amount_centsFROM webhooksWHERE payload ->> '$.data.currency' = 'usd'GROUP BY 1ORDER BY 1""")
Output
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:

Pythontags.py
from shopdb import connect, showdb = connect() # Sparse, per-category attributes live in one JSON column.db.executescript("""ALTER TABLE products ADD COLUMN attrs TEXT NOT NULL DEFAULT '{}';UPDATE products SET attrs = '{"ram_gb": 32, "tags": ["pro", "oled"]}' WHERE id = 1;UPDATE products SET attrs = '{"ram_gb": 16, "tags": ["light"]}' WHERE id = 2;UPDATE products SET attrs = '{"ports": 7, "tags": ["usb-c"]}' WHERE id = 3;UPDATE products SET attrs = '{"switches": "brown", "tags": ["wired"]}' WHERE id = 4;UPDATE products SET attrs = '{"tags": ["wireless"]}' WHERE id = 5;UPDATE products SET attrs = '{"battery_h": 30, "tags": ["wireless", "anc"]}' WHERE id = 6;UPDATE products SET attrs = '{"battery_h": 12, "tags": ["wireless"]}' WHERE id = 7;""") # json_each turns an array into rows, one per element.show(db, """SELECT p.name, t.value AS tagFROM products AS p, json_each(p.attrs, '$.tags') AS tWHERE t.value = 'wireless'ORDER BY p.id""") # Count tags across the catalogue.show(db, """SELECT t.value AS tag, COUNT(*) AS productsFROM products AS p, json_each(p.attrs, '$.tags') AS tGROUP BY t.valueHAVING COUNT(*) > 1""")
Output
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 add push to notify. It replaces the whole notify object, and the user's email and sms preferences are gone. Use jsonb_set on the exact path for nested changes.
  • jsonb_set with 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 added jsonb_set_lax, which lets you choose what NULL means.
  • jsonb_set only creates the last key. If notify itself 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:

Pythonedit_json.py
from shopdb import connectdb = connect()db.executescript("""CREATE TABLE settings (user_id INTEGER PRIMARY KEY, prefs TEXT NOT NULL);INSERT INTO settings VALUES (1, '{"theme": "dark", "notify": {"email": true, "sms": false}, "beta": true}');""") edits = { "set one path": "json_set(prefs, '$.notify.sms', json('true'))", "remove a key": "json_remove(prefs, '$.beta')", "merge patch": "json_patch(prefs, '{\"notify\": {\"push\": true}}')",}for label, expr in edits.items(): (result,) = db.execute(f"SELECT {expr} FROM settings WHERE user_id = 1").fetchone() print(f"{label:13} {result}")
Output
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:

Pythonnested_json.py
from shopdb import connectimport jsondb = connect() # One query returns a customer with their orders and line items nested inside.(doc,) = db.execute("""SELECT json_object( 'id', c.id, 'name', c.name, 'orders', ( SELECT json_group_array(json_object( 'id', o.id, 'status', o.status, 'items', ( SELECT json_group_array(json_object('product', p.name, 'qty', oi.quantity)) FROM order_items AS oi JOIN products AS p ON p.id = oi.product_id WHERE oi.order_id = o.id))) FROM orders AS o WHERE o.customer_id = c.id))FROM customers AS cWHERE c.id = ?""", (2,)).fetchone() print(json.dumps(json.loads(doc), indent=2))
Output
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:

Pythonjson_index.py
from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE signups ( id INTEGER PRIMARY KEY, profile TEXT NOT NULL CHECK (json_valid(profile)));INSERT INTO signups (profile) VALUES ('{"email": "ada@example.com", "plan": "pro", "utm": {"source": "newsletter"}}'), ('{"email": "alan@example.com", "plan": "free"}'), ('{"email": "grace@example.com", "plan": "pro", "utm": {"source": "ads"}}');""") query = "SELECT id FROM signups WHERE profile ->> '$.email' = 'alan@example.com'" def plan(sql): for row in db.execute("EXPLAIN QUERY PLAN " + sql): print(" ", row[-1]) print("no index:")plan(query) # An expression index on exactly the expression the query uses.db.execute("CREATE INDEX signups_email_idx ON signups (profile ->> '$.email')")print("expression index:")plan(query) # Promote a hot field to a generated column, then index it like any column.db.executescript("""ALTER TABLE signups ADD COLUMN plan TEXT GENERATED ALWAYS AS (profile ->> '$.plan') VIRTUAL;CREATE INDEX signups_plan_idx ON signups (plan);""")print("generated column:")plan("SELECT id FROM signups WHERE plan = 'pro'")show(db, "SELECT id, plan, profile ->> '$.utm.source' AS source FROM signups")
Output
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.

Predict the outputPython

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])
Need a nudge? Hints walk you through it.
Quick check
products.attrs has CREATE INDEX ... USING GIN (attrs jsonb_path_ops). Which query can use it?
Need a nudge? A hint rules out a wrong answer.
Quick check
prefs is {"notify": {"email": true, "sms": false}}. You run UPDATE settings SET prefs = prefs || '{"notify": {"push": true}}'. What is prefs now?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Match each Postgres expression to what it does.

Choose an item, then its match on the other side.
Key terms
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.