skip to content

the life of a query

parser, analyzer, rewriter, planner, executor. one query watched at every stage.

address
everything.execution.query_lifecycle
part
part 9, how a query runs
chapter
chapter 2 of 13
reading time
7 min

a query goes through five stages. the parser checks the grammar and builds a tree of words. the analyzer looks every name up in the catalog and turns it into numbers. the rewriter expands views (and rules). the planner picks the cheapest way to run it. the executor runs that plan, one row at a time.

each stage catches its own kind of mistake, which is why the same typo gives different errors depending on where it is.

the picture

you know how a typo in a keyword says "syntax error", a typo in a table name says "does not exist", and a division by zero only fails once rows show up? three different errors, from three different places.

think of a letter going through a post office. the first desk only checks that it looks like a letter: stamp, address in the right place (the parser). the next looks the address up and writes the postcode on it (the analyzer). the next notices it's addressed to a PO box and rewrites it to the real street (the rewriter, expanding a view). the next picks the route (the planner). and the van drives it (the executor).

hover a stage.

the five stages. hover one for what it gets and what it hands on.

one query, watched

here's SELECT name FROM londoners WHERE id = 42, where londoners is a view: SELECT id, name FROM customers WHERE city = 'London'. postgres can log the tree each stage produces (debug_print_parse, debug_print_rewritten, debug_print_plan). those logs are hundreds of lines per stage, so the figure keeps the lines that matter and says how many it dropped:

  1. →
  2. →
  3. →
  4. →
text → parse tree
query.sql
  1. SELECT name FROM londoners WHERE id = 42

parserthe parser sees words: SELECT, an identifier, FROM, another identifier. it checks the order against the grammar and builds a tree of them. it can't log that tree in postgres 18 (debug_print_parse prints the analyzer's tree, next), and it has no idea yet whether londoners exists.

stage 1/5
real output, a postgres 18.6 server · lifecycle
step through the stages, captured on a real postgres 18.6 server. the trees are trimmed: … marks lines left out. watch :relid change from the view (relkind v) to customers (relkind r) at the rewriter, and the plan turn into an index scan on customers_pkey.

the numbers in those trees are oids from the catalog (the system catalog has how to read them back), and you can ask what the two operators are:

sqldb=shop
SELECT oid, oprname, oprleft::regtype AS left_type, oprright::regtype AS right_type
FROM pg_operator
WHERE oid IN (96, 98)
ORDER BY oid;
output, from postgres 18.6
SELECT 2
oidoidoprnamenameleft_typeregtyperight_typeregtype
96=integerinteger
98=texttext
(2 rows)

the parser knows grammar, not tables

the parser has a list of keywords, and how reserved each one is:

sqldb=shop
SELECT word, catdesc
FROM pg_get_keywords()
WHERE word IN ('select', 'from', 'where', 'name', 'form')
ORDER BY word;
output, from postgres 18.6
SELECT 4
wordtextcatdesctext
fromreserved
nameunreserved
selectreserved
wherereserved
(4 rows)

name is unreserved, which is why customers can have a column called that. form isn't a keyword at all, so SELECT name FORM customers doesn't fail at FORM: an identifier after an expression is a column alias (AS is optional), and the grammar only gets stuck one word later. pick a mistake, see who catches it:

mistake in =
query.sql
  1. 1SELECT name FORM customers WHERE id = 42;
ERROR: syntax error at or near "customers"SQLSTATE 42601

the parser: FORM isn't a keyword, so it reads as a column alias (AS is optional), and the grammar only gets stuck one word later, at customers.

real output, postgres 18.6 (PGlite 0.5.12) · lifecycle-errors
one mistake per stage, run for real. the parser and analyzer reject the query before anything is planned; the planner rejects a join it can't build; the executor only fails when a row with id = 42 actually turns up.
predict the output
which stage rejects SELECT name FROM custmers?
sql
SELECT name FROM custmers WHERE id = 42;

the rewriter, and views

a view is stored as a rule in pg_rewrite: "a SELECT from this view is really this query". the rewriter applies it before the planner ever sees the query:

sqldb=shop
CREATE VIEW londoners AS SELECT id, name FROM customers WHERE city = 'London';
 
SELECT rulename, ev_type, is_instead
FROM pg_rewrite
WHERE ev_class = 'londoners'::regclass;
 
EXPLAIN (COSTS OFF) SELECT name FROM londoners WHERE id = 42;
output, from postgres 18.6
#1 · CREATE VIEW
#2 · SELECT 1
rulenamenameev_typecharis_insteadbool
_RETURN1t
(1 row)
#3 · EXPLAIN
Index Scan using customers_pkey on customers Index Cond: (id = 42) Filter: (city = 'London'::text)

one rule, _RETURN, for SELECT (ev_type 1), INSTEAD. and the plan never mentions londoners: the view's query was spliced in, flattened, and its WHERE merged with yours, so customers_pkey can be used for id = 42. a view costs nothing at run time; it's a query you didn't have to type (views).

planning and running

the planner is the optimizer part of this book: it generates candidate plans, estimates their costs from statistics, and keeps the cheapest. the executor is the iterator model: the plan as a tree of nodes, each answering "next row, please?".

the line between them is where prepared statements live. PREPARE runs the parser, analyzer and rewriter once and keeps the result; each EXECUTE plans (or reuses a plan) and runs it. which plans get reused is generic plans.

keylines

  • parser: grammar only. it has never heard of your tables.
  • analyzer: names become oids from the catalog; "does not exist" comes from here.
  • rewriter: views are rules in pg_rewrite, spliced in as subqueries.
  • planner: picks the cheapest plan. executor: runs it, pulling rows up the tree.
  • each stage catches its own mistakes, so the error tells you how far the query got.