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.

R.a values
S.b values
Random relations: R pages, S pages, values
Cost
Step 0 of 0
start
Block 0 Page reads 0 Result pages 0 Tuple comparisons 0 Result tuples 0 Formula predicts 0

Blocks

BlockOuter pagesInner pages readComparisonsResult tuples

Cost

Reading the diagram

Outer page; each row on the left is one block of B − 2 pages
Inner page; faded once scanned for the current block
Tuples compared with the current inner tuple
Matching tuples, joined into the output buffer
Current inner tuple, or page just read or written

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.