SQL Set Operators

Context: FIT2094_MOC Β· combine whole result sets vertically Β· the SQL form of βˆͺ ∩ βˆ’ set algebra Β· needs union-compatible queries Problem it solves: merge, intersect, or subtract the row sets of two SELECTs into one result.

Quick Revision

  • 🎯 Trigger: combine rows of two queries βž” UNION / UNION ALL (βˆͺ), INTERSECT (∩), MINUS (βˆ’).
  • ⚑ Key Constraint: both queries must be union-compatible β€” same column count, compatible types; output names come from the first query.

πŸ”§ Minimal Working Example

SELECT drone_id FROM drone.drone      -- set 1: all drones
MINUS
SELECT drone_id FROM drone.rental     -- set 2: drones ever rented
ORDER BY drone_id;                    -- result: drones NEVER rented

Expected output: drone_ids in set 1 but not set 2 β€” the never-rented drones.

  • UNION ALL βž” all rows from both, keeps duplicates.
  • UNION βž” all rows from both, duplicates removed.
  • INTERSECT βž” rows appearing in both queries.
  • MINUS βž” rows in the first query not in the second.
  • Union-compatible βž” equal column count + compatible types; a single trailing ORDER BY applies to the whole result.

πŸ”€ Variations

OperatorReturnsDuplicates
UNION ALLeverything from bothkept
UNIONeverything from bothremoved
INTERSECTrows in bothn/a
MINUSin first, not secondn/a
  • UNION with labels βž” combine WHERE emp_type='F' (label 'Full Time') with WHERE emp_type='C' (label 'Casual'), then ORDER BY emp_no.
  • INTERSECT βž” SELECT emp_lname FROM drone.employee INTERSECT SELECT cust_lname FROM drone.customer β€” surnames in both.

✍️ Practice

⚠️ Common Mistakes

  • πŸ’‘ Not union-compatible = error βž” mismatched column counts or incompatible types are rejected; align the SELECT lists.
  • πŸ’‘ One ORDER BY, at the very end βž” ordering belongs to the combined result, using the first query’s column names.