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:
FROM
clause: Pull tablerental
into memory as preliminary result set.WHERE
clause: No filtering applied; display full result set.SELECT
clause: Only display columnrental_date
in final result set. (The full table still exists in memory.)GROUP BY
clause: No grouping or aggregation applied.HAVING
clause: No filtering by aggregated values applied.ORDER BY
clause: 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.