Let R {\displaystyle R} and S {\displaystyle S} be relations where | R | < | S | {\displaystyle |R|<|S|} . R {\displaystyle R} fits in P r {\displaystyle P_{r}} pages memory and S {\displaystyle S} fits in P s {\displaystyle P_{s}} pages memory. In the worst case, a sort-merge join will run in O ( P r + P s ) {\displaystyle O(P_{r}+P_{s})} I/O operations. In the case that R {\displaystyle R} and S {\displaystyle S} are not ordered the worst case time cost will contain additional terms of sorting time: O ( P r + P s + P r log ( P r ) + P s log ( P s ) ) {\displaystyle O(P_{r}+P_{s}+P_{r}\log(P_{r})+P_{s}\log(P_{s}))} , which equals O ( P r log ( P r ) + P s log ( P s ) ) {\displaystyle O(P_{r}\log(P_{r})+P_{s}\log(P_{s}))} (as linearithmic terms outweigh the linear terms, see Big O notation – Orders of common functions).
For simplicity, the algorithm is described in the case of an inner join of two relations left and right. Generalization to other join types is straightforward. The output of the algorithm will contain only rows contained in the left and right relation and duplicates form a Cartesian product.
Since the comparison logic is not the central aspect of this algorithm, it is hidden behind a generic comparator and can also consist of several comparison criteria (e.g. multiple columns). The compare function should return if a row is less(-1), equal(0) or bigger(1) than another row:
Note that a relation in terms of this pseudocode supports some basic operations:
Note that this implementation assumes the join attributes are unique, i.e., there is no need to output multiple tuples for a given value of the key.
C# Implementations of Various Join Algorithms
"Sort-Merge Joins". www.dcs.ed.ac.uk. Retrieved 2022-11-02. https://www.dcs.ed.ac.uk/home/tz/phd/thesis/node20.htm ↩