In one MySQL database table, I have the following index:
- type: BTREE
- unique: no
- packed: no
- fields: lastname, firstname, age
When I do a query like this …
SELECT firstname, lastname FROM table ORDER BY lastname ASC, firstname ASC, age DESC
… MySQL doesn’t use the index.
But when I use “age” in ascending order as well, it does:
SELECT firstname, lastname FROM table ORDER BY lastname ASC, firstname ASC, age ASC
Why is this so? Are columns always indexed for ascending-order only? Or can I use them all in descending order as well? Why can’t I use mixed orders?
Thanks in advance!
At this time (MySQL 5.6 and less) indexes are all implemented in ascending order.
If you mix the order (ASC vs DESC) in the ORDER clause, the index cannot be used beyond the point where the order changes.
If you specify all ASC, the index can be utilized fully, and if you specify all DESC, it can still be utilized fully, only MySQL will traverse the index backwards.
You could add another column that has the inverse age (max_age – age), and index on that instead, so that you can use ASC for all of the columns.