Overview Of SQL Union Operator

 

The UNION operator is used to JOIN the result-set of two or more two selected statements.

Using UNION, multiple SELECT statements can be described, and their results can be combined into a single result set.

Each query in a UNION must include the same columns, expressions or combined functions Column data types must be appropriate

The column names in the conclusion are normally balanced with the column names in the first SELECT statement in the UNION.


UNION Syntax

SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

Table name Order

Order IdCustomer NumberOrder DateCity
00145552020-02-03Lucknow
00275552020-07-23Kanpur
00365552020-01-22Noida
00435552020-06-04Mumbai
00585552020-03-18Kolkata

 

Table name Customers

Customer NumberNameCountryCity
7555AlokIndiaKanpur
4555AmitIndiaLucknow
1555PawanIndiaDelhi
2555SumitIndiaPune

Example

SELECT City FROM Customers
UNION
SELECT City FROM Order
ORDER BY City;

In both the table we have a common city each city will only be recorded
once because UNION selects only clear-cut values. Use UNION ALL to include duplicate values.

The UNION naturally deletes any duplicate rows from the query result set.

If you want all instances of all matches returned, then you can use UNION ALL.;

SQL UNION ALL syntax

SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2 ;

Table name Order

Order IdCustomer NumberOrder DateCity
00145552020-02-03Lucknow
00275552020-07-23Kanpur
00365552020-01-22Noida
00435552020-06-04Mumbai
00585552020-03-18Kolkata

 

Table name Customers

Customer NumberNameCountryCity
7555AlokIndiaKanpur
4555AmitIndiaLucknow
1555PawanIndiaDelhi
2555SumitIndiaPune

Example

SELECT City FROM Order
UNION ALL
SELECT City FROM Customers
ORDER BY City;

SQL UNION ALL Instance

Example

Table Name Customers

Customer IdNameAddressCityPostal codeCountry

001

Ankit New Ashok Nagar H.NO 67/6Lucknow82878India

002

VinayB clash society L810PuneNAIndia

003

RajuMathur Road near ICIC bank H.no7/290Delhi29867India

004

Karan H.no 456 near kv schoolNoida98689India

005

Sumit Near SPGI hospital house67GoaNAIndia

 

Table Name Order

Order IdCustomer IdEmployee IdOrder Date    Postal codeshipped Id
1029 0086287902020-09-04NA11900
10220092729892020-07-044849412900
10780052828962020-03-04NA13900
10780042786262020-11-044949014900
SELECT Postalcode FROM Customers
UNION ALL
SELECT Postalcode FROM order
ORDER BY customer Id

SQL UNION ALL with the WHERE

SELECT Postalcode, Name FROM customers
WHERE Postalcode='00'
UNION ALL
SELECT Postalcode, Customer Id FROM customers
WHERE Postalcode='00'
ORDER BY OrderDate  ;

 

 

 

Keywords: