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 jsonbon aneventstable 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)') -- jsonpathCREATE INDEX ON events USING gin (payload); -- default opclass
CREATE INDEX ON events USING gin (payload jsonb_path_ops); -- the lean onejsonb_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?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
MySQL, PostgreSQL, Redis, and MongoDB End-of-Life Dates in 2026
Four major open source databases are hitting end-of-life milestones in 2026, and MySQL 8.0 has already crossed that line. Here's a practical, code-first look at how to audit what you're running, back it up properly, and migrate before the risk compounds.