Database Indexes: B-Tree Samjho

The real cure for slow queries: how B-Tree indexes work, composite indexes, and when indexes hurt.

Beginner6 min read
Language
Theme
No index: scan every rowO(n)B-Tree index: jump to the answerrootnodenodeleaf: rowO(log n): ~27 steps for 100M rowsCost: every write updates indexes. Build from queries, verify with EXPLAIN
Key idea at a glance

What an index actually is

Without an index, WHERE email = 'a@b.com' scans every row: 100M rows, 100M comparisons, seconds to minutes. An index is an auxiliary sorted data structure, usually a B-Tree, mapping the indexed column's values to row locations. Lookup cost drops from O(n) to O(log n): for 100M rows, about 27 comparisons, milliseconds. The trade: extra disk, and every write now also updates every index.

B-Tree intuition (and why it beats a hash for most things)

A phone directory: names sorted, so finding "Sharma" takes a few page-splits, not a full read. A B-Tree generalizes this for disk: fat nodes (hundreds of keys each) so the tree is only 3-4 levels deep even for billions of rows, and each level is one disk page read. Because it is sorted, it also answers range queries (BETWEEN, >, ORDER BY, prefix LIKE 'abc%'), which a hash index cannot.

Composite indexes and the leftmost prefix rule

An index on (user_id, created_at) is sorted by user_id first, then created_at inside each user. It serves: WHERE user_id = 5 (yes), WHERE user_id = 5 AND created_at > X (yes, and sorted for free), WHERE created_at > X alone (no: the index is not sorted by created_at globally). Column order in the index must match your query patterns, which is why "design indexes from queries, not from columns" is the rule.

Covering indexes and other accelerators

  • Covering index: if the index contains every column the query needs, the DB never touches the table ("index-only scan"): the fastest read a B-Tree gives you.
  • Partial index: index only WHERE status = 'pending': tiny index for the hot subset.
  • Specialized: GiST/GIN for full-text, JSONB, geo; Bloom filters in Cassandra-land for "definitely not here" checks.

The costs (interviewers wait for this)

  • Write amplification: 6 indexes = every INSERT does 7 writes. On write-heavy tables, indexes are a tax.
  • Space and cache pressure: indexes compete with data for the buffer pool.
  • Low-cardinality waste: an index on a boolean selects half the table: useless.
  • Unused indexes: audit them (Postgres: pg_stat_user_indexes); drop what no query uses.

Worked example

Query: "a user's 20 most recent orders": WHERE user_id = 42 ORDER BY created_at DESC LIMIT 20. Index (user_id, created_at DESC): the DB walks straight to user 42's slice and reads 20 rows in order. Without it: full scan + sort of all orders. Verify with EXPLAIN: look for "Index Scan" not "Seq Scan".

Common interview traps

  • "Add an index" without naming the query it serves.
  • Composite index columns in the wrong order.
  • Indexing everything on a write-heavy table.
  • Never mentioning EXPLAIN: the tool that proves the index is used.

Interview Q&A

Q: Query was fast, got slow as the table grew, index exists. Why?
A: Check EXPLAIN: the planner may have abandoned the index (data distribution changed, stale statistics, or the query now returns a large fraction of the table where a seq scan wins). Also index bloat from churn. Fixes: ANALYZE/vacuum, rewrite the query, or a better-shaped index.

Q: B-Tree vs LSM-tree?
A: B-Trees (Postgres, InnoDB) update in place: great reads, random-write cost. LSM-trees (Cassandra, RocksDB, LevelDB) buffer writes in memory and flush sorted runs: great write throughput, reads may touch multiple files (compaction keeps it bounded). Write-heavy logs/events favor LSM; read-heavy relational workloads favor B-Trees.

Key takeaways

Interview pointer

After any DB design, expect 'what are your indexes?' Name two or three per table with the reasoning: 'this keeps that query fast.'