A
A
Andrey Pavlenko2016-04-30 19:22:12
MySQL
Andrey Pavlenko, 2016-04-30 19:22:12

Does the second index work after the first one?

I read quite a lot of techniques for optimizing queries using indexes. It turned out that before that my knowledge about indexes was quite fragmentary and inaccurate. But there was one factor I couldn't figure out clearly enough.
Imagine there is a table user with fields id, date, sex, name. We can create a complex index INDEX(date, sex).
In this regard, the first question
is whether the order of the conditions themselves in the query matters. That is, will there be a difference between
select * from user WHERE date='2016-03-03' AND sex='male' AND
select * from user WHERE sex='male' AND date='2016-03-03' ?
Or is MySQL smart enough to put everything in the correct order for the index itself?
And, actually, the second question. If you impose separate indexes on date and on sex. Yes, it will be less efficient than a complex index, but will both indexes be involved, or just the first one that is hit and the second one left out?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
terrier, 2016-04-30
@Akdmeh

There are several points here:
1). Yes, the order of enumeration of conditions in the request does not matter in this case
2). If the iindexes are separate, then the query planner can use both, BUT:
3). In this case, the index on sex has very poor selectivity ( www.akadia.com/services/ora_index_selectivity.html ), so I'd bet a bitten cucumber against a Portuguese escudo to use the index on date and sequentially scan whichever is selected
4). However, in order to finally clarify for yourself what is really used, you need to run explain and these questions will disappear (and new ones will appear :))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question