9 Feb 2012

Outer Joins - Left, Right and Full - Practical Example

Outer Join:
An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table(s) one retains the rows from (left, right, or both). In this case left and right refer to the two sides of the JOIN keyword.
SQL> Select * from A;
emp_idemp_namedpt_id
1001Saran20
1002Jason20
1003Brian20
1004Paul10
1012Mary40
1007Steve30
1008Jim20
1009Mark20
1010Yihong20
1013Melanie30
1011Greathouse50
1014Jie50
1015Raj50



SQL> Select * from B;
dpt_iddpt_name
10Management
20Development
30Usability
40HR
60Sales

Left Outer Join:
This means that a left outer join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate.
SQL> 
select a.EMP_ID, a.EMP_NAME, a.DPT_ID, b.Dpt_name from a 
LEFT OUTER JOIN b on a.DPT_ID = B.DPT_ID 
order by a.EMP_ID;


emp_idemp_namedpt_iddpt_name
1001Saran20Development
1002Jason20Development
1003Brian20Development
1004Paul10Management
1007Steve30Usability
1008Jim20Development
1009Mark20Development
1010Yihong20Development
1011Greathouse50Null
1012Mary40HR
1013Melanie30Usability
1014Jie50Null
1015Raj50Null

Right Outer Join:
This returns all the values from the right table and matched values from the left table or NULL in case of no matching join predicate.
SQL> 
select a.EMP_ID, a.EMP_NAME, a.DPT_ID, b.Dpt_name from a 
RIGHT OUTER JOIN b on a.DPT_ID = B.DPT_ID 
order by a.EMP_ID;


emp_idemp_namedpt_iddpt_name
1001Saran20Development
1002Jason20Development
1003Brian20Development
1004Paul10Management
1007Steve30Usability
1008Jim20Development
1009Mark20Development
1010Yihong20Development
1012Mary40HR
1013Melanie30Usability
NullNullNullSales


Full Outer Join
full outer join combines the effect of applying both left and right outer joins. Where records in the FULL OUTER JOINed tables do not match, the result set will have NULL values for every column of the table that lacks a matching row. For those records that do match, a single row will be produced in the result set.
SQL> 
select a.EMP_ID, a.EMP_NAME, a.DPT_ID, b.Dpt_name from a 
FULL OUTER JOIN b on a.DPT_ID = B.DPT_ID 
order by a.EMP_ID;

emp_idemp_namedpt_iddpt_name
1001Saran20Development
1002Jason20Development
1003Brian20Development
1004Paul10Management
1007Steve30Usability
1008Jim20Development
1009Mark20Development
1010Yihong20Development
1011Greathouse50Null
1012Mary40HR
1013Melanie30Usability
1014Jie50Null
1015Raj50Null
NullNullNullSales

Regards,
- Akash