Learn SQL
-- performance.join_algorithms_nested_hash_merge

Join Algorithms: Nested Loop / Hash / Merge in SQL

Shape data + indexes so the planner can choose well

--concept

Nested loop: per-outer-row inner probe — best small/selective outer with indexed inner. Hash: build hash of one side, probe with other — best large equi-joins. Merge: co-scan two sorted inputs — best when indexes provide order. You do not pick directly; EXPLAIN reveals the choice. Missing indexes force nested loops over scans.

--how it works
1

Nested loop probes

Per-outer-row inner lookup — small selective outer + indexed inner.

2

Hash builds + probes

Hash smaller side, stream larger — big equi-joins without order.

3

Merge co-scans sorted

Both inputs ordered (indexes) — lockstep scan, no hash table.

4

Shape the choice

Index FKs, match types, fix estimates — planner picks from access, not hints.

--visualization
Hash JoinBuild smaller side, stream larger (big equi)
Stage 1 / 1
Index FKs + match types + fresh stats — planner picks from access.
--example
query.sql
1-- EXPLAIN shows: Nested Loop, Hash Join, or Merge Join
Result
algorithmbest case
nested loopsmall outer + indexed inner
hashlarge equi-joins
mergepre-sorted inputs

Same logical join, three physical shapes. Adding the FK index flips a painful nested-loop-over-scan into one hash build + probe.

--variants

Three shapes, one logic

EXPLAIN names the physics.

query.sql
1-- EXPLAIN: Nested Loop | Hash Join | Merge Join
Result
algorithmphysics
nestedprobes
hashbuild+probe
mergeco-scan
1Same JOIN text, different data/index shape.
2Missing FK index strands planner on loops-over-scans.
3Adding it unlocks hash/merge.

Index flips the plan

Access enables algorithms.

query.sql
1CREATE INDEX idx_emp_dept ON employees (department);
Result
stateplan
beforeloops over scans
afterhash build+probe
1Probe side indexed — loop viable for selective.
2Bulk equi-join prefers hash after stats.
3Sorted inputs would invite merge.
--key facts
Nestedselective probes
Hashbig equi build+probe
Mergesorted co-scan
--use cases
Join triage from EXPLAIN algorithm lines
Index justification with plan proof
--under the hood
Hash needs work_mem for the table — spills to disk past it; merge needs sort order, not memory.
Misestimates compound across joins — innermost wrong node misleads all above.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.