Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/advanced-jsonb-indexing.md
1---2title: Index JSONB Columns for Efficient Querying3impact: MEDIUM4impactDescription: 10-100x faster JSONB queries with proper indexing5tags: jsonb, gin, indexes, json6---78## Index JSONB Columns for Efficient Querying910JSONB queries without indexes scan the entire table. Use GIN indexes for containment queries.1112**Incorrect (no index on JSONB):**1314```sql15create table products (16id bigint primary key,17attributes jsonb18);1920-- Full table scan for every query21select * from products where attributes @> '{"color": "red"}';22select * from products where attributes->>'brand' = 'Nike';23```2425**Correct (GIN index for JSONB):**2627```sql28-- GIN index for containment operators (@>, ?, ?&, ?|)29create index products_attrs_gin on products using gin (attributes);3031-- Now containment queries use the index32select * from products where attributes @> '{"color": "red"}';3334-- For specific key lookups, use expression index35create index products_brand_idx on products ((attributes->>'brand'));36select * from products where attributes->>'brand' = 'Nike';37```3839Choose the right operator class:4041```sql42-- jsonb_ops (default): supports all operators, larger index43create index idx1 on products using gin (attributes);4445-- jsonb_path_ops: only @> operator, but 2-3x smaller index46create index idx2 on products using gin (attributes jsonb_path_ops);47```4849Reference: [JSONB Indexes](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING)50