Full answer
Nested loop: for each row of the outer input, look up matching rows of the inner. Cost is roughly outer rows x cost of one lookup, so it shines for '10 orders and their customers by primary key' and degrades badly when the outer side is large and the inner has no index.
Hash join: build a hash table on the smaller input's join key, then scan the larger input and probe. Linear in both inputs; needs memory (work_mem in PostgreSQL) and spills to disk in batches if the table does not fit. Only equality joins.
Merge join: walk two inputs sorted by the join key in step, like merging two sorted lists. Good when both come sorted from indexes, or for very large inputs where sorting beats hashing.
SQLite's planner uses nested loops almost exclusively, relying on indexes and automatic temporary indexes; PostgreSQL and other server databases choose among all three. A bad row estimate commonly leads to a nested loop over far more rows than expected, which is a classic cause of sudden slowness. These are described behaviours, not run here.
Key points
- Nested loops: small outer, indexed inner
- Hash joins: large inputs, equality keys, memory
- Merge joins: sorted inputs
- SQLite mostly uses nested loops
- Bad estimates lead to bad join choices
Common mistakes
- Assuming one join algorithm is always best
- Ignoring work_mem when hash joins spill
Follow-ups
- How would you spot a nested loop over too many rows in EXPLAIN ANALYZE?
- What is an automatic index in SQLite?
Tips
- Tie each algorithm to input sizes