Scrivio Interview library
DebuggingFoundations8 min read · updated 12 November 2026

EXPLAIN ANALYZE shows: Nested Loop (actual time=0.05..9120.4 rows=480000 loops=1) with inner Index Scan on order_items (rows=1 estimated, actual rows=48 loops=10000). What does this tell you and what would you check next?

The planner expected 1 row from order_items per outer row but actually got 48, a 48x underestimate. Because actual rows on an inner node are reported per loop, the inner index scan really returned 48 x 10,000 = 480,000 rows, and the nested loop chosen for a tiny inner side spent 9 seconds doing 10,000 separate lookups. Next we check whether statistics are stale or the data is skewed or correlated, fix the estimate with ANALYZE, a higher statistics target or extended statistics, and confirm that a hash join is faster.

Why this question is asked

A nested loop that runs for seconds is one of the most common slow plans in PostgreSQL, and it is almost always caused by a wrong row estimate rather than by the join itself. Interviewers show a plan fragment like this to see whether we can read per-loop numbers correctly, spot the estimate gap, and follow it to a cause instead of reaching for random settings. In this answer, we will recap what a nested loop does, read the numbers in the plan line by line, see why the planner chose this join, walk through what to check next in the statistics, and finish with a safe way to prove that a different join would be faster.

1A Quick Recap of the Nested Loop Join

A join combines rows from two inputs. In a nested loop, PostgreSQL takes each row from the outer input, the first child in the plan, and for each one runs the inner input, the second child, to find matching rows. With an index on the join key, each inner run is an Index Scan, a lookup that jumps straight to the matching rows through a B-tree index.

This is excellent when the outer side has few rows, because a handful of index lookups costs almost nothing. It becomes expensive when the outer side has many rows or each lookup returns many rows, because the work is the number of outer rows times the cost of one lookup, and each lookup touches index and table pages at random positions.

2Reading the Numbers in This Plan

Let us put the fragment together as PostgreSQL would print it.

Java
Nested Loop (cost=0.85..42000.00 rows=10000 width=64)
(actual time=0.05..9120.4 rows=480000 loops=1)
-> Seq Scan on orders o (... rows=10000 ...) (actual ... rows=10000 loops=1)
-> Index Scan using order_items_order_id_idx on order_items i
(cost=0.43..4.00 rows=1 width=32)
(actual time=0.02..0.85 rows=48 loops=10000)
Index Cond: (order_id = o.id)
Estimated versus actual
NodeEstimatedActualGap
Outer scan of orders10,000 rows10,000 rowscorrect
Inner index scan, per loop1 row48 rows48x too low
Inner index scan, total10,000 rows480,000 rows48 x 10,000 loops
Nested loop output10,000 rows480,000 rowswhole plan built on the wrong size

The key detail is that the actual rows of a node that runs many times is an average per loop. The inner Index Scan ran 10,000 times, once per order, and returned 48 rows each time on average. So the node really produced 48 x 10,000 = 480,000 rows in total, which matches the 480,000 rows that the Nested Loop above it returned. The same rule applies to actual time: 0.85 ms per loop times 10,000 loops is about 8.5 seconds, nearly all of the 9.1 seconds of the whole join.

Now compare that with the estimate. The planner expected rows=1 per loop, so it expected the join to return about 10,000 rows. Reality was 480,000. That is a 48x underestimate, and it is the first thing we would say out loud when we see this plan.

3Why the Planner Chose a Nested Loop

The planner picks the cheapest plan according to its estimates. If each order really had one item, the nested loop would do 10,000 cheap lookups returning 10,000 rows, and that can look cheaper than a hash join, which must first read the whole order_items table and build a hash table in memory. So with the estimate it had, the choice was reasonable.

With the real numbers the picture flips. A hash join would read order_items once sequentially, build or probe a hash table, and match all 480,000 rows in one pass, with no random index lookups. For this many rows that is usually much faster. Notice that the problem is not the nested loop as such; it is the estimate that made the nested loop look cheap. The wrong estimate may also have knock-on effects higher up the plan, where a parent node planned for 10,000 rows receives 480,000.

4What to Check Next

The first suspect is stale statistics. If order_items grew quickly, for example after a migration or a new feature that adds many items per order, the statistics may still describe the old data. pg_stat_user_tables tells us when the table was last analyzed and how many rows changed since then.

SQL
SELECT relname, n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze
FROM pg_stat_user_tables WHERE relname = 'order_items';
-- order_items | 52000000 | 31000000 | null | 2026-09-02 03:10
ANALYZE order_items; -- refresh the statistics now
SELECT n_distinct FROM pg_stats
WHERE tablename = 'order_items' AND attname = 'order_id';
-- the planner estimates rows per order as about n_live_tup / n_distinct

If n_mod_since_analyze is large compared with the table size, ANALYZE alone may fix the estimate. Estimating rows per order_id depends mostly on n_distinct, the number of different order_id values the statistics think exist. If n_distinct is badly overestimated, which can happen on very large tables because ANALYZE samples only part of them, each order seems to have about one item.

