WORKINGCHAPTER 14

The query planner: statistics, cost, join algorithms

How Postgres guesses row counts, prices plans and picks a join, and the three ways the guess goes wrong

55 MINDATABASESUPDATED 2026-11-02
PREDICT

The orders table has 2 million rows and was analysed yesterday. Overnight, 1 million legacy orders dated 2021 are inserted, and autovacuum is behind. You run EXPLAIN on WHERE created_at < '2022-01-01'. How many rows does the planner estimate?

The planner’s job is to turn a declarative question into a program. SQL says which rows you want; it does not say which index to use, which table to read first or how to match rows from two tables. For a five-table join there are thousands of correct programs, and the fastest and slowest of them can differ by a factor of a million. The planner picks one by estimating how many rows each step produces and pricing each candidate with a cost model. Both halves can be wrong, and the first half is wrong far more often.

This chapter walks the pipeline, then the statistics, then the cost model, then the joins, and then the three ways estimates fail in production. The two simulations make the central idea concrete: a plan is only as good as the row count it was priced for.

From SQL text to a running plan

A query passes through four stages in Postgres.

  1. Parse. The parser turns text into a parse tree and rejects syntax errors. It knows nothing about tables yet.
  2. Analyse and rewrite. The analyser resolves names against the catalog: which orders, which column, which operator for = on these types. The rewriter then applies rules, the main one being view expansion: a query against a view becomes a query against the view’s underlying tables.
  3. Plan. The planner (Postgres calls it the optimizer too) generates candidate plans, estimates the rows and cost of each, and keeps the cheapest. This is the only stage that looks at statistics.
  4. Execute. The executor runs the plan tree. Each node pulls rows from its children, one at a time, until the root has produced every row.

Planning is fast, usually well under a millisecond, and it happens every time you run an unprepared statement. Prepared statements change that, which matters later.

The plan is a tree of nodes. Leaves read tables: Seq Scan, Index Scan, Index Only Scan, Bitmap Heap Scan. Inner nodes combine and reshape rows: Nested Loop, Hash Join, Merge Join, Sort, HashAggregate, Limit. EXPLAIN prints that tree with an estimate on every node; EXPLAIN ANALYZE runs it and prints the actual numbers next to the estimates. Learning to read the two side by side is most of the skill.

What the planner knows: statistics

The planner never counts rows while planning. It reads numbers that ANALYZE collected earlier and stored in the catalog.

Table size lives in pg_class: reltuples (estimated row count) and relpages (pages on disk). At plan time Postgres checks the table’s current size in pages and scales reltuples by it, so a table that has doubled in pages is assumed to have doubled in rows. That scaling keeps the row count roughly right after a load. It does nothing for the distribution of values, which is the trap in the Predict above.

Per-column statistics live in pg_statistic, which only superusers can read. Read them through the pg_stats view:

column what it holds what the planner uses it for
null_frac fraction of rows where the column is NULL IS NULL, and discounting NULLs from everything else
n_distinct distinct values; positive is a count, negative is a fraction of rows (-1 means unique) equality on values not in the MCV list, GROUP BY sizes, join sizes
most_common_vals, most_common_freqs the most frequent values and the fraction of rows each takes equality on a common value: the answer is read straight off the list
histogram_bounds values that split the remaining rows into buckets of equal population ranges: <, >, BETWEEN
correlation from -1 to +1, how closely physical row order follows the column’s sort order pricing an index scan: near ±1 means the heap reads are nearly sequential

ANALYZE builds these from a random sample, not the whole table. The sample is 300 rows times the statistics target, so 30,000 rows at the default. The MCV list and the histogram each hold up to default_statistics_target entries, which defaults to 100 and can go to 10000. You can raise it for one column that matters:

ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 1000;
ANALYZE orders;

A bigger target means a bigger sample, more MCVs and finer histogram buckets, so better estimates on skewed columns. It costs ANALYZE time and planning time, since every plan reads these arrays. Raise it per column where you have seen a misestimate, not globally.

