SQL Querying

Set Operations

Set operations combine compatible query results vertically. UNION, INTERSECT, and EXCEPT use distinct semantics by default, while their ALL forms preserve bag multiplicities according to each operator.
  • Operands must have the same degree, and corresponding columns must have compatible types and meanings.
  • UNION removes duplicates; UNION ALL preserves every occurrence.
  • INTERSECT keeps rows appearing in both inputs; EXCEPT keeps left rows absent from the right input.
  • ALL uses occurrence counts.
  • Column names normally come from the first query, while a final ORDER BY applies to the combined result.
  • Parenthesize mixed set operators so precedence and any branch-local ordering or limiting are explicit.

Compatibility and multiplicity

Set-operation semantics
OperatorRows retainedFor counts m=3, n=2Typical intent
UNIONDistinct rows in either input1 copyCombine unique customer IDs
UNION ALLEvery occurrence in both inputs5 copiesAppend compatible event streams
INTERSECTDistinct rows in both inputs1 copyCustomers in both campaigns
INTERSECT ALLMinimum occurrence count2 copiesBag intersection
EXCEPTDistinct left rows absent right0 copiesCatalog IDs not in a feed
EXCEPT ALLPositive left-minus-right count1 copyBag difference
Combine customers reached through two channels
SELECT customer_id
FROM orders
WHERE status = 'PAID'
UNION
SELECT customer_id
FROM orders
WHERE status = 'REFUNDED'
ORDER BY customer_id;

If customer 7 has two paid orders and one refunded order, the first branch produces two 7s and the second one 7. UNION returns one 7; UNION ALL returns three. Choosing between them is a business rule about occurrences, not a performance toggle.