Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Order of Joins

$
0
0

hello guys,
can anybody explain me what is the order of joins when INNER and LEFT joins are combined in one FROM section? here is an example of what I mean:

SELECT      mo.ProductId
                ,pd.TextDescription            
FROM        MyOrders             mo
LEFT JOIN   Product              p
   ON mo.ProductId = p.ProductId            
INNER JOIN  ProductDescription   pd               
   ON p.ProductId = pd.ProductId;

MyOrders table can have products missing in the Product and as a result in the ProductDetails tables (optional foreign key). At the same time, each product from the Product table has a matching description in the ProductDescription table (mandatory foreign key).

I can see two ways of how this sql can be executed:
   1. join Product and ProductDescription tables first and then join the result to MyOrders.
      in this case we get ALL records from the MyOrders table, product description may be missing;
   2. - join MyOrders and Product tables first and join the result to the ProductDescription table.
      in this case we get ONLY THOSE MyOrders records that have matching descriptions;

I heard that the optimizer itself chooses the way to perform joins (it may depend on indexes, statistics etc...) In this case the results may be different for my query with the same initial data... Do I have to define the join order that I want by hints, or there is only one way for the server to execute the query and I'm missing smth?

Thanks in advance!

- BorkaS

   

Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>