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






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.