![]() |
VOOZH | about |
The SQL UNION operator is used to combine the result sets of two or more SELECT queries into a single output. It removes duplicate rows and returns only unique records from all combined queries.
Example: First, we create a demo SQL database and tables, on which we will use the UNION Operator command.
Query:
SELECT city FROM Table1
UNION
SELECT city FROM Table2;
Output:
Syntax:
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
Let's look at an example of UNION operator in SQL to understand it better. Let's create two tables "Emp1" and "Emp2";
In this example, we find the countries (only unique values) from both the "Table1" and the "Table2" tables:
Query:
SELECT Country FROM Emp1
UNION
SELECT Country FROM Emp2
ORDER BY Country;
Output:
Note: The
UNIONoperator combines the results of two queries and removes duplicate rows, whileUNION ALLincludes all rows from both queries without eliminating duplicates.