The following MySQL query completes in under 0.02 seconds:
SELECT
*
FROM
`Table1`
WHERE
`col1` = '43532' AND
`col2` = 'N'
ORDER BY col3 DESC
However, if I add LIMIT 0, 5 at the end of it, it completes in over 7 seconds:
SELECT
*
FROM
`Table1`
WHERE
`col1` = '43532' AND
`col2` = 'N'
ORDER BY col3 DESC
LIMIT 0, 5
This is happening even when the query returns an empty result set.
Why is the addition of LIMIT 0, 5 causing this simple query to be 350 times slower? I need to be able to limit the results for pagination reasons, so how can I fix this?
EDIT:
WITHOUT LIMIT, EXPLAIN says:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE Table1 ref col1,col2 col1 5 const 2441 Using where; Using filesort
WITH LIMIT, EXPLAIN says:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE Table1 index col1,col2 col3 5 NULL 1050 Using where
The problem is that the limit causes MySQL to order the query first, forcing it to order the whole set, and then filter it, not using indexes.
There are directives to tell MySQL which index to use, but it may be better to create a combined index on col1, col2 and col3. MySQL should use that index for filtering and sorting. You should experiment to see whether the query is faster if col3 is the first or the last column in that index.