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_2024That 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 emailRules 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.
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.
Related guides
SQL UNION, INTERSECT, and EXCEPT Explained: Combine and Compare Query Results
Set operations stack or compare whole query results. They are the quickest way to merge yearly exports or find rows that appear in one list but not the other.
SQL Cheat Sheet for Data Analysis: Filter, Group, Join, Dates, and Ranking
One pattern per common analysis question, from previewing a new table to ranking rows inside groups, each linked to a lesson where you can practice it.