Leftmost matching principle on SQL Server indexes

Recently, some friends talking about the left-most matching principle SQL Server indexes, understood as a problem writing order in T-SQL Where condition in the exchange group, this is a misunderstanding.

Look under the following experimental results.

1  , prepare data.

CREATE TABLE [dbo].[t6](

    [id] [int] IDENTITY(1,1) NOT NULL,

    [hour] [int] NULL,

    [ordernumber] [int] NULL,

 CONSTRAINT [PK_t6] PRIMARY KEY CLUSTERED ( [id] ASC )  ON [PRIMARY]

) ON [PRIMARY]

GO

 

insert into t6 values(default,default)

-  Repeat the following statement, generating record 10 + M

insert into t6 select id, hour  from t6

 

update t6 set

    hour=id % convert(int,300000*RAND()+2), ordernumber=id % convert(int,3000*RAND()+2)

2  , create an index 1. http://u48582907.b2bname.com/

create index fhsy1 on t6(hour, ordernumber)

3  , see the two fields are the equivalent query execution plan.

select hour,ordernumber from t6 where hour=1 and ordernumber=1

select hour,ordernumber from t6 where ordernumber=1 and hour=1

bb

bb

4  , creating an index 2.

create index fhsy1 on t6(ordernumber, hour)

5 、再次查看执行计划。

bb

bb

6 、再看一下一个字段为等值,另一个字段为范围查询的执行计划。

select hour,ordernumber from t6 where hour=1 and ordernumber between 1 and 2

select hour,ordernumber from t6 where ordernumber between 1 and 2 and hour=1

bb

bb

select hour,ordernumber from t6 where ordernumber=1 and hour between 1 and 2

select hour,ordernumber from t6 where hour between 1 and 2 and ordernumber=1

 bb

bb

结论

1 、索引的最左匹配,是指的检索条件与索引字段的关系,与在T-SQL语句中Where条件中的书写顺序无关。

索引与搜索条件的书写顺序有关,这在上世纪可能还有可能;现在的数据库引擎的智能化程序,应该可以通过智能优化或语句改写,实现顺序无关。这一点都做不到,这个数据库离淘汰就不远了。郑州不孕不育医院:http://yyk.39.net/zz3/zonghe/1d427.html

2 、从Cost来看,索引总是匹配等值检索字段在前的复合索引,这就是被称为 最左匹配原则 的原因。

3  , the leftmost matching index execution plan, is Index Seek / Scan, which is to be positioned by the equivalent condition, then scanning range by varying conditions. In general, the implementation of this plan is superior Index Scan, that is, the entire index scans.

doubt

In the equivalent query, CBO will automatically select a minimum execution plan Cost, index 1 and index 2 equivalent to final execution plan selection index index 2 instead of 1, for unknown reasons. And the height of the tree should be indexed, statistical information. Of unknown origin.


Guess you like

Origin blog.51cto.com/14510351/2438343