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. function Sort-Merge Join(left: Relation, right: Relation, comparator: Comparator) { result = new Relation() // Ensure that at least one element is present if (!left.hasNext() || !right.hasNext()) { return result } // Sort left and right relation with comparator left.sort(comparator) right.sort(comparator) // Start Merge Join algorithm leftRow = left.next() rightRow = right.next() outerForeverLoop: while (true) { while (comparator.compare(leftRow, rightRow) != 0) { if (comparator.compare(leftRow, rightRow) 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: function compare(leftRow: RelationRow, rightRow: RelationRow): number { // Return -1 if leftRow is less than rightRow // Return 0 if leftRow is equal to rightRow // Return 1 if leftRow is greater than rightRow } Note that a relation in terms of this
pseudocode supports some basic operations: interface Relation { // Returns true if relation has a next row (otherwise false) hasNext(): boolean // Returns the next row of the relation (if any) next(): RelationRow // Sorts the relation with the given comparator sort(comparator: Comparator): void // Marks the current row index mark(): void // Restores the current row index to the marked row index restoreMark(): void } ==Simple C# implementation==