How to Combine the Results of Two Queries in SQL
This operator takes two or more SELECT statements and combines the results into a single result set. For example, if you wanted to combine the results of two queries, you could use the following query:
SELECT * FROM table1
UNION
SELECT * FROM table2;
This query would return the combined results of the two SELECT statements.
Note that each SELECT statement within the UNION operator needs to have the same number of columns and the same data types in each column. Additionally, the columns in every SELECT statement also need to be in the same order.
Examples using the SQL UNION Operator
Let's look at a few examples of how this can be used. Suppose you have two tables, users and orders, with the following data:
name | age |
---|---|
John | 25 |
Jane | 30 |
John | 25 |
Bob | 20 |
name | order |
---|---|
John | Book |
Jane | Pen |
Bob | Pencil |
If you wanted to combine the results of these two tables, you could use the following query:
SELECT * FROM users
UNION
SELECT * FROM orders;
This query would return the following result set:
Name | Age | Order |
---|---|---|
John | 25 | Book |
Jane | 30 | Pen |
John | 25 | NULL |
Bob | 20 | Pencil |
Additional Info About Using the SQL UNION Operator
The UNION operator is just one way to combine the results of two queries in SQL. Depending on your needs, you may also want to look into the INTERSECT and EXCEPT operators. For more information, check out the documentation for your particular database.