In the shop, country is skewed: DE, NG, US, JP and GB take 70% of customers, so they sit in the MCV list with frequencies around 0.14 each and country = 'NG' is estimated almost exactly. orders.status has four values and 85% are shipped; the whole distribution fits in the MCV list. orders.created_at is nearly unique, so it has no useful MCVs, n_distinct = -1, and a histogram over three years of dates.

Who runs ANALYZE. Autovacuum analyses a table when the rows changed since the last analyse exceed autovacuum_analyze_threshold (50) plus autovacuum_analyze_scale_factor (0.1) times the table’s rows. For a 2-million-row table that is about 200,000 changes. It checks this on a cycle (autovacuum_naptime, one minute by default) and then has to get round to the table, so after a bulk load there is a window of seconds to minutes, or much longer if autovacuum is busy or disabled for the table, in which every query on that table is planned with the old numbers. pg_stat_user_tables.last_analyze and last_autoanalyze tell you when the statistics were last refreshed. Any job that bulk-loads and then queries should run ANALYZE itself between the two.

The cost model

With row estimates in hand, the planner prices each plan in abstract units. Five constants do most of the work:

setting default meaning
seq_page_cost 1.0 reading one page as part of a sequential scan
random_page_cost 4.0 reading one page out of order, as an index scan does on the heap
cpu_tuple_cost 0.01 processing one row
cpu_index_tuple_cost 0.005 processing one index entry
cpu_operator_cost 0.0025 evaluating one operator or function in a filter

A seq scan of the shop’s orders table, about 18,000 pages and 2 million rows, costs roughly 18,000 × 1.0 for pages plus 2,000,000 × 0.01 for rows plus 2,000,000 × 0.0025 for the filter: about 43,000. An index scan that fetches 60,000 rows scattered across the heap pays random_page_cost for most heap pages it touches, discounted by correlation and by effective_cache_size (default 4GB), which is the planner’s guess at how much of the data is cached by Postgres and the OS together. Nothing is reserved by that setting; it only changes the prices.

Why 4 is wrong on SSDs. The 4.0 default dates from spinning disks, where a random read costs a seek of several milliseconds and a sequential read streams at over 100 MB/s. The Postgres docs explain that real random access on such disks is far more than four times the cost of sequential access, and that 4.0 already assumes most random reads hit cache. On an NVMe SSD a random 8 KB read takes about 100 microseconds and the gap to sequential is small; if the working set is in RAM the gap is near zero. With 4.0 on that hardware the planner overprices every index scan and chooses seq scans and bitmap scans it should not. Many teams on SSDs set random_page_cost between 1.1 and 2. Do not copy a number; change it in a session, compare EXPLAIN ANALYZE times on your real queries, and then set it in postgresql.conf or per tablespace with ALTER TABLESPACE ... SET (random_page_cost = 1.1). The lab flips a plan with it.

The cost model is crude and it is not where most bad plans come from. Leis et al. measured this directly on Postgres with a realistic benchmark: errors in the cost model changed runtimes by tens of percent, while errors in row estimates changed them by orders of magnitude. Fix estimates first.

Selectivity: turning a WHERE clause into a number

Selectivity is the fraction of rows a predicate keeps. Rows out of a scan are rows in times selectivity. The planner computes it per predicate from the statistics:

  • status = 'placed': placed is in the MCV list, so selectivity is its frequency, about 0.07.
  • customer_id = 4242: not an MCV. Selectivity is the rows not covered by MCVs divided by the remaining distinct values.
  • created_at < '2025-01-01': find the histogram bucket the value falls in, count the full buckets below it and interpolate within the bucket.
  • Two predicates joined by AND: multiply the selectivities. This is the independence assumption, and it is the most common source of error in every planner ever built.

The simulation below shows why the estimate matters even for one table. A rule-based planner uses an index whenever one matches; a cost-based planner estimates the matching rows from statistics and compares an index seek, which pays roughly one heap page per matching row, against a seq scan, which pays every page once. Run the RULE scenario and watch the index scan read more pages than the whole table. Then run the cost-based fix.

