数据库如何决定使用哪个Index

RGI*_*RGI 3 performance index sql-server-2005 sql-server-2008 sql-server query-performance

数据线

create table t
(
    id int,
    id1 int
)

create index Example_Index
  On t(id,id1)

create index Example1_Index
  On t(id1,id)
Run Code Online (Sandbox Code Playgroud)

数据管理语言

insert into t(id, id1)values(1, 100)
insert into t(id, id1)values(1, 101)
insert into t(id, id1)values(2, 103)
insert into t(id, id1)values(1, 104)
insert into t(id, id1)values(3, 105)
insert into t(id, id1)values(1, 106)
insert into t(id, id1)values(2, 107)
insert into t(id, id1)values(3, 108)
Run Code Online (Sandbox Code Playgroud)

SQL查询- select * from t Where id = 107 -用途Example_Index

SQL查询- select * from t Where id1 = 107-用途Example1_Index

SQL查询- select * from t -用途Example1_Index

混乱- 系统如何决定使用Example1_Index

下面是详细...

在此处输入图片说明

Aar*_*and 11

前两个查询是不言自明的 - 它们在所选索引的前导列上执行查找。

第三个是硬币翻转,因为没有聚集索引,两个索引的成本相同。

可能会观察到最近使用的索引(来自查询 2)将用于查询 3 - 但您不应该依赖它。

  • @pst 不一定要。由于表上没有聚簇索引,并且索引包含表中的所有列,因此很可能也是一个表扫描的硬币翻转。但我敢打赌,优化器代码中有一些倾向于索引的东西。 (5认同)