5Fixing Skewed or Correlated Data

If the statistics are fresh and the estimate is still wrong, the data is probably skewed or correlated. Skewed means a few values are very common, for example bulk orders with thousands of items. Correlated means the WHERE clause filters on columns that depend on each other, and PostgreSQL by default assumes columns are independent. For skew we raise the statistics target of the column, so ANALYZE samples more rows and keeps more common values. For correlation we create extended statistics so the planner learns how the columns relate.

SQL
ALTER TABLE order_items ALTER COLUMN order_id SET STATISTICS 1000; -- default target is 100
ANALYZE order_items;
-- if the filters use dependent columns, for example status and warehouse_id:
CREATE STATISTICS oi_stats (dependencies, ndistinct) ON status, warehouse_id FROM order_items;
ANALYZE order_items;

If n_distinct is still wrong after a bigger sample, we can override it with ALTER TABLE ... ALTER COLUMN order_id SET (n_distinct = ...), a value PostgreSQL then uses from the next ANALYZE on. After each step we run EXPLAIN ANALYZE again and look at one thing first: whether the per-loop estimate is now close to 48.

6Proving That a Hash Join Is Faster

We should not change production settings to test a theory. Instead we change the planner settings for our own session only, on a replica or a production-like copy, and compare.

SQL
BEGIN;
SET LOCAL enable_nestloop = off; -- only for this transaction
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;
-- Hash Join (actual time=120.3..610.8 rows=480000 loops=1)
ROLLBACK;

SET LOCAL lasts until the end of the transaction, so nothing leaks to other sessions or to the connection pool. enable_nestloop = off does not forbid nested loops entirely; it makes them look very expensive, so the planner chooses something else if it can. If the hash join takes 0.6 seconds instead of 9, we have proved the point, and the real fix is still the statistics, not leaving this setting off. Turning a planner method off globally would make many other queries worse.

7Follow-up questions

How would you confirm a hash join is faster without changing production settings?

I would run the query on a replica or a copy with production-like data, inside a transaction with SET LOCAL enable_nestloop = off, and compare EXPLAIN (ANALYZE, BUFFERS) output for both plans, including the buffers touched. SET LOCAL affects only that transaction. Once the faster plan is proved, I fix the estimate with ANALYZE, a statistics target or extended statistics so the planner picks the hash join on its own.

Why are actual rows reported per loop and not in total?

Because a node inside a nested loop runs once per outer row, and PostgreSQL reports averages per execution so that the numbers can be compared directly with the estimate, which is also per execution. To get the total we multiply actual rows and actual time by loops. Forgetting this is the most common mistake when reading these plans.

Could the outer side be the problem instead?

Yes, in other plans. If the outer estimate were 100 rows but the actual were 10,000, the nested loop would run 100 times more often than planned. The method is the same: compare estimate and actual at each node, find the lowest node where they diverge, and fix the statistics for the columns involved there.

8Conclusion

In this answer, we read a nested loop plan whose inner index scan was estimated at 1 row per loop but returned 48 over 10,000 loops, which is 480,000 rows and almost all of the 9 seconds. We saw that the planner picked a nested loop because it believed the inner side was tiny, that a hash join would likely be faster for the real volume, and that the cause lies in the estimate. We then checked last_analyze and n_mod_since_analyze, refreshed statistics, considered skew and correlation with a higher statistics target or extended statistics, and proved the faster plan with SET LOCAL on a copy.

What to say in the interviewAbout 90 seconds aloud

Open with

The first thing I notice is the gap between estimate and actual on the inner index scan: the planner expected 1 row per loop and got 48. Actual rows on an inner node are per loop, and it ran 10,000 times, so it really produced 480,000 rows, which matches the nested loop's output, and 0.85 milliseconds per loop times 10,000 loops explains almost all of the 9 seconds.

Then, if they want more

So it is a 48x underestimate. The planner chose a nested loop because, with one row per order, 10,000 index lookups looked cheaper than reading the whole order_items table for a hash join. With 480,000 rows, a hash join that reads the table once would very likely be faster.

Next I would check whether statistics are stale: last_analyze and n_mod_since_analyze in pg_stat_user_tables, and n_distinct for order_id in pg_stats. If the table changed a lot, I run ANALYZE.

If the estimate is still wrong, I look for skewed values, like a few huge orders, and raise the column's statistics target, or for correlated filter columns, where I would add extended statistics.

To prove the hash join is faster, I would use SET LOCAL enable_nestloop = off inside a transaction on a replica or a copy and compare EXPLAIN ANALYZE with buffers. But the actual fix is the estimate, not the setting.

About this answer

Last updated
12 November 2026
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.
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: Nested Loop (actual time=0.05..9120.4 rows=480000 loops=1) with...": https://scrivio-interview-library.netlify.app/databases/query-optimization/a48f741307/