Sub topic 13
Special cases: partitioned tables, temporary tables, stale statistics
This chapter covers the places where the automatic statistics machinery from earlier chapters does not do what you expect. It assumes you can read pg_stats and EXPLAIN (ANALYZE) output, and that you know how autovacuum triggers an automatic analyze (autoanalyze) from n_mod_since_analyze and the scale factor. Partitioned parent tables, temporary tables, and tables that change faster than autoanalyze runs are the usual sources of bad estimates that persist for no obvious reason.
Who refreshes statistics for which kind of table
Autovacuum visits ordinary tables, materialized views, and the leaf partitions of a partitioned table. It skips several kinds of relation, so their statistics are only as fresh as your last manual ANALYZE.
| Relation kind | Autoanalyzed? | What you do |
|---|---|---|
| Ordinary table | Yes | Tune thresholds if needed |
| Leaf partition | Yes, each one on its own | Tune per partition |
| Partitioned parent | No | Schedule `ANALYZE parent` |
| Temporary table | No | Run `ANALYZE` in the same session |
| Foreign table | No | Run `ANALYZE` if the foreign data wrapper supports it |
Partitioned tables
A partitioned table is a parent with no rows of its own, and each partition is a separate physical table. Both levels have statistics, and they serve different purposes.
- Leaf partitions carry normal statistics. Autovacuum analyzes each one when its own change counter crosses its own threshold.
- The parent carries statistics about the union of all partitions. The planner uses them when a query touches many partitions and needs an estimate for the whole hierarchy. Examples are a join between the parent and another table, or a
GROUP BYon a parent column with no partition pruning.
Autovacuum never analyzes the parent. Until you run ANALYZE on it, the planner has no parent-level column statistics. Partition pruning still works, because it uses the partition bounds and not statistics. The estimates for a join or aggregate over the whole hierarchy are what suffer.
Create a small partitioned table and look at the parent before and after.
CREATE TABLE events (
tenant int NOT NULL,
happened_at timestamptz NOT NULL,
kind text NOT NULL
) PARTITION BY RANGE (happened_at);
CREATE TABLE events_2026_01 PARTITION OF events
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE events_2026_02 PARTITION OF events
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
INSERT INTO events (tenant, happened_at, kind)
SELECT (random() * 50)::int,
timestamptz '2026-01-01' + random() * interval '58 days',
'click'
FROM generate_series(1, 200000);
SELECT count(*) AS parent_stat_rows
FROM pg_stats
WHERE tablename = 'events';The query returns 0, because nothing has analyzed the parent. Now analyze it and look again.
ANALYZE events;
SELECT tablename, attname, inherited, n_distinct
FROM pg_stats
WHERE tablename = 'events' AND attname = 'tenant';The new row has inherited = true. That flag marks statistics gathered over a table together with its children. For a partitioned parent, which holds no rows itself, every statistics row is inherited. Running ANALYZE on the parent samples rows across all partitions. It also recurses into each partition and refreshes their statistics, so one command refreshes the whole tree.
A few points matter in practice:
- Since PostgreSQL 14,
pg_class.reltuplesfor a partitioned parent is-1until it has been analyzed. - Autovacuum storage parameters such as
autovacuum_analyze_scale_factorcannot be set on the parent. Set them on individual partitions. - Autoanalyze has no change counter to watch for the parent, so you need a schedule. Use
pg_cron, an external scheduler, or a job that runs after bulk loads. - Time-based partitioning has a trap. The newest partition is the one receiving inserts, and it often has few rows when it is first created. A plan chosen while it was nearly empty can persist until autoanalyze catches up.
-- Newest partition: analyze more eagerly than the 10% default
ALTER TABLE events_2026_02 SET (
autovacuum_analyze_scale_factor = 0.01,
autovacuum_analyze_threshold = 1000
);Temporary tables
Autovacuum cannot analyze a temporary table, because the table's contents live in the owning session's local buffers and other processes cannot read them. A temporary table that you fill and then query in the same session therefore has no statistics unless you create them. This happens most often in ETL scripts that stage data in a temp table and then join it to large tables.
CREATE TEMP TABLE staging AS
SELECT g AS id, (g % 10) AS bucket
FROM generate_series(1, 50000) AS g;
SELECT count(*) FROM pg_stats WHERE tablename = 'staging';
EXPLAIN SELECT * FROM staging WHERE bucket = 3;The pg_stats count is 0. With no statistics for bucket, the planner falls back to a built-in default selectivity for an equality test, about 0.5%. It estimates roughly 250 rows, while the real count is 5,000. The estimated size of the table itself is reasonable, because the planner measures the table's physical size, but its idea of the data's distribution is a guess.
ANALYZE staging;
EXPLAIN SELECT * FROM staging WHERE bucket = 3;After ANALYZE, the bucket statistics list ten common values at about 10% each, and the estimate moves to about 5,000 rows. With a single table and no joins the plan is the same either way, so the effect shows up in joins. A 20-fold underestimate can pick a nested loop where a hash join belongs.
The practical rules:
- Run
ANALYZE tmp_tableright after loading it and before the queries that depend on it. - If you add indexes to the temp table, create them before or after the load as you prefer. Neither affects the need for
ANALYZE. - Statistics for a temp table are visible only in the owning session, and they disappear with the table.
- For very small temp tables the analyze cost is negligible. For large ones it is still usually cheaper than a bad join.
Stale statistics
Statistics are a snapshot, and any snapshot can be out of date. Autoanalyze reduces the problem but does not remove it, for three reasons.
- The trigger is proportional. A table is analyzed when changed rows exceed
autovacuum_analyze_threshold + autovacuum_analyze_scale_factor * reltuples, which is 50 rows plus 10% of the table by default. A table of 100 million rows can change by 10 million rows before any refresh. - Autovacuum is periodic. The launcher wakes up every
autovacuum_naptime, one minute by default, and workers are limited. A bulk load followed immediately by a query runs on the old statistics. - The distribution can shift without volume changing. Updating a column from one value to another keeps the row count constant while changing the most common values and histogram. This is the pattern of a
statuscolumn that moves frompendingtoshipped.
The ascending-key problem
The classic case is a timestamp or sequence column that only grows. The histogram built at the last analyze ends at some maximum. Queries for the newest data ask about values beyond it, which the statistics say do not exist. A naive estimate would be nearly zero rows, so the planner may choose a nested loop or an index scan that is disastrous for the thousands of rows that are actually there.
PostgreSQL softens this. When a constant falls outside the histogram, the planner can look at the actual current minimum or maximum in a btree index on the column. This often rescues range conditions on indexed columns. It does not help columns without a suitable index, and it does not fix join estimates.
Detecting staleness
Check the change counter and the last analyze time together. A large n_mod_since_analyze relative to the table size, with an old last_autoanalyze, marks a suspect.
SELECT relname,
n_live_tup,
n_mod_since_analyze,
round(n_mod_since_analyze::numeric / greatest(n_live_tup, 1), 3)
AS changed_fraction,
last_analyze,
last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_mod_since_analyze DESC
LIMIT 10;Then confirm with EXPLAIN (ANALYZE). If the estimated and actual rows disagree on a table that shows a high changed_fraction, run ANALYZE on it and compare again. If the estimates become accurate, staleness was the cause. If not, return to the workflow from the previous chapter. Look at the column's statistics target, then at correlated columns and extended statistics.
Fixes
- Analyze after bulk operations. Make
ANALYZE tablethe last step of any load, restore, or large delete script. Do not wait for autovacuum. - Lower the scale factor for large tables. Use
ALTER TABLE ... SET (autovacuum_analyze_scale_factor = 0.01), or a fixed threshold, so refreshes happen after a bounded number of changes. - Analyze after restores and major upgrades.
pg_dumpdoes not dump planner statistics, andpg_upgradebefore PostgreSQL 18 does not carry them over. The new cluster starts with empty statistics. Runvacuumdb --all --analyze-in-stagesto get usable estimates quickly and refine them afterwards. Extended statistics definitions survive, but their data must be re-collected byANALYZE. - Do not analyze constantly. Each
ANALYZEtakes a new random sample, so estimates can vary slightly between runs and plans can flip. Frequent, unnecessary analyzing buys nothing.
Putting it together
Treat these cases as a checklist you apply by relation kind. For a partitioned table, schedule ANALYZE on the parent and tune autoanalyze on the active leaf partitions. For a temporary table, analyze after loading. For tables that change in bulk or grow along a monotonic key, analyze at the end of the load or tighten the autoanalyze scale factor.
Exercise
A nightly job loads 5 million rows into a partitioned table sales, then a report joins sales to regions across all partitions. Autovacuum is enabled with default settings, yet the report's row estimate for sales is far off the next morning. Which two things would you check, and what single command would you add to the job?
Show answer
Check whether the parent sales has ever been analyzed (pg_stats has no inherited = true rows for it, or pg_class.reltuples is -1), because autovacuum never analyzes a partitioned parent. Also check n_mod_since_analyze and last_autoanalyze on the leaf partitions that received the load, because the load may not yet have crossed the threshold or the naptime may not have elapsed. Add ANALYZE sales; as the last step of the job. It refreshes the parent's statistics and recurses into each partition.
Exercise
Inside one session you run CREATE TEMP TABLE t AS SELECT ... and then join t to a large table. EXPLAIN estimates 200 rows for a filter on t, but the actual count is 40,000. Why did autovacuum not fix this, and what do you run?
Show answer
Autovacuum cannot access temporary tables, because their data is local to the owning session, so t was never analyzed and the planner used default selectivities. Run ANALYZE t; in the same session after loading it and before the join query.