Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

Merge Join

Also Sort-Merge Join

The merge join computes an equi-join from the join-column values of both tables in sorted order, as (value, row index) pairs, by a Zipper merge that outputs all combinations of rows with equal values.

Formula#

Running time, given the already sorted sequences:

CM⋅(n1+n2+n)+CC⋅n⋅k,C_M \cdot (n_1 + n_2 + n) + C_C \cdot n \cdot k,

where nn and kk are the numbers of rows and columns of the result, CMC_M is the average cost of comparing or writing one element in the Zipper algorithm and CCC_C the average cost of copying one value to the result.

Simplified estimate for query planning (same as for the hash join, constants ignored):

cost∼n1+n2+min⁡(n1,n2)⋅k,rows∼min⁡(n1,n2),cols=k.\text{cost} \sim n_1 + n_2 + \min(n_1, n_2) \cdot k, \qquad \text{rows} \sim \min(n_1, n_2), \qquad \text{cols} = k.

The row estimate assumes each row of the smaller table has exactly one match in the larger one.

Properties#

  • Algorithm (two pointers pp in LXL_X, qq in LYL_Y): if xp<yqx_p < y_q advance pp; if xp>yqx_p > y_q advance qq; if xp=yq=vx_p = y_q = v, determine the runs of pairs with value vv in both lists, output all combinations of the two runs, and advance both pointers past their runs.
  • vs. hash join: asymptotically the same as the hash join CIn1+CLn2+CCnkC_I n_1 + C_L n_2 + C_C n k, but typically CM≪CIC_M \ll C_I and CM<CLC_M < C_L, so the merge join is faster, especially when both n1n_1 and n2n_2 are large. It needs sorted input, which the hash join does not.
  • Worst case: if all join values are equal, n=n1n2n = n_1 n_2 and the merge join is as expensive as the Cartesian Product.
  • Sorted input from indexes: scanning the linked leaves of an index B+ Tree yields all (value, row index) pairs in sorted order. With a B+ tree on both join columns this is exactly the input of the merge join.
  • SQLite3 performs neither merge nor hash joins: it iterates over one join column and looks up each value in an index on the other (built temporarily if none exists), even when both columns have a B+ tree (“an interesting design decision”). A typical RDBMS supports both merge and hash joins, and choosing between them is part of query planning.

Example#

lecture-05, PDF page 14
lecture-05, PDF page 14

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only