▶ SIMULATION
TABLE t
rows 2000 · 10 per page · heap pages 200
a = 1 in 612 rows (30.6%)
stats: none yet
INDEXES · 100 entries per leaf
(none)
PLANNER
mode: rule-based
—
✓ no query reads more pages than a seq scan (200)
SCHEDULE
01[PLANNER]planner: rule-based, use any index whose leading column matches
02[DBA]CREATE INDEX ON t (a, b)
03[DBA]ANALYZE t (count matches per value)
04[APP]SELECT * FROM t WHERE a = 1
05[APP]SELECT * FROM t WHERE b = 7
Start of rule: index if one matches scenario. 5 steps.
-- 30% of rows have a = 1. A rule-based planner sees an index and uses it:
SELECT * FROM t WHERE a = 1;
--  Index Scan using t_a_b_idx   -> ~600 random heap page reads
-- the table is only 200 pages long

-- and (a, b) cannot seek on b alone (without skip scan):
SELECT * FROM t WHERE b = 7;   -- Seq Scan, the index is sorted by a first

What it proves: there is a crossover selectivity, and on the simulated 10-rows-per-page table it sits near one row in ten. The exact point depends on rows per page and on random_page_cost, which is why changing that setting moves plans. Find the crossover yourself:

TUNE IT NOT YET

The rule planner always uses the index for a = 1. Drag ROWS WITH a = 1 to the largest value where the index scan still reads no more pages than the 200-page seq scan. That is the crossover.

GOAL: index scan ≤ seq scan here, and > seq scan one percent higher

Where selectivity goes wrong. Three patterns cause most production misestimates.

Correlated predicates. country = 'NG' AND currency = 'NGN' has selectivity 0.14 × 0.14 ≈ 0.02 under independence. In reality every Nigerian customer pays in naira, so it is 0.14, seven times more. The direction of the error matters: underestimates make the planner choose nested loops and index scans sized for a few rows, which is the expensive mistake. Across a five-way join the errors multiply, and Leis et al. found that estimates for joins of several tables were routinely off by factors of 1,000 or more in every system they tested.

The fix is extended statistics. CREATE STATISTICS registers a group of columns and ANALYZE collects joint information about them:

CREATE STATISTICS customers_country_currency (dependencies, mcv)
  ON country, currency FROM customers;
ANALYZE customers;

dependencies records how strongly one column determines another (the docs’ example shows zip => city with degree 1.0). It applies to equality and IN on constants. mcv stores the most common combinations with their real joint frequencies and covers more clause types. ndistinct records distinct counts for column groups, which fixes GROUP BY a, b estimates. You can inspect the result in pg_stats_ext. Create them for column pairs you filter on together and have seen misestimated: country and currency, city and postcode, product category and brand. Two columns from different tables, such as customers.country and products.category, cannot share an extended statistics object; a correlation across a join stays invisible to the planner.

Functions and expressions on columns. WHERE lower(email) = 'ada@example.com' hides the column from the statistics. The planner falls back to defaults: 0.005 for equality and one third for an inequality. Either rewrite the predicate so the bare column is compared, or create an expression index on lower(email) (ANALYZE then gathers statistics for the expression) or a single-expression CREATE STATISTICS ON (lower(email)) FROM customers.

Parameters. A prepared statement with $1 cannot use the MCV list for a value it does not know. Postgres plans the first five executions with the real values (custom plans), then compares their average cost with a generic plan and switches to the generic one if it is not more expensive. If $1 is sometimes 'shipped' (85% of rows) and sometimes 'cancelled' (3%), one generic plan serves both badly. plan_cache_mode = force_custom_plan for that connection or statement trades planning time for correct plans. ORMs and drivers that prepare statements by default hit this without anyone noticing.

The three join algorithms

Every join of two inputs runs as one of three algorithms. They return the same rows; their costs scale differently.

