SQL Set Operations

Combine the RESULTS of two separate queries — stacked together, not matched by a shared key the way JOIN works.

What & Why

Every join in the previous series combined two tables side by side, matching rows by a key. Set operations do something different: they combine two queries' results vertically — stacking rows from Query A and Query B together — with no key, no matching condition, nothing except the requirement that both queries return the same number of columns, in compatible types.

This lesson series covers UNION (combine, remove duplicates), UNION ALL (combine, keep duplicates), INTERSECT (keep only rows in both), and EXCEPT (keep only rows in one but not the other) — the four ways two result sets can be combined.

See How It Works

BUSINESS QUESTION

Marketing wants one deduplicated calendar containing every campaign start and end date.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT start_date AS campaign_date
FROM marketing.campaigns
UNION
SELECT end_date AS campaign_date
FROM marketing.campaigns
WHERE end_date IS NOT NULL
ORDER BY campaign_date;
RESULT — exact output from the displayed Queryflo rows
campaign_date
2024-01-15
2024-02-10
2024-03-12
2024-03-31
2024-04-01
2024-04-15
2024-05-31
2024-06-30

UNION deduplicates and sorts the four start dates and four end dates.

Now You Try

Practice this concept

Marketing wants one deduplicated calendar of every campaign start and end date.

Available schema
marketing

Prefix tables with marketing.table_name.

campaign_date
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario