Scrivio Interview library
ConceptFoundations8 min read · updated 12 November 2026

Describe nested loop, hash and merge joins. For each, give the case where the planner is likely to pick it.

A nested loop join reads each outer row and probes the inner side for matches; the planner picks it when the outer side is small and the inner side has an index on the join column, and it is the only method that handles any join condition. A hash join builds a hash table on the smaller input and probes it with each row of the larger one; it is chosen for large, unsorted equality joins when the hash fits in memory. A merge join walks two inputs sorted on the join key in step; it is chosen when both are already sorted, for example by indexes, or when the result must be sorted anyway. MySQL added hash joins in 8.0.18; before that it used nested loop variants only.

Why this question is asked

Join algorithms are the part of a query plan we read most often when something is slow. A query that takes 2 milliseconds with a nested loop can take minutes with the same plan when an estimate is off by a factor of a thousand, and knowing what each algorithm costs tells us immediately whether the planner's choice makes sense. Interviewers ask this to check that we understand plans rather than just indexes. In this answer, we will recap what a join algorithm is, then walk through nested loop, hash and merge joins, how each works step by step, what it costs and when the planner chooses it, and finish with MySQL's history.

1A Quick Recap: SQL Says What, the Planner Decides How

A join in SQL only states which rows belong together, for example orders whose customer_id equals a customer's id. It does not say how to find them. The planner, the part of the database that turns SQL into an execution plan, chooses a join algorithm for each pair of inputs based on estimated row counts, available indexes, sort order and memory. In PostgreSQL's EXPLAIN output we see the choice as Nested Loop, Hash Join or Merge Join nodes, each with an outer (first) and an inner (second) child.

2Nested Loop Join

The nested loop is the simplest algorithm. For each row of the outer input, it searches the inner input for matching rows. If the inner side has an index on the join column, each search is a quick index lookup; without one, each search is a full scan of the inner input, which is only acceptable when that input is tiny.

Java
EXPLAIN ANALYZE
SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.id IN (101, 102, 103);
-- Nested Loop (actual rows=3 loops=1)
-- -> Index Scan using orders_pkey on orders o (actual rows=3 loops=1)
-- -> Index Scan using customers_pkey on customers c (actual rows=1 loops=3)
-- Index Cond: (id = o.customer_id)
-- Execution Time: 0.05 ms

Its cost is roughly the number of outer rows times the cost of one inner lookup. With 3 outer rows and an indexed inner side, that is almost nothing, and the nested loop has no startup cost, so it can return the first row immediately, which is great with LIMIT. The planner picks it when the outer side is small, typically after a selective filter, and the inner side has an index. It is also the only algorithm that supports any join condition, including ranges and inequalities, such as joining events to a time window with e.ts BETWEEN w.start_at AND w.end_at. Its danger is a wrong estimate: if the planner expected 3 outer rows and gets 3 million, it does 3 million lookups.

3Hash Join

A hash join works in two phases. In the build phase it reads the smaller input completely and puts each row into an in-memory hash table keyed by the join column. In the probe phase it reads the larger input once and, for each row, looks up the hash table to find matches. Each input is read only once.

Java
EXPLAIN ANALYZE
SELECT c.country, sum(o.total) FROM orders o JOIN customers c ON c.id = o.customer_id
GROUP BY c.country;
-- HashAggregate
-- -> Hash Join (actual rows=50000000 loops=1)
-- Hash Cond: (o.customer_id = c.id)
-- -> Seq Scan on orders o (actual rows=50000000 loops=1) <- probe side
-- -> Hash (actual rows=1000000 loops=1) Buckets: 1048576 Batches: 1 Memory Usage: 52000kB
-- -> Seq Scan on customers c (actual rows=1000000 loops=1) <- build side

Its cost is roughly reading both inputs once plus building the hash, which makes it the best choice for large joins where neither side is sorted and no small outer side would make index lookups cheap. There are two conditions. It only works for equality conditions, because a hash table can only find equal keys, not ranges. And the hash table must fit in memory: in PostgreSQL that is work_mem times hash_mem_multiplier; if it does not fit, the join splits into batches written to disk, shown as Batches greater than 1, and slows down. The build phase also means a startup cost before the first row comes out.

4Merge Join

A merge join needs both inputs sorted on the join key. It then walks through them side by side, like merging two sorted lists: compare the current keys, advance the side with the smaller key, and output pairs when the keys are equal. Each input is read once, in order.

