Sub topic 2
Collecting statistics with ANALYZE
This chapter assumes you can run psql, read simple EXPLAIN output, and know why the planner chooses between an index scan and a sequential scan. The previous chapter explained why the planner needs row estimates. This chapter covers the command that produces the numbers behind them.
What ANALYZE does
ANALYZE reads a sample of rows from a table, computes summary statistics, and stores them in system catalogs. It does not change your data, and it does not rebuild indexes or reclaim space. Its only product is the statistics the planner reads when it plans a query.
Two catalogs receive the results:
pg_classholds table-level figures: the estimated number of rows (reltuples) and pages (relpages).pg_statisticholds per-column figures such as the fraction of nulls, the number of distinct values, common values, and histograms. Thepg_statsview presents this catalog in readable form.
The next two chapters read both of these. Here the focus is how and when the data gets there.
Until a table has been analyzed, the planner has no column statistics for it. It falls back on built-in defaults, such as assuming about 200 distinct values in a column. Those guesses can be far from the truth.
A table to work with
The following script creates a table with a skewed status column. About 95% of the rows are shipped and about 5% are pending. It then runs ANALYZE so the planner has statistics.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (customer_id, status)
SELECT (random() * 1000)::int,
CASE WHEN random() < 0.95 THEN 'shipped' ELSE 'pending' END
FROM generate_series(1, 100000);
ANALYZE orders;If you run EXPLAIN SELECT * FROM orders WHERE status = 'pending' between the INSERT and the ANALYZE, the estimate will usually be far too low, on the order of a few hundred rows. After the ANALYZE it lands near 5000. Autovacuum may analyze the table before you get the chance, so the "before" result is not guaranteed on a busy server.
The forms of the command
You can scope ANALYZE to a whole database, one table, or specific columns.
| Command | What it analyzes |
|---|---|
| `ANALYZE;` | Every table in the current database that you have permission to analyze |
| `ANALYZE orders;` | One table, all columns |
| `ANALYZE orders (status, customer_id);` | Only the listed columns of one table |
| `ANALYZE (VERBOSE) orders;` | One table, with progress and sampling details printed |
| `ANALYZE (SKIP_LOCKED) orders;` | One table, skipped with a notice if the lock is not immediately available |
| `VACUUM (ANALYZE) orders;` | Vacuums the table, then analyzes it in the same command |
Use the column list when only some columns changed character, for example after a backfill of one column. Statistics for the unlisted columns stay as they were.
Permission follows ownership. The table owner, the database owner for shared catalogs, and superusers can analyze a table. In PostgreSQL 17 and later, a role granted the MAINTAIN privilege can too. A bare ANALYZE; quietly skips tables you may not analyze, with a warning.
What happens during a run
ANALYZE does not scan the whole table. It picks a random sample of rows and computes everything from that sample. The sample size is 300 × default_statistics_target. With the default target of 100, that is 30,000 rows. A table with 100,000 rows is sampled at about 30%, while a table with 100 million rows is sampled at about 0.03%. Cost therefore grows slowly with table size. A later chapter covers the target setting in detail.
Because the diagram fence needs the required form, here is the process as a diagram.
The sampling is two-stage. PostgreSQL first chooses a random set of table blocks, then chooses rows from within those blocks. This keeps I/O bounded. It also means the sample is not a perfectly uniform random draw. Columns whose values cluster by physical location can give slightly skewed results. The correlation column in pg_stats records that clustering.
To watch this happen, use VERBOSE:
ANALYZE (VERBOSE) orders;The output includes a line similar to scanned 641 of 641 pages, containing 100000 live rows and 0 dead rows; 30000 rows in sample, 100000 estimated total rows. This line tells you how much of the table was read and how the total row count was extrapolated. On a small table every page is scanned, but only the sample rows feed the column statistics.
Locking and cost
ANALYZE takes a SHARE UPDATE EXCLUSIVE lock on the table. That lock does not block SELECT, INSERT, UPDATE, or DELETE. It does conflict with itself, with VACUUM, and with most ALTER TABLE and CREATE INDEX forms (not CREATE INDEX CONCURRENTLY, which takes the same lock level). If a long-running VACUUM holds the lock, your ANALYZE waits. Use SKIP_LOCKED in scripts where waiting would be worse than skipping.
ANALYZE can run inside a transaction block. That differs from VACUUM, which cannot. Statistics written by a transaction that later rolls back are rolled back too.
VACUUM ANALYZE versus ANALYZE
VACUUM and ANALYZE are separate jobs. VACUUM removes dead row versions and updates the visibility map. ANALYZE refreshes statistics. VACUUM ANALYZE (or VACUUM (ANALYZE)) runs both, one after the other, in one command.
The combination is useful after a large delete or update. The vacuum first removes the dead rows. The analyze that follows then sees a table closer to its settled state, and reltuples reflects the live rows. Running ANALYZE alone after a mass delete still works, but relpages may stay high until a vacuum shrinks or reuses the space.
Checking when a table was last analyzed
PostgreSQL records analyze activity in pg_stat_user_tables:
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';last_analyzeis the time of the last manualANALYZE.last_autoanalyzeis the time of the last run triggered by autovacuum.n_mod_since_analyzeis the estimated number of rows inserted, updated, or deleted since the last analyze of either kind.
Right after the script above, last_analyze is set and n_mod_since_analyze is 0. If you then run UPDATE orders SET status = 'cancelled' WHERE id <= 20000;, the counter jumps to about 20,000 and the statistics describe a table that no longer exists. A large n_mod_since_analyze next to an old timestamp is the first thing to check when a plan suddenly gets worse.
Cases where statistics go missing
- Fresh bulk loads. A table filled with
COPYhas no statistics until someone analyzes it or autovacuum gets to it. Add an explicitANALYZEto the end of load scripts. - Temporary tables. Autovacuum never processes temporary tables, because other sessions cannot see them. If a session builds a temp table and joins against it, run
ANALYZEon it yourself. - After
pg_upgrade. Before PostgreSQL 18, upgrades do not carry planner statistics over. Runvacuumdb --all --analyze-in-stagesafterward, or the first queries run on default guesses. - Expression indexes.
ANALYZEalso gathers statistics on the expressions of an expression index, solower(email)gets its own distribution once analyzed.
Summary of the working model
ANALYZE samples a table, builds statistics, and stores them where the planner can find them. The sample size depends on the statistics target, not on the table size. The command is cheap enough to run after any bulk change. You verify it ran by reading pg_stat_user_tables.
Exercise
You load 5 million rows into a new table with COPY and immediately run a query that joins it to a small table. The plan chooses a nested loop that runs for minutes. What do you check and run first, and why might autovacuum not have helped yet?
Show answer
Check pgstatusertables for the new table: lastanalyze and lastautoanalyze will be empty, so the planner is using default estimates. Run ANALYZE on the table (or VACUUM ANALYZE), then re-run EXPLAIN. Autovacuum may not have helped because it checks tables only periodically (every autovacuumnaptime, one minute by default) and only after the change count passes its threshold, and the workers may be busy with other tables.
Exercise
A script builds a temporary table, fills it, and joins it to large tables. The estimates are far off even though autovacuum is on. Why, and what is the fix?
Show answer
Autovacuum never processes temporary tables, so the temp table has no statistics. Add ANALYZE on the temporary table after filling it and before running the join.