Block nested loops join (code by Claude, guidance by Georgios Evangelidis)
To compute R ⋈R.a = S.b S with B buffer pages, read the outer relation a block of B − 2 pages at a time. For each block, scan the whole inner relation one page at a time and join every inner tuple with the tuples of the block; the last buffer page collects result tuples. The inner relation is scanned once per block instead of once per outer page or tuple, so the cost is M + ⌈M / (B − 2)⌉ · N page reads.
Blocks
| Block | Outer pages | Inner pages read | Comparisons | Result tuples |
|---|
Cost
Reading the diagram
Each tuple shows its join value and its id. A result tuple shows the joined value and the ids of the R and S tuples it combines.
Things to try
The starting example is a key–foreign key join: R.a is a key and every S.b references one R tuple, so the result has exactly one tuple per S tuple (16). With probing, each S tuple finds at most one match.
Raise B from 3 to 8 and watch the number of inner scans, and the cost, fall: with B − 2 ≥ M the whole outer relation fits in one block and each relation is read only once.
Swap the outer relation: the smaller relation should be the outer one, because the larger one is then scanned fewer times.
Switch to probing a hash table: the page reads stay the same, but the number of tuple comparisons drops sharply. Block nested loops saves I/O; the hash table saves CPU.