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:

                                                                                                             
users
nameage
John25
Jane30
John25
Bob20
                                                                                         
orders
nameorder
JohnBook
JanePen
BobPencil

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:

                                                                                                                                           
User orders
NameAgeOrder
John25Book
Jane30Pen
John25NULL
Bob20Pencil


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.

Want to build your own LLM Apps with AirOps👇👇