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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Name the tables involved in this file.
- `pg_class`, `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.