patternsqlModerate
How does the database decide which Index to use
Viewed 0 times
thedatabasedecidedoeshowwhichindexuse
Problem
DDL
DML
Sql Query -
Sql Query -
Sql Query -
Confusion - How does the system decides to use
Below are the details...
create table t
(
id int,
id1 int
)
create index Example_Index
On t(id,id1)
create index Example1_Index
On t(id1,id)DML
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)Sql Query -
select * from t Where id = 107 -- uses Example_IndexSql Query -
select * from t Where id1 = 107 -- uses Example1_IndexSql Query -
select * from t -- uses Example1_IndexConfusion - How does the system decides to use
Example1_IndexBelow are the details...
Solution
First two queries are self-explanatory - they're performing a seek on the leading column in the chosen index.
Third one is a coin-flip since, without a clustered index, both indexes have the same cost.
You might observe that the most recently-used index (from query 2) will be used for query 3 - but you shouldn't rely on it.
Third one is a coin-flip since, without a clustered index, both indexes have the same cost.
You might observe that the most recently-used index (from query 2) will be used for query 3 - but you shouldn't rely on it.
Context
StackExchange Database Administrators Q#21183, answer score: 11
Revisions (0)
No revisions yet.