Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is MySQL LIMIT applied before or after ORDER BY?

Which one comes first when MySQL processes the query?

An example:

SELECT pageRegions FROM pageRegions WHERE(pageID=?) AND(published=true) AND (publishedOn<=?) ORDER BY publishedON DESC LIMIT 1'; 

Will that return the last published pageRegion even if the record does not match the revision datetime IF LIMIT is applied after ORDER BY?

like image 746
Chris Abrams Avatar asked Feb 11 '11 22:02

Chris Abrams


People also ask

Can we use limit with ORDER BY in MySQL?

If you do LIMIT first and then ORDER BY, it will throw an error. ORDER BY must be first in the query.

Can we use limit after ORDER BY in SQL?

In this topic, we described about the ORDER BY LIMIT with detailed example. ORDER BY LIMIT is used to get rows from table in sorting order either in ascending or descending order and to limit rows in result-set. ORDER BY LIMIT is not supported in all databases. ORDER BY LIMIT works only in MySQL.

How does limit work in MySQL?

Limit Data Selections From a MySQL DatabaseMySQL provides a LIMIT clause that is used to specify the number of records to return. The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables. Returning a large number of records can impact on performance.

Does MySQL allow the use of ORDER BY and limit in the same query?

In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.


1 Answers

Yes, it's after the ORDER BY. For your query, you'd get the record with the highest publishedOn, since you're ordering DESC, making the largest value first in the result set, of which you pick out the first one.

like image 144
Marc B Avatar answered Sep 21 '22 14:09

Marc B