Sunday, November 22, 2015

SQL Join Command - Inner, Outer and Left Join

In order to avoid data duplication, data is stored in related tables. Join commands like inner join, outer join and left join is used to fetch data from related tables.
Different type of joins are
  • Join or inner join
  • Outer Join
  • Left Join
  • Full Join
SQL Join query with examples on Employee and Salary table given below are
Table Name : Employee
Employee_IDEmployee_NameAge
1John28
2Alex24
3James35
4Roy22
5Kay44
Table Name : Salary
Employee_ID_RefYearMonthSalary
12015April30000
12015May31000
12015June32000
22015April40000
22015May41000
22015June42000

Inner JOIN

Inner join returns rows when there is at least one match in both tables. SQL query to join above tables is as given below.
select * from employee a join salary b on a.employee_id = b.employee_id_ref
The result of the above given query is as shown below.
Employee_IDEmployee_NameAgeEmployee_ID_RefYearMonthSalary
1John2812015April30000
1John2812015May31000
1John2812015June32000
2Alex2422015April40000
2Alex2422015May41000
2Alex2422015June42000

Left JOIN

Return all rows from the left table, even if there are no matches in the right table. SQL query to left join above tables is as given below.
select * from employee a left join salary b on a.employee_id = b.employee_id_ref
Employee_IDEmployee_NameAgeEmployee_ID_RefYearMonthSalary
1John2812015April30000
1John2812015May31000
1John2812015June32000
2Alex2422015April40000
2Alex2422015May41000
2Alex2422015June42000
3James35
4Roy22
5Kay44

Here, even though there is no matching records for employees "James,Roy and Kay", there names are shown in the results.

Right JOIN

Return all rows from the right table, even if there are no matches in the left table. SQL query to right join above tables are as given below
select * from employee a right join salary b on a.employee_id = b.employee_id_ref
Employee_IDEmployee_NameAgeEmployee_ID_RefYearMonthSalary
1John2812015April30000
1John2812015May31000
1John2812015June32000
2Alex2422015April40000
2Alex2422015May41000
2Alex2422015June42000

Full JOIN

Return rows when there is a match in one of the tables. SQL query to full join above tables are as given below
select * from employee a full join salary b on a.employee_id = b.employee_id_ref
The result of the full join is as shown below.
Employee_IDEmployee_NameAgeEmployee_ID_RefYearMonthSalary
1John2812015April30000
1John2812015May31000
1John2812015June32000
2Alex2422015April40000
2Alex2422015May41000
2Alex2422015June42000
3James35
4Roy22
5Kay44

No comments: