33.9. Avoid Sorting
The SELECT DISTINCT and ORDER BY clauses usually cause a sort in most SQL products, so avoid them unless you really need them. Use them if you need to remove duplicates or if you need to guarantee a particular result set order explicitly. In the case of a small result set, the time to sort it can be longer than the time to process redundant duplicates.
The UNION, INTERSECT, and EXCEPT clauses can do sorts to remove duplicates; the exception is when an index exists that can be used to eliminate the duplicates without sorting. In particular, the UNION ALL will tend to be faster than the plain UNION, so if you have no duplicates or do not mind having them, then use it instead. There are not enough implementations of INTERSECT ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access