在SQL Server中使用Hints测试索引(Using Hints To Test Indexes in SQL Server)

from http://www.mssqltips.com/tip.asp?tip=2045

Using Hints To Test Indexes in SQL Server
Written By: Ken Simmons -- 6/24/2010 -- 1 comments -- print -- free stuff -- Bookmark and Share

Get the MSSQLTips Newsletter
We keep thousands of SQL Server professionals informed daily.
We respect your privacy and you can unsubscribe at any time.


Problem
When tuning indexes, it is somewhat difficult to tell how much impact the changes you have made will have on a query. Other than just looking at the different execution plans, is there an easy way to compare the queries using the old and new indexes? 

Solution
After making index changes, I always like to use hints to see how much impact the change has on a query. Let's take the following query that uses the AdventureWorks database as an example.

USE

 

AdventureWorks
GO

SELECT

NationalIDNumber
FROM
HumanResources.Employee
WHERE
Title = 'Stocker'

As you can see by the following execution plan, the query uses a clustered index scan to retrieve the information.

Since the query is searching by Title and returning the NationalIDNumber, you can create the following non-clustered index on Title and include the NationalIDNumber, so all of the information the query needs is located in the index. You should note that if you did not include the NationalIDNumber, the optimizer would still find it more optimal to scan the clustered index instead of seeking the non-clustered index and having to lookup the NationalIDNumber.

CREATE

INDEX ix_Title_Include
ON HumanResources.Employee(Title)
INCLUDE
(NationalIDNumber)

 

INDEX ix_Title_Include
ON HumanResources.Employee(Title)
INCLUDE
(NationalIDNumber)

INDEX ix_Title_Include
ON HumanResources.Employee(Title)
INCLUDE
(NationalIDNumber)

 

 

After creating the new index and rerunning the original query, you will now see that the query is performing an index seek on the new non-clustered index. That sounds good, but how much more efficient is it?

In order to answer that question, you can use a hint to force one of the queries to use the original index as shown in the following query.

SELECT

 

NationalIDNumber
FROM HumanResources.Employee
WITH (INDEX (PK_Employee_EmployeeID))
WHERE Title = 'Stocker'

SELECT

 

NationalIDNumber
FROM HumanResources.Employee
WHERE Title = 'Stocker'

You can now see that using the new index, the query cost is only 29% compared to the original index which is 71%. If you saw something like 50/50, you may want to rethink the new index, because it hasn't given you any performance and now you have an additional index to update and maintain.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值