šļø Database Indexing & Caching
Composite & Covering Indexes
Designing composite and covering indexes that eliminate table lookups entirely
A well-designed covering index can reduce query execution from hundreds of milliseconds to under 1ms by making the database answer queries entirely from the index structure, never touching the actual table rows.
Key Concepts
Composite Index Design
Column order matters critically. Put equality columns first (WHERE col = X), then range/sort columns last (ORDER BY col). This matches the query pattern to the sorted index order.
Covering Index
When all SELECT, WHERE, and ORDER BY columns are inside the index, PostgreSQL never reads the actual table. This is the Index-Only Scan ā the fastest possible read path.
Index Only vs Heap Fetch
Without covering index: index lookup ā table heap fetch (random I/O, ~10ms). With covering index: index lookup only (sequential I/O, ~0.1ms). 100x speed difference at scale.
The Left-Most Prefix Rule Explained
Understanding the Left-Most Prefix Rule
- Index: (tenant_id, status, created_at) ā the index sorts by tenant_id first, then status within each tenant_id, then created_at within each status
- ā Works: WHERE tenant_id = 1001 ā uses index on first column
- ā Works: WHERE tenant_id = 1001 AND status = 'ACTIVE' ā uses index on first two columns
- ā Works: WHERE tenant_id = 1001 AND status = 'ACTIVE' ORDER BY created_at DESC ā uses all three columns
- ā Fails: WHERE status = 'ACTIVE' ā cannot start at middle of index ā full table scan
- ā Fails: WHERE created_at > '2026-01-01' ā cannot skip tenant_id ā full table scan
Index Scan vs Index-Only Scan
š”
Senior Architect Insight: Use EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL after every schema change. Look for 'Index Only Scan' (best), 'Index Scan' (good), 'Bitmap Heap Scan' (acceptable for range queries), and 'Seq Scan' (fix this immediately on large tables).