SQL tutorial
SQL Union
Learn more about SQL, a standard language for interacting with databases and storing, manipulating, and retrieving data from databases.
Go hands-on with SQL in our free interactive SQL tutorial.
The SQL UNION
clause can be used to concatenate the results of multiple SELECT
statements together into a single result.
In the general form, it is used as linkage between two or more SELECT
statements as below:
SELECT … FROM …
UNION
SELECT … FROM …
UNION
SELECT … FROM …
…
Since the results are being concatenated, it is a requirement that the schema (number of columns and data types) in the results of the individual queries match, otherwise the results will not be able to be concatenated.
For example, we can put together the results of two simple SELECT
statements from the employees table using USING
, to find employees who have first names either “Georgi” or “Annelise”:
SELECT * FROM employees WHERE first_name = "Georgi"
UNION
SELECT * FROM employees WHERE first_name = "Anneke";
For this simple example, it should be noted that an equivalent result can be achieved using a WHERE
clause and OR
with the two predicates, or using IN
and a single predicate with both names:
SELECT * FROM employees WHERE first_name = "Georgi" OR first_name = "Anneke";
In practice, UNION
is most often used when combining different tables with the same schema or in more complex data engineering SQL code. For simpler queries coming from the same table, an equivalent result can usually be arrived upon without requiring its usage, as seen in above.
Learn SQL Today
Get hands-on experience writing code with interactive tutorials in our free online learning platform.
- Free and fun
- Designed for beginners
- No downloads or setup required