I am running into a situation where MySQL is not using the index for ORDER BY, and instead dropping to filesort, which is quite slow for what I need to do. I am using MySQL 5.0.16-max on Windows (but I have also witnessed this with MySQL 5.x on Linux).
I have a simple table with 4 columns and some compound indices on the first 3 columns:
CREATE TABLE gen ( a int(11) default NULL, b int(11) default NULL, c int(11) default NULL, d int(11) default NULL, KEY abc (a,b,c), KEY bc (b,c), KEY c (c)) ENGINE=MyISAM;
I wish to run the following query over this table:
select a, b, c, d from gen order by a;
It seems that this query should use the first index (‘abc’) for the sort, instead of a ‘filesort’; however, that’s not what actually happens:
mysql> explain select a, b, c, d from gen order by a;±—±------------±------±-----±--------------±-----±--------±-----±-------±---------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |±—±------------±------±-----±--------------±-----±--------±-----±-------±---------------+| 1 | SIMPLE | gen | ALL | NULL | NULL | NULL | NULL | 200000 | Using filesort |±—±------------±------±-----±--------------±-----±--------±-----±-------±---------------+1 row in set (0.00 sec)
Even if I supply “use index(abc)” on the query above, it still does filesort.
The only way I can get the query to use the index and not do the filesort is by doing a “select a from gen order by a;” (or, more generally, if the “select” clause picks only data already in the index).
This is quite puzzling to me, it seems there’s no reason why MySQL would not use the index for the sort in this case, since it’s basically free!
I have spent considerable time reading various posts on this topic, and I thought I would open up this discussion to more people on the list to see if anyone has other ideas.
For reference, here are some of the more relevant articles I read on the topic:
http://www.mysqlperformanceblog.com/2006/09/01/order-by-limi t-performance-optimization/
http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization .html
[URL=“http://MySQL :: MySQL 8.0 Reference Manual :: 13.2.10.2 JOIN Clause”]http://dev.mysql.com/doc/refman/5.0/en/join.html[/URL]
Thanks in advance for any thoughts/comments,
Razvan.