Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Explain nested loop, hash join and merge join. When does each one win?

A nested loop takes each outer row and looks up matching inner rows, and wins when the outer side is small and the inner side has an index on the join key. A hash join builds a hash table from the smaller input and probes it with the other, and wins for large unsorted inputs joined on equality, as long as the hash table fits in work_mem. A merge join walks two inputs already sorted on the key, and wins when both arrive sorted, for example from indexes, or for very large inputs. Hash and merge joins need equality conditions, nested loops handle any condition, and since the choice depends on row estimates, bad estimates lead to the wrong method.

Why this question is asked

Reading any non-trivial query plan means reading join nodes, and the most common cause of a slow join is that the planner chose the wrong method for the real data. Interviewers ask this to see whether we understand how each method works and what it costs, rather than just their names. In this answer, we will walk through each of the three methods with a small example and its cost, compare when each one wins, look at which join conditions each can handle, and see why everything depends on row estimates.

1A Quick Recap of Joining

A join combines rows from two inputs where a condition matches, such as orders o JOIN customers c ON c.id = o.customer_id. The database does not have one way to do this; it has three algorithms, and the planner picks one for each join in the plan based on how many rows it expects from each side, whether those rows are sorted, and what indexes exist. In a plan, the first child of a join node is called the outer input and the second the inner input.

2Nested Loop: One Lookup per Outer Row

A nested loop is the simplest method: for each row of the outer input, scan the inner input for matching rows. Without an index, that means reading the whole inner side once per outer row, which is only acceptable when both sides are tiny. With an index on the inner join key, each inner search is a quick index lookup.

Java
-- 50 orders from today, customers has an index on id
Nested Loop (actual rows=50 loops=1)
-> Index Scan using orders_created_at_idx on orders o (actual rows=50 loops=1)
-> Index Scan using customers_pkey on customers c (actual rows=1 loops=50)
Index Cond: (id = o.customer_id)

Notice loops=50 on the inner side: 50 index lookups of a few pages each, finished in a millisecond, and the first result row comes out immediately, which suits queries with LIMIT. The cost grows with outer rows times lookup cost, so with 2 million outer rows it would be 2 million random lookups, and that is when nested loops become the slow plan we see in incidents.

3Hash Join: Build Once, Probe Many Times

A hash join first reads the smaller input, called the build side, and puts each row into an in-memory hash table keyed on the join column. Then it reads the other input, the probe side, and for each row computes the hash of the join key and looks in the table for matches.

