{}DSA Atlas

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.

Intermediate → Advanced9 interview questions

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

30 | 60 10 | 20 40 | 50 70 | 80 3 7 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 90 leaves hold keys + row pointers (or rows), linked left→right for range scans
A B+ tree: internal nodes route, leaves store data and are chained for ordered scans.
  • 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 containsfull row—key + primary key
Row order on diskby index keyinsertion order—
Lookup costone tree walkindex walk + heap fetchindex walk + PK walk
Count per tableonen/amany

Composite indexes

Index on (last_name, first_name, birth_date) is like a phone book: sorted by last name, then first name.

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

SQL
-- 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

TypeGood forNot good for
Hashequality lookupsranges, ordering
Bitmap (Oracle, warehouses; Postgres builds bitmaps at runtime)low-cardinality columns in analytics, combining predicates with AND/ORhigh write rates
GIN (inverted)arrays, JSONB containment, full-text searchfrequent updates (slower writes)
GiST / SP-GiSTgeometric, ranges, nearest-neighbour, exclusion constraints—
BRIN (block range)huge append-only tables ordered by timerandom data
Partial indexWHERE status = 'pending' — index only the hot subset—
Expression indexON users (lower(email))—
Unique indexenforcing business rules—
Full-text (inverted)search with stemming/rankingexact substring search
Vector (HNSW, IVF)approximate nearest neighbour for embeddings (pgvector)exact results
SQL
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.

write memtable (RAM) WAL (sequential append) disk: immutable SSTables L0 L1 L2 (10× larger) flush compaction (merge-sort) read path memtable → L0 files → L1 → L2 … (Bloom filter per SSTable skips files that can't contain the key) deletes write tombstones; space is reclaimed by compaction
Writes are sequential; reads may consult several files; compaction keeps it in check.
B+ treeLSM tree
Write patternrandom in-place updatessequential appends
Write throughputmoderatevery high
Point read1 tree walkmemtable + several SSTables (Bloom filters help)
Range scanexcellentgood (merge across levels)
Space amplificationpage fill factor, bloatduplicates until compaction
Background workvacuum (Postgres), page splitscompaction (I/O spikes)
Typical enginesPostgres, InnoDB, SQL Server, OracleRocksDB, 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

  1. Parse SQL into a tree; rewrite (views, subquery flattening).
  2. Enumerate plans: access paths (seq scan, index scan, index-only scan, bitmap scan), join orders and join algorithms.
  3. Estimate cost using statistics (row counts, histograms, distinct values, most common values, correlation) → pick the cheapest.
  4. 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 flagMeaning
Seq Scan on a large table with a selective filtermissing/unusable index
estimated rows ≪ or ≫ actual rowsstale/insufficient statistics → bad join choices
Sort with external merge Diskwork_mem too small or missing index for ORDER BY
Nested Loop with large loops countshould be a hash join, or missing inner index
Rows Removed by Filter largeindex not selective enough / wrong column order
high Buffers: readcold cache, too much data touched

Join algorithms

AlgorithmBest whenComplexity
Nested loop (+ index)small outer side, indexed innerO(n · log m) with index
Hash joinlarge inputs, equality conditionO(n + m), memory for the build side
Sort-merge joininputs already sorted / huge inputsO(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

0 / 9 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.