I am using the following query on a relatively large table (~20million rows):
SELECT
MAX(`col_1`)
FROM `table`
WHERE
col_2 = X AND
col_3 = Y AND
col_4 = Z
I have a combined index on the columns col_2, col_3 and col_4 and a separate one on col_1, but the query is still multiple orders of magnitude slower than the same query without the WHERE part.
How can I use indices to improve the performance on this?
As documented under How MySQL Uses Indexes:
Therefore, MySQL cannot use the simple index that you have defined on
col_1for findingMAX(col_1)when you are applying a filter: it must instead scan all matching rows (albeit it can do this in descending order ofcol_1by sorting upon that simple index), as would be shown by theEXPLAINoutput for your query.You should use an index on
(col_2, col_3, col_4, col_1).