简体   繁体   English

查询优化程序比索引搜索更喜欢索引扫描

[英]Query optimizer prefers index scan over index seek

I am using AdventureWorks2012 database. 我正在使用AdventureWorks2012数据库。

I created the following index on Sales.SalesOrderHeader table 我在Sales.SalesOrderHeader表上创建了以下索引

create index i1 on 
sales.salesorderheader(purchaseordernumber,salespersonid)
   include(orderdate,shipdate)
   where purchaseordernumber is not null
   and salespersonid is not null

When I run the below query: 当我运行以下查询时:

select 
    PurchaseOrderNumber,
    OrderDate,
    ShipDate,
    SalesPErsonId

from sales.salesorderheader
where purchaseordernumber like '%po5%' and salespersonid is not null

I expect an Index seek not an index scan, as all of the columns which are part of the query are already part of the index. 我希望索引搜索不是索引扫描,因为作为查询一部分的所有列已经是索引的一部分。

I read somewhere that if the query optimizer feels that index scan is cheaper than index seek, then we will index scan. 我在某处读到,如果查询优化器认为索引扫描比索引查找便宜,那么我们将进行索引扫描。 But, I don't understand why it's happening in this case. 但是,我不明白为什么在这种情况下会发生这种情况。 We don't have a lookup at all. 我们根本没有查找。

Can someone explain me please. 有人可以解释一下吗。

An index works just like a phonebook. 索引就像电话簿一样工作。 Where would you look for %po5% in a phonebook? 您在哪里寻找电话簿中的%po5% You'd have to read the entire phonebook, because you don't know the first character. 您必须阅读整个电话簿,因为您不知道第一个字符。

That's why SQL Server scans the entire index. 这就是SQL Server扫描整个索引的原因。 It does not have enough information to seek. 没有足够的信息来寻找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM