Basic Difference Between Union vs Union All Operator
Union: It is an Operator which is used to combine two or more tables.
It gives a unique result set and it will not allow duplicates.
Basic Conditions which need to be fulfilled by tables.
1. Both tables should have the same number of columns.
2. Both table columns should have the same data types.
3. Columns should be in the same order in each table.
Let's take an Example:
We have 2 tables containing employee id and employee name and it has some duplicate values as well.
Table: Employee1
Employee ID | Employee First Name |
---|---|
11 | Bob |
12 | Jerry |
13 | John |
14 | Alex |
15 | Joe |
Table: Employee2
Employee ID | Employee First Name |
---|---|
21 | Marry |
12 | Jerry |
23 | lily |
13 | John |
25 | Mat |
Query: Select from Employee1 Union Select from Employee2;
After Using Union Operator We will get only 8 records instead of 10 because we have 2 duplicates in Table 2.
Employee ID | Employee First Name |
---|---|
11 | Bob |
12 | Jerry |
13 | John |
14 | Alex |
15 | Joe |
21 | Marry |
23 | lily |
25 | Mat |
Union All: It is an operator which works the same as the Union operator and it also allows duplicate values.
Query: Select from Employee1 Union All Select from Employee2;
After Using Union All Operator We will get 10 records which include 2 duplicate values.
Employee ID | Employee First Name |
---|---|
11 | Bob |
12 | Jerry |
13 | John |
14 | Alex |
15 | Joe |
21 | Marry |
12 | Jerry |
23 | lily |
13 | John |
25 | Mat |
Thanks for reading this and I hope you like it.
Mayank Agrawal
- Mayank Agrawal
- Dec, 27 2022