TechnoLearnAcademy

TECHNOLEARN

The UNION Operator

The UNION Operator is used to combine the result sets of two or more queries into a single result set.
      • The data type of each column must be the same.
      • The Order of the columns must be the same in each select statement.
SYNTAX:
                       SELECT column1, column2 , column3 , ..
                       FROM table1
                       UNION
                       SELECT column1, column2 , column3, …                                                                                                                                           FROM table2;
Let’s understand the union with an example. For demonstration purposes, we will be using the table emp.
UNION
Example:
   Objective: In this example, we will combine the results set of the employee table and the customer table.
                      SELECT Ecode, FirstName, LastName, Emailaddress FROM  Tbl_Emp                                                                                              UNION                                                                                                                                                                                                SELECT Ecode, FirstName, LastName, Emailaddress FROM Tbl_Customer                    
Example:
   Objective: In this example, we will combine the results set of the employee table and the customer table with conditions.
                      SELECT Ecode, FirstName, LastName, Emailaddress FROM  Tbl_Emp   WHERE Department = ‘IT’                                                UNION                                                                                                                                                                                                SELECT Ecode, FirstName, LastName, Emailaddress FROM Tbl_Customer WHERE   Department = ‘IT’                
UNION ALL
Example:
   Objective: In this example, we will combine the results set of the employee table and the customer table with conditions.
                      SELECT Ecode, FirstName, LastName, Emailaddress FROM  Tbl_Emp   WHERE Department = ‘IT’                                                UNION  ALL                                                                                                                                                                                        SELECT Ecode, FirstName, LastName, Emailaddress FROM Tbl_Customer WHERE   Department = ‘IT’                
UNION vs UNION ALL
    • UNION will retrieve unique records from two or more queries.
    • UNION ALL will retrieve duplicate records from two or more queries.
Scroll to Top