Backend Case Studies

Topic B2

Database indexes

Why slow queries read the whole table, and how a B-tree index fixes it.

10 min · intermediate

Watch: without an index, every row is read one by one. With an index, the computer goes straight to the rows it wants.

#1#2#3#4#5#6#7#8#9#10#11#12#13#14#15#16table74231942825113304214921517
  • being checked
  • finished / the result
  • no longer used
Step 1 of 18

SELECT * FROM orders WHERE user_id = 42. Without an index, rows sit in the order they arrived, so the database has to read them all.

An index trades a little disk space and a little write time for lookups that never read the whole table.

Like the index at the back of a book

Finding "recursion" in a 500-page book with no index means turning every page. The index at the back lists words alphabetically, each with its page numbers. You find the word in seconds, then go straight to the page. A database index works exactly the same way: sorted, small, and pointing at where the real data lives.

When an index gets used

  • WHERE column = value and ranges (>, <, BETWEEN).
  • ORDER BY column LIMIT n: the data is already sorted in the index, so no sort is needed.
  • JOIN: foreign key columns like orders.user_id almost always need an index. PostgreSQL doesn't create one for you.
Code, for programmersCreating an index, then checking it's used
CREATE INDEX idx_orders_user ON orders (user_id);

EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 42;
-- before: Seq Scan on orders  (rows=10000000)   ~1200 ms
-- after:  Index Scan using idx_orders_user      ~0.1 ms

-- composite index: filter by user, newest first
CREATE INDEX idx_orders_user_created ON orders (user_id, created_at DESC);

When an index doesn't get used

  • The column is wrapped in a function: WHERE lower(email) = … can't use a plain index on email. Index lower(email) instead.
  • LIKE with a leading wildcard: '%gmail.com' has no prefix to look up in sorted data.
  • Column order in a composite index: an index on (user_id, created_at) helps filtering by user_id, but not by created_at alone. Like a phone book sorted by surname, then first name.
  • Almost every row matches: if the query takes 60% of the table, reading the table directly is faster, and the database knows it.

Quiz

  1. A 10-million-row table with no index on user_id. How many rows does WHERE user_id = 42 read?

  2. An index on (user_id, created_at). Which query does it not help?

  3. What is the main cost of an index?

0 of 3 answered.