UNION operator is used to get the combine results of two or more tables.
every select statement of tables must have same fields name with same data type and same order.
it used to get unique value from tables.
For SELECT Statement
Syntax:-
SELECT column_name(s)
FROM table_name1
UNION
SELECT column_name(s)
FROM table_name2
Example:- Suppose we have two table employees and users.
employees Table:-
+----+------------+-----------+----------------+-----------+
| id | first_name | last_name | email | country |
+----+------------+-----------+----------------+-----------+
| 1 | John | Tailor | john@abc.com | USA |
| 2 | Rom | Tailor | rom@abc.com | USA |
| 3 | Andrew | Symonds | andrew@abc.com | Australia |
| 4 | Miacle | Tailor | miacle@abc.com | Australia |
| 5 | Sachin | Tendulkar | sachin@abc.com | India |
| 6 | Virat | Kohli | virat@abc.com | India |
| 7 | rohit | NULL | rohit@abc.com | India |
users table:-
+----+------------+-----------+----------------+---------+
| id | first_name | last_name | email | country |
+----+------------+-----------+----------------+---------+
| 1 | Ramesh | Kumar | ramesh@abc.com | India |
| 2 | Suresh | Kumar | suresh@abc.com | India |
| 3 | Anna | Symonds | anna@abc.com | USA |
+----+------------+-----------+----------------+---------+
3 rows in set (0.00 sec)
Find the country name which has unique name.
Query:-
SELECT country FROM employees
UNION
SELECT country FROM users
Output:-
+-----------+
| country |
+-----------+
| USA |
| Australia |
| India |
+-----------+
3 rows in set (0.00 sec)
SQL UNION Operator – Interview Questions
Q 1: What does UNION do?
Ans: It combines result sets and removes duplicates.
Q 2: Do columns need same count?
Ans: Yes.
Q 3: Do column data types need to match?
Ans: Yes.
Q 4: Can ORDER BY be used with UNION?
Ans: Yes, at the end.
Q 5: Does UNION affect data?
Ans: No.
SQL UNION Operator – Objective Questions (MCQs)
Q1. What does UNION do?
Q2. UNION removes:
Q3. UNION requires:
Q4. UNION is used between:
Q5. UNION sorts data by default?