SQL and Databases on query plans
A query is parsed, planned, then executed
- You say which rows you want. The planner decides how to fetch them.
- It estimates the cost of many paths, such as which index to use, and picks the cheapest.
- The same SQL can get a different plan as the tables grow.
- Parsecheck syntax, build a tree
- Rewriteexpand views
- Planpick the cheapest path
- Executerun the plan, return rows
EXPLAIN ANALYZE shows what really happened
- Put EXPLAIN in front of a query to print its plan without running it.
- EXPLAIN ANALYZE runs the query too, and adds real times and row counts to each step.
- Costs are in the planner's own units, not time. The actual times are milliseconds.
- It really runs the statement. Wrap an UPDATE or DELETE in BEGIN and ROLLBACK.
The plan names how each table is read
- Seq Scan reads the whole table. That is right for tiny tables or when most rows match.
- Index Scan follows an index to the rows. That is right when few rows match.
- Bitmap Heap Scan is the middle case: gather matches from an index, then read them in order.
Bad row estimates cause bad plans
- The planner guesses row counts from statistics that ANALYZE samples from each table.
- Autovacuum reruns ANALYZE by itself once enough rows have changed.
- In the output, compare estimated rows with actual rows. A big gap is the thing to fix.
Keyset pagination beats OFFSET
- OFFSET 10000 makes the database produce 10,000 rows and throw them away.
- New rows also shift every page, so a reader sees repeats.
- Keyset pagination asks for the rows after the last one seen. An index jumps right there.
- Sort by a unique tiebreaker such as id. The cost: you cannot jump to page 50.
SELECT id, created_at, total
FROM orders
WHERE user_id = $1
AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 20;