How SQL DISTINCT and ORDER BY are Related
One of the things that confuse SQL users all the time is how DISTINCT and ORDER BY are related in a SQL query. The Basics Running some queries against the Sakila database , most people quickly understand: SELECT DISTINCT length FROM film This returns results in an arbitrary order, because the database can (and might apply hashing rather than ordering to remove duplicates): length | -------| 129 | 106 | 120 | 171 | 138 | 80 | ... Most people also understand: SELECT length FROM film ORDER BY length This will give us duplicates, but in order: length | -------| 46 | 46 | 46 | 46 | 46 | 47 | 47 | 47 | 47 | 47 | 47 | 47 | 48 | ... And, of course, we can combine the two: SELECT DISTINCT length FROM film ORDER BY length Resulting in… length | -------| 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | ... Then why doesn’t this work? Maybe somewhat intui...