I’m wondering what should be expected from an SQL query that involves the operators DISTINCT, ORDER BY and LIMIT. I think my question is rooted in a misunderstanding of the order in which operators in SQL should be applied
For instance,
CREATE TABLE test(id int)
SELECT DISTINCT id
FROM test
ORDER BY id
LIMIT 10
Based on my knowledge of SQL, I can’t see which (if any) of the following should happen
- The first 10 rows of
testare sorted, then a list of distinctids in that subset are returned - A list of all the distinct
ids in test are sorted, then the top 10 are returned - A list of the distinct
id‘s in the first 10 rows oftestare sorted then returned
If it matters, I’m using MySQL (MyISAM)
SELECT first, then ORDER BY, then LIMIT. That’s true except for a few databases (well, I know one) that has both the TOP and LIMIT keywords. In that engine, LIMIT is part of the WHERE clause (evaluated at the SELECT level) and TOP is applied after ORDERing.