JSONB is the right type for “schemaless” fields in Postgres — webhooks, feature flags, third-party API responses, audit payloads. The default JSONB column has no index, so a query like WHERE data->>'status' = 'paid' does a sequential scan; on a 50 GB table that’s a 30-minute query. This article covers the three viable indexing strategies — GIN with jsonb_ops, GIN with jsonb_path_ops, and expression indexes — and when each pays off.
How to verify
Check the columns and current indexes, then look at the query plan:
psql -d app -c "\d orders"
psql -d app -c "SELECT indexname, indexdef FROM pg_indexes
WHERE tablename = 'orders';"
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM orders WHERE data @> '{\"status\":\"paid\"}';"
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM orders WHERE data->>'status' = 'paid';"
Bitmap Index Scan with a GIN index is the win. Sequential scan on a million-row table is the lose.
What’s happening
JSONB stores parsed, de-duplicated JSON — {"a":1, "a":2} becomes {"a":2}. The operators are:
->returns a JSONB value:data->'address'->>returns text:data->>'status'@>contains:data @> '{"status":"paid"}'?key exists:data ? 'discount'?|any key exists,?&all keys exist@?matches a JSONPath:data @? '$.items[*] ? (@.qty > 5)'@@JSONPath returns true:data @@ '$.status == "paid"'
A GIN index with jsonb_ops indexes every key and every primitive value, separately. It supports the broadest set of operators (@>, ?, ?|, ?&, @?, @@) at the cost of size — typically 2-3x the size of the JSONB column.
A GIN index with jsonb_path_ops indexes only the hash of the JSONPath-style root-to-value paths. It supports only @> (and @?, @@ with restrictions), but is roughly half the size of jsonb_ops and noticeably faster for containment queries.
An expression index on (data->>'status') is a btree on a derived column — small, fast for exact-match on that one path, useless for any other key. Multiple expression indexes are fine; just don’t expect them to compose.
The procedure
-
If you query mostly with containment (
@>): Usejsonb_path_ops:CREATE INDEX orders_data_path_gin ON orders USING GIN (data jsonb_path_ops);Then queries like
WHERE data @> '{"status":"paid", "currency":"USD"}'use it directly. -
If you also need key-existence (
?) or arbitrary key probes: Usejsonb_ops:CREATE INDEX orders_data_gin ON orders USING GIN (data);The default class — slightly bigger, broadly supported.
-
For high-frequency exact-match on one field, an expression btree wins:
CREATE INDEX orders_status_btree ON orders ((data->>'status'));Tiny, fast for
WHERE data->>'status' = 'paid'. AddingORDER BYand range queries works the same as on any btree. -
For numeric JSONB fields, cast in the index:
CREATE INDEX orders_total_btree ON orders (((data->>'total')::numeric));Without the cast, the planner can’t use the index for
WHERE (data->>'total')::numeric > 1000. -
Use JSONPath for queries that need structure-aware predicates:
SELECT id, data FROM orders WHERE data @? '$.items[*] ? (@.qty > 5 && @.price < 100)';JSONPath is the SQL/JSON standard query language.
@?returns true if any path matches;@@returns the boolean result of a predicate. Combined with a GIN index, the planner pushes the path predicate into the index walk. -
For partial indexes when most rows have a null path:
CREATE INDEX orders_paid_at_btree ON orders (((data->>'paid_at')::timestamptz)) WHERE data ? 'paid_at';Excludes the millions of rows that don’t have the key, keeping the index small.
Common pitfalls
- Wrong ops class:
CREATE INDEX ... USING GIN (data)defaults tojsonb_ops. If you only ever query with@>, switch tojsonb_path_opsand reclaim 40-60% of the index size. - Expression indexes need the exact expression in the WHERE clause —
data->>'status'and(data->'status')::textare not interchangeable. IMMUTABLE: indexes on expressions need the expression to be immutable.to_timestampis stable, not immutable; cast through a wrapper if necessary.- JSONB updates rewrite the whole document; a small UPDATE on a 4 KB JSONB row writes 4 KB of WAL and bloats indexes. Don’t store frequently-updated counters inside JSONB.
- The default statistics on JSONB are coarse — the planner doesn’t know about distinct values inside the document. Use
pg_stat_statementsto find slow plans and consider expression indexes for the high-frequency keys.
In the engagements we run, the JSONB indexing default is: jsonb_path_ops if containment dominates, expression btree for hot exact-match keys, and never let JSONB sit unindexed if it appears in a WHERE clause. For typed search and ranking we layer pgvector or full-text search instead. For the operating model behind a Postgres-led mixed-schema stack, see managed operations.