Loop Joins, More rows on top or bottom?

I’ve seen this question come by in the web searches multiple times. The nested loop join is also called an iterative join. This is because it takes the rows from the inner part of the join and compares them through an iterative process (one-by-one) to the rows in the outer part of the join. So, if the optimizer has correctly chosen this operation for your query, you should see FEWER rows in the top, or outer, part of the join and MORE rows in the bottom, or inner, part of the join.

Take this query as an example (run against AdventureWorks2008):

SELECT *
FROM [Sales].[SalesOrderHeader] soh
JOIN [Sales].[SalesOrderDetail] sod
ON soh.[SalesOrderID] = sod.[SalesOrderID]
WHERE soh.[SalesOrderID] = 47716

Here we have a single row from the SalesOrderHeader table and 55 rows from the SalesOrderDetail table. Here’s the execution plan:

This is a classic loop join. Now, if you see a loop join that’s reversed, with more rows on top or one where the same number of rows are on both sides of the join, that’s worth checking out as a problem. It could be missing or incorrect indexes, or, more likely, bad or out of date statistics. Do a statistics update, maybe with a full scan to see if that fixes the problem.

Update: I forgot I recorded a little video on this too. It’s available over at JumpStartTV

Update #2: As was pointed out in the comments below, I had the outer & inner labels swapped. I’ve updated the text to reflect the correction.

3 thoughts on “Loop Joins, More rows on top or bottom?

  • Abram

    This is backwards. Outer table is on top, inner table is on bottom. Nested loop join takes the outer part and and compares to the inner part.

    For Each <— outer
    …For Each <– inner

    • scarydba

      You are right. I do have the labels inner & outer swapped. Sorry about that. As to which one should have fewer rows, the outer part of the operation, as you correctly point out, the top, should have fewer rows, as I said.

Please let me know what you think about this article or any questions:

This site uses Akismet to reduce spam. Learn how your comment data is processed.