非聚集索引列顺序

Man*_*jot 7 sql-server-2008 sql-server nonclustered-index

我有一个表的非聚集索引(称为NCIDX1col1, col2。我col3, col4, col5, col6按此顺序包含作为包含的列。

如果我运行以下查询:

select 
     col1,col2 
from 
     tbl1
where 
     col3 = something
and
     col4 = something
and
     col5 = something
Run Code Online (Sandbox Code Playgroud)

它与运行有什么不同:

select 
     col3,col2 ,col4
from 
     tbl1
where 
     col1 = something
and
     col5 = something
Run Code Online (Sandbox Code Playgroud)

?

我想说的是,当我们创建一个像上面那样的覆盖索引,并且我们改变我们访问数据的顺序时,它还会利用这个覆盖索引吗?

此外,相等列(在它们之间)和非相等列(在它们之间)的顺序......有关系吗?喜欢where equalitycol2='' and equalitycol1=''

gbn*_*gbn 8

一般来说,一个索引应该在

(equalitycol1, equalitycol2, ..., nonequalitycol1, , nonequalitycol2, ...)
INCLUDE
(outputonlycol1, outputonlycol2, ...)
Run Code Online (Sandbox Code Playgroud)

简单地(忽略范围)这分解为

  • equalitycol: WHERE equalitycol = something。最有选择性的第一。可搜索的。寻求。
  • nonequalitycol: WHERE nonequalitycol <> something。残留过滤器
  • outputonlycol: SELECT outputonlycol. 没有过滤或排序

ORDER BYGROUP BY列将是相等或不相等的列。

在这种情况下...

查询 1 根本不匹配索引,真的,所以很可能不会使用索引。但是,优化器可能会决定使用索引比使用其他表访问(例如表扫描或 RID/书签查找)更便宜。

对于查询 2,优化器可能决定使用索引,因为col1它将是一个相等匹配。然后用无序col5INCLUDE。YMMV,但有更高的机会。

对于WHERE子句顺序,不:优化器会解决它。两个索引(col1, col2)(col2, col1)是不同的。Note(col1, col2)将包含在其中,(col1, col2, col3, col4)因此不需要第一个。