Chapter 15 · Lesson 4 of 4
Stacking and Summarizing Results
Stack similar tables with UNION ALL and a literal label column, then group the combined rows, and see why UNION would silently drop repeated rows.
A common real-world pattern: you have the same kind of data split across several files, such as one export per year. Stack them with UNION ALL and add a literal column so you still know where each row came from:
SELECT 2023 AS signup_year, email, country FROM newsletter_2023
UNION ALL
SELECT 2024 AS signup_year, email, country FROM newsletter_2024Wrap the stacked rows in a CTE or subquery and summarize them like any other table:
WITH all_signups AS (
SELECT 2023 AS signup_year, email, country FROM newsletter_2023
UNION ALL
SELECT 2024 AS signup_year, email, country FROM newsletter_2024
)
SELECT signup_year, COUNT(*) AS subscribers
FROM all_signups
GROUP BY signup_yearBe careful with plain UNION here. If two rows are identical, UNION keeps only one, and your counts quietly shrink.
When files have the same columns in a different order, DuckDB's UNION ALL BY NAME matches columns by name instead of position.
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
Stack email and country from both tables with UNION ALL, then return country and subscriptions (the number of stacked rows per country), ordered by subscriptions descending, then country.
Hint: WITH all_signups AS (SELECT email, country FROM newsletter_2023 UNION ALL SELECT email, country FROM newsletter_2024) SELECT country, COUNT(*) AS subscriptions ...
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.