Part 15 / Topic 7 of 7
ANALYZE and statistics
The planner never looks at your actual rows while planning — it consults statistics: per-column histograms, most-common values, distinctness, collected by ANALYZE (autovacuum runs it too). See what it knows about our sensors:
ANALYZE readings;
SELECT attname, n_distinct,
array_length(most_common_vals::text::text[], 1) AS tracked_common_values
FROM pg_stats
WHERE tablename = 'readings' AND attname = 'sensor';
ANALYZE
attname | n_distinct | tracked_common_values
---------+------------+-----------------------
sensor | 50 | 50
(1 row)
50 distinct sensors, all 50 tracked in the most-common-values list — learned from a random sample, which is why stats are estimates (and why the list's internal order differs run to run). Everything Part 16 does — "the planner chose a sequential scan because it estimated 2,000 matches" — flows from this table. The two failure smells worth filing now: stats gone stale after a bulk load (run ANALYZE after big changes; autovacuum catches up eventually), and correlated columns the planner wrongly assumes independent (city and pincode) — CREATE STATISTICS exists for exactly that, and Part 16 shows it.
🧪 Quick quiz — answer from memory, then check.
- What does the planner consult instead of the table itself?
- You bulk-loaded five million rows and queries got weird. First move?
Show the answers
- pg_stats — sampled histograms, common values and distinct counts per column, maintained by ANALYZE.
ANALYZEthe table — the planner is working from pre-load statistics.
Done here? The practice set for Part 15 — 5 exercises with solutions — is on the part page.