The basic problem of a join algorithm is to find, for each distinct value of the join attribute, the set of tuples in each relation which display that value. The key idea of the Sort-merge algorithm is to first sort the relations by the join attribute, so that interleaved linear scans will encounter these sets at the same time.

In practice, the most expensive part of performing a sort-merge join is arranging for both inputs to the algorithm to be presented in sorted order. This can be achieved via an explicit sort operation (often an external sort), or by taking advantage of a pre-existing ordering in one or both of the join relations. The latter condition can occur because an input to the join might be produced by an index scan of a tree-based index, another merge join, or some other plan operator that happens to produce output sorted on an appropriate key.

Let's say that we have two relations and and . fits in pages memory and fits in pages memory. So, in the worst case Sort-Merge Join will run in I/Os. In the case that and are not ordered the worst case time cost will contain additional terms of sorting time: , which equals (as linearithmic terms outweigh the linear terms, see Big O notation – Orders of common functions).

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.

publicclassMergeJoin{// Assume that left and right are already sortedpublicstaticRelationSort(Relationleft,Relationright){Relationoutput=newRelation();while(!left.IsPastEnd()&&!right.IsPastEnd()){if(left.Key==right.Key){output.Add(left.Key);left.Advance();right.Advance();}elseif(left.Key<right.Key)left.Advance();else// if (left.Key > right.Key)right.Advance();}returnoutput;}}publicclassRelation{privateList<int>list;publicconstintENDPOS=-1;publicintposition=0;publicintPosition{get{returnposition;}}publicintKey{get{returnlist[position];}}publicboolAdvance(){if(position==list.Count-1||position==ENDPOS){position=ENDPOS;returnfalse;}position++;returntrue;}publicvoidAdd(intkey){list.Add(key);}publicboolIsPastEnd(){returnposition==ENDPOS;}publicvoidPrint(){foreach(intkeyinlist)Console.WriteLine(key);}publicRelation(List<int>list){this.list=list;}publicRelation(){this.list=newList<int>();}}