Curriculum
This tutorial shows you how to use the SQL UNION to combine two or more result sets from multiple queries and explains the difference between UNION and UNION ALL.
The UNION operator combines result sets of two or more SELECT statements into a single result set. The following statement illustrates how to use the UNION operator to combine result sets of two queries:
SELECT column1, column2 FROM table1 UNION [ALL] SELECT column3, column4 FROM table2;
To use the UNION operator, you write the dividual SELECT statements and join them by the keyword UNION.
The columns returned by the SELECT statements must have the same or convertible data type, size, and be the same order.
The database system processes the query by executing two SELECT statements first. Then, it combines two individual result sets into one and eliminates duplicate rows. To eliminate the duplicate rows, the database system sorts the combined result set by every column and scans it for the matching rows located next to one another.
To retain the duplicate rows in the result set, you use the UNION ALL operator.
The union is different from the join that the join combines columns of multiple tables while the union combines rows of the tables.
To get the data from the A table, you use the following SELECT statement:
SELECT id FROM A;
To retrieve the data from the B table, you use the following statement:
SELECT id FROM B;
To combine result sets of these two queries, you use the UNION operator as follows:
SELECT id FROM a UNION SELECT id FROM b;
The result set includes only 3 rows because the UNION operator removes one duplicate row.
To retain the duplicate row, you use the UNION ALL operator as follows:
To sort the result set, you place the ORDER BY clause after all the SELECT statements as follows:
SELECT id FROM a UNION SELECT id FROM b ORDER BY id DESC;
The database system performs the following steps:
In practice, we often use the UNION operator to combine data from different tables.
The following statement uses the UNION operator to combine the first name and last name of employees and dependents.
SELECT first_name, last_name FROM employees UNION SELECT first_name, last_name FROM dependents ORDER BY last_name;