how it works cost shape wins when
Nested loop for each outer row, look up matching inner rows, usually with an index outer rows × cost of one probe the outer side is small (tens to a few thousand rows) and the inner side has an index on the join key; also the only choice for non-equality joins
Hash join read the smaller input into a hash table on the join key, then stream the larger input and probe it one pass over each input, plus building the table large inputs, equality condition, and the build side fits in work_mem × hash_mem_multiplier (4 MB × 2.0 by default); otherwise it spills into batches on disk
Merge join sort both inputs on the join key (or read them already sorted from an index) and walk them together sorting cost, then one pass each both inputs arrive sorted, or the result must be sorted anyway, or inputs are too large to hash

A nested loop is cheap to start, since it returns its first row after one probe, which is why plans under LIMIT love it. A hash join pays its whole build cost before returning anything. That is the trade the first simulation turns on. It prices a nested loop and a hash join for a join of orders to customers, using the row estimate from the last ANALYZE, and then runs the chosen plan on the real rows. Play FRESH STATS, then STALE STATS, then the fix.

▶ SIMULATION
PLANNER (estimates)
stats: none yet
estimated rows: —
not planned
TABLE orders (actual)
rows: 1,000,000
pending: 100
changed since ANALYZE: 0
customers: 10,000
EXECUTOR (actual)
actual rows: —
not run
last—
✓ planner row estimate within 10x of the actual rows✓ chosen plan costs at most 2x the best plan
SCHEDULE
01[DBA]ANALYZE orders (gather statistics)
02[PLANNER]plan the join from statistics
03[EXECUTOR]run the chosen plan on the real rows
Start of fresh stats scenario. 3 steps.
How the planner priced this join
================================

est_rows = (pending / rows at last ANALYZE) * rows now

nested loop  = est_rows                 fetch matching orders
             + est_rows * 8             one index probe into customers each
hash join    = est_rows                 fetch matching orders
             + 10,000 * 2               build a hash table over customers once
             + est_rows                 probe it once per order

Crossover: 9N = 2N + 20,000  ->  N ~ 2,857 rows.
Below it the nested loop wins; above it the hash join wins.

A bulk load of 999,900 pending orders changes the pending fraction from
0.01% to 50%. Scaling by table size cannot fix that: until ANALYZE runs,
the planner still believes 0.01% and estimates ~200 rows.

PostgreSQL: EXPLAIN ANALYZE prints rows=<estimate> next to actual rows=.
A gap of 10x or more is the first thing to look for in a slow plan.
Autovacuum runs ANALYZE after enough rows change, but not instantly;
run ANALYZE yourself after a bulk load.

Watch the estimate line in the stale scenario: the planner priced a nested loop for about 200 rows and the executor ran it for a million. The crossover in the sim’s cost model is about 2,900 rows; past it the hash join’s one-off build is cheaper than a probe per row. Real Postgres has the same shape with different constants, and you will see the same failure in the lab. Then place the bulk load yourself:

BREAK IT NOT YET

This nightly job analyzes, plans and runs the join on 100 pending orders, and the nested loop is the right call. Inject the backfill at a point where it makes the executor run a plan more than twice as expensive as the best one.

GOAL: the executed plan costs more than 2x the best plan

Join order. For more than two tables, the planner also chooses the order. Selinger’s System R optimizer, the design every relational planner descends from, introduced the method Postgres still uses: dynamic programming over subsets of tables. It finds the best plan for every pair, then every triple built from the best pairs, and so on, keeping a cheaper plan for each subset and also any plan that produces a useful sort order, which Selinger called an interesting order, because a sorted result can save a later sort or enable a merge join.

The number of subsets grows exponentially. Postgres bounds the work in two ways. join_collapse_limit and from_collapse_limit (both 8) stop the planner from reordering beyond 8 items at once; past that it keeps your written order for the rest. And at geqo_threshold (12) FROM items, it switches to GEQO, a genetic algorithm that searches a random sample of join orders instead of all of them. GEQO plans are non-deterministic unless you fix geqo_seed, so a 14-table reporting query can get a different plan on different days with no data change. If you see plan instability on a very wide join, that is the first suspect.

