Sub topic 2
Collecting Statistics with ANALYZE
This chapter assumes you can run SQL with psql, write SELECT and WHERE clauses, and read a simple EXPLAIN plan. You should also know that an index gives PostgreSQL another way to access table rows.
PostgreSQL uses a cost-based planner. Before executing a query, the planner estimates how many rows each operation will produce. It uses those estimates to choose between sequential scans, index scans, join methods, and join orders. ANALYZE collects the statistics used for these estimates.
Running ANALYZE
ANALYZE is a PostgreSQL command that samples table data and stores a summary of its distribution. It does not recalculate every possible query. Instead, it gathers enough information for the planner to estimate common predicates.
Create a test table and collect its 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;The command can target one table, several tables, or the whole database:
ANALYZE orders;
ANALYZE orders (status, customer_id);
ANALYZE;The column-list form is useful when you want to refresh selected columns. The command without a table name analyzes tables in the current database that the current role can access.
A table-level ANALYZE normally updates statistics for all relevant columns. PostgreSQL samples rows rather than reading every row, so the operation is usually much cheaper than a full table scan. The sample is still an estimate, which means statistics can be imperfect.
ANALYZE versus VACUUM ANALYZE
VACUUM reclaims reusable space and maintains visibility information. It does not, by itself, refresh planner statistics. VACUUM ANALYZE performs both operations:
VACUUM ANALYZE orders;Use ANALYZE when the main need is current row-distribution information. Use VACUUM ANALYZE when the table also needs vacuum maintenance. They solve related but different maintenance problems.
A useful distinction is:
| Command | Main purpose | Refreshes planner statistics |
|---|---|---|
| `ANALYZE orders` | Sample table data | Yes |
| `VACUUM orders` | Reclaim reusable space | No |
| `VACUUM ANALYZE orders` | Vacuum and sample data | Yes |
Checking when statistics were collected
PostgreSQL records analysis times in pg_stat_user_tables. This view helps you determine whether a surprising plan might be using old statistics:
SELECT relname,
last_analyze,
last_autoanalyze,
n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';last_analyze records the most recent manual ANALYZE. last_autoanalyze records the most recent automatic analysis by autovacuum. n_mod_since_analyze estimates how many rows have changed since the last analysis.
You can also confirm that the command completed by checking the catalog views used for statistics. The command produces no result set, so a quiet ANALYZE orders; is normally success, not evidence that nothing happened.
The planner can still make a poor choice after fresh analysis. Sampling cannot predict every future predicate, and independent column statistics may miss relationships between columns. Later chapters cover how to inspect those statistics and correct persistent misestimates.
Exercise
Which command should you run if a table has both stale planner statistics and reusable space that vacuum can reclaim?
Show answer
Run VACUUM ANALYZE table_name;. It performs vacuum maintenance and refreshes the planner statistics.