tags:

views:

33

answers:

2

Does it group all possible results and then send back the results found within the given LIMIT?

+1  A: 

The LIMIT clause is only selection of the records returned - it has nothing to do with the value(s) returned from the query itself. For example, if you use LIMIT 10 on a query that only returns 5 rows - you'll only get 5 rows. If the query returned 11+ rows, you'd only get 10 rows. For a query using LIMIT to consistently return the same results, you need to specify an ORDER BY clause.

Think of the query occurring in the following steps:

  1. Query without ORDER BY or LIMIT
  2. ORDER BY criteria applied to query output from Step 1
  3. LIMIT criteria applied to output from Steps 1 & 2

If there's no ORDER BY specified, the step is not performed.

OMG Ponies
right, but im asking if `LIMIT` is given the entire output of `GROUP BY` to limit
Carson
+2  A: 

This page from the MySQL manual explains the ways in which it optimizes queries that use LIMIT:

http://dev.mysql.com/doc/refman/5.1/en/limit-optimization.html

In short, it doesn't just do the naive thing, which would be to compute the entire result set and then send you the first N rows.

There are some things that will prevent optimizations, including using a HAVING clause and using SQL_CALC_FOUND_ROWS.

Nate C-K
The linked page answers the question in this sentence:"In some cases, a GROUP BY can 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, LIMIT row_count does not calculate any unnecessary GROUP BY values."