ANALYZE Refreshes Planner Row Estimates

After a bulk load pg_class.reltuples still reports the old estimate, so EXPLAIN rows go wildly wrong until ANALYZE re-samples the table.

SqlData Integrity

Code

snippet
-- pg_class.reltuples 是 planner 用的行数估算:
-- 从未分析过的表可能是 -1 占位,批量导入后则是上次的旧统计值
SELECT relname, reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'events';

-- ANALYZE 重新采样并更新统计,估算行数与真实规模重新对齐
ANALYZE events;

SELECT relname, reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'events';

-- 统计过期时 EXPLAIN 的 Rows 可能偏离真实值几个数量级,连计划形态都会被带偏
EXPLAIN
SELECT region, COUNT(*) FROM events GROUP BY region;

-- autovacuum 也会定期触发;但批量导入后手动 ANALYZE 立即生效,不必等调度

How it works

Several statements share this file — SELECT / EXPLAIN, with pg_class and events among the objects involved.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group.

Using it

The pg_class table is the working surface here.

Key statements

SELECT relname, reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'events';
EXPLAIN
SELECT region, COUNT(*) FROM events GROUP BY region;
ANALYZE events;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`pg_class`, `events` — referenced directly, no join needed.