Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 16 / Topic 5 of 5

Bad estimates and CREATE STATISTICS

Everything above leaned on one assumption: the row estimates are roughly right. The classic way they break is correlated columns. Build 100,000 addresses where city determines pincode, and ask for a consistent pair:

CREATE TABLE addresses AS
SELECT g AS id,
       CASE WHEN g % 4 = 0 THEN 'Pune'    WHEN g % 4 = 1 THEN 'Delhi'
            WHEN g % 4 = 2 THEN 'Chennai' ELSE 'Mumbai' END AS city,
       CASE WHEN g % 4 = 0 THEN '411001'  WHEN g % 4 = 1 THEN '110001'
            WHEN g % 4 = 2 THEN '600001'  ELSE '400001' END AS pin
FROM generate_series(1, 100000) AS g;
ANALYZE addresses;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM addresses WHERE city = 'Pune' AND pin = '411001';  -- output varies per run
 Seq Scan on addresses  (cost=0.00..2140.00 rows=6287 width=17) (actual rows=25000 loops=1)
   Filter: ((city = 'Pune'::text) AND (pin = '411001'::text))
   Rows Removed by Filter: 75000
(3 rows)

Estimate 6,287, reality 25,000 — off by 4×. The planner multiplied the two conditions' selectivities (¼ × ¼) as if independent; in truth every Pune row is a 411001 row. A 4× error here is survivable; feed it into a join and it compounds into nested loops over 25,000 rows that were "supposed to be" 6,000. The fix is telling Postgres the columns move together:

CREATE STATISTICS addr_city_pin (dependencies) ON city, pin FROM addresses;
ANALYZE addresses;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM addresses WHERE city = 'Pune' AND pin = '411001';  -- output varies per run
 Seq Scan on addresses  (cost=0.00..2140.00 rows=24710 width=17) (actual rows=25000 loops=1)
   Filter: ((city = 'Pune'::text) AND (pin = '411001'::text))
   Rows Removed by Filter: 75000
(3 rows)

Estimate 24,710 — within 1%. The reading skill this section installs: on every suspicious plan, compare rows= with actual rows= node by node; a big gap is the root cause, and the fixes are always some flavour of better statistics — ANALYZE for stale, CREATE STATISTICS for correlated, raised statistics targets for skewed.

🧪 Quick quiz — answer from memory, then check.

  1. Why did the planner estimate 6,287 for Pune + 411001?
  2. Estimated 1 row, actual 50,000 — first thing to check?
Show the answers
  1. It multiplied the two filters' selectivities as if independent — the columns are actually locked together.
  2. The statistics: stale (ANALYZE) or blind to correlation (CREATE STATISTICS).

Done here? The practice set for Part 16 — 4 exercises with solutions — is on the part page.

Search the guide