Home » SQL

How to use UNION in SQL?

In this article, we are going to use UNION clause/operator which combine results of two or may be more than two SELECT statements.
Submitted by Manu Jemini, on March 04, 2018

This somewhat advance in SQL because whenever we need to merge the result of two different SQL SELECT queries results we use UNION keyword.

Now in the example giving below, we got an example explaining just this concept of union. Let’s say we have two different SQL queries:

	Select * from A
	Select * from B

So whenever we this kind of condition we somehow want to have a single result including the results of both of these queries. Yes this can also be don’t with a single SELECT query like:

	SELECT * from A, B

But, what if our SQL query is very complex and we don’t want to make it more complex? At that time when, we have two very complex queries and we want to unite them, all we need to do is to use the union keyword like this:

 SELECT * from A UNION select * from B

Dummy data:

SQL UNION Example

Syntax 1: (UNION)

SELECT c1,c2 FROM table1,table2  [WHERE condition]  UNION
SELECT c1,c2 FROM table1,table2  [WHERE condition]

Syntax 2: (UNION ALL)

SELECT c1,c2 FROM table1, table2 [WHERE condition]  UNION ALL
SELECT c1,c2 FROM table1, table2 [WHERE condition]

Example 1:

SELECT  ID, NAME, SALARY, COMPANY_NAME FROM 'includehelp'.'employee' 
LEFT JOIN 'includehelp'.'company' ON 
'includehelp'.'employee'.ID = 'includehelp'.'company'.COMPANY_ID
UNION
SELECT  ID, NAME, SALARY, COMPANY_NAME FROM 'includehelp'.'employee' 
RIGHT JOIN 'includehelp'.'company' ON 
'includehelp'.'employee'.ID = 'includehelp'.'company'.COMPANY_ID
SQL UNION Example Output 1

Example 2:

SELECT  ID, NAME, SALARY, COMPANY_NAME FROM 'includehelp'.'employee' 
LEFT JOIN 'includehelp'.'company' ON 
'includehelp'.'employee'.ID = 'includehelp'.'company'.COMPANY_ID
UNION ALL
SELECT  ID, NAME, SALARY, COMPANY_NAME FROM 'includehelp'.'employee' 
RIGHT JOIN 'includehelp'.'company' ON 
'includehelp'.'employee'.ID = 'includehelp'.'company'.COMPANY_ID
SQL UNION Example Output 2



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.