33.6. Avoid UNIONs

A UNION is often implemented by constructing the two result sets, then merge-sorting them together. The optimizer works only within a single SELECT statement or subquery. For example:

SELECT *
  FROM Personnel
 WHERE work = 'New York'
UNION
SELECT *
  FROM Personnel
 WHERE home = 'Chicago';

is the same as:

SELECT DISTINCT *
  FROM Personnel
 WHERE work = 'New York'
    OR home = 'Chicago';

The second will run faster.

Another trick is to use UNION ALL in place of UNION whenever duplicates are not a problem. The UNION ALL is implemented as an append operation, without the need for a sort to aid duplicate removal.

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.