Quick revision
The short answer
The root cause is a cardinality estimate that is off by a factor of almost half a million: the planner expected 1 outer row, chose a nested loop because one inner lookup is cheap, and then ran that lookup 480,000 times. Estimates go wrong because of stale statistics, correlated columns, functions applied to columns, or parameters with skewed values. We fix the estimate with ANALYZE, a higher statistics target on skewed columns, or CREATE STATISTICS for correlated columns, make predicates sargable and join column types match, and use pg_hint_plan or enable_nestloop = off only to diagnose, not as the permanent fix.
What to remember
In this answer, we saw that the planner chose a nested loop because it estimated one outer row, and then ran the inner lookup 480,000 times. Estimates fail through stale statistics, skewed values, correlated columns, functions on columns, mismatched join types and generic plans. We fixed the estimate with ANALYZE, a higher statistics target and CREATE STATISTICS, made predicates sargable with matching types, and kept enable_nestloop and pg_hint_plan for diagnosis rather than as permanent fixes.
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.
The root cause is a cardinality estimate that is off by a factor of almost half a million: the planner expected 1 outer row, chose a nested loop because one inner lookup is cheap, and then ran that lookup 480,000 times. Estimates go wrong because of stale statistics, correlated columns, functions applied to columns, or parameters with skewed values. We fix the estimate with ANALYZE, a higher statistics target on skewed columns, or CREATE STATISTICS for correlated columns, make predicates sargable and join column types match, and use pg_hint_plan or enable_nestloop = off only to diagnose, not as the permanent fix.
Why this question is asked
This is the most common way a well-indexed query becomes slow. Nothing is missing, the indexes are there, and the plan looks reasonable, yet it takes 90 seconds. The planner chose its algorithms for a world with 1 row, and the real world had 480,000. Interviewers ask this to see whether we can read the gap between estimated and actual rows, trace it back to why the planner guessed wrong, and fix the guess rather than forcing a plan. In this answer, we will see why the nested loop was chosen, list the usual reasons estimates fail with an example of each, fix them, and discuss when hints are acceptable.
1Why One Row Leads to a Nested Loop
The planner compares the estimated cost of each join algorithm. For a nested loop, the cost is roughly the number of outer rows times the cost of one inner lookup. With 1 outer row and an index on the inner side, that is one lookup, by far the cheapest option, and a hash join would waste time building a hash table. So for the world the planner believed in, its choice was correct.
The key is the pair rows=1 versus actual rows=480000 on the outer side. Every node above it inherits the mistake: the inner index scan runs 480,000 times, and each run is a random read into a large table. A hash join over the same data would read order_items once. So the question is not 'why a nested loop' but 'why did the planner think there was one row'.
2Why Estimates Go Wrong
Stale statistics are the first suspect. PostgreSQL estimates from samples collected by ANALYZE, usually run by autovacuum. After a bulk load or a big status change, such as a backlog of 480,000 orders moved to pending, the statistics may still describe yesterday's data, where pending was rare.
Correlated columns are the second. The planner assumes conditions are independent and multiplies their selectivities. If 1 percent of orders are pending and 1 percent are from the marketplace, it estimates 0.01 percent for both, but if marketplace orders are almost always pending, the real fraction is close to 1 percent, a hundred times more. Functions on columns are the third: for WHERE lower(email) = $1 or date_trunc('day', created_at) = $1, the planner has no statistics on the expression and falls back to fixed default selectivities. And parameters with skewed values are the fourth: a prepared statement may get a generic plan built for an average value, which is terrible for the one customer with half the orders.
| Cause | Example | Fix |
|---|---|---|
| Stale statistics | Bulk load or status backlog since last ANALYZE | ANALYZE; tune autovacuum thresholds |
| Skewed values | A few statuses or tenants hold most rows | SET STATISTICS 1000 on the column |
| Correlated columns | status and channel move together | CREATE STATISTICS (dependencies, mcv) |
| Function on a column | lower(email) = $1 | Expression index, or rewrite the predicate |
| Type mismatch in join | bigint joined to numeric or text | Make the types match |
| Generic plan for skewed parameter | Prepared statement, big tenant | plan_cache_mode, or split the query |
3Fixing the Estimate
We start with the cheapest check: run ANALYZE on the tables and look at the plan again. If the estimate is now close, the problem was stale statistics, and the longer-term fix is to make autovacuum analyze that table more often, for example by lowering autovacuum_analyze_scale_factor for it.
A higher statistics target, the default is 100, stores more of the most common values and a finer histogram, which helps when a few values dominate. Extended statistics, created with CREATE STATISTICS, record how columns depend on each other: dependencies captures that one column determines another, and mcv records the most common combinations of values, available since PostgreSQL 12. After ANALYZE, the planner estimates the combined condition correctly and switches to a hash join. The query goes from 90 seconds to 6, without forcing anything.
4Making Predicates and Joins Plannable
Some estimates cannot be fixed with statistics because the planner cannot see through the expression. A predicate is sargable when the planner can use an index and statistics on the column directly, which means the column stands alone on one side of the comparison. date_trunc('day', created_at) = '2026-03-09' hides the column inside a function; created_at >= '2026-03-09' AND created_at < '2026-03-10' does not. Where the function is genuinely needed, such as lower(email), an expression index on lower(email) both makes the lookup fast and gives ANALYZE statistics on the expression.
Join columns should have the same type on both sides. If orders.customer_id is bigint and a staging table stores customer_id as numeric or text, the join needs a cast, which can prevent index use and hides statistics, often leading to default estimates. Fixing the column type removes the problem at its source.
5Hints and Planner Switches: Diagnosis, Not Cure
To prove that the nested loop is the problem, we can disable it for one session and compare: SET enable_nestloop = off makes the planner treat nested loops as very expensive, so it picks a hash or merge join if possible. If the query becomes fast, the diagnosis is confirmed. The pg_hint_plan extension goes further and lets us write hints such as HashJoin(o i) in a comment.
These are diagnostic tools, and occasionally an emergency measure while a real fix is prepared. As a permanent fix they are fragile: the hint stays when the data changes, when a new index would be better, or after an upgrade improves the planner, and it hides the real cause from the next person. Fixing the estimate lets the planner keep making good choices as the data evolves. If a prepared statement's generic plan is the cause, setting plan_cache_mode = force_custom_plan for that workload, which makes the planner plan with the actual parameter values each time, is a targeted fix rather than a hint.
6Follow-up questions
How do you find the node where the estimate first goes wrong?
Read the plan from the leaves upwards and compare rows (the estimate) with actual rows at each node, remembering that actual rows are per loop. The lowest node with a large gap is where the problem starts; everything above it is a consequence. Tools that render EXPLAIN ANALYZE output highlight these gaps, but reading the two numbers side by side is enough.
Why does a prepared statement sometimes get a worse plan than the same query typed in psql?
PostgreSQL plans a prepared statement with its actual parameters for the first five executions, then may switch to a generic plan that ignores the parameter values if it looks no more expensive on average. For skewed data, the generic plan may be excellent for most values and awful for a few. The JDBC driver uses server-side prepared statements after several executions too, so this appears in Java applications even though psql looks fine.
Can extended statistics hurt?
They cost a little ANALYZE time and storage, and they only help queries whose conditions match the column combination. Creating them for every pair of columns is wasteful. We add them for combinations that real slow queries filter on together, and confirm with EXPLAIN ANALYZE that the estimate improved.
7Conclusion
In this answer, we saw that the planner chose a nested loop because it estimated one outer row, and then ran the inner lookup 480,000 times. Estimates fail through stale statistics, skewed values, correlated columns, functions on columns, mismatched join types and generic plans. We fixed the estimate with ANALYZE, a higher statistics target and CREATE STATISTICS, made predicates sargable with matching types, and kept enable_nestloop and pg_hint_plan for diagnosis rather than as permanent fixes.
Open with
The root cause is the cardinality estimate, not the nested loop itself. The planner thought the outer side would return one row, and for one row a nested loop with an index lookup is the cheapest plan.
Then, if they want more
In reality it got 480,000 rows, so the inner index scan ran 480,000 times with random reads, and that is the 90 seconds. A hash join would have read the inner table once. So I ask why the estimate was wrong.
The usual reasons are stale statistics after a bulk change, skewed values where a few values hold most rows, correlated columns, since the planner multiplies selectivities as if conditions were independent, functions on columns that hide statistics, and generic plans for prepared statements with skewed parameters. I would run ANALYZE first and check the plan again.
If the estimate is still off, I would raise the statistics target on the skewed column and, for correlated filters, create extended statistics with dependencies and mcv on those columns, then ANALYZE.
I would also make predicates sargable, for example a date range instead of date_trunc on the column, add an expression index where a function is needed, and make sure join columns have the same type.
To confirm the diagnosis I might SET enable_nestloop = off in my session, or use pg_hint_plan, but only to test; a permanent hint goes stale as data changes. If it is a generic plan problem, plan_cache_mode force_custom_plan for that workload is a targeted fix.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 12
- 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, The SQL Language
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 "EXPLAIN ANALYZE shows a Nested Loop with rows=1 estimated on the outer side but actual...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/5cf88e54cd/