1.

How can you join a table to itself?

Answer»

Another type of join in SQL is a SELF JOIN, which connects a table to itself. In order to perform a self-join, it is necessary to have at least one column (say X) that serves as the primary key as well as one column (say Y) that contains values that can be matched with those in X. The value of Column Y may be null in some rows, and Column X need not have the exact same value as Column Y for every row.

Example: Consider the table Employees.

Emp_IDEmp_NameEmp_ProfileEmp_CountryManagerId
101Ashish KaktanContent WriterGermany104
104Raj ChoudharyData AnalystIndia108
105Vivek OberoiSoftware EngineerIndia101
108Shantanu KhandelwalDevelopment ExecutiveEurope101
109Khanak DesaiMarketing ManagerMexico 

For instance, we might wish to display results that only include employees with their managers. By using table aliases and a self-join, this can be accomplished easily. 

SELECT e.Emp_ID, e.Emp_Name, m.FullName as ManagerName
FROM Employees e JOIN Employees m ON e.ManagerId = m.Emp_ID

Output:

Emp_IDEmp_NameManagerName
101Ashish KaktanRaj Choudhary
104Raj ChoudharyShantanu Khandelwal
105Vivek OberoiAshish Kaktan
108Shantanu KhandelwalAshish Kaktan
109Khanak DesaiNull



Discussion

No Comment Found