1. “Harward” table:
| Id | Name | Age | Course |
|---|---|---|---|
| 1 | John Travolta | 20 | Computer Graphics |
| 2 | Mary Jones | 21 | Advanced Maths |
| 3 | Jacobs | 22 | Motion Physics |
2. “MIT” table:
| Id | Name | Age | Course |
|---|---|---|---|
| 1 | Mena Suvari | 25 | MBA |
| 2 | John Travolta | 30 | PHD |
Note: Note: Both tables have a duplicate student by the name of ‘John Travolta’.
Now let us select the data from these 2 tables using Union and Union All operators.
Run the following SQL Union All query statement to combine the results from the 2 tables (Harward & MIT).
Select Name, Age From Harward
Union All
Select Name, Age From MIT
You will see the result which is shown below:
| Name | Age | Course |
|---|---|---|
| John Travolta | 20 | Computer Graphics |
| Mary Jones | 21 | Advanced Maths |
| Jacobs | 22 | Motion Physics |
| Mena Suvari | 25 | MBA |
| John Travolta | 30 | PHD |
You can clearly see that Union All presented you with all the records from the 2 tables. That is, the student named ‘John Travolta’ is shown from each of these 2 tables.
Now run the same query with SQL Union operator.
Select Name, Age From Harward
Union
Select Name, Age From MIT
The result in this case is:
| Name | Age | Course |
|---|---|---|
| John Travolta | 20 | Computer Graphics |
| Mary Jones | 21 | Advanced Maths |
| Jacobs | 22 | Motion Physics |
| Mena Suvari | 25 | MBA |
See that the SQL Union has removed the duplicate entry of the student named ‘John Travolta’, from the result-set.
1. The ‘Union’ operator effectively does a SELECT DISTINCT on the results set. If you know that all the records are unique then use Union All instead, since it gives faster results.
2. Union & Union All can be used in place of SQL Joins as they may be faster in certain situations.
3. Inner queries can be rewritten using Union and Union All.