Load/Bearing
Fundamentals · 04 of 22

Database indexing

Before you buy another database, make each query touch fewer rows. Indexes are the cheapest scaling you'll ever do.

4 min readUsed in: 3 · Database Meltdown

Without an index, finding the rows that match WHERE email = 'a@b.com' means reading every row in the table: a full table scan. At a million rows that may take hundreds of milliseconds. An index is a second, sorted structure that maps column values to row locations, so the database can jump straight to the matches, usually in well under a millisecond.

The cost is that every index has to be kept up to date on every write, and it takes space on disk and in memory. Indexing well means knowing which query shapes each kind of index serves, and adding only the ones your queries need.

B-tree indexes

Almost every relational index is a B-tree, or more precisely a B+tree. It's a balanced tree of fixed-size pages. Each page holds hundreds of sorted keys, so the tree is wide and shallow: three or four levels reach a billion rows. Leaf pages hold the keys in order and are linked to each other, which makes range scans cheap.

ROOTa … zINTERNALa … mINTERNALn … zLEAFa … fLEAFg … mLEAFn … sLEAFt … z
A B+tree. Lookups walk root → internal → leaf. Leaves are sorted and linked, so a range query reads neighbouring leaves.

Hash indexes

A hash index maps hash(value) to row locations. An equality lookup costs O(1), but hashing destroys ordering, so it can't answer anything else. PostgreSQL offers hash indexes, and many key-value stores are hash-based internally, but in relational databases B-trees are the default for good reason.

Query shapeB-treeHash
WHERE id = 42✓✓ (slightly faster)
WHERE created_at > '2026-10-01'✓✗
WHERE name LIKE 'sid%' (prefix)✓✗
ORDER BY created_at LIMIT 20✓ (no sort needed)✗
MIN / MAX✓ (first or last leaf)✗
WHERE name LIKE '%sid%'✗ (needs a full scan or a trigram index)✗

Write-heavy stores such as Cassandra and RocksDB use a third structure, the LSM tree. It buffers writes in memory and flushes sorted files to disk, which trades some read speed for much faster writes.

Composite indexes and column order

An index on (user_id, created_at) is sorted by user_id first, then by created_at within each user, like a phone book sorted by last name and then first name. That gives the leftmost-prefix rule:

QueryUses the index?
WHERE user_id = 7✓ the leftmost column
WHERE user_id = 7 AND created_at > …✓ both columns
WHERE user_id = 7 ORDER BY created_at DESC LIMIT 20✓ already in order, so no sort
WHERE created_at > …✗ skips the leftmost column

The usual rule: put columns compared with equality first, then the column used for a range or sort. Once the index hits a range condition, the columns after it can't narrow the search any further.

Covering indexes

An index lookup normally finds row locations, then fetches each row from the table. If the index already contains every column the query needs, the database can skip the table entirely. That's a covering index, and the plan shows an index-only scan.

-- query: SELECT created_at, total FROM orders WHERE user_id = 7 ORDER BY created_at DESC LIMIT 20 CREATE INDEX orders_user_recent ON orders (user_id, created_at) INCLUDE (total); -- PostgreSQL

In MySQL's InnoDB, the table itself is stored as a B-tree on the primary key (a clustered index), and every secondary index stores the primary key. So a secondary index always covers queries that only need its own columns plus the primary key.

When an index makes things slower

Check, don't guess

Run EXPLAIN ANALYZE on slow queries and read the plan. A Seq Scan on a large table with a selective filter means a missing index. An Index Scan means the index is used, and an Index Only Scan means it covers the query. Turn on the slow query log (or pg_stat_statements) to find the queries worth fixing, and check index usage statistics for indexes nothing reads.

In the game: the database's 1,500 reads per second assumes every query is indexed. In real life a missing index can turn a 1 ms lookup into a 500 ms scan and cut capacity by 500 times. When Database Meltdown starts, the first question is whether the queries are cheap, before you reach for a cache or replicas.

Interview checklist

Practise it

Level 3: Database Meltdown

Put this into practice against live traffic. Your progress in the game is saved in your browser.

Play level 3
Workshop drill

Do it by hand

Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.

Index advisor

Further reading