Chapter 15 · Lesson 2 of 4

INTERSECT Finds Rows in Both

Use INTERSECT to return only rows that appear in both query results, such as the newsletter subscribers who signed up in two consecutive years.

INTERSECT keeps only the rows that appear in both results:

SELECT email FROM newsletter_2023
INTERSECT
SELECT email FROM newsletter_2024
ORDER BY email

Like UNION, INTERSECT compares whole rows. If you select email, country, a person only counts as "in both" when the email and the country match.

You could answer the same question with a join or EXISTS, but INTERSECT states the intent directly: "rows common to both lists". It also treats NULL values as equal to each other, which joins do not.

DuckDB also supports INTERSECT ALL, which keeps duplicates as many times as they appear on both sides.

Sample data

This lesson loads the newsletter_2023 and newsletter_2024 tables (5 subscribers each) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for newsletter_2023, newsletter_2024
CREATE OR REPLACE TABLE newsletter_2023 (
    email VARCHAR,
    country VARCHAR
  );

INSERT INTO newsletter_2023 VALUES
    ('[email protected]', 'DE'),
    ('[email protected]', 'US'),
    ('[email protected]', 'KR'),
    ('[email protected]', 'IN'),
    ('[email protected]', 'DE');

CREATE OR REPLACE TABLE newsletter_2024 (
    email VARCHAR,
    country VARCHAR
  );

INSERT INTO newsletter_2024 VALUES
    ('[email protected]', 'US'),
    ('[email protected]', 'IN'),
    ('[email protected]', 'SE'),
    ('[email protected]', 'US'),
    ('[email protected]', 'DE');

Practice challenge

Return the emails that appear in both newsletter_2023 and newsletter_2024, ordered by email.

Hint: SELECT email FROM newsletter_2023 INTERSECT SELECT email FROM newsletter_2024 ORDER BY email

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Set Operations: UNION, INTERSECT, EXCEPT

Combine the results of two queries: stack rows with UNION and UNION ALL, find rows both sides share with INTERSECT, and find rows only one side has with EXCEPT.

  1. 01 · UNION vs UNION ALL
  2. 02 · INTERSECT Finds Rows in Both
  3. 03 · EXCEPT Finds Rows Only on One Side
  4. 04 · Stacking and Summarizing Results

Related guides