Intermediate · Lesson 15 of 20

INTERSECT and EXCEPT

UNION stacks two results together. Two more set operators compare them instead:

  • INTERSECT keeps rows that appear in both results
  • EXCEPT keeps rows from the first result that aren't in the second

Who manages nobody? Take every employee id, then remove every id that appears as someone's manager:

SELECT id FROM employees
EXCEPT
SELECT manager_id FROM employees;

Which departments have someone earning over 130,000 and also someone hired since 2022?

SELECT department_id FROM employees WHERE salary > 130000
INTERSECT
SELECT department_id FROM employees WHERE hire_date >= '2022-01-01';

The rules are the same as UNION:

  • Both queries need the same number of columns
  • Duplicates are removed from the result
  • ORDER BY goes once, at the very end

Oracle calls EXCEPT "MINUS", but it works the same way.

Check your understanding

Return the id of every employee who isn't anyone's manager.

Examples run on the employees sample database. Open any of them in the playground to experiment.