UNION
- SQL course
- Intermediate
- Lesson 59/115
- 4 min
Combine the results of two queries.
UNION
UNION combines two SELECT results and removes duplicate rows.
SELECT name FROM customers
UNION
SELECT name FROM suppliers;This query makes one list of customer and supplier names.
name is selected from customers.
UNION — details
Each SELECT in a UNION must have the same number of columns with compatible types.
For example, to combine customer and supplier names into one list you join two SELECT name queries with UNION; column names come from the first query.
Practice UNION
Combine customer and supplier names with UNION.
Starter code
-- combine
SELECT name FROM customersSample solution
SELECT name FROM customers
UNION
SELECT name FROM suppliers;Expected output
name Ayşe Mehmet ACME
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does UNION do with duplicates?
- Raises an error
- Removes them Correct answer
- Keeps them
- Counts
Explanation: UNION removes duplicate rows.
2 Add UNION
SELECT name FROM customers
____
SELECT name FROM suppliers;
SELECT name FROM customers
UNION
SELECT name FROM suppliers;
Explanation: UNION combines the results of two queries and removes duplicate rows.
3 UNION: match the terms
| Term | Meaning |
|---|---|
UNION |
combine |
INTERSECT |
intersection |
EXCEPT |
difference |
UNION ALL |
with duplicates |