Introduction
Consider a situation where you have two different tables, and your task is to merge both the tables and make them into a single table. In a database, terminology merge is referred to as a union.
Source: imgflip
To solve this task, let’s learn an amazing Clause named UNION.
In this article, we will be analysing how to use the UNION clause. The UNION clause will help merge two or more tables into a single table.
All the queries and questions apply to the following Database Tables.
Consider the FacebookData table and LinkedInData table having all the data of users consisting of columns like PersonID, Name, City, ContactNumber.
Recommended topics, DCL Commands in SQL and Tcl Commands in SQL
UNION clause
The Union clause combines two or more tables without duplicate data in the final table. Union clause can only be applied with the SELECT statement.
Before moving forward, Let’s look at the conditions for which the UNION clause can be applied.
- The number of columns should be the same for the tables a user wants to merge.
- The data type of the columns should be the same. If the column data type is INT in one table, the table the user wants to merge should be INT data type, although the column names do not have to be identical.
- The occurrence of columns in both tables should be in the same order. If table1 has the following columns of data type INT, varchar, INT, then in the second table, the data type of the columns should be of the same order.
The above conditions should be checked before applying the UNION clause. But, there are no restrictions with the entries of the rows in both the tables.
The above image shows how the UNION clause will work internally.
Even though the number of columns and data types are the same in the above table, but not in the same order, the UNION clause will not be applied.
Syntax
SELECT column_name(s) FROM tableName1 UNION SELECT column_name(s) FROM tableName2; |
Let consider an example,
From the given two tables named as FacebookData and LinkedInData. We need to find the union of both the tables and print the resultant table.
SQL Query:
SELECT * FROM FacebookData UNION SELECT * FROM LinkedInData; |
Result for the above query:
Let consider another example,
From the given two tables, FacebookData and LinkedInData, we need to find the union of both the tables and print only the City column in the resultant table.
SQL Query:
SELECT City FROM FacebookData UNION SELECT City FROM LinkedInData; |
Result for the above query:
After looking at the UNION clause, one most common question that comes to mind is that we know that many people have the same name, live in the same city, and have the same contact number because they have a different service provider. So, there may be situations where you want duplicate data entries also.
The UNION ALL clause can be used to solve this type of problem.
Recommended Topic, DCL Commands in SQL