Reading EXPLAIN (ANALYZE, BUFFERS)

EXPLAIN shows the plan and estimates. EXPLAIN (ANALYZE, BUFFERS) runs the query and adds what happened. From Postgres 18, ANALYZE turns BUFFERS on by default; on 17, which the shop runs, you ask for it. A node looks like this:

->  Index Scan using customers_pkey on customers c  (cost=0.42..8.44 rows=1 width=11) (actual time=0.002..0.002 rows=1 loops=1000000)
      Index Cond: (id = o.customer_id)
      Buffers: shared hit=4000000
  • cost=0.42..8.44 is startup cost then total cost, in the units above, for one execution.
  • rows=1 in the first parentheses is the estimate. rows=1 in the second is the actual count per loop. Multiply by loops for the total: this node ran a million times and returned a million rows.
  • Buffers: shared hit counts pages found in Postgres’s buffer cache; read counts pages fetched from the OS or disk. Buffer counts include the node’s children. Four million page hits for a lookup that should be one hash table is the smell of a bad nested loop.

The method is the same every time. Start at the leaves, compare estimated and actual rows, and find the lowest node where they diverge by 10x or more. Everything above it was planned for the wrong number. Then ask which statistic fed that estimate: stale (ANALYZE), correlated columns (CREATE STATISTICS), a function hiding a column (rewrite or expression statistics), or a parameter (custom plans). Do not reach for enable_nestloop = off or planner hints first; they fix today’s plan and leave the wrong estimate in place for the next query.

LAB Mislead the planner, then fix it three ways ~40 MIN
YOU NEEDDocker with the labs/databases stack (Postgres 17, the shop loaded at scale=1; scale=0.1 works with smaller numbers)about 1 GB of free disk for the extra rowsa terminal in labs/databases

You will plan a report on stale statistics, fix it with ANALYZE, fix a correlated-column misestimate with CREATE STATISTICS, and flip a plan with random_page_cost. Start the shop and load it as labs/databases/shop/README.md describes, then work from labs/databases. Every step pipes SQL into psql in the db container.

1. Look at what the planner knows.

docker compose exec -T db psql -U atlas shop <<'SQL'
ANALYZE orders;
SELECT relname, reltuples::bigint, relpages FROM pg_class WHERE relname = 'orders';
SELECT attname, n_distinct, most_common_vals, most_common_freqs, correlation
FROM pg_stats WHERE tablename = 'orders' AND attname IN ('status', 'created_at');
SELECT (histogram_bounds::text::timestamptz[])[1] AS oldest_bucket_starts
FROM pg_stats WHERE tablename = 'orders' AND attname = 'created_at';
SQL
reltuples about 2,000,000 over roughly 18,400 pages (200,000 over 1,840 at scale 0.1). status has n_distinct = 4 and an MCV list with shipped near 0.85. created_at has n_distinct = -1 (unique), no MCVs, and a histogram whose first bound is on 2023-11-01, the first day load.sql generates. Nothing in these statistics describes a date before that. If your D1 index set has an index that leads with orders.created_at, the scan on orders in step 2 is an index scan rather than a sequential scan; the misestimate and the nested loop above it are the same.

2. Import legacy orders and do not analyse. Turn autovacuum off for this table so it cannot rescue you, insert a million orders from 2021, and explain a report over them:

docker compose exec -T db psql -U atlas shop <<'SQL'
ALTER TABLE orders SET (autovacuum_enabled = off);
INSERT INTO orders (customer_id, status, total_cents, created_at, shipped_at)
SELECT 1 + (random() * (SELECT max(id) - 1 FROM customers))::int, 'shipped', 500 + (random() * 99500)::int, ts, ts + interval '3 days'
FROM (SELECT timestamptz '2021-01-01' + random() * interval '365 days' AS ts
      FROM generate_series(1, 1000000)) g;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.country, count(*), sum(o.total_cents)
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at < '2022-01-01'
GROUP BY c.country ORDER BY 2 DESC;
SQL
The scan on orders estimates a few hundred rows or fewer (per parallel worker, if it is parallel) and returns about a million in total (rows=333333 loops=3 across three processes). Above it sits a Nested Loop whose inner side is Index Scan using customers_pkey with loops=1000000 and about Buffers: shared hit=4000000. The sort and aggregate above are sized for a few hundred rows, so the sort may spill to disk (Sort Method: external merge). On a laptop this takes 0.5 to 2 seconds at scale 1. Every node above the scan was priced for the wrong number.

