All posts

Database indexes, explained with a phone book

Databases · 2 min read ·

Every slow query I have ever fixed came down to the same picture. You ask MySQL for WHERE email = 'omar@example.com' and, without an index, it does the only thing it can:

users table · 1,000,000 rows reads every single row like finding a name in a phone book by reading page 1, then page 2, then page 3...
A full table scan. Fine at 1,000 rows, painful at 1,000,000.

What an index actually is

An index is a second, sorted structure next to your table: a B-tree. Sorted things can be searched by halving, so the database takes hops, not steps. Same query, with an index on email:

A - Z A - M N - Z A - F G - M N - S T - Z hop 1 hop 2 hop 3: found it. Three reads instead of a million.
B-tree lookup: every hop cuts the search space in half or better.

When to add one

  • Columns in WHERE, JOIN ... ON, and ORDER BY of your hot queries.
  • Foreign keys, always.
  • Not on columns you almost never filter by: every index slows down writes a little.
Before guessing, run EXPLAIN on the query. If you see type: ALL, that is the first sketch: a full scan. After the right index it becomes ref or range, the second sketch.

The 20% performance win I shipped at Getmayes was mostly this: reading EXPLAIN output, drawing the tree, and adding the four indexes the queries were begging for.

Notes from readers

  1. No notes yet. The first one is the bravest.
Building something like this? I can help. Contact