HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

How does the database decide which Index to use

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thedatabasedecidedoeshowwhichindexuse

Problem

DDL

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_Index

Sql Query - select * from t Where id1 = 107 -- uses Example1_Index

Sql Query - select * from t -- uses Example1_Index

Confusion - How does the system decides to use Example1_Index

Below 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.

Context

StackExchange Database Administrators Q#21183, answer score: 11

Revisions (0)

No revisions yet.