This piece of mysql code
SELECT id, value, LENGTH(stuffing)
FROM t_limit ORDER BY id LIMIT 150000, 10
can be optimized for better performance by rewriting it like this
Note:Table has Index on Id
SELECT l.id, value, LENGTH(stuffing)
FROM (
SELECT id
FROM t_limit
ORDER BY
id
LIMIT 150000, 10
) o
JOIN t_limit l
ON l.id = o.id
ORDER BY
l.id
Ref:http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
Now how to optimize this piece of code in a similar way
SELECT id, value, LENGTH(stuffing)
FROM t_limit where value>100 ORDER BY id LIMIT 150000, 10
The basic idea behind the optimization presented in the mentioned post is to query only the index pages without touching data pages. If you look at the query plan of the non-optimized query:
it would be:
So it’s a simple table-scan. With the subquery optimization we receive:
Look at the
keycolumn which shows that the inner most statement used the PRIMARY index. I slightly modified your query so the value type is compatible:You need to consider what the
wherecondition does. If you placed it in the outer query you would filter only the 10 rows returned from the inner query – I suppose that it was not what you were asking for. Now in the presented case (thewherecondition in the inner statement) you will end up with a table scan as there is no index that could fulfill your query:To profit from the same optimization as presented in the blog post you would need an additional non-clustered index, eg.
Now, when you run the above query the plan would be:
And again we are only scanning index pages.