I have a simple query - it only looks at one table and has a choice of 2 columns for indexing, an ErrorTypeId (points to a lookup table of about 20 unique values) and DateOccurred (a datetime column that could have any date in it).
In most cases it is fine but under certain scenarios the query will time-out. Looking into it, the index that is chosen (ErrorTypeId) has fewer rows in it's plan than the other (DateOccurred) but for some reason takes far longer to run than if I manually force it to use the other index.
/* This execution plan has fewer rows than the second one - and as a result this is
* the one chosen. But it is much much slower.
*/
EXPLAIN
SELECT * FROM my_log_table
WHERE DateOccurred BETWEEN '2013-06-11 00:00:00' AND '2013-06-22 00:00:00' AND ErrorTypeId = 4
ORDER BY DateOccurred DESC
LIMIT 1000;
/* Many more rows - but much much quicker to execute.
* Is it the spread of data across pages? Is there a
* way other than USE/FORCE INDEX to improve execution plan?
*/
EXPLAIN
SELECT * FROM my_log_table USE INDEX (DateOccurred_Index)
WHERE DateOccurred BETWEEN '2013-06-11 00:00:00' AND '2013-06-22 00:00:00' AND ErrorTypeId = 4
ORDER BY DateOccurred DESC
LIMIT 1000;
Why is the 2nd query faster when there are more rows to look at?
Is there a way to help MySql choose the faster index without using USE/FORCE index?