Skip to content

What happens when you run a SELECT

BasicsUnder the hoodYou should know: basic SQL

You type a SELECT, press Enter, and rows appear. In between, the database turns your text into a tree, checks it, picks a way to run it and pulls rows through that plan one at a time. Here is that journey for one small query in Postgres.

01 One query, four stages

We will follow one query against a six-row users table. Every SQL database goes through roughly the same stages; the names below are the ones Postgres uses.

query.sql
SELECT name FROM users
WHERE age > 30
ORDER BY name
LIMIT 2;
The life of one query in Postgres
StageQuestion it answersProduces
ParseIs this valid SQL grammar?A parse tree
Analyse and rewriteDo these tables, columns and types exist? Are there views to expand?A query tree
PlanWhich of the possible ways to run this is cheapest?A plan tree
ExecuteWhat are the rows?Rows, sent to the client as they are made

02 Parse and analyse: is this a real query?

The parser checks grammar only. It turns the text into a tree (a SELECT with a target list, a FROM, a WHERE condition) without looking at any table. The analyser then looks every name up in the system catalogue: does users exist, does it have name and age, and which > operator fits an integer column and the number 30? If users were a view, the rewriter would now swap in the view’s own query.

The error you get tells you which stage stopped. A typo in a keyword fails in the parser; a typo in a column name gets through the parser and fails in the analyser.

Stopped by the parser
=> SELEC name FROM users;
ERROR: syntax error at or near "SELEC"
LINE 1: SELEC name FROM users;
^
Stopped by the analyser
=> SELECT nme FROM users;
ERROR: column "nme" does not exist
LINE 1: SELECT nme FROM users;
^
HINT: Perhaps you meant to reference the column "users.name".

03 Plan: choose how to get the rows

SQL says what you want, not how to get it. For one query there are often many ways: read the whole table or use an index, sort everything or read an index that is already in order, join A to B or B to A. The planner estimates the cost of each way from table statistics (row counts, common values, gathered by ANALYZE) and keeps the cheapest.

The result is a tree of plan nodes. EXPLAIN prints it, top node first. Each node pulls rows from the node below it.

Text
=> EXPLAIN SELECT name FROM users WHERE age > 30 ORDER BY name LIMIT 2;
Limit
-> Sort
Sort Key: name
-> Seq Scan on users
Filter: (age > 30)
-- cost and row estimates trimmed

With six rows and no index on age, reading the whole table is the only sensible plan. On a big table with an index on name, the planner might instead walk the index in name order and stop after two matches, with no sort at all.

04 Execute: rows are pulled up the tree

Postgres runs the plan from the top. Each node has one job: when asked, hand back the next row, or say “no more”. A node that needs rows asks its child. Rows travel up one at a time, which is why a LIMIT can stop work early.

Running the plan for LIMIT 2
Step 1 of 11
plan
Limit 2
Sort name
Seq Scanage > 30
users (name, age), as stored
eli 52
ben 25
ana 34
dev 30
fay 38
cho 41
Sort keeps (best 2)
Empty
sent to the client
Empty
  • working now
  • waiting on child
  • failed the filter
  • passed, or done
  • just added
  • not read yet

The planner has built this tree. Nothing has run yet: no row has been read and the client has nothing.

0 of 6 rows read

Look at the cost: Seq Scan read all six rows even though only two came out. A sort has to see everything before it can return the first row. Because of the LIMIT, Postgres used a top-N sort that keeps only the best 2 in memory; EXPLAIN ANALYZE reports it as Sort Method: top-N heapsort.

05 Return: rows on the wire

The server does not build a finished result and then send it. As each row leaves the top node it is written to the connection as a message. The Postgres wire protocol for our query looks like this:

Messages the server sends back
MessageCarries
RowDescriptionColumn names and types: one column, `name`, of type text
DataRowana
DataRowcho
CommandCompleteThe tag `SELECT 2`: two rows
ReadyForQueryThe server is free for the next query

Your client library usually collects all the DataRow messages into a list before your code sees any of them. For a huge result that list can fill your app’s memory; use a cursor or a streaming API to read rows in batches instead.

06 You write it in one order; it runs in another

The trace shows the filter running long before the SELECT list is worked out. SQL’s clauses are evaluated, in meaning, in this order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. That explains some confusing errors.

Fails
SELECT age * 12 AS months
FROM users
WHERE months > 400;
-- ERROR: column "months" does not exist
-- LINE 3: WHERE months > 400;
-- ^
Works
SELECT age * 12 AS months
FROM users
ORDER BY months;

WHERE runs before SELECT has named the alias, so months does not exist yet. ORDER BY runs after, so it can use it.

07 When it bites

SELECT name FROM users LIMIT 2;LIMIT with no ORDER BYWithout an order, the plan returns whichever rows it reaches first. A different plan or a vacuum can change which two you get.
WHERE count(*) > 1An aggregate in WHEREWHERE filters rows before they are grouped, so there is no count yet. Filter groups with HAVING count(*) > 1.
Statistics out of dateThe planner trusts its row estimates. After a big load or delete, stale statistics can make it pick a slow plan. Autovacuum usually refreshes them; run ANALYZE users by hand after a bulk change.
Fetching a million rows into a listMost drivers buffer the whole result before returning. Stream with a cursor, or page with WHERE id > $1 ORDER BY id LIMIT 1000.

08 Check yourself

Question

SELECT * FROM userz; fails because there is no userz table. Which stage reports it?

Question

The plan is Limit 1 over a Seq Scan, with no sort. The first row matches. How many rows does Seq Scan read?

Question

Why can ORDER BY use a column alias from the SELECT list when WHERE cannot?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?