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, loginid from humanresources.employee where nationalidnumber = 112457891
我们可以通过两种方式避免sql做隐式转换:
1:确保比较的两者具有相同的数据类型。
2:使用强制转换(explicit conversion)方式。
我们通过确保比较的两者数据类型相同后,就可以让sql走索引查找(index seek),如下所示
select nationalidnumber, loginid from humanresources.employee where nationalidnumber = n'112457891'
注意:并不是所有的隐式转换都会导致索引查找(index seek)变成索引扫描(index scan),implicit conversions that cause index scans 博客里面介绍了那些数据类型之间的隐式转换才会导致索引扫描(index scan)。如下图所示,在此不做过多介绍。
避免隐式转换的一些措施与方法
1:良好的设计和代码规范(前期)
2:对发布脚本进行rreview(中期)
3:通过脚本查询隐式转换的sql(后期)
下面是在数据库从执行计划中搜索隐式转换的sql语句
set transaction isolation level read uncommitted declare @dbname sysname set @dbname = quotename(db_name()); with xmlnamespaces (default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') select stmt.value('(@statementtext)[1]', 'varchar(max)'), t.value('(scalaroperator/identifier/columnreference/@schema)[1]', 'varchar(128)'), t.value('(scalaroperator/identifier/columnreference/@table)[1]', 'varchar(128)'), t.value('(scalaroperator/identifier/columnreference/@column)[1]', 'varchar(128)'), ic.data_type as convertfrom, ic.character_maximum_length as convertfromlength, t.value('(@datatype)[1]', 'varchar(128)') as convertto, t.value('(@length)[1]', 'int') as converttolength, query_plan from sys.dm_exec_cached_plans as cp cross apply sys.dm_exec_query_plan(plan_handle) as qp cross apply query_plan.nodes('/showplanxml/batchsequence/batch/statements/stmtsimple') as batch(stmt) cross apply stmt.nodes('.//convert[@implicit="1"]') as n(t) join information_schema.columns as ic on quotename(ic.table_schema) = t.value('(scalaroperator/identifier/columnreference/@schema)[1]', 'varchar(128)') and quotename(ic.table_name) = t.value('(scalaroperator/identifier/columnreference/@table)[1]', 'varchar(128)') and ic.column_name = t.value('(scalaroperator/identifier/columnreference/@column)[1]', 'varchar(128)') where t.exist('scalaroperator/identifier/columnreference[@database=sql:variable("@dbname")][@schema!="[sys]"]') = 1
2:非sarg谓词会导致执行计划从索引查找(index seek)变为索引扫描(index scan)
sarg(searchable arguments)又叫查询参数, 它的定义:用于限制搜索的一个操作,因为它通常是指一个特定的匹配,一个值的范围内的匹配或者两个以上条件的and连接。不满足sarg形式的语句最典型的情况就是包括非操作符的语句,如:not、!=、<>;、!<;、!>;not exists、not in、not like等,另外还有像在谓词使用函数、谓词进行运算等。
2.1:索引字段使用函数会导致索引扫描(index scan)
select nationalidnumber, loginid from humanresources.employee where substring(nationalidnumber,1,3) = '112'
2.2索引字段进行运算会导致索引扫描(index scan)
对索引字段字段进行运算会导致执行计划从索引查找(index seek)变成索引扫描(index scan):
select * from person.person where businessentityid + 10 < 260
一般要尽量避免这种情况出现,如果可以的话,尽量对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%'
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 test create table test (object_id int, name varchar(8)); create index pk_test on test(object_id) declare @index int =1; while @index <= 10000 begin insert into test select @index, 'kerry'; set @index = @index +1; end update statistics test with fullscan; select * from test where object_id= 1
如上所示,当我们查询object_id=1的数据时,优化器使用索引查找(index seek)
上面object_id=1的数据只有一条,如果object_id=1的数据达到全表总数据量的20%会怎么样? 我们可以手工更新2001条数据。此时sql的执行计划变成全表扫描(table scan)了。
update test set object_id =1 where object_id<=2000; update statistics test with fullscan; select * from test where object_id= 1
临界点决定了sql server是使用书签查找还是全表/索引扫描。这也意味着临界点只与非覆盖、非聚集索引有关(重点)。
why is the tipping point interesting?
it shows that narrow (non-covering) nonclustered indexes have fewer uses than often expected (just because a query has a column in the where clause doesn’t mean that sql server’s going to use that index)
it happens at a point that’s typically much earlier than expected… and, in fact, sometimes this is a very bad thing!
only nonclustered indexes that do not cover a query have a tipping point. covering indexes don’t have this same issue (which further proves why they’re so important for performance tuning)
you might find larger tables/queries performing table scans when in fact, it might be better to use a nonclustered index. how do you know, how do you test, how do you hint and/or force… and, is that a good thing?
4:统计信息缺失或不正确会导致索引扫描(index scan)
统计信息缺失或不正确,很容易导致索引查找(index seek)变成索引扫描(index scan)。 这个倒是很容易理解,但是构造这样的案例比较难,一时没有想到,在此略过。
5:谓词不是联合索引的第一列会导致索引扫描(index scan)
select * into sales.salesorderdetail_tmp from sales.salesorderdetail;
create index pk_salesorderdetail_tmp on sales.salesorderdetail_tmp(salesorderid, salesorderdetailid);
update statistics sales.salesorderdetail_tmp with fullscan;
下面这个sql语句得到的结果是一致的,但是第二个sql语句由于谓词不是联合索引第一列,导致索引扫描
select * from sales.salesorderdetail_tmp where salesorderid=43659 and salesorderdetailid<10
select * from sales.salesorderdetail_tmp where salesorderdetailid<10