← Back to SQL, page 24

sql-0464 · Medium mid

Walk through what a database does between receiving a SELECT and returning rows.

The statement is parsed into a syntax tree, checked against the catalog (tables, columns, permissions), rewritten (views expanded, rules applied), planned by the optimizer, which estimates costs of alternative access paths and join orders using statistics, and then executed by operators that read pages from cache or disk and stream rows back to the client.

Full answer

Stages in more detail:

  1. Parse: text to a tree; syntax errors are reported here.
  2. Analyse: names resolved, types checked, privileges verified.
  3. Rewrite: views replaced by their definitions; in PostgreSQL, row-level security policies are added.
  4. 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.
  5. Execute: plan nodes pull rows from their children (scan, filter, join, aggregate, sort, limit), reading pages through the buffer cache.
  6. 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