Sort-merge join (code by Claude, guidance by Georgios Evangelidis)

To compute R ⋈R.a = S.b S, sort both relations on the join attribute, then scan them together. Pointer Tr walks R and Gs walks S; whichever points at the smaller value advances. When the values are equal, Gs marks the start of a partition of equal S values, and every R tuple with that value is joined with the whole partition, rewinding the scan pointer Ts to Gs for each one. If that partition has left memory, the rewind costs extra page reads.

Inputs
R.a values
S.b values
Random relations: R pages, S pages, values
Cost
Step 0 of 0
start
Phase – Sorting I/O 0 Merge reads 0 of which re-reads 0 Comparisons 0 Result tuples 0

Partitions

ValueR tuplesS tuplesS pagesResult tuplesS re-reads

Cost

Reading the diagram

TrCurrent R tuple
GsStart of the current S group (partition)
TsS tuple being scanned inside the partition
Values being compared
Tuples of the current matching partition
Pair just joined, and its result tuple
Page currently in a buffer

Things to try

The starting example is the textbook Sailors ⋈ Reserves on sid, with Sailors as R. Since sid is a key of Sailors, no R value repeats, Ts never has to rewind, and the merge reads exactly M + N pages.

Now choose “S.b is a key”: Reserves becomes R and Sailors S. Every repeated R value (two 28s, three 31s) rewinds Ts to Gs. Each group in S is a single tuple, but checking where it ends reads ahead into the next S page, so with B = 3 the rewind re-reads the evicted page: 2 re-reads. With B = 4 they disappear. For a key–foreign key join, let Tr walk the key relation.

“Many-to-many” adds a second sailor 31, giving a partition that spans two S pages: with B = 3 rewinding to it costs 2 re-reads, again none with B = 4.

Generate relations with values 1–4: partitions get large, re-reads multiply, and the merge phase moves away from M + N towards the worst case M · N.

Switch off sorting with already sorted inputs to see the merge phase cost on its own, exactly M + N when no partition outgrows memory.