Overview and Index Taxonomy
An improper index is far worse than no index at all. A table without an index is slow, but transparent. A table burdened with improper indexes degrades write throughput, inflates disk usage, pollutes buffer pool memory, and misleads the query planner into executing catastrophic nested loops.
In this deep dive, you will master PostgreSQL's 5 core index access methods: B-Tree, Hash, GiST, GIN, and BRIN. You will understand which engine access method fits which data layout, where specific types fail catastrophically, how to navigate the index selection decision tree, and how to audit redundant indexes in production.
Scenario
The 8-Index Dilemma. An orders table contains 12 million rows. Following intermittent latency complaints, the development team created 8 separate indexes over several months.
Despite the indexes, customer lookup queries remain sluggish. Worse, INSERT and UPDATE throughput has plummeted by 45%. Disk consumption swells by 40 GB every month.
The DBA inspects the system catalog and uncovers the reality:
- •3 indexes have recorded zero lifetime scans (
idx_scan = 0). - •2 composite indexes index the exact same columns in different order, with the non-selective status flag placed first.
- •1 index on a JSONB payload is a standard B-Tree that cannot support containment operators.
The problem was never a lack of indexes; it was index pollution. This guide explains how to purge index bloat and engineer high-performance indexes.
Index Physics: The Cost of Indexing
An index functions like a book's back-of-the-book index: it lets the database find matching pages without scanning every chapter from start to finish. However, adding 8 separate indexes thickens the book, inflates printing overhead, and makes revising content expensive.
In PostgreSQL, every index imposes concrete operational overhead:
- •Accelerates Reads: A selective index allows reading 10 pages instead of 100,000 pages.
- •Penalizes Writes: Every
INSERT,DELETE, and non-HOTUPDATEmust physically write new entries to all table indexes. - •Consumes Buffer Pool Cache: Indexes compete directly with table data for space inside
shared_buffers. - •Complicates Planner Heuristics: Redundant or overlapping indexes increase planning overhead and risk poor node choices.
PostgreSQL Index Types: Architectural Comparison Matrix
| Access Method | Default? | Primary Use Cases | Unsuitable For | Storage Footprint |
|---|---|---|---|---|
| B-Tree | Yes | Equality (=), range (<, >, BETWEEN), ordering (ORDER BY), JOIN predicates | JSONB containment, arrays, geospatial | Moderate to Large |
| Hash | No | Pure equality comparisons on long text strings | Range scans, sorting, pattern matching (LIKE) | Compact |
| GiST | No | Geometric (PostGIS), range types, nearest-neighbor (KNN), exclusion constraints | Simple scalar equalities | Moderate |
| GIN | No | JSONB (@>), arrays (&&), full-text search (tsvector), trigrams | High-update single-value scalar columns | Large (Write-heavy) |
| BRIN | No | Massive, physically ordered append-only time series and logs | Randomly distributed or frequently updated tables | Microscopic (< 1% of B-Tree) |
1. B-Tree (Balanced Tree) — The Production Default
When you execute CREATE INDEX without declaring an access method, PostgreSQL builds a B-Tree:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);
-- Identical to:
CREATE INDEX idx_orders_customer_id ON orders USING btree (customer_id);▸When to Use
- •Equality lookups:
WHERE customer_id = 123 - •Range scans:
WHERE created_at BETWEEN '2026-11-01' AND '2026-11-30' - •Sorting:
ORDER BY created_at DESC - •Foreign key joins and grouping:
JOIN,GROUP BY
B-Trees cover ~85% of general enterprise queries. When uncertain, start with B-Tree.
▸Composite B-Trees: Column Order Dictates Utility
The most frequent architectural mistake is choosing the wrong column order in multi-column indexes:
-- Target Query:
SELECT * FROM orders WHERE customer_id = 123 AND status = 'open';
-- Correct: High selectivity column placed first
CREATE INDEX idx_orders_customer_status ON orders (customer_id, status);
-- Counter-Productive: Low selectivity column placed first
CREATE INDEX idx_orders_status_customer ON orders (status, customer_id);Rule: Place the most selective column first. Selectivity refers to the fraction of rows eliminated by a predicate. If customer_id has 500,000 distinct values, it is highly selective. If status contains only 3 values (open, shipped, cancelled), it has poor selectivity. Placing status first forces index scans to inspect wide ranges of identical keys.
2. Hash Indexes — Pure Equality Lookups
Historically avoided due to lack of crash recovery, Hash indexes became fully WAL-logged and crash-safe in PostgreSQL 10.
CREATE INDEX idx_users_email_hash ON users USING hash (email);▸When to Use
- •Long strings or UUIDs where queries only filter by strict equality (
=). - •Hash indexes are slightly smaller and marginally faster than B-Trees for long text keys because they store 4-byte hash values rather than full variable-length string keys.
▸Limitations
- •No range scanning: Cannot satisfy
>,<, orBETWEEN. - •No sorting: Cannot satisfy
ORDER BY.
3. GiST (Generalized Search Tree) — Multi-Dimensional Data
GiST is a balanced tree infrastructure supporting arbitrary indexing schemes:
-- Indexing range types or geometry
CREATE INDEX idx_reservations_during ON reservations USING gist (room_id WITH =, during WITH &&);▸When to Use
- •Range Types:
daterange,tsrange,int4range(e.g., booking overlap prevention). - •PostGIS Geospatial: Polygons, bounding boxes, spatial containment (
ST_DWithin,ST_Contains). - •Nearest Neighbor (KNN): Distance calculations (
ORDER BY location <-> point). - •Exclusion Constraints: Guaranteeing no two overlapping bookings exist for the same conference room.
4. GIN (Generalized Inverted Index) — Multi-Valued Attributes
A GIN index is an inverted index: each unique internal element maps to a posting list of row pointers where that element appears.
-- GIN on JSONB document
CREATE INDEX idx_products_attributes ON products USING gin (attributes);
-- GIN with Trigram ops for fast wildcard text search
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_users_name_trgm ON users USING gin (full_name gin_trgm_ops);▸When to Use
- •JSONB Containment:
WHERE attributes @> '{"color": "red"}' - •Array Containment / Overlap:
WHERE tags && ARRAY['dba', 'sre'] - •Full-Text Search:
to_tsvector('english', body) @@ to_tsquery('postgres') - •Wildcard Substrings: Fast resolution of
LIKE '%pattern%'usingpg_trgm.
▸Operational Warning: Write Penalty
Every INSERT or UPDATE on a row with 20 tags requires inserting 20 separate entries into the GIN index. Use fastupdate = on (the default) to buffer writes in a pending list, and ensure background workers vacuum the GIN structure regularly.
5. BRIN (Block Range Index) — Massive Time-Series
BRIN does not store individual row pointers. Instead, it inspects physical disk blocks (default: 128 pages = 1 MB) and records only the minimum and maximum value for each block range.
CREATE INDEX idx_metrics_created_at_brin ON system_metrics USING brin (created_at);▸The BRIN Storage Miracle
On a 50 GB append-only audit table:
- •Standard B-Tree index: ~11 GB
- •BRIN index: ~15 MB (Over 99% storage reduction!)
▸When to Use
- •Massive tables (> 20 million rows) where data is physically inserted in monotonic order (e.g., auto-incrementing IDs, timestamps).
- •Always verify physical correlation in
pg_statsprior to deploying BRIN:
SELECT tablename, attname, correlation
FROM pg_stats
WHERE tablename = 'system_metrics' AND attname = 'created_at';correlation is greater than 0.95 (or less than -0.95), data is physically ordered on disk and BRIN will deliver exceptional speed. If correlation is near 0 (randomly distributed), BRIN will perform poorly.Index Selection Decision Tree
Use this decision matrix when designing indexes:
Is the target column a multi-valued type (JSONB, Array, Text Vector)?
├── YES ────────► Use GIN
└── NO
Is the column geometric, spatial (PostGIS), or a Range Type?
├── YES ────► Use GiST
└── NO
Is the table massive (>20M rows), append-only, and physically correlated?
├── YES ──► Use BRIN
└── NO
Does the query ONLY filter by exact string equality (=)?
├── YES ──► Consider Hash (or B-Tree)
└── NO ───► Use B-Tree (Default)Production Index Auditing Queries
▸1. Identify Unused Indexes
Indexes that consume disk space and write I/O without ever serving queries:
SELECT
schemaname,
relname AS table_name,
indexrelname AS index_name,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
idx_scan AS lifetime_scans
FROM pg_stat_user_indexes
WHERE idx_scan = 0
AND indexrelname NOT LIKE '%_pkey'
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 15;*Action:* If idx_scan = 0 after 30 days of representative production workload, safely drop the index.
▸2. Identify Redundant and Duplicate Indexes
If you have an index on (customer_id, status), a separate single-column index on (customer_id) is redundant because B-Trees can satisfy leftmost-prefix lookups.
SELECT
t.relname AS table_name,
i1.relname AS redundant_index,
i2.relname AS composite_index
FROM pg_index x1
JOIN pg_index x2 ON x1.indrelid = x2.indrelid AND x1.indexrelid <> x2.indexrelid
JOIN pg_class t ON t.oid = x1.indrelid
JOIN pg_class i1 ON i1.oid = x1.indexrelid
JOIN pg_class i2 ON i2.oid = x2.indexrelid
WHERE x1.indkey[0] = x2.indkey[0]
AND x1.indnatts < x2.indnatts;Operational Checklist
- Most expensive query isolated via
pg_stat_statements EXPLAIN (ANALYZE, BUFFERS)evaluated for target statement- Index access method chosen via decision tree (B-Tree / Hash / GiST / GIN / BRIN)
- High-selectivity column placed first in composite index definitions
- Physical correlation checked in
pg_statsbefore deploying BRIN - Index benchmarked in staging environment first
- Production index deployed strictly with
CONCURRENTLY - Unused indexes audited across database relations
- Duplicate and redundant prefix indexes identified
- Index-to-table size ratio verified
- Post-deployment
idx_scanandmean_exec_timetelemetry verified - Unused or counter-productive indexes dropped safely
Related Guides in Series
- •Pillar: Performance & Query Optimization
- •Cluster: Finding Top 20 Expensive Queries with pg_stat_statements
- •Cluster: The N+1 Query Problem and Connection Pool Saturation
- •Cluster: Reading and Deconstructing EXPLAIN ANALYZE
- •Cluster: Vacuum, Analyze, and Autovacuum Tuning
- •Cluster: Memory Tuning: shared_buffers, work_mem, effective_cache_size