runtime
27 / 88

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 · keyviewer_idintegervideo_idintegerwatched_attextwatch_secondsinteger
1112025-01-01 10:00:00300
2122025-01-01 11:00:00450
3212025-01-02 12:00:00600
4332025-01-02 13:00:00120
5142025-01-02 14:00:00700

showing 5 of 26 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
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.

  1. 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.sql
    SELECT viewer_id
    FROM watch_events
    WHERE video_id = 1
    ORDER BY viewer_id;
  2. Keep viewers in both sets. INTERSECT returns distinct rows present in both SELECT results. Column positions must align.

    step-2.sql
    SELECT viewer_id
    FROM watch_events
    WHERE video_id = 1
    INTERSECT
    SELECT viewer_id
    FROM watch_events
    WHERE video_id = 2;

challenge 1

Return viewer_id for viewers who watched both video 1 and video 2. Each viewer appears once.

Return viewer_idany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.