In SQL, the UNION ALL
operation is used to combine the results of two or more SELECT
statements into a single result set. Unlike the UNION
operator, which removes duplicate rows, UNION ALL
retains all rows from each SELECT statement, resulting in a larger result set.
Syntax
The basic syntax for using UNION ALL
is as follows:
SELECT column1, column2, ... FROM table1
UNION ALL
SELECT column1, column2, ... FROM table2
Each SELECT
statement must have the same number of columns with compatible data types.
Example
Let’s consider a simple example where we have two tables, customers
and employees
, that store information about company personnel. We want to combine the data from both tables to get a comprehensive list of all individuals associated with the company.
SELECT full_name, email FROM customers
UNION ALL
SELECT full_name, email FROM employees;
In this example, we have specified the full_name
and email
columns from both the customers
and employees
tables. The UNION ALL
operation will merge the results from both tables, preserving duplicate rows.
Use Cases
The UNION ALL
operation is commonly used in scenarios where you need to combine data from multiple tables or queries. Some common use cases include:
- Consolidating information from multiple tables into a single report or result set.
- Combining similar data from different sources or databases.
- Merging data from temporary or staging tables before further processing.
It’s important to note that UNION ALL
does not perform any sorting or filtering. To sort or eliminate duplicate rows from the result set, you can use the ORDER BY
and DISTINCT
keywords respectively.
Conclusion
The UNION ALL
operation is a powerful feature in SQL that allows you to combine the results of multiple SELECT
statements. It retains all rows from each query, making it useful for scenarios where you need to simply merge data without considering duplicates. By utilizing UNION ALL
, you can efficiently consolidate and analyze data from various sources in your SQL queries.
#SQL #UNIONALL