Here is the query:
SELECT * FROM table WHERE accountid = 1 ORDER BY logindate DESC LIMIT 1
Now if I added an index with multiple columns on the fields:
INDEX(accountid,logindate)
Would MySQL take advantage of this multiple column index? Or would it not use it because one field is in the where clause and the other is in an order statement? Or does it not matter as long as I use the fields in the order of the multiple column index?
Good question.
Indexes work left to right, so your
WHEREcriteria would use the index. The sort would also utilize the index in this case (execution plan below).From the manual:
If you had a single column index (
accountid), a filesort would be used instead. Therefore, your query does benefit from that index.Two Column Index
Execution Plan
Single Column Index
Execution Plan