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

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.

  1. What does the planner consult instead of the table itself?
  2. You bulk-loaded five million rows and queries got weird. First move?
Show the answers
  1. pg_stats — sampled histograms, common values and distinct counts per column, maintained by ANALYZE.
  2. ANALYZE the 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.

Search the guide