Mental model
An index trades extra background storage and write-path update work (INSERT/UPDATE/DELETE) for fast selective disk pruning cleanly at query time. Because distinct data layouts carry radically asymmetric access costs, PostgreSQL implements specialized index engines—B-Tree for sorted scalar keys/ranges, BRIN for compact physical page-range summaries on append-only timeseries, GIN for multi-element arrays/jsonb/FTS, and GiST for geometric overlaps and nearest-neighbor ranges!
Learning outcomes
- Select properly cleanly among B-Tree (
composite leftmost-prefix + INCLUDE), BRIN (< 1%storage cleanly on monotonic heap tables!), GIN (inverted posting trees), and GiST (EXCLUDE USING gistoverlap prevention!). - Slash index RAM footprint and write amplification cleanly using Partial Indexes (
WHERE deleted_at IS NULLorstatus = 'queued') on heavily skewed columns cleanly. - Build indexes zero-downtime safely in production strictly via
CREATE INDEX CONCURRENTLYcleanly rather than locking active writes cleanly!
Theory
Teams routinely drop standalone single-column B-Tree indexes on every column blindly—creating 5x slow writes cleanly while leaving multi-predicate queries doing expensive bitmap AND merges! Understanding physical structure resolves sizing cleanly:
| Index Engine | Internal Data Structure | Disk Size & Write Tax | Exact Workload Fit & Critical Guardrail |
|---|---|---|---|
B-Tree (default) | Balanced multi-way sorted search tree (O(log N)) | Moderate size; blocks HOT heap-only updates if indexed columns mutate cleanly! | Leftmost composite (tenant_id, status, created_at DESC) INCLUDE (title) matches equality first, range second! |
Partial Index (WHERE ...) | Standard B-Tree indexing strictly matching rows cleanly | Tiny (e.g. indexing strictly the 0.1% pending jobs!) | Query WHERE clause MUST match partial predicate verbatim to trigger scan cleanly! |
BRIN (Block Range Index) | Stores solely (min, max) per 128 contiguous heap pages (1 MB chunk!) | Often < 0.5% B-Tree size cleanly (MBs vs tens of GBs!) | Works ONLY when physical disk insertion order stays tightly correlated (correlation ~ 1.0) with column! |
GIN (Inverted Index) | Maps distinct array keys / lexemes / JSON paths -> sorted posting lists/trees | Expensive random updates (uses pending_list fastupdate buffer -> periodic clean stalls!) | Arrays @>, JSONB jsonb_path_ops, tsvector full-text (set gin_pending_list_limit carefully!) |
GiST (Balanced Tree) | Generalized Search Tree partitioning bounding boxes / intervals | Supports lossy candidate filtering + recheck | Geo ranges, tsrange non-overlapping reservation EXCLUDE USING gist, trigrams pg_trgm |
Crucially, never run raw CREATE INDEX idx ON big_table(col) cleanly against live systems: standard creation acquires a SHARE lock blocking 100% of concurrent INSERT/UPDATE/DELETE statements for minutes! Always pass CREATE INDEX CONCURRENTLY outside transactions cleanly (watching for INVALID leftover statuses if aborted)!
sql-- 1. Zero-downtime composite partial covering index cleanly (`tiny & skips archived history!`)CREATE INDEX CONCURRENTLY idx_jobs_active_pollON background_jobs (tenant_id, run_after)INCLUDE (payload_ref)WHERE status IN ('queued', 'retrying');-- 2. Ultra-compact BRIN timeseries index (`99.5% smaller cleanly on append-only OTel telemetry logs!`)CREATE INDEX CONCURRENTLY idx_otel_created_brinON telemetry_events USING brin (created_at) WITH (pages_per_range = 64);-- 3. Prevent overlapping booking schedules declaratively inside Postgres cleanly via GiST exclusion-- ALTER TABLE gpu_reservations ADD CONSTRAINT no_overlap_slot EXCLUDE USING gist (gpu_id WITH =, reserved_window WITH &&);
Trade-offs
Using Partial Covering B-Trees (WHERE ... INCLUDE) and BRIN (append-only timestamp logs) preserves fast sub-millisecond query performance while trimming 80–99% of index RAM buffers (shared_buffers caches working data longer cleanly!) and slashing write amplification cleanly during hot updates. Meanwhile, GIN unlocks rapid multi-tag and full-text filtering cleanly inside Postgres without managing external Elastic clusters—yet high-churn GIN tables require tuning fastupdate pending-list sizes cleanly so periodic buffer flushes don't cause tail write latency spikes!
Failure modes and misconceptions
- Deploying
BRINon Randomly Inserted / Updated UUIDs or Shuffled Timestamps: Because BRIN stores min/max per physical1 MBpage group, out-of-order updates stretchmin..maxranges across every block—forcing BRIN to scan 100% of the entire table cleanly! - Running Plain
CREATE INDEXWithoutCONCURRENTLYin Live Production: Halting every APIINSERT/UPDATEon a 50M-row table for 12 minutes cleanly during index build triggers immediate site downtime cleanly. - Indexing Low-Selectivity Booleans (
CREATE INDEX ON users(is_active)) WithoutWHERE: Indexing 99%truebooleans wastes write I/O (planner rejects the index cleanly anyway), whereasWHERE is_active = falsecleanly indexes solely the tiny 1% inactive subset! - Ignoring Composite Column Leftmost Prefix Ordering: Building
(created_at, tenant_id)fails cleanly onWHERE tenant_id = 'acme' AND created_at > ...cleanly unless equality columntenant_idleads cleanly before range columncreated_at!
Decision scenario
A 400M-row Postgres LLM audit table has three unused low-selectivity B-Trees costing 180 GB disk and crippling insert throughput, while an index build script accidentally locked live API inserts cleanly for 6 minutes! Audit dead indexes cleanly via pg_stat_user_indexes (idx_scan = 0), drop redundant singles cleanly, create composite equality-first partial covering B-Tree (WHERE status='error') cleanly using CONCURRENTLY, and replace the 65 GB created_at B-Tree cleanly on the append-only partition with a 40 MB BRIN index cleanly (verifying correlation >= 0.99 in pg_stats)!