SQL Joins

Consider two tables employee and salary.

Employee

Employee_id

Name

Age

1

George

56

2

Tom

23

3

Lee

35

4

Jade

49


Salary

Salary_id

Employee_id

Amount

1

4

45000

2

5

50500

3

1

17500

4

2

24000

5

6

17000



Inner Join

select ep.name, sy.amount
from employee ep
inner join salary sy on sy.employee_id = ep.employee_id

The above code will return rows with employee_id in both the tables.

Name

Amount

Jade

45000

George

17500

Tom

24000



Left Join

select ep.name, sy.amount
from employee ep
left join salary sy on sy.employee_id = ep.employee_id

The above code will return all the rows from the employee table.

If no matching employee_id from the employee table is found in the salary table, it returns a null value.

Name

Amount

George

17500

Tom

24000

Lee

NULL

Jade

45000



Right Join

select ep.name, sy.amount
from employee ep
right join salary sy on sy.employee_id = ep.employee_id

The above code will return all the rows from the salary table.

If no matching employee_id from the salary table is found in the employee table a null value is returned.

Name

Amount

Jade

45000

NULL

50500

George

17500

Tom

24000

NULL

17000




NOTE

select ep.name, sy.amount
from employee ep
left join salary sy on sy.employee_id = ep.employee_id

is the same as

select ep.name, sy.amount
from salary sy
right join employee ep on sy.employee_id = ep.employee_id


No comments: