How Postgres runs your query

Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 7:40 on Monday. The nightly revenue report took 4 seconds in May and 40 minutes last night, and Tess's dashboard was still empty at breakfast. Nobody touched the SQL. Nora's only advice: "The plan says why, if you can read it."

You'll learn to

  • Read a plan: its nodes, estimated against actual rows, and buffers
  • Explain how the planner turns statistics into row guesses and costs
  • Predict which scan a filter gets: sequential, index, bitmap, index-only
  • Spot a spill past work_mem and a wrong row guess

Learn

Your SQL says what, not how

SQL says what you want. It never says how to get it: which table to read first, whether to use an index, which join method. A part of Postgres called the planner decides that, a moment before the query runs.

Think of the route planner in a car. You type a destination. It compares routes on its map and picks the one it expects to be fastest. If the map is out of date, it sends you down a closed road with full confidence.

The planner's map is a set of statistics about your tables. EXPLAIN prints the route it chose, called the plan, and runs nothing. EXPLAIN ANALYZE runs the statement and adds what really happened.

The life of a query

Four stages in a row: the parser builds a parse tree, the analyzer and rewriter resolve names and expand views, the planner picks the cheapest plan using statistics, and the executor runs the plan tree.

Read it left to right: every statement passes these four stages. The executor runs the plan as a tree of steps called nodes. Each node pulls rows from the nodes below it one at a time, which is why a Limit can stop a scan early. EXPLAIN stops after the planner.

The planner prices every route

To compare plans, the planner gives each one a cost: a guess at the work, in its own unit. One unit is reading one page in sequence. A page is the 8 kB block Postgres reads at a time.

The default prices:

  • a page read in sequence: seq_page_cost = 1.0
  • a page read out of order: random_page_cost = 4.0
  • a row processed: cpu_tuple_cost = 0.01
  • an operator evaluated: cpu_operator_cost = 0.0025

Work one out, for SELECT * FROM orders WHERE status = 'cancelled'. The table is 1 page and 80 rows:

  • 1 page x 1.0 = 1.00
  • 80 rows x 0.01 = 0.80
  • 80 comparisons x 0.0025 = 0.20

Total 2.00, exactly the cost=0.00..2.00 that EXPLAIN prints.

Size, statistics and the estimate

SELECT relname, reltuples, relpages
FROM pg_class
WHERE relname IN ('orders', 'payments')
ORDER BY relname;

EXPLAIN
SELECT *
FROM orders
WHERE status = 'cancelled';

EXPLAIN
SELECT *
FROM payments
WHERE status = 'failed';

The first result is the planner's idea of each table's size, kept in pg_class: reltuples rows in relpages pages. VACUUM, ANALYZE and CREATE INDEX refresh it. Plain EXPLAIN then shows (cost=... rows=... width=...). The first cost is the cost before the first row comes out, the second is the total. rows is the estimated row count and width the average row size in bytes. Both tables fit in one page.

Where the row guess comes from

The cost depends on how many rows the planner expects. That guess comes from statistics. A command named ANALYZE collects them for every column (it is not the ANALYZE in EXPLAIN ANALYZE). You can read them in pg_stats, one of Postgres's own tables about your tables. The main ones:

  • null_frac: the share of NULLs.
  • n_distinct: how many different values. A negative number means a fraction of the rows, and -1 means every value is unique.
  • most_common_vals and most_common_freqs: the most frequent values, and the share of rows each one has.
  • histogram_bounds: the other values, cut into buckets that hold equal numbers of rows.

For status = 'cancelled', the value is in the most-common list with frequency 0.1125. So the guess is 80 x 0.1125 = 9 rows.

What ANALYZE wrote down about orders.status

Five bars, one per order status in the most-common list, each showing the estimated rows as the frequency times 80 rows: delivered 29, shipped 26, cancelled 9, placed 8 and returned 8.

Each bar is one entry of most_common_vals: its frequency times the table's 80 rows is the row guess for a filter on that value. A value outside the list gets a share of what the list leaves, and a range is read off the histogram.

What the planner knows about orders

SELECT attname, null_frac, n_distinct,
       most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'orders'
  AND attname IN ('status', 'customer_id')
ORDER BY attname;

SELECT null_frac
FROM pg_stats
WHERE tablename = 'events'
  AND attname = 'user_id';

customer_id has n_distinct = -0.35: 35% of 80 rows, about 28 different customers. events.user_id is 21% NULL, the anonymous clicks of Lesson 2.1.

Remember: estimated rows = rows in the table x the share the statistics give your filter. When the statistics are old, the estimate is old, and so is the plan.

Four ways to read a table

With a row guess in hand, the planner picks how to read each table. Think of a thick reference book. You can read it cover to cover, or look a word up in the index at the back and jump to the pages it lists.

Reading everything in order is a Seq Scan. Using the index (the B-tree of Lesson 2.4) comes in three kinds. The walkthrough below shows all four.

The share of rows decides. For a few rows, jumping around is cheap. For most of the table it costs more than reading straight through: a page read out of order is priced at 4.0, a page in sequence at 1.0.

Four scans, one table and one index

An index on customer_id beside the 640-page table big_orders; four steps show which of the two a sequential scan, an index scan, a bitmap heap scan and an index-only scan read, and in what order.

  1. Seq Scan. Read every page of the table in file order and test each row. The index is not used. Reading in sequence is the cheapest way to read a page, so this wins when most rows match.

  2. Index Scan. Walk the B-tree to the matching entries, and fetch each match's table page as you meet it. Those are random reads: one page per row in the worst case. Good for a handful of rows.

  3. Bitmap Heap Scan. First collect the addresses of all matches from the index into a bitmap sorted by page. Then read each needed page once, in file order. It sits between the first two.

  4. Index Only Scan. Every column the query needs is in the index, so the index answers alone. The table is not read, as long as its pages are marked all-visible. The next section explains that mark.

Watch the Table box: all pages in order, then scattered pages, then only the needed pages in order, then none.

One index, three filters, three plans

CREATE INDEX big_orders_customer_idx ON big_orders (customer_id);

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE customer_id = 42;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE customer_id < 200;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE customer_id < 3000;

-- only the indexed column, after VACUUM: the index alone answers
VACUUM big_orders;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT customer_id FROM big_orders WHERE customer_id = 42;

Postgres calls the table's own pages the heap (not the sorting heap of Lesson 2.3). Heap Blocks: exact=20 and exact=637 count the table pages each bitmap scan read. Rows Removed by Filter: 40020 is the price of the Seq Scan. The last plan reads Index Only Scan ... Heap Fetches: 0.

What the planner chose, by share of rows

FilterRows matchedSharePlanTable pages read
customerid = 42200.02%Bitmap Heap Scan20
customerid < 2003,9804%Bitmap Heap Scan637 of 640
customerid < 300059,98060%Seq Scanall 640
customerid = 42, only that column, after VACUUM200.02%Index Only Scan0

Read down the Share column: the plan changes as the share grows. The planner decides from estimates, before any page is read. The last column is what EXPLAIN ANALYZE saw afterwards.

An index-only scan that reads the table

The fourth scan has a catch. An index entry has no xmin or xmax, so the index alone cannot tell whether the row version it points to is visible to you (Lesson 2.7).

Postgres keeps a visibility map for that: one bit per table page, meaning "every row here is visible to everyone". VACUUM sets the bits. Any insert, update or delete on a page clears its bit.

An Index Only Scan checks the bit, and visits the table page only when it is clear. EXPLAIN ANALYZE counts those visits as Heap Fetches. So a freshly loaded table, or one updated all day with no VACUUM, gets "index-only" scans that read the table anyway.

Same question, two plans, and VACUUM

-- a function on the column: the index cannot help
EXPLAIN (COSTS OFF)
SELECT COUNT(*)
FROM big_events
WHERE DATE(event_ts) = DATE '2025-06-02';

-- the same day as a range on the bare column
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT COUNT(*)
FROM big_events
WHERE event_ts >= '2025-06-02'
  AND event_ts < '2025-06-03';

-- VACUUM sets the visibility map bits
VACUUM big_events;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT COUNT(*)
FROM big_events
WHERE event_ts >= '2025-06-02'
  AND event_ts < '2025-06-03';

