ORDER BY or LIMIT. What is processed first in SQL Select?

Asked

Viewed 578 times

1

Friends, what is first processed in SQL Select? "Order by" or "Limit"?

For example, if I have a table with cities of several states. Then I search the cities with more than 100 thousand inhabitants of the state X, resulting in 6 cities (ex: cities listed without using order by: Gama, Alfa, Zeta, Teta, Delta and Beta) .

Then I change sql and sort by ASC Name and limit to 4 cities (Limit 4).

How will Select proceed? Will he first sort the 6 cities (all the result) in ascending alphabetical order and limit the first 4 (result: Alpha, Beta, Delta and Gamma)? Or will first limit 4 search cities (first it limits the result) and then sort them in alphabetical order (result: Alpha, Gamma, Theta and Zeta)?

The amount of table records (if they are many) can influence the Select procedure to limit first or sort first?

I’m using BD Mysql, I don’t know if it makes any difference in this case.

Thanks for your help!

Ps: in the tests I did with few records, he ordered first and only then limited, but I wanted to be sure if it is this same procedure always, independent of number of records in the table or of some other variable that I do not know.

  • 4

    yes, sort first and limit later, regardless of the number of records in the table.

1 answer

1


In order to order and limit, SELECT will first need to know all the records, then order them and only then apply LIMIT. It would be impossible to apply a LIMIT with ORDER BY without first having the complete SELECT to be ordered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.