MySQL — Union
UNION
Combines results from two or more SELECT statements, removing duplicate rows:
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
UNION ALL
Keeps all rows including duplicates — faster than UNION:
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
Rules for UNION
- All SELECT statements must have the same number of columns
- Columns must have compatible data types
- ORDER BY can only appear at the end
- Column names come from the first SELECT
SELECT name, email FROM customers
UNION
SELECT name, email FROM vendors
ORDER BY name;
UNION with WHERE
Each SELECT can have its own WHERE clause:
SELECT name, 'Active' AS status FROM active_users
UNION
SELECT name, 'Inactive' AS status FROM inactive_users;
UNION vs JOIN
| Feature | UNION | JOIN |
|---|---|---|
| Direction | Vertical (rows) | Horizontal (columns) |
| Tables | Similar data | Related data |
| Columns | Same count | Can differ |
Mini Practice
Write SQL code that:
- Uses UNION to combine two result sets
- Uses UNION ALL to show duplicates
- Adds ORDER BY at the end
- Applies different WHERE clauses to each SELECT
Up Next
Continue with Subqueries — nested queries inside other statements.
Related Topics
Frequently Asked Questions about Union
What is Union in MySQL?
Union is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Union?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Union.
Why is Union important in MySQL?
Union is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.