I have two queries,
select some_other_column
from `table`
order by primary_index_column asc
limit 4000000, 10;
and
select some_other_column
from `table`
order by secondary_index_column asc
limit 4000000, 10;
Both return 10 rows; the first takes 2.74 seconds, and the second takes 7.07 seconds. some_other_column is not a part of any index. primary_index_column is the primary key column; secondary_index_column has a b-tree index and a cardinality of 200 (according to MySQL).
Here are the explain results:
mysql> explain select some_other_column from `table` order by primary_index_column limit 4000000, 10;
+----+-------------+---------+-------+---------------+---------+---------+------+---------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+---------+---------+------+---------+-------+
| 1 | SIMPLE | table | index | NULL | PRIMARY | 4 | NULL | 4000010 | |
+----+-------------+---------+-------+---------------+---------+---------+------+---------+-------+
mysql> explain select some_other_column from `table` order by secondary_index_column limit 4000000, 10;
+----+-------------+---------+------+---------------+------+---------+------+---------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+------+---------------+------+---------+------+---------+----------------+
| 1 | SIMPLE | table | ALL | NULL | NULL | NULL | NULL | 4642945 | Using filesort |
+----+-------------+---------+------+---------------+------+---------+------+---------+----------------+
Why does MySQL choose that specific execution plan for the second query? I don't understand why it can use the index for the first query but not for the second query.
LIMIT 10 OFFSET 4000000part which means that the SQL engine has to somehow (index or otherwise) get 4 million (and 10) rows and discard the first(!) 4 million of them. Don't be surprised if using the index doesn't happen or is slow. – ypercubeᵀᴹ Mar 23 '12 at 07:14COMMON THINGSto explain the optimizer behavior behind your queries. – RolandoMySQLDBA Mar 26 '12 at 16:03