SQL Server Query Optimizer and a trivial observation

This is a very short post on a trivial observation about SQL Server query optimizer. Look at the following query on AdventureWorksDW2012 database.

SELECT FinanceKey
,Amount
,DATE
FROM [dbo].[FactFinance] FF
INNER JOIN dbo.DimDate DD ON FF.DateKey = DD.DateKey
INNER JOIN dbo.DimOrganization DO ON FF.OrganizationKey = Do.OrganizationKey

And now look at the execution plan
Query Execution Plan

The joins to the dimension tables are missing. Now look at the query again. The optimizer was intelligent to recognize that the join would not have any effect on the final result set. We are not selecting anything from the dimension table neither there is a filtering condition. Hence the optimizer removed it from the plan altogether to make it more efficient.
Now lets add WHERE clause
SELECT FinanceKey
,Amount
,DATE
FROM [dbo].[FactFinance] FF
INNER JOIN dbo.DimDate DD ON FF.DateKey = DD.DateKey
INNER JOIN dbo.DimOrganization DO ON FF.OrganizationKey = Do.OrganizationKey
where DD.CalendarYear = 2005

and look at the execution plan. The WHERE clause adds a clustered index scan on DimDate but DimOrganization is still missing since nothing is selected or filtered on the table. Clever!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s