Indexing & Query Execution
How databases store rows in pages, B-trees vs B+ trees, clustered vs secondary indexes, composite and covering indexes and the leftmost-prefix rule, hash, bitmap, GIN/GiST, partial and expression indexes, LSM trees, the query optimizer, EXPLAIN, and join algorithms.
How rows live on disk
Databases read and write fixed-size pages (Postgres 8 KB, InnoDB 16 KB). A table is a set of pages; a query that needs one row still reads its whole page. The buffer pool caches hot pages in RAM. Fewer pages touched = faster queries — that is what indexes buy you.
Without an index, SELECT * FROM users WHERE email = 'a@b.com' is a full table scan: read every page. With 100 M rows, that's gigabytes of I/O for one row.
B-trees and B+ trees
- B-tree: keys and values in all nodes.
- B+ tree: values only in leaves; internal nodes hold separator keys (higher fan-out); leaves linked for range scans. This is what databases actually use.
Fan-out math: an 8 KB page with ~16-byte entries holds ~500 keys. Three levels address 500³ = 125 M rows; four levels, 62 billion. The root and second level stay in RAM, so a point lookup costs 1–2 disk reads.
Clustered vs secondary indexes
| Clustered (InnoDB PK, SQL Server clustered) | Heap + secondary (Postgres) | Secondary in InnoDB | |
|---|---|---|---|
| Leaf contains | full row | — | key + primary key |
| Row order on disk | by index key | insertion order | — |
| Lookup cost | one tree walk | index walk + heap fetch | index walk + PK walk |
| Count per table | one | n/a | many |
Composite indexes
Index on (last_name, first_name, birth_date) is like a phone book: sorted by last name, then first name.
| Query | Uses index? |
|---|---|
WHERE last_name = 'Rao' | ✓ seek |
WHERE last_name = 'Rao' AND first_name = 'Anil' | ✓ seek |
WHERE last_name = 'Rao' ORDER BY first_name | ✓ seek, no sort |
WHERE first_name = 'Anil' | ✗ (not the leftmost prefix; maybe skip-scan) |
WHERE last_name LIKE 'Ra%' | ✓ range |
WHERE last_name = 'Rao' AND birth_date = '1990-01-01' | partial: seek on last_name, filter birth_date |
Design rule (ESR): Equality columns first, then Sort columns, then Range columns.
-- query
SELECT id, total FROM orders
WHERE tenant_id = $1 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 50;
-- index that serves it with a single seek and no sort
CREATE INDEX CONCURRENTLY orders_tenant_status_created
ON orders (tenant_id, status, created_at DESC) INCLUDE (total);
Other index types
| Type | Good for | Not good for |
|---|---|---|
| Hash | equality lookups | ranges, ordering |
| Bitmap (Oracle, warehouses; Postgres builds bitmaps at runtime) | low-cardinality columns in analytics, combining predicates with AND/OR | high write rates |
| GIN (inverted) | arrays, JSONB containment, full-text search | frequent updates (slower writes) |
| GiST / SP-GiST | geometric, ranges, nearest-neighbour, exclusion constraints | — |
| BRIN (block range) | huge append-only tables ordered by time | random data |
| Partial index | WHERE status = 'pending' — index only the hot subset | — |
| Expression index | ON users (lower(email)) | — |
| Unique index | enforcing business rules | — |
| Full-text (inverted) | search with stemming/ranking | exact substring search |
| Vector (HNSW, IVF) | approximate nearest neighbour for embeddings (pgvector) | exact results |
CREATE UNIQUE INDEX users_email_lower ON users (lower(email)); -- case-insensitive uniqueness
CREATE INDEX jobs_pending ON jobs (run_at) WHERE status = 'pending'; -- tiny, hot partial index
CREATE INDEX events_payload ON events USING gin (payload jsonb_path_ops);
CREATE INDEX metrics_ts_brin ON metrics USING brin (ts);
LSM trees (log-structured merge trees)
Optimised for writes. Used by RocksDB, Cassandra, ScyllaDB, HBase, LevelDB, and as storage under CockroachDB, TiKV, YugabyteDB, Kafka Streams state stores.
| B+ tree | LSM tree | |
|---|---|---|
| Write pattern | random in-place updates | sequential appends |
| Write throughput | moderate | very high |
| Point read | 1 tree walk | memtable + several SSTables (Bloom filters help) |
| Range scan | excellent | good (merge across levels) |
| Space amplification | page fill factor, bloat | duplicates until compaction |
| Background work | vacuum (Postgres), page splits | compaction (I/O spikes) |
| Typical engines | Postgres, InnoDB, SQL Server, Oracle | RocksDB, Cassandra, HBase |
Amplification trade-off (RUM conjecture): you can optimise two of Read, Update (write) and Memory/space amplification, at the cost of the third.
The query optimizer
- Parse SQL into a tree; rewrite (views, subquery flattening).
- Enumerate plans: access paths (seq scan, index scan, index-only scan, bitmap scan), join orders and join algorithms.
- Estimate cost using statistics (row counts, histograms, distinct values, most common values, correlation) → pick the cheapest.
- Execute the plan tree (volcano/iterator model, or vectorised execution in analytics engines).
Reading EXPLAIN
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total FROM orders o
WHERE o.tenant_id = 42 AND o.status = 'paid'
ORDER BY o.created_at DESC LIMIT 50;
Limit (cost=0.56..48.10 rows=50 width=16) (actual time=0.041..0.180 rows=50 loops=1)
-> Index Scan using orders_tenant_status_created on orders o
(cost=0.56..9521.33 rows=10012 width=16) (actual time=0.040..0.170 rows=50 loops=1)
Index Cond: ((tenant_id = 42) AND (status = 'paid'::text))
Buffers: shared hit=53
Planning Time: 0.210 ms
Execution Time: 0.205 ms
What to look for:
| Red flag | Meaning |
|---|---|
Seq Scan on a large table with a selective filter | missing/unusable index |
| estimated rows ≪ or ≫ actual rows | stale/insufficient statistics → bad join choices |
Sort with external merge Disk | work_mem too small or missing index for ORDER BY |
Nested Loop with large loops count | should be a hash join, or missing inner index |
Rows Removed by Filter large | index not selective enough / wrong column order |
high Buffers: read | cold cache, too much data touched |
Join algorithms
| Algorithm | Best when | Complexity |
|---|---|---|
| Nested loop (+ index) | small outer side, indexed inner | O(n · log m) with index |
| Hash join | large inputs, equality condition | O(n + m), memory for the build side |
| Sort-merge join | inputs already sorted / huge inputs | O(n log n + m log m), or O(n + m) if sorted |
Partitioning (within one database)
Split a big table into child tables by range (month), list (region) or hash (id). Benefits: partition pruning, cheap retention (DROP an old partition instead of DELETE), smaller indexes. Not the same as sharding across machines — see Distributed data.
Indexing checklist
- Index foreign keys used in joins (Postgres doesn't do it automatically).
- Design composite indexes from real queries: equality → sort → range.
- Prefer covering indexes for the hottest queries.
- Use partial indexes for "hot subset" queries (pending jobs, active users).
- Drop unused indexes (
pg_stat_user_indexes.idx_scan = 0) — they cost on every write. - Create indexes concurrently/online in production.
- Keep statistics fresh; consider extended statistics for correlated columns.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.