Answer: A self-join is simply a normal SQL join that joins one table to itself. Joining a table to itself can be useful when you want to compare values in a column to other values in the same column.
Question: Is Self Join Inner Join or Outer Join?
Answer: A self-join can be an inner join or an outer join or even a cross join. A table is joined to itself based upon a column that have duplicate data in different rows.
Question: What is a practical use of the Self Join in the real world?
Answer: The best example of self join in the real world is when we have a table with Employee data and each row contains information about employee and his/her manager. You can use self join in this scenario and retrieve relevant information. Let us see an example, over here.
Let us first create the same table for an employee.
One of the columns in the same table contains the ID of the manger, who is also an employee for the same company. Now all the employees and their managers are present in the same table. Let us see how Self Join works in the real world scenario now.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| USE TempDbGO-- Create a TableCREATE TABLE Employee(EmployeeID INT PRIMARY KEY,Name NVARCHAR(50),ManagerID INT)GO-- Insert Sample DataINSERT INTO EmployeeSELECT 1, 'Mike', 3UNION ALLSELECT 2, 'David', 3UNION ALLSELECT 3, 'Roger', NULLUNION ALLSELECT 4, 'Marry',2UNION ALLSELECT 5, 'Joseph',2UNION ALLSELECT 7, 'Ben',2GO-- Check the dataSELECT *FROM EmployeeGO |

Let us now connect the Employee table with itself with the help of INNER JOIN.
1
2
3
4
5
6
| -- Inner JoinSELECT e1.Name EmployeeName, e2.name AS ManagerNameFROM Employee e1INNER JOIN Employee e2ON e1.ManagerID = e2.EmployeeIDGO |

In the result set, we can see that all the employees who have a manager are visible. Though the above solution has one limitation. The limitation is that we are not able to find out the top manager of the company in our result set. Inner join does not display any result which does not have a manager id in our scenario.
Next let us convert Inner Join to Outer Join and then see the result set.
1
2
3
4
5
6
| -- Outer JoinSELECT e1.Name EmployeeName, ISNULL(e2.name, 'Top Manager') AS ManagerNameFROM Employee e1LEFT JOIN Employee e2ON e1.ManagerID = e2.EmployeeIDGO |

Now we have converted Inner Join to Outer Join for the same table and we can see Top Manager in resultset.
I hope it is clear from the example that SELF JOIN can be INNER JOIN or OUTER JOIN.
No comments:
Post a Comment