3. Fix it with ANALYZE.

docker compose exec -T db psql -U atlas shop <<'SQL'
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.country, count(*), sum(o.total_cents)
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at < '2022-01-01'
GROUP BY c.country ORDER BY 2 DESC;
SQL
The estimate on the orders scan is now in the hundreds of thousands per worker, close to the actual. The join is a Parallel Hash Join with a Parallel Seq Scan on customers as the build side, buffers drop from millions to tens of thousands, and the query runs in a few hundred milliseconds, two to three times faster. Same SQL, same indexes, one statement.

4. Correlated columns. In the shop, shipped_at is set only when an order is shipped, so status and shipped_at IS NULL are correlated. Check that, then compare the estimate with the truth before and after extended statistics:

docker compose exec -T db psql -U atlas shop <<'SQL'
SELECT status, count(*), count(shipped_at) AS with_shipped_at FROM orders GROUP BY status;
EXPLAIN ANALYZE SELECT count(*) FROM orders WHERE status = 'placed' AND shipped_at IS NULL;
CREATE STATISTICS orders_status_shipped (mcv) ON status, shipped_at FROM orders;
ANALYZE orders;
EXPLAIN ANALYZE SELECT count(*) FROM orders WHERE status = 'placed' AND shipped_at IS NULL;
SELECT statistics_name, attnames, most_common_vals, most_common_freqs
FROM pg_stats_ext WHERE statistics_name = 'orders_status_shipped';
SQL
The first query shows with_shipped_at is 0 for every status except shipped. Before CREATE STATISTICS the scan’s estimated rows are the placed fraction times the NULL fraction of shipped_at, about ten times lower than the actual count (in a parallel plan the rows= shown is per process; multiply by 2.4 for two workers and the leader), because the planner multiplied two probabilities that are not independent. After it, the estimate is within a few percent of actual. pg_stats_ext shows the combinations it learned, such as {placed,NULL} with its real frequency. In a join, an underestimate this size is enough to pick a nested loop where a hash join belongs.

5. Flip a plan with random_page_cost. Add an index on total_cents and explain a range query at the default and at an SSD-friendly value. Try several thresholds, because the flip happens at a different one on every machine:

docker compose exec -T db psql -U atlas shop <<'SQL'
CREATE INDEX orders_total_cents_idx ON orders (total_cents);
ANALYZE orders;
SHOW random_page_cost;
EXPLAIN SELECT * FROM orders WHERE total_cents > 99000 AND status = 'placed';
EXPLAIN SELECT * FROM orders WHERE total_cents > 97000 AND status = 'placed';
EXPLAIN SELECT * FROM orders WHERE total_cents > 90000 AND status = 'placed';
SET random_page_cost = 1.1;
EXPLAIN SELECT * FROM orders WHERE total_cents > 99000 AND status = 'placed';
EXPLAIN SELECT * FROM orders WHERE total_cents > 97000 AND status = 'placed';
EXPLAIN SELECT * FROM orders WHERE total_cents > 90000 AND status = 'placed';
SQL
At 4.0 the wider ranges use a Bitmap Heap Scan (or a seq scan): the planner thinks fetching rows in index order is too expensive, so it collects them in a bitmap and reads the heap in page order. At 1.1 the same queries become a plain Index Scan using orders_total_cents_idx with a lower total cost. Neither plan is wrong in general. Rerun the pair with EXPLAIN (ANALYZE, BUFFERS) and keep the setting that is faster on your disk; on a laptop SSD with a warm cache the two are often close, which is the point: 4.0 prices a gap that is not there.

