dataiotech Labs
Back to Performance Guide
[PostgreSQL]DEEP DIVEPostgreSQL 16 / 1726 minSenior DBA / SRE + Backend Developer

[PostgreSQL] DEEP DIVE: Index Architecture — B-Tree, Hash, GiST, GIN, BRIN Deep Dive

An improper index degrades write performance, consumes disk space, and misleads the query planner. Choose deliberately between B-Tree, Hash, GiST, GIN, and BRIN for specialized data layouts.

Production Incident Scenario

An orders table with 12M rows has accumulated 8 separate indexes. Queries remain sluggish while INSERTs degrade. Index size exceeds table size, with 3 indexes having zero scans (idx_scan = 0) and duplicated prefixes.

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-HOT UPDATE must 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.
The Golden Rule: Every index must justify its write-amplification penalty by delivering a measurable, high-frequency read optimization.

PostgreSQL Index Types: Architectural Comparison Matrix

Access MethodDefault?Primary Use CasesUnsuitable ForStorage Footprint
B-TreeYesEquality (=), range (<, >, BETWEEN), ordering (ORDER BY), JOIN predicatesJSONB containment, arrays, geospatialModerate to Large
HashNoPure equality comparisons on long text stringsRange scans, sorting, pattern matching (LIKE)Compact
GiSTNoGeometric (PostGIS), range types, nearest-neighbor (KNN), exclusion constraintsSimple scalar equalitiesModerate
GINNoJSONB (@>), arrays (&&), full-text search (tsvector), trigramsHigh-update single-value scalar columnsLarge (Write-heavy)
BRINNoMassive, physically ordered append-only time series and logsRandomly distributed or frequently updated tablesMicroscopic (< 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:

sql
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:

sql
-- 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.

sql
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 >, <, or BETWEEN.
  • •No sorting: Cannot satisfy ORDER BY.

3. GiST (Generalized Search Tree) — Multi-Dimensional Data

GiST is a balanced tree infrastructure supporting arbitrary indexing schemes:

sql
-- 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.

sql
-- 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%' using pg_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.

sql
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_stats prior to deploying BRIN:
sql
SELECT tablename, attname, correlation FROM pg_stats WHERE tablename = 'system_metrics' AND attname = 'created_at';
Rule: If 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:

text
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:

sql
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.

sql
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_stats before 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_scan and mean_exec_time telemetry 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
Operational Checklist

Verify each operational safety check before completing the task: