Reputation: 1690
just to better understand in which cases index is correctly used i would like to enumerate possible cases.
let's assume we have a table with "a", "b", "c", "d" columns.
we create an index on (a, b, c, d):
create index my_index on table my_table (a, b, c, d)
is it used when:
1)
where a=% and b=% and c=% and d=%
2)
where a=% and b=%
3)
where a=%
4)
where b=% and c=% and d=%
5)
where c=% order by b
6)
where a=% and b=% and c=% order by case when d is not null then d else c end
7) let's assume now we have more column for the 7 point but the index only on (a, b, c, d)
where a=% and b=% and c=% and d=% and e=% and f=% and g=%
Upvotes: 0
Views: 59
Reputation: 1269443
MySQL has pretty good documentation explaining multi-column indexes. The rules are basically the same across databases (although there is some more advanced stuff).
Of course, there are other factors -- such as what is going on in the from
clause, what columns are being selected, statistics about the tables, and so on.
The following is basic guidance:
1) where a=% and b=% and c=% and d=%
Yes, as long as all the conditions are equality. I don't know what happens with collation conflicts.
2) where a=% and b=%
Yes, as long as all the conditions are equality. I don't know what happens with collation conflicts.
3) where a=%
Yes, as long as all the conditions are equality. I don't know what happens with collation conflicts.
4) where b=% and c=% and d=%
Probably not. If used, the index would need to be scanned. This would be the case if the index covered the query.
5) where c=% order by b
Probably not.
6) where a=% and b=% and c=% order by case when d is not null then d else c end
Should be used for the where
clause. A sort will still be needed.
Upvotes: 3