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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PortletPaulEE Topic AdvisorCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.