How to Optimize JSONB Query Performance
Prefer containment operators, add expression and GIN indexes for hot paths, promote frequent fields to columns, and verify with EXPLAIN ANALYZE.
On this page
Introduction
JSONB gives PostgreSQL schema-flexible documents: rows carry a jsonb column holding whatever the application decided, queried with arrow operators when needed. That flexibility is bought with a cost structure the default access path makes brutal: a predicate like data->>‘status’ = ‘pending’ is a function call evaluated per row, over every row, on every query, because the planner has no index to use for an expression buried inside a document. A million-row table scans a million documents to return fifty. The optimizer toolbox is real, though: containment operators that indexes understand, expression indexes that promote a single hot field to index-eligible form, GIN indexes that index the entire document structure, and the promotion strategy of moving structural fields into real columns. This tutorial profiles the hot queries, rewrites them into indexable shapes, chooses between expression and GIN indexing by access pattern, and defines the promotion boundary that keeps flexibility where it pays and columns where they pay.
The per-row function cost
Understand what the naive query does. The expression data->>‘status’ extracts text from the jsonb blob, and ->> is a function: for every candidate row the engine parses into the document, extracts the value, casts, and compares. Without an index the candidate set is the entire table, so the function runs N times per query. It is not that jsonb is slow; it is that this access shape cannot use any index, because the B-tree indexes sit on columns, not on paths inside documents. The first diagnostic is EXPLAIN with a Seq Scan and a Filter containing the arrow expression, and the gap between rows removed by the filter and rows returned is the wasted function-call count. The second diagnostic is query frequency: pg_stat_statements ranks these predicates, and the optimization budget belongs to the ones that run constantly, not the ones that run in a monthly report. Both diagnostics together, hot predicate plus full scan, define each optimization target.
Rewrite to containment
The single most effective rewrite moves equality on document fields to the containment operator. The query data->>‘status’ = ‘pending’ becomes data @> ‘{“status”:“pending”}’, which reads as the document contains this object. Containment is indexable by GIN and by GiST, so the rewrite converts an unindexable per-row function into an index-supported operation, often with no other change.
-- before: function per row, no index possible
SELECT id FROM events
WHERE payload->>'status' = 'pending'
AND payload->>'region' = 'eu';
-- after: containment, GIN-indexable
SELECT id FROM events
WHERE payload @> '{"status":"pending","region":"eu"}';
Containment semantics deserve respect: for objects it means the document contains at least these keys with at least these values, so extra keys in the document do not block the match, which matches the intuition of filtering on fields. Arrays and nesting behave compositionally, and partial matches on arrays, any-element containment, make it a superset of simple equality. The rewrite carries one behavioral shift: containment on non-scalar values matches structure, so ‘{“tags”:[“beta”]}’ matches documents whose tags array contains beta, where the arrow-equality form would compare the whole array. Test the rewrite against representative documents rather than assuming equivalence.
Expression indexes for single hot fields
When one or two document fields dominate filtering, an expression index promotes them into index-eligible form: a B-tree over the extracted value, maintained on write, usable by equality and range predicates exactly like a column index.
CREATE INDEX idx_events_status
ON events ((payload->>'status'));
CREATE INDEX idx_events_created
ON events (((payload->>'created_ts')::timestamptz));
SELECT id FROM events
WHERE payload->>'status' = 'pending'
AND (payload->>'created_ts')::timestamptz > now() - interval '1 day';
The query predicate must match the index expression exactly, same operators, same casts, or the planner cannot use it, which is the most common reason a created expression index sits unused: the query casts to timestamptz while the index indexes raw text, and the mismatch is invisible without comparing EXPLAIN output. Expression indexes are cheap to maintain relative to GIN and precise for equality and range, making them the default first choice for a small set of known-hot fields. They also cover ORDER BY on the extracted value, which GIN does not, so paginated feeds sorted by a document field get constant-cost sorting from the expression index.
GIN indexes for whole-document access
When the querying application filters on many different fields, combinations that change with each release, indexing one expression per field degenerates into an index farm. GIN indexes the document structure itself: every key and scalar value becomes an index entry, and containment queries resolve through the index for any field combination.
CREATE INDEX idx_events_payload_gin
ON events USING gin (payload jsonb_path_ops);
SELECT id FROM events
WHERE payload @> '{"status":"pending","region":"eu","severity":3}';
The jsonb_path_ops opclass indexes only paths and values, not the full key set, producing a substantially smaller and faster GIN than the default opclass at the cost of supporting only containment, not existence operators like ? for keys. Choose it when containment is the access pattern, which after the rewrite section it should be. The costs are real: GIN maintenance makes every insert and document update slower, the index can approach the table in size on wide documents, and fast updates accumulate pending entries that periodic cleanup merges. Measure write-rate impact before adopting it table-wide, and consider partial GIN indexes, WHERE on an outer column restricting the indexed rows, to keep the index to the hot subset.
Promote structural fields to columns
The strongest optimization is admitting that some fields are not actually flexible. A field that is always present, always filtered or joined on, and stable in type, is structural, and it belongs in a column: real constraints, real statistics for the planner, real foreign keys, ordinary index semantics, and no per-row extraction cost. The promotion boundary is worth stating as a rule: promote fields that appear in WHERE clauses of hot queries or in JOIN conditions; keep in JSONB the genuinely variable tail, vendor-specific attributes, per-tenant extensions, payloads whose shape varies by source. Migration is incremental: add the column, backfill from the document with an UPDATE reading the arrow expression, add the constraint or index, and keep the document in sync during the transition with a trigger or disciplined write path. Statistics are an underrated reason: the planner knows column cardinalities and can choose join strategies and scan types accordingly, while jsonb paths are opaque to statistics, so complex plans over extracted values are built half-blind. Promotion restores the planner’s vision.
Verify and guard with plans
Every optimization here is verifiable in the plan, and the verification belongs in CI because it decays: a query rewrite that changes the predicate form silently strands an expression index, and a statistics shift can flip a plan to a scan. For each hot query, EXPLAIN ANALYZE before and after, confirming index usage in the plan node and comparing timing. For expression indexes, assert the query predicate text matches the indexed expression, including casts, which a simple EXPLAIN on the canonical query catches. For GIN, confirm the containment form, not an arrow-equality leftover, and watch the maintenance cost in write-path benchmarks. Keep a plan-assertion suite for the top JSONB queries by frequency, and re-run it after every application release that touches query construction, because the application owns the predicate text and only the plan proves the index is still earning its write cost.
EXPLAIN ANALYZE
SELECT id FROM events WHERE payload @> '{"status":"pending"}';
-- expect: Bitmap Index Scan on idx_events_payload_gin
Common pitfalls
- Arrow-equality on hot paths. data->>‘k’ = ‘v’ is a per-row function no index can serve; rewrite to containment.
- Cast mismatches on expression indexes. The query casts, the index does not, or vice versa, and the index sits unused.
- GIN on write-heavy tables unmeasured. GIN maintenance can double insert cost; benchmark the write path before adopting.
- Default GIN opclass when containment is the only pattern. jsonb_path_ops is smaller and faster for @> queries.
- Promoting everything. Wholesale promotion loses the flexibility JSONB exists for; promote the structural subset.
- Unguarded rewrites. Containment on arrays and structures differs subtly from equality; test against real documents.
Conclusion
JSONB performance is an access-path problem: the default arrow operators evaluate per row over the whole table, and every optimization is about giving the planner an index it can use. Rewrite hot equality predicates to containment so GIN becomes usable. Add expression indexes for the few fields that dominate filtering and sorting, matching casts exactly. Adopt a jsonb_path_ops GIN when the field combinations vary widely, after measuring its write-path cost. Promote structural fields, always present and always filtered, into real columns, restoring constraints, statistics, and planner visibility. Verify each win in EXPLAIN ANALYZE and guard the plans in CI, because index-dependent queries decay silently when application code drifts. Applied in that order, JSONB goes from the slow-flexible trap to flexible where it matters and indexed where it counts.
Sources: PostgreSQL: JSON types, PostgreSQL: JSON indexing, PostgreSQL: JSON functions.
FAQ
- Is jsonb slower than json in PostgreSQL?
- Reading is slower in jsonb for whole-document retrieval because it is a parsed binary form, but querying and indexing are much faster, and jsonb removes duplicate keys and normalizes whitespace. Use jsonb for anything queried; use json only for pass-through storage.
- When is a GIN index worth its cost?
- When containment or existence queries on JSONB documents are frequent and the document count is large. GIN maintenance slows writes and the index can be large; for one or two hot fields, expression btree indexes are far cheaper.
- Should I just promote every field to a column?
- That trades flexibility for speed wholesale and loses the point of JSONB. Promote fields that are always present, always filtered or joined on, and structurally stable; keep genuinely variable payloads in JSONB with targeted indexes.
Report a problem with this articleOpens a pre-filled issue on GitHub.