Rules & Sorting

Rules for Set Operators

  1. Every SELECT must have the same number of columns.
  2. Matching columns must have compatible data types.
  3. Column names in the result come from the first SELECT.
  4. ORDER BY may appear only once, at the very end, and sorts the combined result.

Sorting the Combined Result

Example

Employees and customer contacts in one alphabetical list:

SELECT FirstName AS Name, 'Employee' AS Type FROM Employees
UNION ALL
SELECT ContactName, 'Customer contact' FROM Customers
ORDER BY Name
LIMIT 6;

Result: 6 rows

NameType
Aarav ShahCustomer contact
AnanyaEmployee
DavidEmployee
Emma ClarkCustomer contact
FatimaEmployee
Ingrid OlsenCustomer contact

Set Operators vs Joins

Joins combine tables side by side (more columns). Set operators stack results on top of each other (more rows).