Full answer
Stages in more detail:
- Parse: text to a tree; syntax errors are reported here.
- Analyse: names resolved, types checked, privileges verified.
- Rewrite: views replaced by their definitions; in PostgreSQL, row-level security policies are added.
- Plan: the optimizer enumerates candidate plans (sequential scan versus index scan, nested loop versus hash join, join order) and estimates their cost from table statistics; the cheapest is chosen.
- Execute: plan nodes pull rows from their children (scan, filter, join, aggregate, sort, limit), reading pages through the buffer cache.
- Return: rows are sent to the client in batches; a cursor can fetch them gradually.
Why it matters in interviews: slow queries are usually a planning problem (bad estimates, missing index) or an execution problem (too much data read, sorts spilling to disk). EXPLAIN shows step 4's choice; EXPLAIN ANALYZE also runs step 5 and reports actual rows and times. SQLite follows the same broad stages with its own bytecode engine, visible with EXPLAIN.
Key points
- Parse, analyse, rewrite, plan, execute
- The planner uses statistics to estimate costs
- Execution operators pull rows from children
- EXPLAIN shows the plan; ANALYZE adds actuals
- Views are expanded before planning
Common mistakes
- Thinking the database runs SQL clauses in written order
- Ignoring planning when diagnosing slow queries
Follow-ups
- What statistics does the planner use?
- Why can the same query get different plans?
Tips
- Name each stage in order