System Design · 03. Data & Storage · 10 min · Intermediate

Indexes

A sorted shortcut that turns a slow search into a fast lookup.

In short

Without an index, the database scans all 10,000,000 rows: 2,000 ms. A B-tree index finds one row in 4 page reads: 0.4 ms, and it also serves ranges and sorting.

Composite indexes follow the left-prefix rule, and covering indexes skip the table. Every index costs space and slows each write, so index the queries you actually run.

Key ideas

  • An index is an extra structure, kept up to date by the database, that trades storage and write time for read speed. (step 2)
  • Put the columns you compare with equals first, and a range column last. Check what the database really does with EXPLAIN. (step 6)

Good to know

  • The tree stays shallow and balanced as the table grows. 125 million rows still fit in 3 levels, and the database keeps the top levels in memory. (step 3)
  • In SQL you create it with one line: CREATE INDEX idx_users_email ON users (email); (step 4)
  • Cover your hottest queries, and keep the extra columns few and small. (step 7)

Watch out

  • A query that is fast on 1,000 test rows can be very slow on 10 million. The cost grows with the table. (step 1)
  • A hash index finds exact matches only. B-trees are the default because they handle ranges, sorting and exact matches. (step 5)
  • Reads get faster, writes get slower. For read-heavy tables that is a great trade; for write-heavy tables, think harder. (step 8)
  • Also do not index columns with few values (like a yes/no flag) on their own: they cannot narrow the search much. (step 9)
AppB-tree index on emailusers table (10M rows)

Key numbers

Rows checked
1
Query time
0.4 ms
Per insert
2 page writes

Terms

Full table scan
Reading every row of a table to find the ones that match, which gets slower as the table grows.
Index
A sorted extra structure that points to rows, so a search can skip most of the table.
Binary search
Finding a value in a sorted list by repeatedly discarding the wrong half.
B-tree
A shallow, balanced tree of disk pages, each holding hundreds of keys, used by most database indexes.
Index lookup
Walking from the root of the tree to a leaf, then following a pointer to the table row.
Range query
A query for values between two limits, which a sorted index answers by walking along its leaves.
Composite index
An index on several columns, sorted by the first, then the second, and so on.
Left-prefix rule
A composite index helps queries that use its first columns, in order, but not later columns alone.
Covering index
An index that holds every column a query needs, so the table is never read (an index-only scan).
Write amplification from indexes
Each insert, update or delete must also change every index on the table.
EXPLAIN
A command that shows how the database will run a query, including which index it uses.