Make slow queries fast: read the plan, add the right index, fetch less.
Query optimization means making a database query use less work: fewer rows read, less data sent, fewer round trips. The result is the same answer, much faster.
You write SQL that says what you want. The database decides how to get it. A part called the query planner (or optimizer) picks a plan. It guesses the cost of each possible plan, using statistics about your tables, and runs the cheapest. Most of the time this works. When it does not, queries get slow.
A plan is a tree of steps. The most important question for each step is: how many rows does it touch? A step that reads a million rows to return ten is the problem.
| Lever | What you do | Why it helps |
|---|---|---|
| Add the right index | Index the columns used in WHERE, JOIN, ORDER BY. A composite index follows the order: equality columns first, then range or sort. | Turns a scan into a seek, and can remove the sort step. |
| Select fewer columns | Name the columns. Avoid SELECT *. | Less data to read, send and parse. May allow an index-only scan (a covering index). |
| Limit the rows | Add LIMIT. Use keyset paging (WHERE id > last_seen) instead of big OFFSET. | The database can stop early. OFFSET 100000 still reads and drops 100000 rows. |
| Fix N+1 | Use a JOIN, or one IN (...) query, or batching. | Removes many network round trips. |
| Keep filters index-friendly | Avoid functions on indexed columns (WHERE LOWER(email) = ...) and leading wildcards (LIKE '%abc'). | Otherwise the index cannot be used. |
| Update statistics | Run ANALYZE (or your engine's equivalent). | The planner picks plans from stats. Old stats lead to bad plans. |
| Rewrite the query | Replace correlated subqueries with joins, use EXISTS instead of IN on big sets, filter early. | Gives the planner a cheaper path. |
| Cache or precompute | Cache the result, or store it in a summary table or materialized view. | Avoids running the heavy query at all. |
EXPLAIN ANALYZE SELECT id, title, created_at FROM posts WHERE author_id = 42 ORDER BY created_at DESC LIMIT 20; -- Fix: one composite index serves both the filter and the sort CREATE INDEX posts_author_created ON posts (author_id, created_at DESC);
SELECT * FROM posts p WHERE p.author_id = 42 ORDER BY p.created_at DESC ;
A simplified cost model with made-up but sensible constants (deterministic, no timing of real databases). Real plans from EXPLAIN look different and depend on your data, statistics and engine. The lesson is the order of impact: avoid reading rows you do not need, then avoid sending data you do not need, then avoid extra round trips.
| Term | Meaning in easy words |
|---|---|
| Query planner / optimizer | The part of the database that chooses how to run a query |
| Query plan | The chosen list of steps, shown by EXPLAIN |
| Full table scan | Reading every row of a table |
| Index seek / scan | Using an index to find matching rows quickly |
| Covering index | An index that holds all the columns the query needs, so the table is not read |
| Selectivity | How small a share of rows a filter keeps. A highly selective filter keeps few rows. |
| Cardinality estimate | The planner's guess of how many rows a step returns |
| Statistics | Summaries of the data (counts, value spread) that the planner uses |
| N+1 problem | One query for a list, then one more query for each item |
| Keyset (seek) pagination | Paging with WHERE id > last_seen instead of OFFSET |
| Slow query log | A log of queries that took longer than a set time |
| Choice | We gain | We lose |
|---|---|---|
| More indexes | Faster reads | Slower writes, more disk and memory |
| Covering index | No table lookups | A bigger index to maintain |
| Denormalize or precompute | Skip joins and heavy work | Stale or duplicated data |
| Cache the result | No query at all on a hit | Invalidation and stale data |
| Query hints | Force a known good plan | Fragile when data changes |
| Bigger LIMIT, bigger pages | Fewer round trips | More data per request |
WHERE DATE(created_at) = ... cannot use an index on created_at. Use a range instead.