Wednesday, 8 August 2012

SQL -UNION

Union
Union is an operation of combining the output of two SELECT statements. Union of two SELECT statements can be performed only if their outputs contain same number of columns and data types of corresponding columns are also the same. The syntax of UNION in its simplest form is:

SELECT <select_list>
FROM <tablename>
[WHERE <condition> ]
UNION [ALL]
SELECT <select_list>
FROM <tablename>
[WHERE <condition> ];

Union does not display any duplicate rows unless ALL is specified with it.

Example:
Suppose a company deals in two different categories of items. Each category contains a number of items and for each category there are different customers. In the database there are two customer tables: Customer_Cat_1 and Customer_Cat_2. If it is required to produce a combined list of all the customers, then it can be done as follows:
SELECT Cust_Code from Customer_Cat_1
UNION
SELECT Cust_Code from Customer_Cat_2;

If a customer exists with same customer code in both the tables, its code will be displayed
only once - because Union does display duplicate rows. If we explicitly want the duplicate
rows, then we can enter the statement:

SELECT Cust_Code from Customer_Cat_1
UNION ALL
SELECT Cust_Code from Customer_Cat_2;

2 comments: