Spec-Zone .ru
спецификации, руководства, описания, API

8.2.1.3. Optimizing LIMIT Queries

If you need only a specified number of rows from a result set, use a LIMIT clause in the query, rather than fetching the whole result set and throwing away the extra data.

MySQL sometimes optimizes a query that has a LIMIT row_count clause and no HAVING clause:

As of MySQL 5.6.2, the optimizer more efficiently handles queries (and subqueries) of the following form:

SELECT ... FROM single_table ... ORDER BY non_index_column [DESC] LIMIT [M,]N;

That type of query is common in web applications that display only a few rows from a larger result set. For example:

SELECT col1, ... FROM t1 ... ORDER BY name LIMIT 10;SELECT col1, ... FROM t1 ... ORDER BY RAND() LIMIT 15;

The sort buffer has a size of sort_buffer_size. If the sort elements for N rows are small enough to fit in the sort buffer (M+N rows if M was specified), the server can avoid using a merge file and perform the sort entirely in memory by treating the sort buffer as a priority queue:

Previously, the server performed this operation by using a merge file for the sort:

The cost of the table scan is the same for the queue and merge-file methods, so the optimizer chooses between methods based on other costs:

The optimizer considers the balance between these factors for particular values of N and the row size.