← Back to SQL, page 18

sql-0360 · Hard senior

A query that ran in 20 ms yesterday takes 30 seconds today, with no code change. What might have changed?

Most often the planner switched plans because table statistics or data distribution changed, for example after a bulk load, or a stale estimate made a nested loop look cheap. Compare the current plan with the old one, run ANALYZE, and check for parameter-specific plans, lock waits or a dropped index.

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:

  1. EXPLAIN (ANALYZE, BUFFERS) the slow query and compare estimates with actual rows.
  2. ANALYZE the tables involved; if the plan changes back, set up better statistics (more default_statistics_target or extended statistics for correlated columns).
  3. 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