Basic UNION ALL query
suggest changeCREATE 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents