Chapter 15 · Lesson 1 of 4

UNION vs UNION ALL

Stack the rows of two queries with UNION ALL, remove duplicate rows with UNION, and learn the column rules both sides of a set operation must follow.

Joins combine tables side by side. Set operations combine query results on top of each other.

UNION ALL stacks every row from both queries:

SELECT email FROM newsletter_2023
UNION ALL
SELECT email FROM newsletter_2024

That returns 10 rows, because three people subscribed in both years. UNION removes duplicate rows from the combined result:

SELECT email FROM newsletter_2023
UNION
SELECT email FROM newsletter_2024
ORDER BY email

Rules for every set operation:

• Both queries must return the same number of columns. • Columns are matched by position, not by name, so keep them in the same order with compatible types. • ORDER BY goes at the very end and sorts the combined result.

Prefer UNION ALL when you know there are no duplicates or you want to keep them. It skips the duplicate check, so it is cheaper.

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 every distinct email that appears in either newsletter_2023 or newsletter_2024, ordered by email.

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