Java
EXPLAIN
SELECT * FROM orders o JOIN order_items i ON i.order_id = o.id
WHERE o.id BETWEEN 1000000 AND 2000000;
-- Merge Join
-- Merge Cond: (o.id = i.order_id)
-- -> Index Scan using orders_pkey on orders o (already sorted by id)
-- -> Index Scan using order_items_order_id_idx on order_items i (already sorted by order_id)
Choosing a join algorithm
AlgorithmHow it worksPlanner picks it whenConditions
Nested loopProbe inner side for each outer rowOuter side small, inner side indexedAny condition
Hash joinBuild hash on smaller side, probe with largerLarge unsorted inputs, hash fits in memoryEquality only
Merge joinWalk two sorted inputs in stepBoth inputs already sorted, or sorted output usefulEquality (in PostgreSQL)

If both inputs come already sorted, from indexes or from an earlier sort step, a merge join is very cheap and uses almost no memory, and its output is sorted, which can save a later ORDER BY. If the planner has to sort large inputs first, the sorts usually make it more expensive than a hash join. In PostgreSQL, like the hash join, it needs an equality condition between the keys; only the nested loop handles arbitrary conditions. So we see it most for joins between large tables on indexed keys, such as orders and their items on the order id, or when the query also orders by the join key.

5MySQL's Join Algorithms

For many years MySQL had only nested loop joins: the index nested loop, which probes an index per row, and the block nested loop, which buffered rows of the outer side in a join buffer to scan the inner table fewer times when no index existed. MySQL 8.0.18 added the hash join for equality joins without a usable index, and from 8.0.20 the hash join replaced the block nested loop entirely. MySQL does not have a merge join in the PostgreSQL sense; when sorted access helps, it uses indexes within nested loops.

This history explains some advice that still circulates, for example that joins on unindexed columns are always disastrous in MySQL or that big reporting joins should be done in application code. On current versions, the hash join removes much of that pain, though an index on the join column is still the first thing to check for OLTP queries.

6Follow-up questions

How can you tell which side is the build side of a hash join in PostgreSQL?

In EXPLAIN, the inner child of a Hash Join is always a Hash node, and that is the build side; the other child is the probe side. The planner normally builds on the smaller input. If the Hash node shows far more rows than expected, or Batches above 1, the estimate was off or memory was too small, and that is usually where the time goes.

Can you force a particular join algorithm?

For diagnosis, yes: in a session, SET enable_nestloop = off, enable_hashjoin = off or enable_mergejoin = off makes the planner avoid that method, so we can compare plans and see whether the estimate or the algorithm is wrong. These settings should not be used permanently in application code; the lasting fix is usually better statistics, an index or a rewritten predicate. PostgreSQL has no built-in hints; the pg_hint_plan extension adds them. MySQL has optimizer hints for join methods, and which hint controls hash joins changed during the 8.0 series (BNL and NO_BNL in later releases), so check your version.

Why might the planner pick a nested loop over two big tables?

Usually because it thinks one side is small. A stale or misleading estimate, such as a filter on correlated columns estimated at 10 rows that really returns 500,000, makes the nested loop look cheap. Comparing estimated rows with actual rows in EXPLAIN ANALYZE shows this immediately, and refreshing statistics or adding extended statistics usually fixes it.

7Conclusion

In this answer, we saw that the nested loop probes the inner side once per outer row and suits a small outer side with an indexed inner side, handling any condition; that the hash join builds a hash table on the smaller input and probes it with the larger one, suiting large unsorted equality joins that fit in memory; and that the merge join walks two sorted inputs in step, suiting inputs already sorted by indexes. We also saw that MySQL relied on nested loop variants until it added hash joins in 8.0.18.

What to say in the interviewAbout 100 seconds aloud

Open with

There are three classic join algorithms. A nested loop takes each row from the outer side and looks for matches on the inner side. If the inner side has an index on the join column, each lookup is cheap, so the planner picks it when the outer side is small, say a few rows after a selective filter, and it can return rows immediately, which is good with LIMIT.

Then, if they want more

It is also the only one that handles any condition, like ranges or inequalities. Its weakness is a bad estimate: a million outer rows means a million lookups. A hash join reads the smaller input and builds an in-memory hash table on the join key, then reads the larger input once and probes the table.

It is the usual choice for large joins with no useful sort order, but it only works for equality, and the hash must fit in memory, work_mem times hash_mem_multiplier in PostgreSQL, or it spills to disk in batches. A merge join needs both inputs sorted on the key, then walks them together like merging two sorted lists.

It is chosen when both sides are already sorted, typically by indexes on the join keys, or when the output must be sorted anyway; if it must sort big inputs first, a hash join usually wins. In PostgreSQL merge joins also need an equality condition.

MySQL only had nested loop variants until 8.0.18 added hash joins, which then replaced the block nested loop in 8.0.20.

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 "Describe nested loop, hash and merge joins. For each, give the case where the planner is...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/dadce55f09/