SQL UNION Operation

In this tutorial you will learn how to combine the results of two or more SQL queries.

The UNION Operator

The UNION operator is used to combine the results of two or more SELECT queries into a single result set. The union operation is different from using joins that combine columns from two tables. The union operation creates a new table by placing all rows from two source tables into a single result table, placing the rows on top of one another.

These are basic rules for combining the result sets of two SELECT queries by using UNION:

  • The number and the order of the columns must be the same in all queries.
  • The data types of the corresponding columns must be compatible.

When these criteria are met, the tables are union-compatible:

Syntax

The basic syntax of UNION can be given with:

SELECT `column_list` FROM `table1_name`
UNION SELECT `column_list` FROM `table2_name`;

To understand the union operation in a better way, let’s assume that some hypothetical fields, like first_name and last_name exists in our employees and customers tables. Please note that these fields do not actually exist in our demo database tables.

![image-20240813224629233](C:\Users\The_MAK\OneDrive\Desktop\Lectures\Docs\MySQL\Level 00\image-20240813224629233.png)

Let’s perform a union operation to combine the results of two queries.

The following statement returns the first and last names of all the customers and employees:

Example

SELECT first_name, last_name FROM employees 
UNION
SELECT first_name, last_name FROM customers;

After executing the above statement, the result set will look something like this:

+---------------+--------------+
| first_name    | last_name    |
+---------------+--------------+
| Ethan         | Hunt         |
| Tony          | Montana      |
| Sarah         | Connor       |
| Rick          | Deckard      |
| Martin        | Blank        |
| Maria         | Anders       |
| Fran          | Wilson       |
| Dominique     | Perrier      |
| Thomas        | Hardy        |
+---------------+--------------+

The UNION operation eliminates the duplicate rows from the combined result set, by default. That’s why the above query returns only 9 rows, because if you notice the name “Martin Blank” appears in both the employees and customers tables.

However, if you want to keep the duplicate rows you can use the ALL keyword, as follow:

Example

SELECT first_name, last_name FROM employees 
UNION ALL
SELECT first_name, last_name FROM customers;
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team