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 ...

Get Joe Celko's SQL for Smarties, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.