System Design Playbook
04 · Data & databases9 min read

How to optimize an SQL query: indexes and other fixes

Why a query that took 2 ms in development takes 4 seconds in production, how indexes turn a full table scan into a few page reads, and the checklist to make slow database fetches fast.

In one sentence

An index is a sorted copy of one or more columns that lets the database jump to the rows it needs instead of reading the whole table.

Why queries get slow

With 1,000 rows, everything is fast. With 10 million, a query that has to read every row (a *full table scan*) gets slower in direct proportion to the table size. That's O(n): double the rows, double the time.

Run the query below with and without an index, and try the different table sizes.

Full table scan vs index lookup
Table size
SELECT * FROM users WHERE email = 'lucia@mail.com';users table · 1,000,0001mark@mail.comUS2sofia@mail.comES3liam@mail.comUK4ana@mail.comMX5noah@mail.comUS6emma@mail.comFR7diego@mail.comAR8yuki@mail.comJP9lucia@mail.comES10omar@mail.comEG11chloe@mail.comCA12ivan@mail.comPL13zoe@mail.comAU⋮ 999,987No index: the database has to read every rowdone 0%
Rows examined
0
Pages read
0
Est. time
…
Rows returned
0
Without an index the database reads the whole table (O(n)). A B-tree index keeps emails sorted, so it walks root → branch → leaf and jumps straight to the row (O(log n)).
Without an index the database checks every row. With a B-tree index on email it walks three or four levels and jumps to the row.

How an index works

Most databases store indexes as a B-tree: a sorted, balanced tree where each node holds hundreds of keys. Because each level divides the search space by a few hundred, even 100 million rows need only 3 or 4 page reads to find a value. That's O(log n).

It's the same idea as the index at the back of a book: you don't read every page to find "sharding", you look it up alphabetically and jump to the page.

-- Before: Seq Scan on users (rows=10,000,000)
CREATE INDEX idx_users_email ON users (email);
-- After:  Index Scan using idx_users_email (rows=1)

Composite indexes and the leftmost rule

An index can cover several columns, for example (user_id, created_at). It's sorted by the first column, then by the second inside each value of the first, like a phone book sorted by last name and then first name.

QueryCan use (user_id, created_at)?
WHERE user_id = 7✓ Yes, uses the first column
WHERE user_id = 7 ORDER BY created_at DESC LIMIT 20✓ Perfect: filter and order straight from the index
WHERE created_at > '2026-01-01'✕ No: it skips the first column

Indexes aren't free

  • Every INSERT, UPDATE and DELETE also has to update every index on the table, so writes get slower.
  • Indexes take disk and memory: a table with 12 indexes can be mostly index.
  • Low-selectivity columns (like is_active with two values) rarely help: the database will scan anyway.
  • Unused indexes are pure cost. Most databases can tell you which ones are never used.

That's why read-heavy tables can afford many indexes, while write-heavy tables (logs, events) should keep very few.

The query optimization checklist

  1. Measure first. Run EXPLAIN ANALYZE and look for Seq Scan on big tables, huge row estimates and sorts on disk.
  2. Add the right index for the WHERE, JOIN and ORDER BY columns of your hottest queries.
  3. Select only the columns you need. SELECT * drags big columns over the network and can prevent index-only scans.
  4. Don't wrap indexed columns in functions. WHERE LOWER(email) = … can't use a plain index on email; store it normalized or create an expression index.
  5. Kill N+1 queries. Loading 50 posts and then querying the author of each one is 51 queries. Use a JOIN or a single WHERE id IN (…).
  6. Paginate with keysets, not big offsets. OFFSET 100000 still reads 100,000 rows; WHERE id < last_seen_id ORDER BY id DESC LIMIT 20 doesn't.
  7. Cache or precompute results that are expensive and read often.
  8. Scale reads with read replicas once a single machine is the limit.

Key takeaways

  • 01A full table scan grows with the table (O(n)); an index lookup barely grows (O(log n)).
  • 02Composite indexes follow the leftmost-column rule: order the columns to match your queries.
  • 03Every index speeds up some reads and slows down every write.
  • 04Always confirm with EXPLAIN ANALYZE instead of guessing.

Check your understanding

1 of 3

What does an index let the database do?

Related concepts