From: http://www.cnblogs.com/kerrycode/p/4806236.html
SQL Server 中什么情况会导致其执行计划从索引查找(Index Seek)变成索引扫描(Index Scan)呢? 下面从几个方面结合上下文具体场景做了下测试、总结、归纳。 1:隐式转换会导致执行计划从索引查找(Index Seek)变为索引扫描(Index Scan)
Implicit Conversion will cause index scan instead of index seek. While implicit conversions occur in SQL Server to allow data evaluations against different data types, they can introduce performance problems for specific data type conversions that result in an index scan occurring during the execution. Good design practices and code reviews can easily prevent implicit conversion issues from ever occurring in your design or workload.
如下示例,AdventureWorks2014数据库的HumanResources.Employee表,由于NationalIDNumber字段类型为NVARCHAR,下面SQL发生了隐式转换,导致其走索引扫描(Index Scan)
SELECT NationalIDNumber, LoginIDFROM HumanResources.EmployeeWHERE NationalIDNumber = 112457891
注意:并不是所有的隐式转换都会导致索引查找(Index Seek)变成索引扫描(Index Scan),Implicit Conversions that cause Index Scans 博客里面介绍了那些数据类型之间的隐式转换才会导致索引扫描(Index Scan)。如下图所示,在此不做过多介绍。
一般要尽量避免这种情况出现,如果可以的话,尽量对SQL进行逻辑转换(如下所示)。虽然这个例子看起来很简单,但是在实际中,还是见过许多这样的案例,就像很多人知道抽烟有害健康,但是就是戒不掉!很多人可能了解这个,但是在实际操作中还是一直会犯这个错误。道理就是如此! SELECT * FROM Person.Person WHERE BusinessEntityID < 250
2.3 LIKE模糊查询回导致索引扫描(Index Scan)
Like语句是否属于SARG取决于所使用的通配符的类型, LIKE 'Condition%' 就属于SARG、LIKE ’%Condition'就属于非SARG谓词操作
SELECT * FROM Person.Person WHERE LastName LIKE 'Ma%'
3:SQL查询返回数据页(Pages)达到了临界点(Tipping Point)会导致索引扫描(Index Scan)或表扫描(Table Scan)
What is the tipping point?
It's the point where the number of rows returned is "no longer selective enough". SQL Server chooses NOT to use the nonclustered index to look up the corresponding data rows and instead performs a table scan.
关于临界点(Tipping Point),我们下面先不纠结概念了,先从一个鲜活的例子开始吧:
SET NOCOUNT ON;DROP TABLE TESTCREATE TABLE TEST (OBJECT_ID INT, NAME VARCHAR(8));CREATE INDEX PK_TEST ON TEST(OBJECT_ID)DECLARE @Index INT =1;WHILE @Index