lesson 27 Joins & sets · intermediate
INTERSECT & EXCEPT
Find values shared by two results or present in only one.
the idea
INTERSECT keeps distinct rows appearing in both results. EXCEPT keeps distinct rows from the first result that are absent from the second. Column positions and types should align.
tables in this lesson
The challenges use this data. Each column shows its type underneath; → marks a link to another table.
watch_events5 columns · 26 rows
| idinteger · key | viewer_idinteger | video_idinteger | watched_attext | watch_secondsinteger |
|---|---|---|---|---|
| 1 | 1 | 1 | 2025-01-01 10:00:00 | 300 |
| 2 | 1 | 2 | 2025-01-01 11:00:00 | 450 |
| 3 | 2 | 1 | 2025-01-02 12:00:00 | 600 |
| 4 | 3 | 3 | 2025-01-02 13:00:00 | 120 |
| 5 | 1 | 4 | 2025-01-02 14:00:00 | 700 |
showing 5 of 26 rows
example
The idea in one query. Press Run to see what it returns; running examples never affects your progress.
SELECT viewer_id FROM watch_events WHERE video_id=1 INTERSECT SELECT viewer_id FROM watch_events WHERE video_id=2;
Watch for: UNION means either set, which answers a different question.
build it step by step
Each step changes one thing. Run them in order and watch the result change.
List viewers of video 1. INTERSECT will keep viewers who also watched video 2. EXCEPT would keep viewers of video 1 who never watched video 2.
step-1.sqlSELECT viewer_id FROM watch_events WHERE video_id = 1 ORDER BY viewer_id;
Keep viewers in both sets. INTERSECT returns distinct rows present in both SELECT results. Column positions must align.
step-2.sqlSELECT viewer_id FROM watch_events WHERE video_id = 1 INTERSECT SELECT viewer_id FROM watch_events WHERE video_id = 2;