Indexing & query plans

B+ trees, composite index column order, covering indexes, why the planner ignores yours (functions, leading wildcards, low selectivity). EXPLAIN is the answer key.

About 29 min read3-question knowledge check

The mental model

An index is the index at the back of a textbook. Without it, finding every page that mentions "mitochondria" means reading all 900 pages cover to cover (a sequential scan). With it, you flip to the M section, find "mitochondria — pp. 412, 588", and jump straight there. The index is a separate, sorted structure that maps a value to the location of the rows that contain it, so the database can seek instead of scan.

The structure is almost always a **B+ tree**: a balanced tree, kept shallow (typically 3-4 levels even for hundreds of millions of rows), where every search — equality, range, sorted retrieval — costs a handful of page reads instead of a full-table read. Leaf nodes are linked in sorted order, which is why a range scan (WHERE created_at > x) and an ORDER BY on an indexed column are both cheap: you find the start and walk the leaves.

**Why this exists — what breaks without it.** A query on an unindexed 40-million-row table reads all 40 million rows every time. Add ten of those a second and the database CPU is pinned, every query queues, and the whole service degrades — an outage that begins in a WHERE clause. But the opposite failure is just as real: indexes are not free. Each one must be updated on every INSERT, UPDATE, and DELETE, so a table with fifteen indexes writes slowly, and the wrong index is dead weight the planner ignores while you still pay to maintain it. The senior skill is not "add indexes" — it is knowing *which* index, in *which column order*, and reading EXPLAIN to know why the planner used yours or refused to.

**EXPLAIN is the answer key.** You never guess whether an index is used; you ask the planner and it tells you.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision