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

1

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

For example, if I have a table with multi-state cities. Then I look for cities with more than 100 thousand inhabitants of state X, resulting in 6 cities (eg cities listed without using order by: Range, Alpha, Zeta, Theta, Delta and Beta).

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

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

Can the number of records in the table (if many) influence the Select procedure to limit first or sort first?

I'm using MySql DB, I do not know if it makes any difference in this case.

Thanks in advance for the help!

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

    
asked by anonymous 07.06.2018 / 09:27

1 answer

1

To be able to sort and limit, SELECT will first need to know all records, then sort them and then apply LIMIT. It would be impossible to apply a LIMIT with ORDER BY without first having the full SELECT to be ordered.

    
07.06.2018 / 13:20