MySQL UNION Clause
The UNION operator in MySQL is used to combine the result sets of two or more SELECT statements into a single result set, eliminating duplicate rows by default. The combined result set will have columns matching the first SELECT statement.
Syntax
UNION: Combines the results of two or moreSELECTstatements.UNION ALL: Includes duplicate rows in the result set.
Key Rules for Using UNION
Column Alignment:
- Each
SELECTstatement must return the same number of columns. - The data types of the columns in corresponding positions must be compatible.
- Each
Order of Columns:
- Column names in the result set are taken from the first
SELECTstatement.
- Column names in the result set are taken from the first
Default Behavior:
- By default,
UNIONeliminates duplicate rows. UseUNION ALLto include duplicates.
- By default,
Examples
Example 1: Basic UNION
Goal: Combine data from two tables: customers_usa and customers_canada.
Result:
Example 2: UNION ALL (Retain Duplicates)
Result:
Example 3: Adding Filters
Goal: Retrieve customers with IDs less than 5 from one table and IDs greater than 10 from another.
Example 4: Sorting the Result Set
To sort the combined results, use ORDER BY after the final SELECT statement.
Example 5: Combining Data from the Same Table
Goal: Retrieve a list of employees, combining different job titles into a single result set.
UNION vs. UNION ALL
| Feature | UNION | UNION ALL |
|---|---|---|
| Duplicates | Removes duplicate rows | Keeps duplicate rows |
| Performance | Slightly slower due to duplicate checks | Faster as no duplicate checks |
| Use Case | Unique rows only | All rows, including duplicates |
Common Errors and How to Fix Them
Mismatch in Number of Columns:
- Error:
#1222 - The used SELECT statements have a different number of columns - Fix: Ensure all
SELECTstatements have the same number of columns.
- Error:
Data Type Incompatibility:
- Ensure corresponding columns in the
SELECTstatements have compatible data types.
- Ensure corresponding columns in the
Using
ORDER BYin Intermediate Queries:- Error:
ORDER BYmust be at the end of the UNION query. - Fix: Move
ORDER BYto the final query.
- Error:
Performance Tips
- Use
UNION ALLif you do not need to remove duplicates—it avoids the overhead of sorting and comparing rows. - Add indexes on columns used in the
SELECTandWHEREclauses to improve performance. - Filter rows in individual
SELECTstatements before applyingUNION.
Conclusion
The UNION operator is a powerful tool for combining datasets from multiple queries into a unified result set. By using variations like UNION and UNION ALL, you can control the inclusion of duplicates based on your needs. With proper optimization, it becomes a vital query mechanism in MySQL

