If you know you only need 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
clause and no
row_countHAVING clause:
If you select only a few rows with
LIMIT, MySQL uses indexes in some cases when normally it would prefer to do a full table scan.If you use
LIMITwithrow_countORDER BY, MySQL ends the sorting as soon as it has found the firstrow_countrows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without theLIMITclause are selected, and most or all of them are sorted, before the firstrow_countare found. After the initial rows have been found, MySQL does not sort any remainder of the result set.When combining
LIMITwithrow_countDISTINCT, MySQL stops as soon as it findsrow_countunique rows.In some cases, a
GROUP BYcan be resolved by reading the key in order (or doing a sort on the key) and then calculating summaries until the key value changes. In this case,LIMITdoes not calculate any unnecessaryrow_countGROUP BYvalues.As soon as MySQL has sent the required number of rows to the client, it aborts the query unless you are using
SQL_CALC_FOUND_ROWS.LIMIT 0quickly returns an empty set. This can be useful for checking the validity of a query. When using one of the MySQL APIs, it can also be employed for obtaining the types of the result columns. (This trick does not work in the MySQL Monitor (the mysql program), which merely displaysEmpty setin such cases; instead, useSHOW COLUMNSorDESCRIBEfor this purpose.)When the server uses temporary tables to resolve the query, it uses the
LIMITclause to calculate how much space is required.row_count