Monday, 11 February 2013

SQL Server - LEFT Outer JOIN Syntax and Example

SQL LEFT JOIN
The LEFT JOIN returns all rows from the Left Table (Table_I), includes the matching rows from the Right Table (Table_2).

In other words it returns all the matching rows from both the tables and non matching rows from left table.




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

Hint: In some databases LEFT JOIN is called LEFT 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 Left Join Query :

Select O.Order_Id,C.Cust_Name,C.Cust_Id,C.Cust_Location,O.Sales_Period,O.Sales from ORDERS O LEFT JOIN CUSTOMERS C 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
BCD_2345
NULL
NULL
NULL
Q2-2014
44321
CDE_3456
CDE Info Pvt Ltd
Cust_3456
West
Q3-2014
19906
DEF_4567
NULL
NULL
NULL
Q4-2014
34943
EFG_1122
EFC Tech Pvt Ltd.
Cust_1122
South
Q1-2015
22114
FGH_3344
NULL
NULL
NULL
Q2-2015
41364
GHI_5566
GHI Services Pvt Ltd.
Cust_5566
North
Q3-2015
16157
IJK_7788
NULL
NULL
NULL
Q4-2015
36054

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


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




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

Output :
Order_Id
Cust_Name
Cust_Id
Cust_Location
Sales_Period
Sales
BCD_2345
NULL
NULL
NULL
Q2-2014
44321
DEF_4567
NULL
NULL
NULL
Q4-2014
34943
FGH_3344
NULL
NULL
NULL
Q2-2015
41364
IJK_7788
NULL
NULL
NULL
Q4-2015
36054

Thanks,
TAMATAM

No comments:

Post a Comment

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts