10774 - merge join vs. NESTED LOOP JOIN

i execute this query
SELECT soh.*
FROM Sales.SalesOrderHeader soh JOIN Sales.SalesOrderDetail sod
      ON soh.SalesOrderID = sod.SalesOrderID
in the execution plan see MERGE JOIN

when execute
SELECT soh.*
FROM Sales.SalesOrderHeader soh JOIN Sales.SalesOrderDetail sod
      ON soh.SalesOrderID = sod.SalesOrderID
WHERE soh.SalesOrderID = 71832
in the execution plan see NESTED LOOP JOIN

why?
enrique_aeoAsked:
Who is Participating?
 
PortletPaulfreelancerCommented:
first one has no filtering predicates (the MERGE JOIN)

the second has a filtering predicate that specifically limits the outer table (soh) to one row (the NESTED LOOP)

A nested loops join is particularly effective if the outer input is small and the inner input is preindexed and large. In many small transactions, such as those affecting only a small set of rows, index nested loops joins are superior to both merge joins and hash joins. In large queries, however, nested loops joins are often not the optimal choice.

There is no need to do matching of soh.SalesOrderID = sod.SalesOrderID on all possible values for the second query.

Matching of soh.SalesOrderID = sod.SalesOrderID on all possible is what the MERGE JOIN is used for in the first query.

if the data volume is large and the desired data can be obtained presorted from existing B-tree indexes, merge join is often the fastest available join algorithm.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.