Skip to content

Lesson 8 of 14 · 18m

JSONB: When the Document Earns Its Column

jsonb is the right tool for sparse, varying, write-once data — and the wrong tool for keys you filter on daily, because the planner barely understands it.

Every mature Postgres schema has the argument: "should this just be a jsonb column?" The answer isn't taste — it's mechanics. jsonb stores a parsed binary document; it supports containment, key existence, jsonpath operators, and GIN indexing. What it does not give you is types, constraints, meaningful planner statistics, or cheap partial updates. Those absences are what decide the question.

Where jsonb earns its place

  • Sparse, varying attributes — product specs, user preferences, form-builder answers, where rows share a spine but not a shape.
  • Event and audit payloads — payload jsonb on an events table where you write once and read whole documents.
  • API request/response logs — you'll never filter on most keys; you need faithful capture.

The spine still belongs in real columns. id, user_id, created_at, status — anything you join on, constrain, or filter constantly — is a column. The document is for the long tail.

Where it betrays you

Statistics. Postgres keeps almost no useful stats inside a jsonb document. WHERE payload @> '{"status":"open"}' — the planner's selectivity estimate for containment is a guess dressed as a number. On a big table, expect seq scans and surprising plans. EXPLAIN will show you rows=1 estimated, rows=900000 actual, and no index fixes a bad guess cheaply.

Whole-document rewrites. jsonb_set(payload, '{a,b}', '"c"') doesn't patch three bytes — it rewrites the entire document. A 200KB jsonb with one edited key is a 200KB write, a 200KB WAL record, a new dead tuple. Do that in a hot loop and you've reinvented write amplification. TOAST (the >2KB out-of-line storage mechanism) helps on read; it does nothing for the rewrite.

No enforcement. Nothing stops {"price": "nineteen"}. Any validation lives in your app or a CHECK constraint on jsonb_typeof.

Indexing the document

Before indexing anything, decide which operators your queries need:

payload @> '{"status": "open"}'              -- containment
payload ? 'status'                            -- key exists
jsonb_path_exists(payload, '$.a.b ? (@ > 5)') -- jsonpath
CREATE INDEX ON events USING gin (payload);                    -- default opclass
CREATE INDEX ON events USING gin (payload jsonb_path_ops);   -- the lean one

jsonb_path_ops produces a much smaller index but only serves containment (@>) and the jsonpath operators (@?, @@) — it drops support for key-existence operators (?, ?|, ?&). The default GIN opclass covers everything at 2–3× the index size. GIN maintenance is heavy — every insert updates many posting entries, and fastupdate = on trades insert latency for slightly stale index contents that get merged on scan or vacuum.

The escape hatch: generated extraction

When a key inside the document becomes hot — queries filtering payload->>'status' every second — don't debate GIN. Extract it:

ALTER TABLE events
  ADD COLUMN status text
  GENERATED ALWAYS AS (payload->>'status') STORED;
CREATE INDEX ON events (status);

A maintained-in-database real column: typed, constrained, indexed, with proper statistics, and no application code can forget to populate it. This is the correct sequence — data starts as document, the hot key graduates to a column when a workload proves it needs one. Since Postgres 18 you can also declare the column VIRTUAL (computed on read, no storage), though virtual columns can't be indexed — for this purpose you want STORED.

The practice

Columns for what you query and constrain; jsonb for what you carry. Index the document only if queries actually traverse it — a GIN you don't use is the most expensive index you'll ever maintain. And when a key graduates to hot-path status, graduate it physically: generated column, real index, real stats.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.