SQL UNION, INTERSECT, EXCEPT
intermediateadvanced
2 min read
What are Set Operations?
Set operations combine the results of two or more SELECT queries:
UNION— All unique rows from both queries.UNION ALL— All rows including duplicates.INTERSECT— Rows that appear in both queries.EXCEPT— Rows in the first query but not the second.
Syntax
SELECT columns FROM table1
UNION
SELECT columns FROM table2;When to Use
- Combining results from different tables with the same structure
- Finding common records between datasets
- Identifying records in one set but not another
Key Points
- Same Columns — All queries must return the same number of columns with compatible types.
- UNION vs UNION ALL — UNION removes duplicates (slower). UNION ALL keeps them (faster).
- ORDER BY — Apply ORDER BY only at the end, after the last SELECT.
- Column Names — The column names come from the first SELECT.
- EXCEPT vs NOT IN — EXCEPT handles NULLs correctly and is more readable.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
SQL UNION, INTERSECT, EXCEPT Challenge
Write a query that solve this task: get all unique names from students and employees.
Expected result
A unique, sorted list of all first names from both tables.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What are Set Operations?
Initializing database...Each run starts from fresh sample data.
More Examples
Find students not enrolled in any course
Use EXCEPT to find students with no enrollments.
Initializing database...Each run starts from fresh sample data.
Common names
Find names that appear in both students and employees.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the difference between UNION and UNION ALL?
UNION removes duplicate rows. UNION ALL includes all rows, including duplicates. UNION ALL is faster.
Can I use ORDER BY with UNION?
Yes, but only at the end of the entire statement. It applies to the combined result.