Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

4 · Estimates and joins

In one sentence: the planner builds every node for the number of rows it expects, an estimate taken from statistics that ANALYZE collects from a sample; when the estimate is far from the real count, the join method and the memory it plans for are made for a different query.

The problem

In Practical 1’s Break it, the lower(status) scan expected rows=4167 per process and returned 19,868.67. With parallel workers off, the same condition (SELECT * FROM orders WHERE lower(status) = 'pending'):

 Seq Scan on orders  (cost=0.00..46667.00 rows=10000 width=37) (actual time=0.996..2079.001 rows=59606.00 loops=1)

10,000 expected, 59,606 found. Where does 10,000 come from? And why care, when the rows returned are right anyway? Every node above the scan is chosen for the rows the planner expects: a join chosen for 10 rows can be wrong for 50,000.

Where estimates come from

ANALYZE reads a random sample of a table, 30,000 rows here (300 × default_statistics_target, which is 100), and stores a summary of each column in pg_stats (Statistics Used by the Planner). Autovacuum reruns it when enough rows change.

SELECT n_distinct, most_common_vals, most_common_freqs FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';
          4 | {delivered,shipped,pending,cancelled} | {0.9009333,0.0596,0.029833334,0.009633333}

For status = 'pending', the planner multiplies the value’s share by the table’s row count (reltuples in pg_class, 2,000,000): 0.029833334 × 2,000,000 = 59,667, the rows=59667 that EXPLAIN shows. The real count is 59,606.

It’s a sample, so every ANALYZE gives slightly different estimates. The next one on the same data gave 56,933, and yours will differ again.

When there is nothing to look up

The statistics describe status, not lower(status). For = on an expression it has no statistics for, the planner assumes 200 distinct values (DEFAULT_NUM_DISTINCT in selfuncs.h), so 1/200 = 0.5% of the rows: 2,000,000 × 0.005 = 10,000. Practical 1’s rows=4167 is the same guess per process: with two workers, the planner divides by 2.4, because the leader process counts for 0.4 of a worker.

You can give it statistics on the expression:

CREATE STATISTICS orders_lower_status_stats ON (lower(status)) FROM orders;
ANALYZE orders;
 Seq Scan on orders  (cost=0.00..46667.00 rows=56933 width=37)

Right after CREATE STATISTICS it was still 10,000: CREATE STATISTICS declares; ANALYZE collects.

For AND, the planner multiplies the two shares, as if unrelated: wrong when a city tells you the country. Practical 2 measures it.

Three ways to join

JoinHow it worksFast when
Nested Loopfor each row of the outer side, looks up its matches on the inner side, usually through an indexthe outer side has few rows
Hash Joinreads one side into a hash table in memory, then streams the other through itmany rows, in no useful order
Merge Joinreads both sides sorted on the join key and walks them togetherboth come sorted already, from an index

Two of lesson 2’s queries, forced into each method in turn (SET enable_nestloop = off; and so on, parallel workers off, the second and third of three runs; the planner’s own choice in bold):

QueryNested LoopHash JoinMerge Join
10 customers with their orders (88 rows)1.6–1.7 ms750–773 ms107–108 ms
October’s revenue (56,987 orders)690–704 ms252–263 ms327–338 ms

For 10 customers, the Hash Join reads all 2,000,000 orders; the Nested Loop makes 10 index lookups. For October, the Nested Loop looks up a customer 49,564 times; the Hash Join reads the 200,000 customers once.

The planner picks by the estimated rows. Here both were close; when one is far off, it picks the method for the wrong row count. Practical 2 has you find one.

Memory: work_mem

Each Sort and each hash table gets work_mem of memory, 4 MB by default; hash tables get twice that (hash_mem_multiplier = 2) (Resource Consumption). What doesn’t fit goes to temporary files on disk. Sorting this year’s orders by total:

 Sort  (cost=114655.42..116281.60 rows=650472 width=12) (actual time=746.517..956.474 rows=656205.00 loops=1)
   Sort Key: total_cents DESC
   Sort Method: external merge  Disk: 14184kB
   Buffers: shared hit=8664, temp read=1773 written=1782

external merge Disk: 14184kB is a sort that spilled; temp counts its temporary file pages. With SET work_mem = '64MB';: quicksort Memory: 45083kB, 921–929 ms instead of 1,031–1,047 ms. A spill cost little.

The planner knows work_mem too: it prices a hash that won’t fit with its spill to disk, and may then prefer another plan. That choice can cost far more than a spill: Practical 2 has one.

Try it on your computer

Practical 2 · When the planner guesses wrong: a backlog the statistics haven’t seen, two columns that go together, and a report that needs more memory.

Go deeper: Memoize, a Nested Loop that remembers

In the forced Nested Loop for October, a Memoize node sat between the join and its customer lookup:

               ->  Memoize  (cost=0.43..0.61 rows=1 width=11) (actual time=0.010..0.010 rows=1.00 loops=56987)
                     Cache Key: o.customer_id
                     Estimates: capacity=50174 distinct keys=50174 lookups=58044 hit percent=13.56%
                     Hits: 7423  Misses: 49564  Evictions: 0  Overflows: 0  Memory Usage: 5809kB

It keeps the result of each lookup by customer_id; an order whose customer was already looked up is answered from memory. 56,987 orders came from 49,564 customers, so 7,423 lookups were saved. The Estimates: line is the planner’s guess from n_distinct (hit percent=13.56%); Hits: is what happened (13.0%). Memoize is chosen only when the planner expects repeats: one more decision taken from an estimate.

Common misunderstandings

  • “ANALYZE runs the query.” ANALYZE orders collects statistics; EXPLAIN ANALYZE runs a query.
  • “More work_mem for everyone fixes spills.” Every Sort and hash node of every query on every connection may use that much: 100 connections × 3 nodes × 64 MB is 19,200 MB, and hash nodes up to twice that. Raise it for the query that needs it.

Check yourself

1. A Nested Loop's outer side shows rows=1 estimated and rows=40000.00 actual; the inner Index Scan has loops=40000. What happened, and what do you try first? A Nested Loop chosen for one row ran 40,000 lookups. Find why the estimate is wrong: statistics older than the data (run ANALYZE), an expression with no statistics, or correlated conditions.
2. A plan shows Filter: (date_trunc('day', created_at) = '2026-10-01') with rows=10000 on a 2,000,000-row table. Where does 10,000 come from? The fixed 0.5% guess for an expression without statistics: 2,000,000 × 0.005. Fix it with CREATE STATISTICS ... ON (date_trunc('day', created_at)) and ANALYZE, or rewrite the condition on the column (created_at >= '2026-10-01' AND created_at < '2026-10-02').
3. A nightly report shows Sort Method: external merge Disk: 120000kB. Name two ways to fix it. Give that report's session more memory (SET work_mem = '256MB'; before it runs), or avoid the sort: an index that already returns the rows in that order, or fewer rows to sort.

Next: Practical 2 · When the planner guesses wrong, then lesson 5 · In production.