欢迎投稿

今日深度:

分析SQL Server 给出的missing index建议

分析SQL Server 给出的missing index建议


测试基于SQL Server 2008 AdventureWorks2008,TablePerson.Person.表中已经存在的索引定义:

 

NONCLUSTERED INDEX [IX_Person_LastName_FirstName_MiddleName] [Person][Person]

[LastName]

[FirstName]

[MiddleName]

[PRIMARY]

 

 

我想根据FirstName查询LastName,执行后看执行计划:

  

可以看到SQL Server执行了Index Scan,虽然SQLServer没有以FirstName开头的索引。刚开始学习SQL Server的时候认为SQL Server只有filter的字段是索引的第一个字段时才可以使用索引。其实看过这个例子就知道,这个理解是不对的。因为之前在表上已经存在了LastName的索引,SQL Server引擎会知道索引中存在FirstName的字段,而且IndexPage页面的数量远远少于整张表Page的数量,所以用Index Scan是最快的方法,所以仍然会使用Index Scan.

  

回到SQL Server给出的Missing Index脚本:

 

[AdventureWorks2008]

CREATENONCLUSTEREDINDEX [ix1]

[Person][Person][FirstName]

 

可以看到SQL Server使用了Index Scan+Key Lookup,而且Key LookupCost占到了87%。解决KeyLookup的问题我们可以使用IncludeIndex,将这个字段包含到上面创建的索引中。索引修改后的代码:

 [AdventureWorks2008]

CREATENONCLUSTEREDINDEX [ix_firstname]

[Person][Person][FirstName]

includeLastName

 

重新运行看到SQL Server 选择了Index Seek

 这次的性能要比上次的好,使用下面的脚本可以证明:

 

 

LastName PersonPersonwhere FirstName


所以即使SQL Server给出的Missing Index也要最好分析之后进行使用。创建Index之后要关注Index的使用状况,比如Seek/Scan/Lookup/Update的比例,根据这些数据,进行相应的调整。因为对于更新多而查询非常少的案例,创建多的索引可能会在造成负担。

 

www.htsjk.Com true http://www.htsjk.com/shujukunews/308.html NewsArticle 分析SQL Server 给出的missing index建议 测试基于 SQL Server 2008AdventureWorks2008,TablePerson.Person. 表中已经存在的索引定义: NONCLUSTERED INDEX [IX_Person_LastName_FirstName_MiddleName] [Person] [Person] [LastName]...
相关文章
    暂无相关文章
评论暂时关闭