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.
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.
| Query | Can 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_activewith 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
- Measure first. Run
EXPLAIN ANALYZEand look forSeq Scanon big tables, huge row estimates and sorts on disk. - Add the right index for the WHERE, JOIN and ORDER BY columns of your hottest queries.
- Select only the columns you need.
SELECT *drags big columns over the network and can prevent index-only scans. - 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. - 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 (…). - Paginate with keysets, not big offsets.
OFFSET 100000still reads 100,000 rows;WHERE id < last_seen_id ORDER BY id DESC LIMIT 20doesn't. - Cache or precompute results that are expensive and read often.
- 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
Precomputing values
Precomputing means doing the expensive work at write time (or on a schedule) and storing the result, so every read is a cheap lookup instead of a fresh calculation.
7 min read →Read replicas
A read replica is a copy of the database that receives every change from the primary and answers read queries, so you can add read capacity without touching writes.
7 min read →Partitioning strategies
Partitioning divides one large table into smaller pieces by a rule (by date, by region, by hash, or by columns), so each query only reads the pieces that can contain its answer.
8 min read →