SQL Server › Joins

How does SQL Server's query optimizer decide which physical join algorithm, such as nested loops, merge join, or hash join, to actually use for a given query?

Advanced

Answer

The optimizer considers the size of the tables involved, whether useful indexes exist on the join columns, and the estimated number of rows on each side, generally preferring nested loops for small result sets with good indexes, merge joins when both inputs are already sorted on the join column, and hash joins for large, unsorted data sets without helpful indexes.
-- View the chosen join algorithm in the execution plan
SET STATISTICS XML ON;
SELECT o.OrderId, c.Name FROM Orders o JOIN Customers c ON o.CustomerId = c.CustomerId;
Real-world example A database administrator examines an execution plan and notices a slow hash join is being used where a fast nested loop join would be more efficient, and adds a missing index that lets the optimizer choose the better join strategy.

Common follow-ups: How do you force the optimizer to use a specific join algorithm if needed?;What statistics does the optimizer rely on to make these join decisions?