UNION ALL
- SQL course
- Intermediate
- Lesson 60/115
- 4 min
Keep duplicates when combining.
UNION ALL
UNION ALL combines two SELECT results keeping duplicates. It is faster than UNION.
SELECT name FROM customers
UNION ALL
SELECT name FROM suppliers;This query gives all names including duplicates.
name is selected from customers.
UNION ALL — details
UNION ALL is faster because it does not filter duplicates. Use it when duplicates matter.
For example, if the same person is both a customer and a supplier, UNION ALL shows them twice and UNION once.
Practice UNION ALL
Combine customer and supplier names with UNION ALL keeping duplicates.
Starter code
-- with duplicates
SELECT name FROM customers
UNIONSample solution
SELECT name FROM customers
UNION ALL
SELECT name FROM suppliers;Expected output
name Ayşe Mehmet Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add ALL
SELECT name FROM customers
UNION ____
SELECT name FROM suppliers;
SELECT name FROM customers
UNION ALL
SELECT name FROM suppliers;
Explanation: UNION ALL keeps duplicate rows too and is faster than UNION.
2 What does UNION ALL do with duplicates?
- Removes them
- Counts
- Keeps them Correct answer
- Raises an error
Explanation: UNION ALL keeps duplicates.
3 UNION ALL: match the terms
| Term | Meaning |
|---|---|
UNION |
no duplicates |
UNION ALL |
with duplicates |
fast |
no filtering |
DISTINCT |
unique |