SQL Basic UNION ALL query


Example

CREATE TABLE HR_EMPLOYEES
(
    PersonID int,
    LastName VARCHAR(30),
    FirstName VARCHAR(30),
    Position VARCHAR(30)
);

CREATE TABLE FINANCE_EMPLOYEES
(
    PersonID INT,
    LastName VARCHAR(30),
    FirstName VARCHAR(30),
    Position VARCHAR(30)
);

Let's say we want to extract the names of all the managers from our departments.

Using a UNION we can get all the employees from both HR and Finance departments, which hold the position of a manager

SELECT 
    FirstName, LastName   
FROM 
    HR_EMPLOYEES  
WHERE 
    Position = 'manager'  
UNION ALL  
SELECT 
    FirstName, LastName  
FROM 
    FINANCE_EMPLOYEES  
WHERE 
    Position = 'manager'  

The UNION statement removes duplicate rows from the query results. Since it is possible to have people having the same Name and position in both departments we are using UNION ALL, in order not to remove duplicates.

If you want to use an alias for each output column, you can just put them in the first select statement, as follows:

SELECT 
    FirstName as 'First Name', LastName as 'Last Name'
FROM 
    HR_EMPLOYEES  
WHERE 
    Position = 'manager'  
UNION ALL  
SELECT 
    FirstName, LastName  
FROM 
    FINANCE_EMPLOYEES  
WHERE 
    Position = 'manager'