SQL Day 14: Self Joins

LO1: Joining a table with itself

LO2: Classification of Self Join

Prerequisite: Joins 

When we join the table with itself then join is called Self Join. Self join can be classified as Inner Self Join, Outer Self Join, and Cross Self Join.

Joining a table with itself

Let’s have a look on the tblemployee table.



In the tblemployee table, we have the column ManagerID which contains the ID of manager for that employee.

Let’s say we need to find the Manager name for the employee, to achieve this we need to use the Self Join.

In self join we are taking the ManagerID and lookup in the ID column of the same table. In this way, we can find the employee manager.

By running following query we will get the employee name and manager name + employee name for which the no manager is assigned maybe we can call him BOSS!

select          e.Name as Employee, m.Name as Manager
from            tblemployee e
Left Join       tblemployee m
ON              e.ManagerID=m.ID



In the same way, we can use the INNER JOIN which will remove the null record that displays as BOSS.

select          e.Name as Employee, m.Name as Manager
from            tblemployee e
INNER Join      tblemployee m
ON              e.ManagerID=m.ID



We can also apply the self CROSS JOIN on the table.

select          e.Name as Employee, m.Name as Manager
from            tblemployee e
CROSS Join      tblemployee m




That’s all for today. Thank You.

Comments

Popular posts from this blog

SQL Day 11: Group By in SQL Server

JAVA Script Executor Code to Click on an Element

SQL Day 2: Creating, Altering and Dropping a Database