Indexing JSONB Columns That Actually Get Used
Expression indexes, containment operators and the query shapes that let PostgreSQL keep a flexible schema without paying for it on every read.
- Databases
- PostgreSQL
- Indexes
- Query Plans
JSONB buys schema flexibility, then quietly charges it back on every filter. A predicate like metadata->>'plan' = 'pro' cannot use a plain B-tree on the column; without the right index it scans the whole table. The fix is not to abandon JSONB — it is to index the exact expression the application queries.
Match the expression, not the idea
An index on (metadata->>'plan') only helps when the query writes the same expression. metadata @> '{"plan":"pro"}' is a different operator and needs a GIN index instead. Pick one access path per hot predicate and make the application use it consistently.
CREATE INDEX CONCURRENTLY idx_accounts_plan
ON accounts ((metadata ->> 'plan'));
CREATE INDEX CONCURRENTLY idx_accounts_metadata_gin
ON accounts USING gin (metadata jsonb_path_ops);
Prefer jsonb_path_ops when you only use containment
The default GIN opclass indexes every key and value, which is generous but bulky. jsonb_path_ops indexes containment paths only: smaller, faster to build, and unable to answer key-existence queries. If every hot query is @>, that is a good trade.
Verify with EXPLAIN (ANALYZE, BUFFERS)
Plans change as tables grow. Run EXPLAIN against production-shaped data and look for Index Scan or Bitmap Index Scan, not just the absence of a sequential scan. Buffers tell you whether the index fit in cache — an index that always hits disk can still lose to a scan.
Keep a list of sanctioned paths
Flexible schemas fail when every team invents a new predicate. Document the three or four JSONB query shapes the service supports, index those, and treat anything else as a migration to the relational columns. Flexibility is a tool, not a licence to scan.