Quick revision
The short answer
When the code did not change but the query did slow down, the plan almost always changed. We capture today's plan with EXPLAIN (ANALYZE, BUFFERS), compare it with the old plan from auto_explain logs or a restored backup, and then look for what moved the planner: new statistics, data growth past a threshold, a value that became frequent, a bloated or dropped index, a changed setting, or a prepared statement that switched to a generic plan. We fix that cause instead of only forcing the old plan back.
What to remember
In this answer, we saw that a query that slows down without a code change usually has a new plan, because the planner works from statistics and data that change on their own. We confirm the plan, compare it with the old one from auto_explain or a backup, check last_analyze, dead tuples and pg_stats for the filtered columns, and check whether a prepared statement switched to a generic plan. Then we fix the cause with statistics targets, extended statistics, indexes or a rewrite, using forced plans only as a temporary mitigation.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
When the code did not change but the query did slow down, the plan almost always changed. We capture today's plan with EXPLAIN (ANALYZE, BUFFERS), compare it with the old plan from auto_explain logs or a restored backup, and then look for what moved the planner: new statistics, data growth past a threshold, a value that became frequent, a bloated or dropped index, a changed setting, or a prepared statement that switched to a generic plan. We fix that cause instead of only forcing the old plan back.
Why this question is asked
This is one of the most realistic database incidents, and one of the most stressful, because nothing in the deploy history explains it. Interviewers ask it to see whether we debug methodically from evidence or start adding indexes at random. In this answer, we will recap why plans change on their own, confirm that the plan is the culprit, find the old plan to compare with, check statistics and data, look at the prepared statement case, and finally choose a fix that addresses the cause.
1A Quick Recap: Why a Plan Can Change by Itself
PostgreSQL decides how to run a query each time it plans it. The planner, the part of the database that chooses between scans and joins, estimates how many rows each step will produce and picks the cheapest plan it can find. Those estimates come from statistics: samples of each column's values, the most common values and their frequencies, and a histogram of the rest, collected by ANALYZE and by autovacuum's automatic analyze.
So the plan depends on things that change without any deploy: the statistics, the size of the table, the indexes that exist, and settings such as work_mem or random_page_cost. When one of them crosses a threshold, the cheapest estimated plan can flip, for example from an index scan to a sequential scan or from a nested loop to a hash join. If the estimate behind that flip is wrong, a 20 ms query can become an 8 second one overnight.
2Confirm the Plan and Find the Old One
First we confirm the query itself is slow, not the connection pool or locks. pg_stat_statements shows the mean time per normalized query, and pg_stat_activity shows whether sessions are waiting on locks. Then we capture the current plan with real numbers.
- Slow query confirmedpg_stat_statements mean time, no lock waits
- Capture plan nowEXPLAIN (ANALYZE, BUFFERS)
- Get old planauto_explain log or restored backup
- Estimates far from actuals?YesCheck statistics and dataNoCheck indexes and settings
- Prepared statement?YesCompare generic and custom plansNoFix the cause found
- Fix the causestatistics, index, query
6 steps in order. Play them, or step through them one at a time.
The comparison between the two plans tells us where to look; guessing does not.
Notice the most important clue in any plan: estimated rows versus actual rows. A factor of thousands means the planner chose on false information. To see what changed, we need the old plan. If auto_explain was already logging slow queries, it may hold it; some teams store plans from regular snapshots. If not, we restore yesterday's backup or use a staging copy that has not been re-analyzed, run the same EXPLAIN there, and compare the two plans step by step.
3Check Statistics and the Data
Next we look at when the statistics were last refreshed and how the data looks now.
Each finding points to a typical cause. A recent autoanalyze right before the slowdown suggests the new sample shifted an estimate. A table that grew past some size can flip the cost comparison between plans. A value that used to be rare and is now frequent, here IN_TRANSIT after a carrier outage, changes selectivity. Many dead tuples, rows left behind by updates and deletes that vacuum has not cleaned yet, suggest bloat, which makes index and table scans read far more pages. And a dropped or invalid index, or a setting changed with ALTER SYSTEM, shows up when we compare indexes and pg_settings between the old and new environment.
Correlated columns are a frequent root cause. The planner assumes carrier_id and status are independent and multiplies their selectivities, so if carrier 12 has almost all in-transit shipments, the estimate can be off by a large factor. That is exactly what extended statistics fix.
4The Prepared Statement Case
If the application uses prepared statements, as JDBC does, there is one more cause. PostgreSQL plans the first five executions of a prepared statement with the actual parameter values, called custom plans. After that it may switch to a generic plan, one plan for any value, if its estimated cost is not much worse. A generic plan built for an average value can be terrible for a skewed one.
If the query is fast in psql with literal values but slow from the application, and forcing custom plans makes it fast again, the generic plan is the culprit. pg_prepared_statements only shows the current session's statements, so we run this from a session that executes the query like the application does.
5Fix the Cause, Not Just the Symptom
Once we know the cause, the fix follows. Bad estimates from a skewed column call for a larger statistics target, so ANALYZE keeps more common values; correlated columns call for extended statistics; bloat calls for vacuum and REINDEX CONCURRENTLY; a missing index calls for recreating it; a generic plan problem calls for plan_cache_mode = force_custom_plan on that role or query, or a query rewrite.
Forcing the old plan with a hint extension such as pg_hint_plan can be a valid emergency mitigation, but it freezes a plan that may become wrong as data keeps changing, and it hides the real problem. So we use it to stop the bleeding if needed, fix the cause, remove the hint, and add auto_explain and plan monitoring so the next regression arrives with its evidence already recorded.
6Follow-up questions
Why not just run ANALYZE and move on?
ANALYZE is often the quick mitigation, and sometimes it is enough. But if the regression came from an analyze in the first place, a fresh sample may produce the same bad estimate tomorrow. We still need to understand which estimate was wrong and fix it structurally.
How do you get an old plan if nothing was logged?
Restore a backup from before the slowdown, or use a copy whose statistics were not refreshed, and run the same EXPLAIN there. pg_stat_statements also shows when mean time jumped, which narrows down what changed at that moment, such as an analyze, a bulk load or a settings change.
Could the cause be outside the plan?
Yes. Lock waits, a saturated disk, a checkpoint storm or a replica falling behind can all slow a query with an unchanged plan. That is why the first step compares the plan: if the plan is the same and buffers read are similar, we look at waits and resources instead.
7Conclusion
In this answer, we saw that a query that slows down without a code change usually has a new plan, because the planner works from statistics and data that change on their own. We confirm the plan, compare it with the old one from auto_explain or a backup, check last_analyze, dead tuples and pg_stats for the filtered columns, and check whether a prepared statement switched to a generic plan. Then we fix the cause with statistics targets, extended statistics, indexes or a rewrite, using forced plans only as a temporary mitigation.
Open with
If the code did not change, I assume the plan did. First I confirm in pg_stat_statements that the query's mean time jumped and check pg_stat_activity that it is not lock waits.
Then, if they want more
Then I capture EXPLAIN ANALYZE with buffers and look at estimated versus actual rows, because a big gap means the planner chose on bad information. I want the old plan to compare: from auto_explain logs if we have them, otherwise by running the query on a restored backup or a copy that was not re-analyzed.
Then I look for what moved: pg_stat_user_tables for last_analyze, last_autoanalyze and n_dead_tup, pg_stats for the most common values and frequencies of the filtered columns, table growth, and whether an index was dropped or a setting changed. Typical causes are a new statistics sample, a value that became frequent, correlated columns, bloat or a threshold crossed by growth.
If the app uses prepared statements, I check whether it switched to a generic plan after five executions, by testing plan_cache_mode = force_custom_plan. The fix targets the cause: a higher statistics target, extended statistics, a reindex or a new index, or a query change.
A hint to force the old plan is only an emergency measure, and afterwards I make sure auto_explain is on so the next one is easier.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 14, PostgreSQL 16
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A query that ran in 20 ms for a year suddenly takes 8 seconds after no code change. Walk...": https://scrivio-interview-library.netlify.app/databases/query-optimization/d87be61012/