Monday, 11 February 2013

SQL Server RIGHT Outer JOIN Syntax and Example

SQL RIGHT JOIN
The RIGHT JOIN returns all rows from the Right Table (Table_I), includes the matching rows from the Left Table (Table_2).
In other words it returns all the matching rows from both the tables and non matching rows from right table.


Syntax:
SELECT Column_name(s) FROM Table_1 T1 RIGHT JOIN Table_2 T2
ON  T1.Column_name=T2.Column_name

Hint: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.


Example :

Suppose we have two tables as follows

The "ORDERS" Table:
Order_Id
Sales_Period
Cust_Id
Sales
ABC_1234
Q1-2014
Cust_1234
40474
BCD_2345
Q2-2014
Cust_2345
44321
CDE_3456
Q3-2014
Cust_3456
19906
DEF_4567
Q4-2014
Cust_4567
34943
EFG_1122
Q1-2015
Cust_1122
22114
FGH_3344
Q2-2015
Cust_3344
41364
GHI_5566
Q3-2015
Cust_5566
16157
IJK_7788
Q4-2015
Cust_7788
36054


The "CUSTOMERS" Table:

Cust_Id
Cust_Name
Cust_Location
Cust_1234
ABC Soft Pvt 
Ltd
East
Cust_3456
CDE Info Pvt 
Ltd
West
Cust_4466
FFDD Info Pvt Ltd
Mid-West
Cust_1122
EFC Tech Pvt Ltd
South
Cust_6688
HHFF Tech Pvt Ltd
Mid-South
Cust_5566
GHI Services Pvt Ltd
North

Now we want to list all the Orders and the corresponding Customers details.
We use the following Right Join Query :

Select O.Order_Id,C.Cust_Name,C.Cust_Id,C.Cust_Location,O.Sales_Period,O.Sales from ORDERS RIGHT JOIN CUSTOMERS ON C.Cust_Id = O.Cust_Id

Output :

Order_Id
Cust_Name
Cust_Id
Cust_Location
Sales_Period
Sales
ABC_1234
ABC Soft Pvt Ltd.
Cust_1234
East
Q1-2014
40474
CDE_3456
CDE Info Pvt Ltd
Cust_3456
West
Q3-2014
19906
NULL
FFDD Infor Pvt Ltd.
Cust_4466
Mid-West
NULL
NULL
EFG_1122
EFC Tech Pvt Ltd.
Cust_1122
South
Q1-2015
22114
NULL
HHFF Tech Pvt Ltd.
Cust_6688
Mid-South
NULL
NULL
GHI_5566
GHI Services Pvt Ltd.
Cust_5566
North
Q3-2015
16157

-------------------------------------------------------------------------------------------------------------------

Right Join with Non Match in Left Table :
Right outer join produces a complete set of records from Right Table, with the matching records (where available) in Left Table. If there is no match, the left side will contain null.


The following Right Join Query gives the results only from Right Table that do not have Match in Left Table :





Select O.Order_Id,C.Cust_Name,C.Cust_Id,C.Cust_Location,O.Sales_Period,O.Sales from ORDERS RIGHT JOIN CUSTOMERS ON C.Cust_Id = O.Cust_Id  WHERE O.Cust_Id IS Null

Output :
Order_Id
Cust_Name
Cust_Id
Cust_Location
Sales_Period
Sales
NULL
FFDD Infor Pvt Ltd.
Cust_4466
Mid-West
NULL
NULL
NULL
HHFF Tech Pvt Ltd.
Cust_6688
Mid-South
NULL
NULL

--------------------------------------------------------------------------------------------------------

Thanks, TAMATAM ; Business Intelligence Professional
--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts