Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 132/ 160
07. Indexing, Query Optimization & Performance Tuning

Table Statistics, Cardinality Estimation & ANALYZE / VACUUM

Keep planner stats fresh and reclaim dead tuples with ANALYZE and VACUUM.

IntermediateANALYZE · VACUUM3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Looking at a column's statisticsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  n_distinct,3  most_common_vals,4  most_common_freqs,5  null_frac6FROM7  pg_stats8WHERE9  tablename = 'orders'10  AND attname = 'status';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Sample statistics for orders.status1 sample row
Sample statistics for orders.status
n_distinctmost_common_valsmost_common_freqsnull_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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

End every bulk load with ANALYZEQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1COPY staging_orders2FROM3  '/data/orders.csv'4WITH5  (FORMAT csv);67ANALYZE staging_orders;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative load and statistics status
COPY 2500 ANALYZE

Note: Assumes the CSV has 2,500 valid rows; COPY counts and command tags depend on the file and client dialect.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: ANALYZE after big changes; raise statistics targets on skewed columns.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1EXPLAIN ANALYZE

Spot a bad estimate

Compare estimated and actual rows on each node. A 10× or bigger gap is the signal.

SQL at this step
1rows = 10 vs actual rows = 250000
What to watch at this step
Gap
≥ 10×
Tip: use ← → to move between steps

When 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

ANALYZE
Best for: Refreshing planner statistics after data changes

Strengths: Fast, samples rows, doesn't block reads or writes.

Watch out: Does nothing about dead rows.

VACUUM
Best for: Reclaiming dead row versions for reuse

Strengths: Prevents bloat; runs online.

Watch out: Doesn't refresh statistics.

VACUUM ANALYZE
Best for: After large updates or deletes

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?
Interview tip: Tell the bulk-load story: statistics said empty, the plan was a nested loop, one ANALYZE fixed it. It's memorable and shows you know estimates drive plans.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Join Algorithms Under the Hood (Nested Loop, Hash Join, Merge Join)
Next topic
SARGable Queries (Writing Index-Friendly WHERE Clauses)