Java
-- join 5 million orders with 200,000 customers
Hash Join (actual rows=5000000 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (actual rows=5000000 loops=1)
-> Hash (Buckets: 262144 Batches: 1 Memory Usage: 14000kB)
-> Seq Scan on customers c (actual rows=200000 loops=1)

Each input is read once, in sequence, with no random index lookups, so the cost grows roughly with the sum of both sizes instead of their product. That is why hash joins win for large unsorted inputs. The limit is memory. The hash table must fit in work_mem (multiplied by hash_mem_multiplier in recent PostgreSQL versions); if it does not, the join splits into batches written to temporary files. Batches: 1 above means it fitted. A hash join also cannot return any row before the whole build side is read.

4Merge Join: Walking Two Sorted Lists

A merge join needs both inputs sorted on the join key. It then walks them side by side like merging two sorted lists: compare the current keys, advance the side with the smaller key, and output a match when they are equal.

Java
-- both tables read in id order from their indexes
Merge Join (actual rows=5000000 loops=1)
Merge Cond: (o.customer_id = c.id)
-> Index Scan using orders_customer_id_idx on orders o
-> Index Scan using customers_pkey on customers c
When each join method wins
MethodHow it worksWins whenWeak when
Nested looplookup inner rows for each outer rowsmall outer side, index on inner keymany outer rows
Hash joinhash the smaller side, probe with the otherlarge unsorted inputs, equality joinbuild side exceeds work_mem
Merge joinwalk two sorted inputs togetherinputs already sorted, very large inputsinputs need expensive sorts

If the inputs already arrive sorted, from an index or from an earlier sort, the merge itself is very cheap and needs almost no memory. If they must be sorted first, the sorts can dominate the cost. Merge joins therefore win when sorted order comes for free, when the result must be ordered by the join key anyway, or for very large inputs where a hash table would spill far beyond memory.

5Which Conditions Each Method Can Handle

Hash and merge joins only work for equality conditions. A hash table can find rows with exactly the same key, and a merge walk relies on matching equal keys in sorted order. A condition like o.created_at BETWEEN p.start_date AND p.end_date, or o.amount > c.credit_limit, cannot be hashed or merged. A nested loop handles any condition at all, because it simply evaluates the condition for each pair it considers. So for range joins and inequality joins, the nested loop is often the only option, and an index that supports the range on the inner side becomes essential.

6Why Row Estimates Decide Everything

The planner chooses among the methods by estimated cost, and the costs depend almost entirely on the estimated row counts of each input. If it thinks the outer side has 10 rows, a nested loop with 10 index lookups looks unbeatable. If the real number is 2 million, that same plan does 2 million lookups and takes minutes, while a hash join would have taken seconds. The reverse mistake, estimating millions when the reality is a handful, makes the planner build a big hash table for nothing.

This is why, when a join is slow, we first compare estimated and actual rows on its inputs in EXPLAIN ANALYZE. A large gap there explains the wrong method, and the fix is usually in the statistics, not in the join.

7Follow-up questions

What happens when a hash join's table does not fit in work_mem?

PostgreSQL splits the work into batches. It partitions both inputs by hash value, keeps one batch of the build side in memory and writes the others to temporary files, then processes the batches one at a time. The plan shows Batches greater than 1 and temp reads and writes in BUFFERS. The join still works but becomes much slower because of the extra I/O. Raising work_mem or hash_mem_multiplier for that query, or reducing the build side by filtering earlier, brings it back to one batch.

Why does a nested loop suit queries with LIMIT?

Because it produces its first matching row almost immediately and the plan can stop as soon as enough rows have been returned. A hash join must read its entire build side before it outputs anything, so for LIMIT 10 the nested loop often has a much lower startup cost.

Does MySQL have all three methods?

MySQL has long used nested loop joins, including variants that use index lookups and buffers. Since MySQL 8.0.18 it also has hash joins for equality conditions, which replaced the older block nested loop. It does not have a separate merge join method like PostgreSQL's.

8Conclusion

In this answer, we saw that a nested loop looks up inner rows for every outer row and wins with a small outer side and an indexed inner key, a hash join builds a hash table on the smaller input and probes it, winning for large unsorted equality joins within work_mem, and a merge join walks two sorted inputs, winning when sorted order comes for free or inputs are very large. Hash and merge joins need equality conditions while nested loops handle any condition, and since the choice rests on row estimates, wrong estimates lead to the wrong method.

What to say in the interviewAbout 100 seconds aloud

Open with

There are three methods. A nested loop takes each row from the outer side and looks for matches on the inner side, ideally through an index on the join key.

Then, if they want more

It is the best choice when the outer side is small, say 50 orders from today, because that is 50 quick index lookups and the first row comes out immediately. It gets slow when the outer side is large, because the work is outer rows times lookups.

A hash join reads the smaller input, builds a hash table on the join key, then reads the other input once and probes the table. Both inputs are read once, sequentially, so it wins for large unsorted inputs, as long as the hash table fits in work_mem; otherwise it spills into batches on disk.

A merge join needs both inputs sorted on the key and walks them together like merging sorted lists. It wins when the order comes for free from indexes, or for very large inputs where a hash table would not fit, and it uses little memory.

Hash and merge joins only work with equality conditions, while a nested loop can handle any condition, like a range join on dates.

The planner chooses by estimated cost, which depends on estimated row counts, so if it thinks the outer side has 10 rows and it really has 2 million, it will pick a nested loop that runs for minutes. That is why I check estimates first when a join is slow.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.0
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 nested loop, hash join and merge join. When does each one win?": https://scrivio-interview-library.netlify.app/databases/query-optimization/710518f616/