30.06.2013 Views

SQL Server Execution Plans - Red Gate Software

SQL Server Execution Plans - Red Gate Software

SQL Server Execution Plans - Red Gate Software

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5: Controlling <strong>Execution</strong> <strong>Plans</strong> with Hints<br />

It's using the clustered index for both queries now because the optimizer is not sure<br />

which of the values available in the table is most likely going to be passed in as @City.<br />

That means it samples the values in the statistics and chooses a generic plan based on an<br />

average value, from the sampled data.<br />

Let's make one more modification. In the second query, we instruct the optimizer to<br />

optimize for 'Mentor'.<br />

DECLARE @City NVARCHAR(30)<br />

SET @City = 'London'<br />

SELECT *<br />

FROM Person.Address<br />

WHERE City = @City<br />

SET @City = 'London'<br />

SELECT *<br />

FROM Person.Address<br />

WHERE City = @City<br />

OPTION ( OPTIMIZE FOR ( @City = 'Mentor' ) );<br />

Listing 5.23<br />

The value 'London' has a very low level of selectivity within the index (i.e. there are a lot<br />

of values equal to 'London'), and this is displayed by the Clustered Index Scan in the first<br />

query. Despite the fact that the second query looks up the same value, it's now the faster<br />

of the two queries for values other than those of 'London'. The OPTIMIZE FOR query<br />

hint was able to trick the optimizer into creating a plan that assumed that the data was<br />

highly selective, even though it was not. The execution plan created was one for the more<br />

selective value 'Mentor' and helps that execution, but hurts that of 'London'.<br />

Use of this hint requires intimate knowledge of the underlying data. Choosing the wrong<br />

value for OPTIMIZE FOR will not only fail to help performance, but could have a very<br />

serious negative impact. You could supply the hint for a value that doesn't represent the<br />

most frequently referenced data set, which would mean you've hurt performance instead<br />

of helping.<br />

203

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!