SQL Server – Difference Between Hash, Merge, and Loop Join

sql server

In SQL Server you can specify the join hints:

  • HASH JOIN
  • MERGE JOIN
  • LOOP JOIN

What is the definition of those three join hints, and when should each be used?

Best Answer

From MSDN, in the topic of Advanced Query Tuning Concepts:

SQL Server employs three types of join operations:

  • Nested loops joins

  • Merge joins

  • Hash joins

If one join input is small (fewer than 10 rows) and the other join input is fairly large and indexed on its join columns, an index nested loops join is the fastest join operation because they require the least I/O and the fewest comparisons. For more information about nested loops, see Understanding Nested Loops Joins.

If the two join inputs are not small but are sorted on their join column (for example, if they were obtained by scanning sorted indexes), a merge join is the fastest join operation. If both join inputs are large and the two inputs are of similar sizes, a merge join with prior sorting and a hash join offer similar performance. However, hash join operations are often much faster if the two input sizes differ significantly from each other. For more information, see Understanding Merge Joins.

Hash joins can efficiently process large, unsorted, non indexed inputs.

But I believe that you should start with a more basic topic: Query Tuning and lastly go to using the query hints.