6 March 2013

Self - Join in SQL Server

A self-join is simply a normal SQL join that joins one table to itself. 
This is accomplished by using table name aliases to give each instance of the table a separate name.

When Useful?Joining a table to itself can be useful when you want to compare values in a column to 
other values in the same column.

We have sample records in Employee table.


Inner Join Example----

SELECT e1.Name EmployeeName, e2.name AS ManagerNameFROM Employee e1
INNER JOIN Employee e2ON e1.ManagerID = e2.EmployeeID

Outer Join example---

SELECT e1.Name EmployeeName, ISNULL(e2.name, 'Top Manager') ASManagerNameFROM Employee e1
LEFT JOIN Employee e2ON e1.ManagerID = e2.EmployeeID