views:

58

answers:

2

If I submit a query to SQL Server 2005 which contains a number of LEFT JOIN clauses where the table joined to is then never referenced, will the joins still happen or is SQL Server intelligent enough to discard them?

Obviously it wouldn't be able to discard INNER JOINs [false assumption! see answers] as that would potentially change the result, but can it do it for LEFT JOINs?

+3  A: 

A left join could potentially multiply your result set if there are many matches.

So therefore it would still be evaluated.

Robin Day
Of course; I didn't think of that, thanks. If I added a DISTINCT - which may not be so bad as I am only selecting the primary key of one table - would it optimise the left joins out then?
kasey
The easiest way to find out is to try it. Look at the execution plan with and without your joins.
Robin Day
Thanks for the tip; looks like in my specific case, even without the DISTINCT, SQL Server is able to optimise out all the unwanted left joins. I guess it's able to deduce that there will never be multiple matches per join from existing constraints and unique indexes on the tables.
kasey
+3  A: 

It can discard both INNER and LEFT JOINs by inspecting the constraints. If you don't use a column in the table and there is a guaranteed single row existence by (FK) constraint, then the table does not need to be used. Obviously it depends on the query, it's possible that the table still gets used because it's the best plan.

This is yet another reason that constraints are tremendously useful and should be considered more frequently than they often are in designs.

Cade Roux
Thanks for the insight, I have edited the question to highlight my false assumption for future readers.
kasey