Basic UNION ALL query

suggest change
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 UNION ALL we can get all the employees from both HR and Finance who hold the position of 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 people can have the same name and position in both departments, this example uses UNION ALL so that duplicates are kept.

If you want to use an alias for each output column, you can 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'

A single-quoted alias is accepted by SQL Server and MySQL. Standard SQL uses an unquoted alias or a delimited identifier.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents