Sub topic 8
Autoanalyze: when statistics refresh themselves
This chapter assumes you can run psql, read pg_stats and pg_class as shown in the earlier chapters, and know that ANALYZE stores the statistics the planner uses. Here you will learn when PostgreSQL runs ANALYZE for you, how to predict that moment, and how to change it for tables that behave differently from the default assumptions.
Who runs ANALYZE if you don't
Nobody types ANALYZE after every batch of writes. PostgreSQL has a background facility called autovacuum. It has two parts:
- The autovacuum launcher is a single background process. It wakes up regularly and starts workers for databases that need attention.
- Autovacuum workers connect to a database, check each table, and run
VACUUM,ANALYZE, or both on the tables that qualify.
The analyze half of this work is called autoanalyze. It runs the same sampling ANALYZE you run by hand and writes the same rows to pg_statistic. It does not need a special mode or extra permissions. Autoanalyze is on by default.
Two settings must be on for any of this to work:
SHOW autovacuum;
SHOW track_counts;Both should return on. Workers decide what to do by reading change counters that the statistics system keeps, and track_counts controls whether those counters are collected. If either setting is off, tables are never analyzed automatically.
The trigger rule
A table is analyzed when the number of rows changed since its last analyze exceeds this value:
autovacuum_analyze_threshold + autovacuum_analyze_scale_factor * reltuplesThe defaults are a threshold of 50 rows and a scale factor of 0.1, which means 10% of the table. reltuples is the table's row estimate in pg_class.
For the 100,000-row orders table from earlier chapters:
50 + 0.1 * 100000 = 10050After about 10,050 inserted, updated, or deleted rows, autoanalyze will refresh the statistics. Each change counts once:
- an inserted row counts as one change
- an updated row counts as one change
- a deleted row counts as one change
The running total is the n_mod_since_analyze column in pg_stat_user_tables. It resets to zero after a successful analyze.
The fixed threshold of 50 prevents tiny tables from being analyzed constantly. The scale factor makes big tables wait longer. That scaling is the main reason autoanalyze can be late on large tables, as the next section shows.
Watching the counter and the trigger point
This query shows the counter next to the trigger point, using the global settings:
SELECT s.relname,
s.n_mod_since_analyze,
c.reltuples::bigint AS reltuples,
current_setting('autovacuum_analyze_threshold')::int
+ current_setting('autovacuum_analyze_scale_factor')::float8 * c.reltuples
AS analyze_trigger_at,
s.last_autoanalyze,
s.autoanalyze_count
FROM pg_stat_user_tables s
JOIN pg_class c ON c.oid = s.relid
WHERE s.relname = 'orders';The query ignores per-table overrides. Check those separately:
SELECT relname, reloptions
FROM pg_class
WHERE relname = 'orders';If reloptions is not null and contains autovacuum_analyze_scale_factor or autovacuum_analyze_threshold, the table's own values replace the global ones in the formula.
A worked example of stale statistics
Run this against the orders table. It makes about 20% of the rows pending. That is more than the 10,050-row trigger, but the old statistics still say about 5% are pending.
UPDATE orders SET status = 'pending' WHERE id <= 20000;
EXPLAIN (ANALYZE)
SELECT * FROM orders WHERE status = 'pending';Run the EXPLAIN right after the update, before the next autovacuum cycle. The estimate will be near the old figure of roughly 5,000 rows, and the actual count will be around 24,000. The planner is working from statistics that describe the table before the update.
Now check the counter:
SELECT relname, n_mod_since_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE relname = 'orders';n_mod_since_analyze should be about 20,000. Wait a minute or two and run it again. The counter should drop to near zero and last_autoanalyze should show a new time. Run the EXPLAIN (ANALYZE) again and the estimate will match the actual count much more closely.
The delay you saw has a cause: the launcher does not check continuously. It visits each database about once every autovacuum_naptime, which defaults to one minute. On a busy cluster with many databases or tables, a table can wait longer for a free worker. The limit is autovacuum_max_workers (default 3).
The cycle as a whole
Tuning for tables with unusual change patterns
The global defaults suit medium-sized tables with steady writes. Two patterns break that assumption.
Large tables. At the default scale factor, a table with 100 million rows needs about 10 million changed rows before autoanalyze fires. If a few percent of the rows can shift a column's distribution, the statistics stay stale for a long time. Lower the scale factor for that table:
ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.02);For orders this changes the trigger from 10,050 to 50 + 0.02 * 100000 = 2050 changed rows. The change affects only this table.
For very large tables, set the scale factor to zero and use a fixed threshold, so the trigger no longer grows with the table:
ALTER TABLE orders SET (
autovacuum_analyze_scale_factor = 0,
autovacuum_analyze_threshold = 50000
);Now the table is analyzed every 50,000 changed rows (50,000 + 0 × reltuples).
Small, fast-changing tables. A queue table with a few hundred rows that is emptied and refilled constantly may have a tiny reltuples, so the trigger is close to 50. It can be analyzed very often, which is cheap and usually right. If you see excess analyze activity on such a table, raising autovacuum_analyze_threshold for it is the lever to use.
To undo a per-table setting, reset it:
ALTER TABLE orders RESET (autovacuum_analyze_scale_factor, autovacuum_analyze_threshold);Seeing what autoanalyze did
To see each run in the server log, set a duration limit. A value of 0 logs every autovacuum and autoanalyze action:
ALTER SYSTEM SET log_autovacuum_min_duration = 0;
SELECT pg_reload_conf();Logging every run can be noisy on a busy cluster. A value such as 1s logs only the slow ones. The log line for an analyze names the table and includes timing and I/O figures. Use it to confirm that a table you tuned is being analyzed when you expect.
The cumulative counters are also useful. autoanalyze_count and analyze_count in pg_stat_user_tables show how often each path ran. A large table with autoanalyze_count = 0 after weeks of writes is a sign that the scale factor is too high for it.
What autoanalyze does not cover
Several cases need a manual ANALYZE:
- Partitioned parent tables. Autovacuum analyzes each partition, but it never analyzes the parent. Statistics on the parent, which the planner uses for some queries that span partitions, are only refreshed by running
ANALYZEon the parent yourself. - Temporary tables. Autovacuum workers cannot access other sessions' temporary tables. If a session loads a temp table and joins on it, run
ANALYZEon it in that session. - After a bulk load. A large
COPYorINSERT ... SELECTcan leave a table with no statistics until the next naptime visit. If the next query runs right after the load, runANALYZEin the same script. - After a crash or major upgrade. The change counters are not guaranteed to survive a crash. Statistics also are not carried over by
pg_upgradein older major versions. In those cases runANALYZEon all tables, for example withvacuumdb --all --analyze-in-stages.
Cost of running analyze automatically
Autoanalyze reads a sample, not the whole table. The sample size is tied to the statistics target from the previous chapter, so the cost grows slowly with table size. Workers also respect the cost-based delay settings (autovacuum_vacuum_cost_delay and autovacuum_vacuum_cost_limit), which throttle their I/O. A very large sample on a slow disk can therefore take noticeably longer than the same ANALYZE run by hand, because manual runs are not throttled by default.
Summary checklist
When estimates look stale, work through these checks in order:
- Confirm
autovacuumandtrack_countsareon. - Read
last_autoanalyzeandn_mod_since_analyzefor the table. - Compute the trigger from
reloptionsfirst and the global settings second. - If the counter is above the trigger and nothing has run, look at worker availability and the log.
- If the counter is below the trigger, lower the scale factor or threshold for that table, or run
ANALYZEyourself.
Exercise
A table has reltuples = 2,000,000 and uses the default autovacuum settings. About how many changed rows are needed before autoanalyze fires? What per-table setting would make it fire after about 20,000 changed rows, and how would you write it?
Show answer
With the defaults, the trigger is 50 + 0.1 2,000,000 = 200,050 changed rows. To fire after about 20,000 changes, set the scale factor to 0.01 (50 + 0.01 2,000,000 = 20,050): ALTER TABLE t SET (autovacuumanalyzescalefactor = 0.01); Another option is a fixed threshold: ALTER TABLE t SET (autovacuumanalyzescalefactor = 0, autovacuumanalyzethreshold = 20000);
Exercise
You partition a table by month and load data into each partition. The partitions are analyzed regularly, but a query that joins across the parent still gets bad row estimates, and last_autoanalyze for the parent is empty. Why, and what do you do?
Show answer
Autovacuum never analyzes a partitioned parent table, only its partitions. The parent's statistics are refreshed only when you run ANALYZE on it yourself. Run ANALYZE on the parent after loading data, and schedule it if the data changes regularly.