Joins and set operations
UNION, UNION ALL, INTERSECT, and EXCEPT
Compare two compatible sets of customer IDs.
Lesson 37 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Intermediate
On this page6 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Compare two compatible sets of customer IDs.
Run the example
sql
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (1, 2)
UNION
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (2, 3)
ORDER BY CustomerID;Read it step by step
- Both SELECT branches return one compatible int column.
- UNION combines the branches and removes the repeated ID 2.
- UNION ALL would keep both copies; INTERSECT would keep only ID 2; EXCEPT, with the first branch on the left, would keep only ID 1.
Check the result
| CustomerID |
|---|
| 1 |
| 2 |
| 3 |
ORDER BY is applied to the combined result, not to each input branch.
UNION ALL keeps duplicates
sql
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (1, 2)
UNION ALL
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (2, 3)
ORDER BY CustomerID;| CustomerID |
|---|
| 1 |
| 2 |
| 2 |
| 3 |
The shared ID 2 appears twice.
EXCEPT is directional
sql
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (1, 2)
EXCEPT
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (2, 3)
ORDER BY CustomerID;| CustomerID |
|---|
| 1 |
Only ID 1 appears because it exists in the left input but not the right.
Practice
Use INTERSECT to find IDs shared by the sets (1, 2) and (2, 3).
Check your answer and expected result
Reveal answer
sql
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (1, 2)
INTERSECT
SELECT CustomerID FROM dbo.Customers WHERE CustomerID IN (2, 3)
ORDER BY CustomerID;| CustomerID |
|---|
| 2 |
Only CustomerID 2 belongs to both inputs.
Your progress
Reveal the check answer or reach the end to complete this lesson.