6. Put the shop back. Other chapters use the same database.

The legacy orders have no items or payments, but a plain DELETE does not know that: the foreign keys from order_items and payments make it check both tables for each of the million rows, and with no index on their order_id that is a sequential scan each time, which runs for hours. Skip those checks for this one statement, the same way load.sql does (atlas is a superuser in the container):

docker compose exec -T db psql -U atlas shop <<'SQL'
SET session_replication_role = replica;
DELETE FROM orders WHERE created_at < '2022-01-01';
RESET session_replication_role;
DROP INDEX orders_total_cents_idx;
DROP STATISTICS orders_status_shipped;
ALTER TABLE orders RESET (autovacuum_enabled);
VACUUM ANALYZE orders;
SQL
DELETE 1000000 in about a second, then DROP INDEX, DROP STATISTICS, ALTER TABLE and VACUUM. The table holds its loaded rows again with fresh statistics; the heap keeps the extra pages as free space until the next reload.
Repeat step 2 with autovacuum left on, and in a second terminal run SELECT last_autoanalyze FROM pg_stat_user_tables WHERE relname = 'orders'; every few seconds while you rerun the EXPLAIN. For the first seconds to minute after the insert, the plan is the bad nested loop; once autoanalyze has run, it is the hash join, with nobody touching anything. That window is where real incidents live: a nightly job that loads and then immediately queries hits it every night, and it looks random because autovacuum’s timing is. The fix is an explicit ANALYZE in the job, not hoping the daemon is quick. Run step 6 afterwards.
DECIDE

After a release, a dashboard query that joins orders, order_items and products went from 200 ms to 25 s. EXPLAIN ANALYZE shows the scan on order_items estimating 40 rows and returning 300,000, feeding a nested loop. Statistics were refreshed an hour ago. The filter is WHERE p.category = $1 AND oi.created_at > now() - interval '7 days' and the app uses prepared statements. On-call wants it fast within the hour. What do you do first?

READING
  1. PAPER
    Access Path Selection in a Relational Database Management System Selinger, Astrahan, Chamberlin, Lorie, Price, 1979

    The paper that defined cost-based optimisation: selectivity factors, a cost formula of pages plus weighted CPU, and dynamic programming over join orders. Forty-five years on, the Postgres planner is recognisably this design. Read: SIGMOD 1979. Read sections 4 and 5 (cost of single-relation access paths, and join ordering with interesting orders); skim the System R background.

  2. PAPER
    How Good Are Query Optimizers, Really? Leis, Gubichev, Mirchev, Boncz, Kemper, Neumann, 2015

    Measures real optimizers, Postgres included, on the IMDB-based Join Order Benchmark. Shows estimates are off by orders of magnitude on multi-way joins, and that this matters far more than the cost model. The evidence behind this chapter's advice to fix estimates first. Read: PVLDB 9(3). Sections 3 and 4 (cardinality estimation errors and when they cause slow queries) and section 5 on the cost model; section 6 on plan enumeration is optional.

  3. DOC
    PostgreSQL documentation: Using EXPLAIN

    The canonical guide to reading plans: cost units, rows versus actual rows, loops, buffers, and the caveats about timing overhead. Read all of section 14.1.

  4. DOC
    PostgreSQL documentation: Statistics Used by the Planner

    What lives in pg_class and pg_statistic, how to raise the statistics target, and worked examples of each kind of extended statistics with the zip-code data set. Pair with the next item.

  5. DOC
    PostgreSQL documentation: Row Estimation Examples

    Walks the actual arithmetic the planner does for equality, ranges with histogram interpolation, and joins, on real catalog numbers. The fastest way to be able to predict an estimate by hand.

  6. DOC
    PostgreSQL documentation: Query Planning configuration

    Every cost constant, enable_* switch, join_collapse_limit, geqo setting and plan_cache_mode with its default and the docs' own advice on random_page_cost. Keep it open when tuning; skip the GEQO internals.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: LSM trees and the write-optimised world →