SQL UNION
Introduction
When working with databases, you'll often need to combine data from different tables or query results. SQL provides several ways to do this, and one of the most powerful is the UNION
operator.
The UNION
operator allows you to combine the result sets of two or more SELECT statements into a single result set. This is particularly useful when you need to retrieve similar data from different tables, or when you want to combine results that meet different criteria from the same table.
In this tutorial, you'll learn:
- How
UNION
andUNION ALL
work - The rules for using these operators
- Practical examples using real-world scenarios
- Common use cases and best practices
UNION Basics
What is SQL UNION?
The UNION
operator combines the results of two or more SELECT statements into a single result set. The basic syntax is:
SELECT column1, column2, ... FROM table1
UNION
SELECT column1, column2, ... FROM table2;
Key characteristics of UNION
:
- Removes duplicate rows from the combined result set
- Returns only distinct values
- Requires the same number of columns in each SELECT statement
- Column data types must be compatible
- The column names from the first SELECT statement are used as the column names for the result set
What is SQL UNION ALL?
UNION ALL
works similarly to UNION
, but it includes all rows, even duplicates:
SELECT column1, column2, ... FROM table1
UNION ALL
SELECT column1, column2, ... FROM table2;
UNION ALL
is generally faster than UNION
because it doesn't need to perform the additional processing to remove duplicates.
Rules for Using UNION
For UNION
to work properly, both SELECT statements must follow these rules:
- Both SELECT statements must have the same number of columns
- Corresponding columns must have compatible data types
- The column order matters and should match in both queries
- Column names from the first SELECT statement are used in the result
- ORDER BY clause can only appear at the end of the entire query