Is MySQL LIMIT applied before or after ORDER BY?

后端 未结 3 2046
孤街浪徒
孤街浪徒 2020-12-28 12:50

Which one comes first when MySQL processes the query?

An example:

SELECT pageRegions
FROM pageRegions WHERE(pageID=?) AND(published=true) AND (publis         


        
相关标签:
3条回答
  • 2020-12-28 13:12

    The limit is always applied at the end of result gathering, therefore after order by.

    Given all your clauses, the order of processing will be

    • FROM
    • WHERE
    • SELECT
    • ORDER BY
    • LIMIT

    So you will get the closest record <= publishedOn matching all the conditions in the WHERE clause.

    0 讨论(0)
  • 2020-12-28 13:16

    Just wanted to point out the in case of MySQL ordering is applied before limiting the results. But this is not true for other DB.

    For example Oracle first limits results and applies ordering on said results. It makes sense when you think about it from a performance point of view. In MySQL you are actually ordering the entire DB(> 1000 records) to get 2

    0 讨论(0)
  • 2020-12-28 13:25

    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.

    0 讨论(0)
提交回复
热议问题