![]() |
VOOZH | about |
The UNION ALL operator in MySQL combines the results of multiple SELECT statements while retaining duplicate rows. It is faster and more efficient when duplicate removal is not required.
Syntax:
SELECT column1, column2, ...
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2;Note: Each SELECT statement can include optional WHERE conditions.
It demonstrates how the MySQL UNION ALL operator is used to combine results from multiple queries. First, we create a demo table on which the UNION ALL operator will be used:
This example retrieves a combined list of employee names based on different conditions. It includes duplicate values if they satisfy both conditions.
Query:
SELECT name FROM employees
WHERE department = 'HR'
UNION ALL
SELECT name FROM employees
WHERE position = 'Developer';Output:
This example combines filtered data and sorts the final result. It demonstrates ordering after merging results.
Query:
SELECT name, position FROM employees
WHERE department = 'HR'
UNION ALL
SELECT name, position FROM employees
WHERE position = 'Developer'
ORDER BY position;Output:
Here are some key differences between UNION ALL and UNION operator:
UNION ALL | UNION |
|---|---|
Combines results of SELECT statements and includes all duplicates. | Combines results of SELECT statements and removes duplicate rows. |
Faster, as it does not perform duplicate removal. | Slower, as it performs a distinct operation to remove duplicates. |
Useful when you need to include every row from the combined queries, including duplicates. | Useful when you need to eliminate duplicate rows and only see unique results. |
More efficient for large datasets with duplicates. | Less efficient due to the overhead of duplicate checking. |
The UNION ALL operator offers performance and efficiency benefits when working with combined datasets.