Three plans. First, a function around the column: DATE(event_ts) blocks the index, which is sorted by event_ts, not by its date, so the plan is a Seq Scan. The function also hides the column from the statistics, so the planner guesses 500 rows of 100,000 where 13,601 match. Second, the same day as a range on the bare column: an Index Only Scan with Heap Fetches: 13601, because the table was never vacuumed. Third, after VACUUM: Heap Fetches: 0.

Dead tuples, VACUUM and the visibility-map bit

One heap page of orders: an UPDATE writes a new tuple version and leaves a dead one, a DELETE leaves another, VACUUM frees the slots and sets the page's all-visible bit, and the next insert clears it.

Step through one page of orders: an UPDATE leaves a dead version, VACUUM frees it and sets the bit, and the next insert clears it. Watch the visibility map label on the page and the All-visible bit below it.

Memory is per step, not per query

Sorts and hash tables need memory, and you have met their budget all through this module: work_mem, 4 MB by default.

The catch: it is the budget of each sort or hash node, not of the whole query. Hash nodes get work_mem x hash_mem_multiplier, which is 8 MB.

Work it out for a plan with two hash joins and one sort:

  • two hash joins: 8 + 8 = 16 MB
  • one sort: 4 MB
  • one session: 20 MB
  • 40 sessions at once: 40 x 20 = 800 MB

That is why work_mem is raised for one session or one role, for the heavy batch job (SET work_mem = '256MB', ALTER ROLE etl SET work_mem = ...), and not for the whole server.

A spill in the buffers, then a cap

SET work_mem = '64kB';

-- buffers are part of EXPLAIN ANALYZE since Postgres 18
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT *
FROM big_orders
ORDER BY amount;

-- an admin caps the temporary files a session may write
SET temp_file_limit = '1MB';
SELECT order_id
FROM big_orders
ORDER BY amount, order_id;

The plan shows Sort Method: external merge Disk: 3288kB and Buffers: shared hit=640, temp read=1217 written=1302. Buffers are the pages a node touched: here the 640 table pages, then the sort's own temporary pages. The second query stops with temporary file size exceeds "temp_file_limit" (1024kB).

When the guess is wrong

Back to the report. Nora opens its plan and points at two numbers on one line: rows=1 and actual rows=250000.

A plan is only as good as its row guesses. Compare rows= (the estimate) with actual rows=, node by node. A gap of 10 times or more, especially below a join, is where to look.

Here the planner expected 1 row from order_items. For one row a nested loop is perfect: one index lookup in orders. It met 250,000 rows, so it did 250,000 lookups.

There are three usual causes:

  • Stale statistics. This one: a bulk load doubled the table, and the statistics still described May.
  • Correlated columns. The planner multiplies shares as if columns were independent.
  • Functions on columns. They get a flat guess.

The June plan: built for 1 row

A plan tree: a nested loop estimated at 1 row that really produced 250,000; its outer index scan on order_items was estimated at 1 row and returned 250,000, so the inner index scan on orders ran 250,000 times.

Compare the two numbers on each red line: the planner expected 1 row and got 250,000. That gap is why the amber scan ran 250,000 times.

Correlated columns, before and after CREATE STATISTICS

-- 20,000 addresses: every Toronto row is in Canada
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT *
FROM addresses
WHERE city = 'Toronto'
  AND country = 'Canada';

CREATE STATISTICS addresses_city_country (dependencies)
  ON city, country FROM addresses;
ANALYZE addresses;

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT *
FROM addresses
WHERE city = 'Toronto'
  AND country = 'Canada';

The second cause, live. Before: rows=400, from 20,000 x 0.1 (Toronto) x 0.2 (Canada), against actual rows=2000.00. Every Toronto row is in Canada, so the two shares should not be multiplied. CREATE STATISTICS ... (dependencies) teaches the planner the link. After: rows=2000. Here the plan is a Seq Scan either way; under a join, a 5x error decides the algorithm.

Rows for Toronto and Canada

Bars compare the planner estimate of 400 rows when it assumes city and country are independent, 2,000 rows with dependency statistics, and the actual 2,000 rows.

Compare the red bar with the grey one: the planner was 5 times too low until it learned that the city decides the country.

The trap: EXPLAIN ANALYZE runs the statement. EXPLAIN ANALYZE DELETE ... deletes the rows, and an UPDATE really updates. To see the real plan of a change without keeping it, wrap it: BEGIN; EXPLAIN ANALYZE UPDATE ...; ROLLBACK;. And never judge a plan from a laptop with 1,000 rows: the planner picks different plans for different sizes.

