What is SELF JOIN and when would you use it?

Imran picture Imran · Jul 29, 2010 · Viewed 440.9k times · Source

What is self join and when would you use it? I don't understand self joins so a layman explanation with an example would be great.

Answer

D'Arcy Rittich picture D'Arcy Rittich · Jul 29, 2010

You use a self join when a table references data in itself.

E.g., an Employee table may have a SupervisorID column that points to the employee that is the boss of the current employee.

To query the data and get information for both people in one row, you could self join like this:

select e1.EmployeeID, 
    e1.FirstName, 
    e1.LastName,
    e1.SupervisorID, 
    e2.FirstName as SupervisorFirstName, 
    e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID