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
test
are sorted, then a list of distinct id
s in that subset are returned id
s in test are sorted, then the top 10 are returned id
's in the first 10 rows of test
are sorted then returned If it matters, I'm using MySQL (MyISAM)
Think of it in terms of "inside to out", so the following happens:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.