Chapter 15 · Lesson 3 of 4

EXCEPT Finds Rows Only on One Side

Use EXCEPT to return rows from the first query that are missing from the second, such as subscribers who did not come back the following year.

EXCEPT returns rows from the first query that do not appear in the second:

SELECT email FROM newsletter_2023
EXCEPT
SELECT email FROM newsletter_2024
ORDER BY email

Order matters. Swap the two queries and you get the opposite question: who is new in 2024?

SELECT email FROM newsletter_2024
EXCEPT
SELECT email FROM newsletter_2023
ORDER BY email

EXCEPT is a compact way to compare two lists, for example to find records that disappeared between two exports of the same file. Some databases call it MINUS. DuckDB also supports EXCEPT ALL, which subtracts matching rows one at a time instead of removing every copy.

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 of 2023 subscribers who are not in newsletter_2024, ordered by email.

Hint: SELECT email FROM newsletter_2023 EXCEPT 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