TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
SQL UNION Operator
Morteza Mousavi
Oct 13, 2017
6.3
k
0
1
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
The SQL UNION operator combines two or more SELECT statements.
The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
SQL UNION Syntax
SELECT
column_name(s)
FROM
table_name1
UNION
SELECT
column_name(s)
FROM
table_name2
Note
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
SQL UNION ALL Syntax
SELECT
column_name(s)
FROM
table_name1
UNION
ALL
SELECT
column_name(s)
FROM
table_name2
Note
The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.
SQL UNION Example
Look at the following tables,
"Employees_England"
E_ID
E_NAME
1
Barnes, Stephen
2
Dean, Alex
3
Taylor, John
4
Young, Colin
E_ID
E_NAME
1
Taylor, John
2
Johnson, James
3
Brown, Mike
4
Miller, Andrew
Now we want to list all the different employees in England and USA.
We use the following SELECT statement,
SELECT
E_Name
FROM
Employees_England
UNION
SELECT
E_Name
FROM
Employees_USA
The result-set will look like this,
E_NAME
Barnes, Stephen
Dean, Alex
Taylor, John
Young, Colin
Johnson, James
Brown, Mike
Miller, Andrew
Note
This command cannot be used to list all employees in England and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.
SQL UNION ALL Example
Now we want to list all employees in England and USA,
SELECT
E_Name
FROM
Employees_England
UNION
ALL
SELECT
E_Name
FROM
Employees_USA
Result
E_NAME
Barnes, Stephen
Dean, Alex
Taylor, John
Young, Colin
Taylor, John
Johnson, James
Brown, Mike
Miller, Andrew
UNION Operator
SQL Server
Next Recommended Reading
SQL Server - Union Vs. Union All