Join Algorithms Under the Hood (Nested Loop, Hash Join, Merge Join)
Recognize nested loop, hash, and merge joins and when planners pick each.
In plain words
The database has three ways to match rows from two tables: look each one up, sort them into buckets, or line both up in order and walk through them together.
Think of it like…
Matching guests to tables at a wedding. Nested loop: for each guest, look their name up in the seating chart's index. Hash join: put every table's guest list into labelled boxes, then drop each guest into their box. Merge join: line up both the guest list and the seating chart alphabetically and walk down both together.
Where you’ve seen it
Joining 20 recent orders to customers uses a nested loop with an index lookup per order (microseconds). Joining 50 million order lines to 2 million products for a nightly report uses a hash join. If the planner wrongly expects 20 rows and gets 2 million, it may still pick a nested loop and run for an hour.
Words you’ll hear
- Outer / inner (probe / build)
- The two sides of a join; which is which affects the cost.
- Nested loop
- For each outer row, find inner matches (ideally via an index). Supports any join condition.
- Hash join
- Hash the smaller input, probe with the larger. Equality conditions only; needs memory.
- Merge join
- Both inputs sorted on the key, scanned together. Good for large pre-sorted inputs.
Visual diagram
Theory & example queries
How each algorithm works
Nested loop: for every row of the outer input, find matching rows in the inner input. With an index on the inner join column, each lookup is a few page reads, so it's ideal when the outer side is small. Without an index, every outer row scans the inner table, which is quadratic and becomes disastrous on big tables. It's the only algorithm that handles any join condition, including ranges and inequalities.
Hash join: read the smaller input, build an in-memory hash table on the join key, then stream the larger input and look each row up. The cost is roughly linear in both sizes, but it needs memory (work_mem in PostgreSQL) and only works for equality joins. Merge join: if both inputs are sorted on the join key (from indexes or an explicit sort), walk them in parallel like merging two sorted lists. It's efficient for large inputs, especially when the sort order is free.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
EXPLAIN ( ANALYZE, BUFFERS)SELECT oi.id, p.nameFROM order_items AS oi JOIN products AS p ON p.id = oi.product_id;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative plan fragment
Note: The exact costs, timings and scan choices depend on the database version, statistics, indexes and data volume. Read the node that performs the join and then compare estimated versus actual rows.
A plan with Hash Join (Hash Cond: (oi.product_id = p.id)) means products, the smaller side, is hashed and order_items probes it. A different row estimate or index can produce a nested loop or merge join.
Key takeaway: Nested loop for small + indexed, hash for big equality joins, merge for big sorted inputs.
Why the planner picks badly, and what to do
The planner estimates how many rows each side will produce and prices each algorithm accordingly. If it underestimates (stale statistics, correlated filters, a function in the WHERE), it may choose a nested loop for what is actually millions of rows. The symptom in EXPLAIN ANALYZE is a nested loop whose actual loops count is far above the estimate.
Fix the estimate rather than forcing the algorithm: run ANALYZE, raise the statistics target on skewed columns, create extended statistics for correlated columns, or rewrite a non-SARGable condition. Settings like enable_nestloop = off are useful for diagnosis, not production. A hash join spilling to disk (Batches: 16 in EXPLAIN) can be fixed with more work_mem for that query.
Nested Loop (rows=12) (actual rows=1830442 loops=1) → inner Index Scan … (actual loops=1830442): the planner expected 12 outer rows and got 1.8 million. Refresh statistics and check the filters feeding it.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Run EXPLAIN ANALYZE
Find the join node (Nested Loop, Hash Join or Merge Join) that consumes most of the time.
EXPLAIN (ANALYZE, BUFFERS)SELECT …When to use it & trade-offs
What it is
Databases physically execute joins with three main algorithms. A nested loop looks up matching inner rows for each outer row, which is fast when the outer side is small and the inner side has an index. A hash join builds a hash table from the smaller input and probes it with the larger one, which suits big unsorted equality joins. A merge join walks two inputs already sorted on the join key in step.
Why it matters: When a join is slow, EXPLAIN tells you which algorithm the planner picked, and a bad choice (usually caused by wrong row estimates) is a common root cause. Senior backend and database interviews ask how each works and when each wins.
When to reach for it
- Diagnosing slow joins from EXPLAIN output
- Explaining why an index made a join fast
- Senior-level database interview questions
When to avoid or be careful
- Disabling join algorithms globally to "fix" one query
- Assuming a hash join is always best for large tables
- Ignoring wrong row estimates in favour of rewriting the SQL
Nested loop vs hash join vs merge join
Strengths: Fast start, minimal memory, works for inequalities.
Watch out: Disastrous when the outer side is large or the inner side has no index.
Strengths: Roughly linear cost; no index needed.
Watch out: Needs memory for the hash table; equality joins only.
Strengths: Streams both inputs; no hash table.
Watch out: Sorting unsorted inputs first can be expensive.
Interview signals & numbers to know
When this topic comes up
- “Why is this join slow?”
- “Explain hash join vs nested loop”
- Nested Loop with a huge loops count
- Hash join batches spilling to disk
- Query planner behaviour
Benchmarks & rules of thumb
- 3
- main join algorithms
- O(n × m)
- nested loop without an index
- MySQL 8.0.18
- first version with hash joins
Common mistakes & follow-ups
Common interview mistakes
- Assuming the SQL text decides the algorithm; the planner chooses it from estimates.
- Missing an index on the inner side of a nested loop, so every outer row scans the whole inner table.
- Setting enable_nestloop = off globally and making many other queries slower.
Likely interviewer follow-ups
- When would the planner choose a nested loop over a hash join?
- Why can't a hash join handle a condition like a.ts BETWEEN b.start AND b.end?
- The planner picked a nested loop and the query takes minutes. How do you investigate?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Join Algorithms Under the Hood (Nested Loop, Hash Join, Merge Join) with hands-on SQL practice and interview Q&A.