
On this page
- When does a JSONB column actually earn its place?
- What does JSONB cost you at query time?
- Can’t you just add a GIN index and move on?
- What breaks first: constraints, writes, or migrations?
- How do you promote a JSONB key to a real column without downtime?
- How do you decide between JSONB and separate tables?
- Why is JSONB’s flexibility a loan?
- Questions people ask
Look for a JSONB column called metadata, attributes, properties or extra in your schema, and ask what lives inside it. If the honest answer isn’t “documents” but “stuff we hadn’t decided on yet”, this article is about that column.
The reflex is easy to understand. Adding a column means a migration, a review, maybe a conversation about coordinating the deploy. Dropping a key into an existing JSONB blob means none of that. So the blob grows, one deferred decision at a time, until half the application’s WHERE clauses are reaching inside it.
My point here is narrower than “JSONB bad”. JSONB is one of the best reasons to pick Postgres (it’s one of the capabilities in Postgres does more than you think), and there’s a class of data where it’s clearly the right answer. But there’s a line, and it’s crisper than most teams think: JSONB is for data that really is a document. It isn’t a place to park modeling decisions you don’t want to make yet. This article is about telling those two apart, and what it costs when you don’t.
When does a JSONB column actually earn its place?
When the data is genuinely a document: it arrives whole, it leaves whole, and its shape is decided somewhere you don’t control. Webhook payloads, third-party API responses, audit snapshots and user-defined custom fields all qualify. In each of them the schema lives outside your codebase, and pretending otherwise means chasing someone else’s changes with migrations forever.
The classic example is a webhook inbox. Stripe, GitHub or whoever else sends you an event, and your job is to record it exactly as it came in, then process it later:
CREATE TABLE webhook_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
source text NOT NULL,
event_type text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL
);
-- The keys you route on live as real columns.
-- The document you don't control stays a document.
CREATE INDEX ON webhook_events (source, event_type, received_at);Notice what happened there. The fields your system makes decisions on (source, event_type, received_at) were promoted to columns at design time, even though every one of them also exists inside the payload. That duplication isn’t waste. It’s the whole pattern, and it’s worth naming: promote on ingest. Extract the routing keys to columns at write time, and keep the raw document for everything else. Relational data on the outside, opaque document on the inside.
Audit snapshots belong in the same category for a different reason. When you record “this is exactly what the order looked like when it shipped”, you want a frozen copy, deliberately decoupled from the live tables. If the products table changes next quarter, the snapshot shouldn’t. A document is the honest representation of a point-in-time copy, and normalizing it would actively break its meaning.
The same logic covers user-defined attributes. If your customers can define their own fields per tenant, you genuinely can’t know the keys, and a JSONB column beats the entity-attribute-value table people used to build for this.
| Data | Who controls the shape | JSONB? |
|---|---|---|
| Webhook payloads | The sender | Yes, with routing keys promoted to columns |
| Third-party API responses | The vendor | Yes |
| Audit snapshots | Nobody: they’re frozen at a point in time | Yes, normalizing them would break their meaning |
| Per-tenant custom fields | Your customers | Yes, ahead of an entity-attribute-value table |
Your own team’s metadata column | Your team | Usually not |
What’s the difference between the last row and the four above it? Control. Your team knows the keys. It just hasn’t written them down.
What does JSONB cost you at query time?
The biggest query-time cost isn’t parsing. It’s what the planner can’t see. Postgres keeps detailed statistics for regular columns: distinct-value counts, most-common values, histograms. For keys inside a JSONB document it keeps nothing by default, so a predicate like payload->>'status' = 'failed' gets a fixed default estimate, 0.5% of the table for an equality test, whatever your data says.
Why does an estimate matter if the query still returns the right rows? Because estimates drive plans. If Postgres guesses that a filter matches a large slice of the table when it really matches a sliver, or the reverse, it picks the wrong join strategy, the wrong index, the wrong order. The query is correct and slow, which is the worst kind of wrong, because it degrades quietly as the table grows.
EXPLAIN
SELECT *
FROM webhook_events
WHERE payload->>'status' = 'failed';
-- The row estimate here comes from a default fraction,
-- not from statistics about the status key.
-- Compare against a real column, where pg_stats has
-- most-common values and an accurate histogram.There’s a second cost that shows up with large documents: TOAST. When a row gets wider than about 2 kB, Postgres tries compressing its large values and, if that isn’t enough, moves them out of line into a separate TOAST table. The jsonb operators work on the whole value, so getting any key back means reassembling all of it.
Mid-sized documents that stay inline drag down queries that never mention them, too. A sequential scan reads whole pages, and when every row carries a kilobyte or two of inline payload, only a handful of rows fit on each 8 kB page. Even a count over a plain column churns through more I/O than the same table would need without the blob. The document doesn’t have to be queried to be paid for. It just has to be there.
Picture a reporting query that needs one boolean per row, buried in a payload column averaging tens of kilobytes. Every row pays the detoast toll to read that one flag, and the planner estimates the filter blind. Promoting that single key to a real column fixes both: the filter gets cheap, and the planner sees the data for the first time.
On small tables and cold paths, none of this matters, and reaching into a document occasionally is fine. It starts to matter when a JSONB predicate sits on a hot path over a growing table, because the estimate error and the detoast toll both compound with size.
Can’t you just add a GIN index and move on?
A GIN index fixes containment-style lookups, and little else. It’s the standard reflex once JSONB queries slow down, so it’s worth being precise about what it buys. With the default jsonb_ops, or the usually much smaller jsonb_path_ops, it answers one family of questions: does this document contain this key-value pair, or match this jsonpath equality?
CREATE INDEX idx_events_payload
ON webhook_events
USING GIN (payload jsonb_path_ops);
-- Fast: containment.
SELECT id
FROM webhook_events
WHERE payload @> '{"status": "failed"}';That’s a real capability, and for genuine document workloads (find every event mentioning this customer, anywhere in the payload) it’s exactly what you want. The default jsonb_ops can also answer “does this key exist?” with ?. But look at what the jsonb GIN classes don’t cover. Range predicates: no. Sorting by a key: no. Joining on a key: no. The everyday relational operations that pushed you toward indexing in the first place are precisely the ones GIN doesn’t help with.
The usual next step is an expression B-tree index on the specific key:
CREATE INDEX idx_events_status
ON webhook_events ((payload->>'status'));
-- Now equality and range work through the index,
-- and ANALYZE collects statistics on the expression.This genuinely works, and it even fixes part of the statistics problem from the last section, because Postgres gathers statistics on indexed expressions. (If you only need the estimates, CREATE STATISTICS on the expression, available since Postgres 14, gathers them without an index.) Here’s how the three options compare:
| What you need | GIN on the document | Expression B-tree on one key | A real column |
|---|---|---|---|
| Containment across unpredictable keys | Yes | No | Not applicable |
| Equality and range on a known key | No | Yes | Yes |
| Sorting by the key | No | Yes | Yes |
| Planner statistics for the key | No | Yes, on the expression | Yes |
| Types, NOT NULL, foreign keys | No | No | Yes |
But be honest about what the expression index did. You committed to that key’s name, its location in the document and its text representation, permanently, in your schema. You made a column commitment. You just made it in the least visible place possible, with no type enforcement, no NOT NULL, and, for anything but text, a cast in front of every comparison.
One expression index is pragmatic. Three or four on the same JSONB column is a table announcing that it wants to exist. And every one of them adds write amplification, because every insert, and every update that touches the document, maintains them all. How each index type pays for itself is a topic of its own, covered in indexing strategies: when each index type actually pays off.
What breaks first: constraints, writes, or migrations?
Constraints break first, and writes hurt the longest. Inside a JSONB document there are no foreign keys, no per-key NOT NULL and no enforced types. A customer_id inside a payload can point at a customer deleted last year, and nothing in the database will ever object. A typo writes staus instead of status, and you’ve silently forked your schema.
Constraints are the cost teams feel last and should feel first. You can claw some of it back with CHECK constraints, and for a small contract it’s worth doing:
ALTER TABLE webhook_events
ADD CONSTRAINT payload_has_status
CHECK (
payload ? 'status'
AND payload->>'status' IN ('pending', 'processed', 'failed')
);But notice the shape of what you’re writing. That’s a schema definition, expressed in far clumsier syntax than a column definition, checked only when rows are written, and invisible to anyone reading the column types. If you find yourself writing more than one or two of these against the same column, the database is telling you something.
Writes are the quieter problem. JSONB has no in-place update. Changing one key means writing a complete new copy of the document and, because of MVCC, a complete new version of the row. A one-character change to a 30 KB document rewrites all 30 KB (less, if it compresses), writes that new copy to the WAL too, maintains every index from the last section, and leaves dead row versions for autovacuum to clean up. Update-heavy JSONB columns are how tables bloat while looking innocent.
The textbook case is a tenant settings document that’s rewritten every time any user toggles any preference. Move the hot keys to a narrow table with one row per setting, keep the cold ones in the document, and each toggle shrinks from a whole-document rewrite to a one-row update. If your Postgres runs on a managed service, database choices that quietly kill your AWS bill is the companion read on where database spend leaks.
And migrations? The dirty secret is that JSONB doesn’t remove them. It moves them into application code:
- Renaming a key means every reader handles both spellings until a backfill finishes.
- Changing a value’s type means defensive parsing forever.
- The schema still exists. It’s enforced by convention, in every service that touches the column, instead of in one place by the database.
Documents that are written once and read whole (audit logs, inbound events, snapshots) dodge almost all of this, which is exactly why they’re the good use case. Documents that are updated key by key under load are paying the full price.
How do you promote a JSONB key to a real column without downtime?
The same way you make any risky schema change on a live table: expand, backfill, flip, contract. Nothing about JSONB changes the playbook; it just adds a step where the data comes out of the document. The general patterns are in zero-downtime database migrations, and this is their JSONB-specific shape.
On large, live tables, the sequence has five steps:
- Expand. Add the column, nullable, with no default.
- Dual-write going forward. Do it in application code, or with a trigger if you can’t touch every writer.
- Backfill in small batches. Key the batches on the primary key and pause between them, so you never hold long locks or flood WAL.
- Index the new column concurrently.
- Enforce without a long lock. Add the check as
NOT VALID, then validate it as a separate step.
-- 1. Expand: add the column, nullable, no default.
ALTER TABLE webhook_events ADD COLUMN status text;
-- 2. Dual-write going forward (app code, or a trigger
-- if you can't touch every writer):
CREATE OR REPLACE FUNCTION sync_status() RETURNS trigger AS $$
BEGIN
NEW.status := NEW.payload->>'status';
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_sync_status
BEFORE INSERT OR UPDATE ON webhook_events
FOR EACH ROW EXECUTE FUNCTION sync_status();
-- 3. Backfill in small batches, keyed on the primary key,
-- with pauses, so you never hold long locks or flood WAL.
UPDATE webhook_events
SET status = payload->>'status'
WHERE id BETWEEN 1 AND 10000 AND status IS NULL;
-- 4. Index the new column, concurrently.
CREATE INDEX CONCURRENTLY idx_events_status_col
ON webhook_events (status);
-- 5. Enforce, without a long lock.
ALTER TABLE webhook_events
ADD CONSTRAINT status_not_null CHECK (status IS NOT NULL) NOT VALID;
ALTER TABLE webhook_events VALIDATE CONSTRAINT status_not_null;Then flip reads to the column, watch it for a cycle, and only afterwards decide whether the key stays in the document (harmless for an append-only inbox) or gets stripped from new writes.
There are two shortcuts, and only one is worth taking. If the table is small, skip the ceremony: add the column and backfill in one transaction during a quiet window, and it’s over quickly.
This playbook is for tables large and hot enough that a rewrite hurts. If a full rewrite finishes inside your maintenance tolerance, the five-step dance is overhead. Measure first.
How do you decide between JSONB and separate tables?
Four questions settle most JSONB vs separate tables calls: who controls the shape, whether you filter, sort or join on it, whether it needs to be correct, and whether you update it independently. Ask them per field, not per feature, because the right answer is usually a mix.
- Who controls the shape? If the keys are defined by an external system or by your end users, JSONB is honest: you can’t write a migration for a schema you don’t own. If your own team controls the keys, the flexibility argument is mostly an excuse to skip a review.
- Do you filter, sort or join on it? Any key that appears in a
WHERE,ORDER BYorJOINon a path you care about wants planner statistics, a typed index and cheap access. That’s a column. One occasional ad-hoc query doesn’t count. A dashboard does. - Does it need to be correct? Foreign keys,
NOT NULL, enum-style value sets, type guarantees. If wrong values in this field create incidents, the database should be allowed to reject them, and it can only do that properly for columns. - Do you update it independently? Fields that change on their own schedule, under real write volume, don’t belong inside a document that gets fully rewritten each time. Whole-document replacement is fine. Key-by-key churn isn’t.
Read the answers the obvious way:
| What the answers say | Where the field belongs |
|---|---|
| Externally controlled, read whole, rarely filtered, rarely updated in place | JSONB |
| A strong yes on question 2, 3 or 4 | A column, or a child table |
| A document with three hot keys and forty cold ones | Promote the three, keep the blob |
That last row is the webhook table from the first section: relational data on the outside, a document on the inside. For more on schema design and running Postgres well, the Databases section of crafted.data collects the rest.
Why is JSONB’s flexibility a loan?
Because it’s borrowed against future query plans, future constraints and future migrations. The practical default is dull and it works: model what you know as columns and tables, and reserve JSONB for data that’s genuinely a document with a shape you don’t control. That isn’t a compromise position. It’s what each tool is actually for.
The failure mode is always the same, and it’s never dramatic. A metadata column absorbs one deferred decision, then ten. Expression indexes accumulate. CHECK constraints try to hold the line. Queries slow down in ways EXPLAIN half-explains, and one day the team is running an expand-and-backfill migration under pressure that would have been a boring CREATE TABLE two years earlier, for free.
Borrow JSONB’s flexibility for documents, where you never have to pay it back. When you borrow it to skip a modeling conversation, the interest compounds quietly, and that’s when flexibility becomes debt.
Key takeaways
- A JSONB column earns its place when the data arrives as a document, leaves as a document, and its shape is controlled by someone outside your codebase.
- The hidden cost isn't storage. It's the planner: by default Postgres keeps no statistics for keys inside a document, so it estimates them with a fixed guess, and plans can go sideways as tables grow.
- Every expression index on a JSONB key is a column commitment you're already making, minus the types, NOT NULL and constraints that make columns worth having.
- JSONB has no in-place update. Changing one key writes a new copy of the whole document and a new row version, which is how update-heavy JSONB columns bloat tables and WAL.
- The decision rule: if you filter, sort, join or validate on a key, it wants to be a column. If you store and retrieve the whole thing, JSONB is fine.

Questions people ask
Is JSONB slower than regular columns in Postgres?
For whole-document reads and writes, no, it performs well. For filtering, sorting or joining on individual keys, yes: planner estimates fall back to defaults, large documents detoast on every access, and single-key updates rewrite the whole document. Speed depends on your access pattern, not on the type itself.
When should I use JSONB instead of a separate table?
Use JSONB when data arrives and leaves as a whole document and its shape is controlled externally: webhook payloads, third-party API responses, audit snapshots, user-defined attributes. Use separate tables the moment you filter, sort, join or validate individual fields, because those operations want columns, statistics and constraints.
Can you index individual JSONB fields in Postgres?
Yes, two ways. A GIN index accelerates containment and key-existence queries across the whole document. An expression B-tree index on a specific key supports equality, range and sort operations for that key. Each expression index is effectively a per-key schema commitment, so heavily indexed keys usually belong in real columns.
How do I move a JSONB field into a real column without downtime?
Expand and contract. Add a nullable column, dual-write from the application or a trigger, backfill existing rows in small batches, index the new column concurrently, validate a NOT NULL check, then flip reads. Avoid stored generated columns on large tables, since adding one forces a full table rewrite.
Does JSONB give Postgres the same flexibility as MongoDB?
Mostly, for storage. JSONB holds schemaless documents with indexing and a rich operator set, which covers the common document use cases inside a relational system. The difference is workload shape: MongoDB's own modeling guidance is to store data that's accessed together in one document, while Postgres treats documents as one tool among many.
Get the next article by email
One email when a new deep-dive is out: databases, cloud and AI, with the code. Unsubscribe in one click.
Email signups open soon. Until then, new articles are announced on Instagram.
