Professional Documents
Culture Documents
Question
Explain self join with the help of scenarios and examples.
Give the codes or queries as well.
Explanation:
Self join links a table to itself. this is usually done by joining a table to itself just
once within a sql query while most joins link two or more tables with each other to
present their data together.
The self join, as its name implies, joins a table to itself. To use a self join, the table
must contain a column that acts as the primary key and a different column that
stores values that can be matched up with the values in that column. The values of
both columns do not have to be the same for any given row, and the value in
second column may even be null.
Manager
Id FullName Salary
Id
Jane
2 12000 3
Anderson
This type of table structure is very common in hierarchies. Now, to show the name
of the manager for each employee in the same row, we can run the following
query:
Query:
SELECT employee.Id, employee.FullName, employee.ManagerId,
manager.FullName as ManagerName FROM Employees employee JOIN Employees
manager ON employee.ManagerId = manager.Id
Manager Manager
Id Full Name
Id Name
Jane
2 3 Tom Lanon
Anderson
Jeremy
5 1 John Smith
York
References:
1) What Is a Self Join in SQL? An Explanation With Seven Examples |
LearnSQL.com
2) Lec-38: Self Join operation with Example | Database Management System -
YouTube