Is MySQL LIMIT applied before or after ORDER BY?

Chris Abrams picture Chris Abrams · Feb 11, 2011 · Viewed 27.9k times · Source

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?

Answer

Marc B picture Marc B · Feb 11, 2011

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.