MOCKSTACKS
EN
Questions And Answers

More Tutorials









SQLServer UNION UNION ALL

Basic UNION ALL query


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'



Conclusion

In this page (written and validated by ) you learned about SQLServer UNION UNION ALL . What's Next? If you are interested in completing SQLServer tutorial, your next topic will be learning about: SQLServer ALTER TABLE.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.