Skip to main content
Set operations combine the results of two or more SELECT statements. Both queries must produce the same number of columns, and corresponding columns must have compatible types.

UNION

Combines two result sets and removes duplicate rows:
Because deduplication requires comparing every row, UNION is slower than UNION ALL. Use it only when you actually need distinct results.

UNION ALL

Combines two result sets and keeps all rows, including duplicates:
UNION ALL is faster than UNION because no deduplication step is needed. Prefer it when duplicates are acceptable or when you know the two result sets are already disjoint.

EXCEPT

Returns rows from the left query that do not appear in the right query, with duplicates removed:

EXCEPT ALL

Like EXCEPT, but preserves multiplicity. If a row appears m times on the left and n times on the right, the result contains max(m - n, 0) copies of that row:

INTERSECT

Returns rows that appear in both the left and right query, with duplicates removed:

INTERSECT ALL

Like INTERSECT, but preserves multiplicity. If a row appears m times on the left and n times on the right, the result contains min(m, n) copies of that row:

ORDER BY after set operations

ORDER BY is supported after any set operation. However, you must reference columns by position (1-based) or by alias — not by the original column name from the base tables:
LIMIT and OFFSET / FETCH may follow ORDER BY as usual:

Chaining Multiple Set Operations

Set operations associate left-to-right. UNION ALL followed by EXCEPT first unions the two queries, then removes rows from the third:

Not Supported

  • Parenthesized set operations (e.g., (SELECT ... UNION SELECT ...) UNION SELECT ...)