Table Statistics, Cardinality Estimation & ANALYZE / VACUUM
Keep planner stats fresh and reclaim dead tuples with ANALYZE and VACUUM.
In plain words
The database keeps notes about what's in each column so it can plan queries. ANALYZE updates the notes; VACUUM clears out old leftover rows.
Think of it like…
A delivery company planning routes from last year's census: if a new housing estate appeared, the plan sends one van where ten are needed. ANALYZE is taking a fresh census. VACUUM is clearing abandoned houses so the streets are usable.
Where you’ve seen it
After a nightly import adds 5 million rows to an empty staging table, a join on it runs as a nested loop because the statistics still say "0 rows". Adding ANALYZE staging_orders; at the end of the import makes the planner pick a hash join, and the job goes from 40 minutes to 2.
Words you’ll hear
- Cardinality estimate
- How many rows the planner expects a step to produce.
- pg_stats
- View showing per-column statistics: n_distinct, most_common_vals, histogram_bounds, null_frac.
- Statistics target
- How detailed the statistics are (default 100); raise it for skewed columns.
- Extended statistics
- CREATE STATISTICS for correlated columns, such as city and postcode (PostgreSQL 10+).
Visual diagram
Theory & example queries
How estimates are made
ANALYZE reads a random sample (300 × the statistics target rows, so 30,000 by default) and records, per column, the number of distinct values, the most common values with their frequencies, a histogram of the remaining values, and the share of NULLs. For WHERE status = 'pending', the planner looks up 'pending' in the common values list; for a range, it reads the histogram.
For conditions on several columns, PostgreSQL assumes they're independent and multiplies their selectivities. That underestimates rows when columns are correlated (city = 'Pune' AND state = 'Maharashtra'). CREATE STATISTICS … (dependencies) ON city, state FROM addresses teaches the planner about the correlation.
SELECT n_distinct, most_common_vals, most_common_freqs, null_fracFROM pg_statsWHERE tablename = 'orders' AND attname = 'status';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Sample statistics for orders.status1 sample row
| n_distinct | most_common_vals | most_common_freqs | null_frac |
|---|---|---|---|
| 4 | {paid,shipped,cancelled,refunded} | {0.42,0.31,0.18,0.09} | 0.01 |
Note: PostgreSQL pg_stats arrays are shown as strings because the output schema stores scalar cells; all values are illustrative estimates from statistics.
Key takeaway: Estimates come from sampled statistics, and correlated columns fool them.
Keeping statistics fresh
Autovacuum also runs ANALYZE automatically once enough rows change (by default 50 rows plus 10% of the table). That's fine for steady traffic, but after a bulk load, a large delete or creating a new table, run ANALYZE table_name yourself so the next queries are planned with current numbers. ANALYZE is quick and doesn't block reads or writes.
For skewed columns where the default 100 common values isn't enough (thousands of tenants with very different sizes), raise the target for that column: ALTER TABLE orders ALTER COLUMN tenant_id SET STATISTICS 1000; ANALYZE orders;. VACUUM ANALYZE does both jobs in one pass. In MySQL, the equivalents are ANALYZE TABLE and, since 8.0, column histograms.
COPY staging_ordersFROM '/data/orders.csv'WITH (FORMAT csv);ANALYZE staging_orders;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative load and statistics status
Note: Assumes the CSV has 2,500 valid rows; COPY counts and command tags depend on the file and client dialect.
Key takeaway: ANALYZE after big changes; raise statistics targets on skewed columns.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Spot a bad estimate
Compare estimated and actual rows on each node. A 10× or bigger gap is the signal.
rows = 10 vs actual rows = 250000When to use it & trade-offs
What it is
The query planner chooses plans from statistics about each column: how many distinct values, the most common values, a histogram of the rest, and the fraction of NULLs. ANALYZE samples the table to refresh these statistics. VACUUM is a different job: it cleans up dead row versions. Autovacuum runs both automatically, but not always at the right moment.
Why it matters: Bad plans usually start with bad estimates, and bad estimates usually come from stale or too-coarse statistics. The classic production story is "the query was fast until we bulk-loaded data", fixed by a single ANALYZE. Senior database interviews ask how estimates are made and how to correct them.
When to reach for it
- After bulk loads and large deletes
- Diagnosing plans with wildly wrong row estimates
- Tuning queries on skewed or correlated columns
When to avoid or be careful
- Relying on autovacuum's timing right after loading a new table
- Forcing join types instead of fixing the estimates
- Confusing VACUUM with ANALYZE
ANALYZE vs VACUUM vs VACUUM ANALYZE
Strengths: Fast, samples rows, doesn't block reads or writes.
Watch out: Does nothing about dead rows.
Strengths: Prevents bloat; runs online.
Watch out: Doesn't refresh statistics.
Strengths: Cleans up and refreshes statistics in one pass.
Watch out: Takes longer than ANALYZE alone.
Interview signals & numbers to know
When this topic comes up
- “The query was fast yesterday and slow after the import”
- Estimated vs actual rows far apart
- “How does the planner estimate row counts?”
- Skewed data (a few huge tenants)
- Correlated filters
Benchmarks & rules of thumb
- 100
- default statistics target
- 30,000
- rows sampled at the default target
- 50 + 10%
- rows changed before auto-analyze runs
Common mistakes & follow-ups
Common interview mistakes
- Loading millions of rows and querying immediately with statistics that still say the table is empty.
- Running VACUUM to fix bad estimates, which doesn't update statistics.
- Rewriting a query repeatedly when one ANALYZE would have fixed the plan.
Likely interviewer follow-ups
- How does PostgreSQL estimate the number of rows a WHERE clause returns?
- What's the difference between VACUUM and ANALYZE?
- How would you fix a bad estimate on two correlated columns?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Table Statistics, Cardinality Estimation & ANALYZE / VACUUM with hands-on SQL practice and interview Q&A.