Module 4 · Caching and performanceLesson 41 of 887 minIntermediate
Database query optimization
Before adding caches or servers, make the queries themselves cheap. Most slow apps are slow because of a few bad queries.
Compare the number of queries and the time in "N+1 queries" and "One query". Then see what fetching only the needed columns saves.
Caching hides slow queries; optimizing removes them. Start here.
1. Measure
- Turn on the slow query log to find queries above, say, 100 ms.
- Look at total time, not just the slowest: a 5 ms query run 10,000 times a minute matters more than a 2 s report run once a day.
- Run
EXPLAIN ANALYZEto see what the database actually does: which indexes, how many rows scanned.
2. Fix the common problems
The N+1 problem: load a list, then run one more query per item. ORMs make this very easy to write by accident.
- Use a join, or load related rows in one batch:
SELECT * FROM authors WHERE id IN (3, 8, 12, ...). - Most ORMs have an "eager loading" option for exactly this.
Missing indexes: a filter or sort on an unindexed column scans the table (see the indexing lesson).
SELECT *: fetching 40 columns, including large text, when the page shows 2. Select only what you need.
Big offsets: OFFSET 100000 still reads and throws away 100,000 rows. Use keyset pagination: WHERE id > last_seen_id ORDER BY id LIMIT 50.
Functions on columns: WHERE DATE(created_at) = ... can't use an index on created_at. Rewrite it as a range.
Counting everything: COUNT(*) over millions of rows on every page view. Keep a running counter or an estimate instead.
3. Then reduce load
- Cache results that are expensive and read often.
- Move heavy reports to a read replica or a separate analytics database.
- Precompute: materialized views or summary tables updated in the background.
One good index or one removed N+1 often does more than another server.