Sort-merge join

Sort-merge join

The Sort-Merge Join (also known as Merge-Join) is an example of a join algorithm and is used in the implementation of a relational database management system.

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 R and S and | R | < | S | . R fits in Pr pages memory and S fits in Ps pages memory. So, in the worst case Sort-Merge Join will run in O(Pr + Ps) I/Os. In the case that R and S are not ordered the worst case will be O(Pr + Ps + 2(Pr + Prlog(Pr) + Ps + Pslog(Ps))) (where the last two terms are the cost of ordering both of them first).

Pseudocode

For simplicity, the algorithm is described in the case of an inner join of two relations on a single attribute. Generalization to other join types, more relations and more keys is straightforward.

 function sortMerge(relation left, relation right, attribute a)
     var relation output
     var list left_sorted := sort(left, a)
     var list right_sorted := sort(right, a)
     var left_key
     var right_key
     var set left_subset
     var set right_subset
     advance(left_subset, left_sorted, left_key, a)
     advance(right_subset, right_sorted, right_key, a)
     while not empty(left_subset) and not empty(right_subset)
         if left_key = right_key
             add cross product of left_subset and right_subset to output
             advance(left_subset, left_sorted, left_key, a)
             advance(right_subset, right_sorted, right_key, a)
         else if left_key < right_key
            advance(left_subset, left_sorted, left_key, a)
         else // left_key > right_key
            advance(right_subset, right_sorted, right_key, a)
     return output
 function advance(subset, sorted, key, a)
     key = sorted[1].a
     subset = emptySet
     while not empty(sorted) and sorted[1].a = key
         insert(subset, sorted[1])
         remove first element from sorted

Simple C# Implementation

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.

 public class MergeJoin
    {
        // Assume that left and right are already sorted
        public static Relation Sort(Relation left, Relation right)
        {
            Relation output = new Relation();
            while (!left.IsPastEnd() && !right.IsPastEnd())
            {
                if (left.Key == right.Key)
                {
                    output.Add(left.Key);
                    left.Advance();
                    right.Advance();
                }
                else if (left.Key < right.Key)
                    left.Advance();
                else //(left.Key > right.Key)
                    right.Advance();
            }
            return output;
        }
    }
 
 public class Relation
    {
        private List<int> list;
        public const int ENDPOS = -1;
 
        public int position = 0;
        public int Position
        {
            get { return position; }
        }
 
        public int Key
        {
            get { return list[position]; }
        }
 
        public bool Advance()
        {
            if (position ==list.Count - 1 || position== ENDPOS)
            {
                position = ENDPOS;
                return false;
            }
            position++;
            return true;
        }
 
        public void Add(int key)
        {
            list.Add(key);
        }
 
        public bool IsPastEnd()
        {
            return position == ENDPOS;
        }
 
        public void Print()
        {
            foreach (int key in list)
                Console.WriteLine(key);
        }
 
        public Relation(List<int> list)
        {
            this.list = list;
        }
 
        public Relation()
        {
            this.list = new List<int>();
        }
    }

External links

C# Implementations of Various Join Algorithms [1]


Wikimedia Foundation. 2010.

Игры ⚽ Поможем решить контрольную работу

Look at other dictionaries:

  • Join (SQL) — An SQL join clause combines records from two or more tables in a database.[1] It creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values common to each. ANSI standard SQL… …   Wikipedia

  • join — Synonyms and related words: abut, abut on, accompany, accord, accouple, accumulate, act in concert, act together, act with, add, adhere, adjoin, affiliate, affiliate with, affix, agglomerate, agglutinate, aggregate, aggroup, agree, align with,… …   Moby Thesaurus

  • Joinalgorithmen — sind mögliche Strategien (Algorithmen) zur Implementierung von Joins. Die optimale Strategie hängt von Größe und Struktur der am Join beteiligten Relationen, verwendeten oder verwendbaren Indizes, der Größe des Hauptspeichers als auch der Join… …   Deutsch Wikipedia

  • Query optimizer — The query optimizer is the component of a database management system that attempts to determine the most efficient way to execute a query. The optimizer considers the possible query plans for a given input query, and attempts to determine which… …   Wikipedia

  • Алгоритм соединения слиянием сортированных списков — (merge join, sort merge join, sort merge join) разновидность алгоритма соединения. Алгоритм получает на вход 2 таблицы и условие соединения. Результатом его работы является таблица с результатами соединения. Входные таблицы должны быть… …   Википедия

  • Optimizador de consultas — Se ha sugerido que este artículo o sección sea fusionado con Optimización de consultas (discusión). Una vez que hayas realizado la fusión de artículos, pide la fusión de historiales aquí. El optimizador de consultas es el componente del sistema… …   Wikipedia Español

  • Query optimization — is a function of many relational database management systems in which multiple query plans for satisfying a query are examined and a good query plan is identified. This may or not be the absolute best strategy because there are many ways of doing …   Wikipedia

  • List of Unix utilities — This is a list of UNIX utilities as specified by IEEE Std 1003.1 2008, which is part of the Single UNIX Specification (SUS). These utilities can be found on UNIX Operating systems and most UNIX like operating systems. List IEEE Std 1003.1 2008… …   Wikipedia

  • SQL Server Integration Services — (SSIS) is a component of Microsoft SQL Server 2005 and 2008. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is available in the Standard ,… …   Wikipedia

  • France — /frans, frahns/; Fr. /frddahonns/, n. 1. Anatole /ann nann tawl /, (Jacques Anatole Thibault), 1844 1924, French novelist and essayist: Nobel prize 1921. 2. a republic in W Europe. 58,470,421; 212,736 sq. mi. (550,985 sq. km). Cap.: Paris. 3.… …   Universalium

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”