Numbers to remember

WhatNumber or nameWhat it means
seqpagecost, randompagecost1.0 and 4.0On SSDs teams often lower randompagecost towards 1.1, which makes index scans look cheaper
cputuplecost, cpuoperatorcost0.01 and 0.0025The page term dominates small tables, the per-row terms dominate big ones
defaultstatisticstarget100Caps the most-common list and the histogram at 100 entries each. Big tables are sampled, so their statistics move a little with every ANALYZE
correlation in pgstatsNear 1 or -1 makes index scans cheaperHow closely the physical row order follows the value order
autovacuumanalyzescalefactor0.1Autovacuum analyzes on its own only after about 10% of a table changed. Run ANALYZE as the last step of a bulk load
geqothreshold12With fewer tables than this, the planner searches join orders almost exhaustively, so one bad estimate can pick a bad order
workmem, and for hash nodes4 MB, and 8 MBPer sort or hash node, in every session
Signs of a spillexternal merge Disk:, Batches above 1, Disk Usage, Storage: Disk, temp read=... written=...On a Sort, a Hash, a HashAggregate, a WindowAgg, and in the buffers line
tempfilelimitNo limit by defaultCaps the temporary files one session may write
Buffers in EXPLAIN ANALYZEOn by default since Postgres 18The 8 kB pages each node touched
Finding slow plansautoexplain, pgstatstatementsThe first logs the plan of every statement slower than a threshold. The second ranks queries by total time

What changed at SwiftKart

You run ANALYZE order_items. The planner now expects 250,000 rows, swaps the nested loop for a hash join, and the report is back to seconds. Then you make ANALYZE the last step of the bulk load, so the map is redrawn whenever the table changes.

That closes Module 2. You can keep a join from changing the row count, group and rank without surprises, keep the latest row, look across rows, rerun a load safely, and read the plan when something is slow.

So far the data was already in tables. The next data arrives as files: CSV, JSON, text with odd characters. Module 3 picks up there, with Python and Lesson 3.1, files and formats.

In one line

The planner estimates rows from statistics, prices each plan in page reads (sequential 1.0, random 4.0) and keeps the cheapest; when a query turns slow, compare estimated with actual rows and look for spills past work_mem.

Interview corner

A query went from 4 seconds to 40 minutes with no code change. How do you find out why?

Get the real plan with EXPLAIN (ANALYZE, BUFFERS), on a copy or inside a transaction I roll back if it writes. Walk it node by node and look for the first place where estimated and actual rows differ by 10x or more, usually under a join, and for nodes with big buffer or temp counts. Typical causes: statistics that predate a bulk load, so a nested loop meets 250,000 rows instead of 1; a spill past work_mem; an index that stopped being usable because someone wrapped the column in a function. Fix the cause (ANALYZE, extended statistics, rewrite the predicate, session work_mem), rerun the plan to prove it, and add the ANALYZE to the load.

Why might Postgres not use an index on a filtered column?

The filter matches too large a share of rows, so a sequential scan of the pages in order is cheaper than random index reads; the column is wrapped in a function or cast, so the index cannot be searched; the index columns are in the wrong order for the filter; or the estimate is wrong because statistics are stale. EXPLAIN shows which: compare the estimated rows with reality, and check that the condition appears as an Index Cond.

What is work_mem, and why not set it to 1 GB?

It is the memory each sort or hash node may use before spilling to temporary files, 4 MB by default, times hash_mem_multiplier (2.0) for hash nodes. It is per node and per session, not per server: a plan with three such nodes and 100 sessions could ask for 300 GB at 1 GB each. So I keep the default modest and raise it with SET or ALTER ROLE for the batch jobs whose plans show external merge or Batches above 1.

An index-only scan still reads the table. Why?

Index entries carry no visibility information, so for each match Postgres checks the visibility-map bit of its table page; if the bit is clear the page is fetched to check the row version, which shows as Heap Fetches. The bits are set by VACUUM and cleared by any change, so a frequently loaded table needs VACUUM, or a tuned autovacuum, after loads for index-only scans to pay off.