Set operations
Concept  ·  SQL & Querying

Set operations align columns by position, not by name — swapped columns produce silently plausible garbage.

UNION's contract is arity plus type compatibility per position; names are decoration. Two text columns swapped is the classic: no error, plausible rows, wrong data — found weeks later when a 'technician' named North Tower turns up in a filter. The defences are habits: explicit column lists in a fixed order, or a canonical CTE both branches select from.

See it break
log_a
techbuilding
AdaNorth Tower
log_b
buildingtech
South TowerBen
The trap
SELECT
  tech,
  building
FROM
  log_a
UNION ALL
SELECT
  building,
  techFROM
  log_b
ORDER BY
  tech;
The fix
SELECT
  tech,
  building
FROM
  log_a
UNION ALL
SELECT
  tech,
  building
FROM
  log_b
ORDER BY
  tech;
INPUTYour queryThe fix
AdaNorth TowerNorth Tower
South TowerBenSouth Tower

The merged inspection log put a building name in the technician column — set operations align by position, not by name, and the swapped SELECT lined up silently.

The rule

Align by rewriting the second SELECT to the same column order, or have both branches select from one shared-shape CTE.

Shows up elsewhere
UNION dedups; UNION ALL doesn'tSet ops treat NULLs as equal
Try one →Prove it in practice →