debugMajorpending
PostgreSQL slow queries from missing statistics or wrong plan
Viewed 0 times
ANALYZEstatistics targetquery planwork_memrandom_page_costplan regression
linux
Error Messages
Problem
PostgreSQL chooses a bad query plan — sequential scan instead of index scan, or wrong join order. The query is fast on a small dataset but slow on production. EXPLAIN shows estimates wildly different from actuals.
Solution
(1) Update statistics: ANALYZE table_name — refreshes the statistics the planner uses. (2) Check if autovacuum is running ANALYZE (it should by default). (3) Increase statistics target for columns with skewed distributions: ALTER TABLE t ALTER COLUMN c SET STATISTICS 1000 (default 100). Then ANALYZE. (4) Extended statistics for correlated columns: CREATE STATISTICS stat_name ON col1, col2 FROM table. (5) Check for plan regression after Postgres upgrade: use pg_hint_plan to force specific plans while investigating. (6) work_mem: increase for complex sorts and hash joins (default 4MB is often too low). (7) random_page_cost: lower to 1.1 for SSDs (default 4.0 assumes spinning disk).
Why
The query planner estimates row counts and costs based on column statistics (histograms, distinct values, correlation). If statistics are stale or inaccurate (skewed data, correlated columns), the planner makes bad decisions.
Revisions (0)
No revisions yet.