Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 131/ 160
07. Indexing, Query Optimization & Performance Tuning

Join Algorithms Under the Hood (Nested Loop, Hash Join, Merge Join)

Recognize nested loop, hash, and merge joins and when planners pick each.

AdvancedNested Loop · Hash Join3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Reading it in EXPLAINQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1EXPLAIN (2  ANALYZE,3  BUFFERS4)5SELECT6  oi.id,7  p.name8FROM9  order_items AS oi10  JOIN products AS p ON p.id = oi.product_id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative plan fragment
Hash Join (actual rows=125000 loops=1) Hash Cond: (oi.product_id = p.id) -> Seq Scan on order_items oi -> Hash -> Seq Scan on products p

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Spotting a bad nested loop

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.

Key takeaway: Fix row estimates first; force algorithms only to diagnose.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Plan

Run EXPLAIN ANALYZE

Find the join node (Nested Loop, Hash Join or Merge Join) that consumes most of the time.

SQL at this stepReadable preview
1EXPLAIN (ANALYZE,2  BUFFERS)3SELECT …
What to watch at this step
Look for
slowest join node
Tip: use ← → to move between steps

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

Nested loop
Best for: Small outer input with an index on the inner join key; any join condition

Strengths: Fast start, minimal memory, works for inequalities.

Watch out: Disastrous when the outer side is large or the inner side has no index.

Hash join
Best for: Large, unsorted inputs joined on equality

Strengths: Roughly linear cost; no index needed.

Watch out: Needs memory for the hash table; equality joins only.

Merge join
Best for: Large inputs already sorted on the join key

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?
Interview tip: Describe each algorithm in one sentence with its best case, then talk about estimates: "the planner picks by estimated rows, so bad estimates mean bad joins". That's the insight senior interviewers are after.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Understanding Cost, Rows, Width, Buffers, Cache Hits & Disk Reads
Next topic
Table Statistics, Cardinality Estimation & ANALYZE / VACUUM