Join Algorithms: Nested Loop / Hash / Merge in SQL
Shape data + indexes so the planner can choose well
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.
Nested loop probes
Per-outer-row inner lookup — small selective outer + indexed inner.
Hash builds + probes
Hash smaller side, stream larger — big equi-joins without order.
Merge co-scans sorted
Both inputs ordered (indexes) — lockstep scan, no hash table.
Shape the choice
Index FKs, match types, fix estimates — planner picks from access, not hints.
1-- EXPLAIN shows: Nested Loop, Hash Join, or Merge Join
| algorithm | best case |
|---|---|
| nested loop | small outer + indexed inner |
| hash | large equi-joins |
| merge | pre-sorted inputs |
Same logical join, three physical shapes. Adding the FK index flips a painful nested-loop-over-scan into one hash build + probe.
Three shapes, one logic
EXPLAIN names the physics.
1-- EXPLAIN: Nested Loop | Hash Join | Merge Join
| algorithm | physics |
|---|---|
| nested | probes |
| hash | build+probe |
| merge | co-scan |
Index flips the plan
Access enables algorithms.
1CREATE INDEX idx_emp_dept ON employees (department);
| state | plan |
|---|---|
| before | loops over scans |
| after | hash build+probe |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.