One of the best practices on using MySQL is to avoid filesort.
However there are cases where it is inevitable (e.g. ordering the
result of fulltext search by modification date), and although in
most cases we only the top N rows of sorted resultset are needed,
MySQL does not implement top N sort.
After wondering for couple of months if I should hack the MySQL
core to implement top-N-sort, today I decided to write a UDF that
performs top N sort, and see how well it performs. And here it
is: top-n-sort.c.
First the benchmark. When performing order by 〜 limit on
an unindexed column of a 100k row table, top N sort is more than
two times faster than the internal sort algorithm.
mysql> SELECT id,priority FROM testsort ORDER BY priority LIMIT 10;
(snip)
10 rows in set (0.11 sec)
mysql> SELECT topn_get(v) AS …
[Read more]