The INTERSECT
and EXCEPT
operators are used to compare two query results. Both require the same number of columns with compatible data types.
Example – Students with both enrollments and scores:
SELECT student_id FROM enrollments
INTERSECT
SELECT student_id FROM scores;
This returns the student_id
values that exist in both tables.
Example – Students who are enrolled but have no score recorded:
SELECT id FROM enrollments
EXCEPT
SELECT id FROM scores;
INTERSECT
→ Common rows in both queries.EXCEPT
→ Rows in the first query but not in the second.