How a Query Runs
When a SQL query runs, the database parses it, rewrites it, chooses a plan with a cost-based optimizer, and then executes that plan. Understanding these stages explains most performance questions: why the same query can be fast one day and slow the next, why an index is sometimes ignored, and why ANALYZE matters. SQL says what you want; the planner decides how to get it. In this lesson, we will follow a query through the four stages, see the planner's cost estimates, and look at the statistics it bases them on.
In One Minute
- Parse: check the SQL's grammar and turn it into a tree.
- Rewrite: expand views and apply rules.
- Plan: consider many ways to run the query and pick the one with the lowest estimated cost.
- Execute: run the chosen plan and return rows.
- Estimates come from statistics that
ANALYZEgathers; stale statistics mean bad plans.
The Four Stages
| Stage | Does | Errors you see here |
|---|---|---|
| Parse | Checks grammar, builds a parse tree, looks up tables and columns | syntax error, relation does not exist |
| Rewrite | Replaces views with their queries, applies rules | |
| Plan | Lists possible plans, estimates each one's cost, keeps the cheapest | |
| Execute | Runs the plan, reading and combining rows | division by zero, constraint violations |
Explanation: A typo fails at parse time, before any data is read. A division by zero fails during execution, possibly after many rows have been processed.
A Table to Plan For
The examples use a generated table of 20,000 payments for 5,000 students over two years. (At 20,000 rows, ANALYZE reads every row, so the statistics and estimates here are exact and repeatable; on bigger tables it reads a random sample.)
CREATE TABLE big_payments (
payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
student_id INTEGER NOT NULL,
paid_on DATE NOT NULL,
amount_usd NUMERIC(8,2) NOT NULL,
method TEXT
);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method)
SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400),
(ARRAY['card', 'check', 'cash'])[1 + g % 3]
FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;The Planner's Estimate
EXPLAIN shows the plan the planner chose, with its cost estimate, without running the query:
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
EXPLAIN SELECT * FROM big_payments WHERE student_id = 1234;CREATE TABLE
INSERT 0 20000
ANALYZE
QUERY PLAN
---------------------------------------------------------------
Seq Scan on big_payments (cost=0.00..378.00 rows=4 width=22)
Filter: (student_id = 1234)
(2 rows)Explanation: cost=0.00..378.00 is the estimated cost to return the first row and all rows, in arbitrary units (roughly, pages read and rows processed). rows=4 is how many rows the planner expects, and width=22 the average row size in bytes. With no index on student_id, the only option is a sequential scan of the whole table. Reading EXPLAIN explains every part of a plan.
Statistics: What the Planner Knows
The planner doesn't look at your data when planning; it looks at statistics about it. ANALYZE stores them in the catalogs:
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
SELECT reltuples AS estimated_rows, relpages AS pages
FROM pg_class WHERE relname = 'big_payments';
SELECT attname AS column_name, n_distinct
FROM pg_stats
WHERE tablename = 'big_payments' AND attname IN ('student_id', 'method')
ORDER BY attname;CREATE TABLE
INSERT 0 20000
ANALYZE
estimated_rows | pages
----------------+-------
20000 | 128
(1 row)
column_name | n_distinct
-------------+------------
method | 3
student_id | -0.25
(2 rows)Explanation: The planner knows the table has 20,000 rows on 128 pages, and that method has 3 distinct values. For student_id, n_distinct is -0.25: a negative number means a fraction of the row count, used when distinct values grow with the table. A quarter of 20,000 is 5,000 distinct students. From that, it estimates student_id = 1234 matches 20,000 / 5,000 = 4 rows: exactly the rows=4 in the plan. pg_stats also keeps the most common values and a histogram of each column.
Keeping Statistics Fresh
Autovacuum runs ANALYZE automatically when enough of a table has changed. After a big load, though, statistics can lag behind: a table loaded with a million rows a minute ago may still be estimated at zero. Run ANALYZE table_name yourself after bulk loads or large deletes, before running heavy queries.
Common Mistakes
Assuming SQL runs in the order it's written. The planner may reorder joins and filters freely.
Skipping ANALYZE after bulk loads. The planner works from old numbers.
Reading costs as milliseconds. They're relative units for comparing plans.
Trusting timings in a browser. Try it runs PostgreSQL in your browser; compare plans, rows and buffers, not milliseconds.
Interview Corner
What are the stages of query processing?
Parsing (grammar and names), rewriting (views and rules), planning (choosing the cheapest estimated plan) and execution (running it).
What is a cost-based optimizer?
A planner that estimates the cost of alternative plans, using table statistics, and chooses the one with the lowest estimated cost.
What does ANALYZE do?
It samples a table and stores statistics, such as row counts, distinct values and value distributions, which the planner uses for its estimates.
Practice
Challenge: Using the generated table, show the planner's estimate for WHERE method = 'cash' with EXPLAIN. Given 3 distinct methods and 20,000 rows, what row estimate do you expect?
Show solution
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
EXPLAIN SELECT * FROM big_payments WHERE method = 'cash';CREATE TABLE
INSERT 0 20000
ANALYZE
QUERY PLAN
------------------------------------------------------------------
Seq Scan on big_payments (cost=0.00..378.00 rows=6667 width=22)
Filter: (method = 'cash'::text)
(2 rows)About a third of 20,000. Here the planner uses the column's most-common-values list, which records each method's exact share, so its estimate matches the real count closely.
Key Takeaways
| You want to | Use |
|---|---|
| See the chosen plan | EXPLAIN SELECT ... |
| Refresh statistics | ANALYZE table_name; |
| See what the planner knows | pg_class.reltuples, pg_stats |
Was this tutorial helpful?