I googled the question and all answers said SELECT was executed before ORDER BY. But the simple example below (using MySQL and sakila database) gives the correct sorted results. Obviously, ORDER BY is not executed after SELECT, as customer_id is not selected by SELECT. Can anybody explain what happened?
SELECT rental_date FROM rental ORDER BY customer_id LIMIT 10;
Advertisement
Answer
Is this what you’re looking for?
Bear in mind that the execution sequence is a general rule, and how any given query is parsed may vary, depending on indexes, caches, etc.
But with that said, if you’re trying to understand how your query was parsed under those general guidelines, it would be something like this:
General execution sequence:
FROMclause: Pull tablerentalinto memory as preliminary result set.WHEREclause: No filtering applied; display full result set.SELECTclause: Only display columnrental_datein final result set. (The full table still exists in memory.)GROUP BYclause: No grouping or aggregation applied.HAVINGclause: No filtering by aggregated values applied.ORDER BYclause: Sort the displayed result set using the columncustomer_id.
The engine may sort all of the results, but may only sort enough results to fulfill the LIMIT clause before displaying the number of rows requested in that clause.