Hash join (code by Claude, guidance by Georgios Evangelidis)
Grace hash join computes R ⋈R.a = S.b S in two phases. Partitioning: read each relation once and send every tuple to one of B − 1 partitions with a hash function h₁, using one input buffer and B − 1 output buffers. Tuples that can join land in partitions with the same number. Probing: for each partition i, load Rᵢ into memory, build a hash table on it with a different function h₂, then scan Sᵢ and look each tuple up in that table. Each relation is read twice and written once, so the cost is about 3(M + N).
Partitions
| Partition | Rᵢ pages | Sᵢ pages | Fits in B − 2? | Sᵢ scans | Result tuples |
|---|
Cost
Reading the diagram
h₁(k) = k mod (B − 1) picks the partition. h₂(k) = ⌊k / (B − 1)⌋ mod 4 picks a bucket inside the in-memory table; it must differ from h₁, because every tuple in a partition has the same h₁ value.
Things to try
Step through partitioning and watch tuples with the same value always land in the same partition number in R and in S, so partition i of R only ever needs to meet partition i of S.
The starting example is a key–foreign key join: R.a is a key, so every probe finds at most one match and the result has exactly one tuple per S tuple (16).
Lower B from 4 to 3: there are only 2 partitions, R1 and R2 get 3 and 4 pages but just 1 page fits in memory, so each Sᵢ is scanned once per chunk and the total jumps from 44 to 70 I/Os.
Generate skewed relations: one partition gets most of R and no longer fits in B − 2 pages. It is then processed in chunks, scanning Sᵢ once per chunk, and the cost rises above 3(M + N). A real system would partition it again recursively with another hash function.
Raise B: more partitions, each smaller, and the √M condition becomes easy to meet.