Friday, June 3, 2016

How LEFT JOIN and RIGHT JOIN works

As usual, we are keeping the same two table Employee and location to explain left and right joins.

Employee Table

empIdEmpName
101Rajesh
102Vinodh
103Kumar
104Mukesh

Location Table

empIdLocation
101Chennai
102Mumbai
103Kolkatta
105Hyderabad

What is LEFT Join ?

The LEFT JOIN keyword returns all rows from the left table (What is left table ? ), with whatever matching rows in the right table (What is right table ?).

Suppose if there is no match in the right side, result is NULL.

We can write query first for this left join, after that I will explain. Left join query will be,

select * from employee left join location 
on employee.empID = location.empID;

Output : 

Employee.empIDEmployee.empNameLocation.empIDLocation.empLocation
101Rajesh101Chennai
102Vinodh102Mumbai
103Kumar103Kolkatta
104MukeshNullNull

From the result, we able to understand , left join query taking the rows from left table completely. If there is no match in the right tale it will return null like above.

Ven Diagram 
Left
Left Join Ven diagram














What is Right Join ?

The RIGHT JOIN returns all rows from the right table with the matching rows in the left table. If there is no match in the left table it will return NULL. 

Ven diagram of Right Join
right join
Right Join Ven diagram
 












Right Join Query

select * from employee right join location
on employee.empID = location.empID
 
Below figure represents some clear idea about left and right join.  

pointing
Table pointing identification of right and left join












1 comment:

  1. Awesome information. Thanks for this useful information about SQL. learning MYSQL along with PHP, laravel gives good future scope. PHP training in Bangalore

    ReplyDelete