SQL SELECT union

In SQL, the UNION operator allows you to combine the results of multiple SELECT queries into a single result set. This can be useful when you want to retrieve data from different tables or apply different conditions to the same table.

Syntax

The basic syntax for using the UNION operator is as follows:

SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;

Both SELECT queries must have the same number of columns, and the corresponding column types must also match.

Example

Let’s say we have two tables: employees and customers. We want to retrieve a unified list of names and emails from both tables.

SELECT name, email FROM employees
UNION
SELECT name, email FROM customers;

This query will return a result set containing the combined names and emails from the two tables.

Sorting the Result Set

By default, the UNION operator removes duplicate rows from the result set. If you want to include duplicate rows, you can use the UNION ALL operator instead.

Additionally, you can sort the result set using the ORDER BY clause. For example:

SELECT name, email FROM employees
UNION
SELECT name, email FROM customers
ORDER BY name;

In this case, the result set will be sorted in ascending order based on the name column.

Conclusion

The SQL UNION operator allows you to combine the results of multiple SELECT queries, providing a way to retrieve a unified result set. This can be particularly useful when working with multiple tables or applying different conditions to the same table. Remember to ensure that the number of columns and their types match in each SELECT query when using UNION.