In SQL, the UNION ALL operator is used to combine the results of two or more SELECT statements into a single result set, including duplicates. This operator is similar to the UNION operator, but it does not remove the duplicates from the result set.
The syntax of the UNION ALL operator is as follows:
SELECT column1, column2, ...
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2;
Here, the SELECT statements can include any valid SQL statement, including subqueries, functions, and expressions.
Let’s take an example to understand how the UNION ALL operator works in SQL:
Assume that we have two tables, Table1 and Table2, with the following data:
Table1:
Id | Name | Age | City |
---|---|---|---|
1 | John | 25 | New York |
2 | Sarah | 30 | Chicago |
3 | Peter | 28 | Miami |
4 | Rachel | 24 | Boston |
Table2:
Id | Name | Age | City |
---|---|---|---|
5 | Michael | 32 | Dallas |
6 | Emily | 27 | Boston |
7 | David | 29 | Miami |
8 | Alice | 26 | Denver |
Now, if we want to combine the data from both tables, including duplicates, we can use the UNION ALL operator, as shown below:
SELECT Id, Name, Age, City
FROM Table1
UNION ALL
SELECT Id, Name, Age, City
FROM Table2;
The result set of this query would be as follows:
Id | Name | Age | City |
---|---|---|---|
1 | John | 25 | New York |
2 | Sarah | 30 | Chicago |
3 | Peter | 28 | Miami |
4 | Rachel | 24 | Boston |
5 | Michael | 32 | Dallas |
6 | Emily | 27 | Boston |
7 | David | 29 | Miami |
8 | Alice | 26 | Denver |
As you can see, the result set includes all the rows from both tables, including duplicates.
In conclusion, the UNION ALL operator is used to combine the results of two or more SELECT statements into a single result set, including duplicates. It is useful when we want to retrieve all the data from multiple tables, without removing the duplicates.
Also check WHAT IS GIT ? It’s Easy If You Do It Smart
You can also visite the Git website (https://git-scm.com/)