Reading query plans
Step 1 · The pattern
The planner picks a plan
The app lists pending orders with their customers. The planner's statistics say about 50 rows are pending, so it picks a nested loop: one index lookup per order. For 50 rows that is the best plan there is.
- query
- answered
In short
Reading query plans: how it works and how it breaks
Before it runs a query, the database's planner picks a plan: which indexes to read, in what order to join tables and by which method. It chooses by estimating how many rows each step will return, using statistics it keeps about every table. EXPLAIN prints the chosen plan with those estimates. EXPLAIN ANALYZE also runs the query and prints what really happened beside them: actual rows, actual time and how many times each step ran. Read a plan from the most indented steps outwards and compare estimated rows with actual rows at each one. Where they differ by orders of magnitude, the planner chose with wrong information, and every step above inherits the mistake. The usual cause is stale statistics, and refreshing them with ANALYZE is the usual fix. A plan is only wrong for a row count: a nested loop suits fifty rows and is ruinous for 400,000.
What this simulation simplifies
- A real plan has more steps than two, and the planner weighs many more alternatives than one loop against one hash join.
- Hold times are scaled for the animation. Real timings depend on caching, hardware and how wide the rows are.
How this comes up in interviews
"A query that normally takes milliseconds now takes several seconds, with no code change. How do you find out why from its plan?"
Then they ask
- What is the difference between EXPLAIN and EXPLAIN ANALYZE, and when is the second one unsafe?
- A step shows a tiny actual time but a very large loops count. What does that tell you?
- The estimate is 50 rows and the actual is 400,000. What do you do next?
A strong answer covers
- The planner chooses from estimated row counts, so a wrong estimate gives a plan that suits the wrong amount of data.
- EXPLAIN shows estimates only. EXPLAIN ANALYZE runs the query and adds actual rows, time and loops.
- Read from the innermost steps outwards and find the lowest step where estimated and actual rows part ways.
- Actual time is per loop, so multiply it by loops before deciding which step is expensive.
- Stale statistics are the usual cause. Refresh them with ANALYZE and check the plan again.
Points to cover, not a script. Say them in your own words and tie them to a system you have worked on.
On one page: the track cheat sheet.
Sources: PostgreSQL documentation: using EXPLAIN ↗ · PostgreSQL documentation: EXPLAIN command reference ↗ · PostgreSQL documentation: statistics used by the planner ↗ · PostgreSQL documentation: routine vacuuming, updating planner statistics ↗ · Report a problem
Diagrams are our own simulations: the timings, rates and counts in them are illustrative, not measurements. Captions are original wording.