Module 3 · Database designLesson 23 of 887 minIntermediate

Database indexes

An index is a sorted shortcut to your rows. It turns "check every row" into "follow three or four signposts".

Try it

Grow the table and search with the index off: watch rows checked and time explode. Turn the index on and compare. Notice the cost it adds to every insert.

When you ask a database for WHERE email = 'sam@example.com', it needs to find the matching rows. Without help, it reads every row and checks. That's a full table scan: fine at 1,000 rows, painful at 100 million.

The B-tree

Most indexes are B-trees: a shallow, wide tree of sorted pages.

  • The root page says "emails A to F are down this branch, G to M down that one...".
  • Each level narrows the range.
  • The leaf pages hold the values and point to the actual rows.

Each page holds hundreds of entries, so the tree is very shallow. Three or four levels can cover billions of rows. Finding one row costs a handful of page reads instead of millions.

B-trees keep data sorted, so they also help with ranges (WHERE created_at > '2026-01-01') and ORDER BY.

Indexes aren't free

  • Writes get slower: every insert or update must also update every index on that table.
  • Storage: indexes take disk and memory.
  • Unused indexes are pure cost.

So index what you search, join and sort by, not everything.

Practical tips

  • Use EXPLAIN to see whether a query uses an index or scans.
  • Composite indexes cover several columns, like (user_id, created_at). Column order matters: it helps queries that filter on user_id, but not ones that only filter on created_at.
  • A covering index contains every column the query needs, so the database never touches the table.
  • Functions hide columns from indexes: WHERE LOWER(email) = ... can't use a plain index on email.
  • Other index types exist: hash indexes for exact matches, full-text indexes for search, and vector indexes for AI search (coming in the last module).

Quick check

A query filters users by email and is slow on a 50 million row table. What's the most likely fix?