Full answer
Common causes:
- Stale or skewed statistics: a bulk insert changed the data, autoanalyze has not run yet, and the planner misjudges row counts.
- Plan flip at a threshold: as a table grows, a hash join or sequential scan becomes cheaper on paper, sometimes wrongly.
- Generic prepared-statement plans: after several executions, PostgreSQL may switch to a generic plan that suits typical values but not skewed ones.
- External factors: lock waits, a missing or invalid index after a failed concurrent build, or a cold cache after a restart.
Steps:
EXPLAIN (ANALYZE, BUFFERS)the slow query and compare estimates with actual rows.ANALYZEthe tables involved; if the plan changes back, set up better statistics (moredefault_statistics_targetor extended statistics for correlated columns).- Keep a record of plans for critical queries (for example with
auto_explain) so changes can be compared.
These are PostgreSQL-oriented descriptions, not run here.
Key points
- Plan changes cause sudden slowdowns
- Stale statistics mislead the planner
- Generic plans can suit skewed values badly
- Compare estimates with actual rows
- Record plans for critical queries
Common mistakes
- Rewriting the query before checking statistics
- Assuming no deploy means no change
Follow-ups
- What are extended statistics?
- How does auto_explain help?
Tips
- List statistics first