SQL SELF JOIN

SQL SELF JOIN is a type of join operation in Structured Query Language (SQL) used to join a table with itself. A self-join is useful when we want to compare rows within a table and retrieve the data based on the relationship between the rows.

Employees Table:

IDNameManager
1William3
2Alice3
3Bob4
4CharlieNULL

Suppose we want to retrieve the name of the employee and the name of the employee's manager. In that case, we can use the SELF JOIN to join the Employees table with itself as follows:

1SELECT e1.Name as Employee, e2.Name as Manager 2FROM Employees e1 3JOIN Employees e2 4ON e1.Manager = e2.ID;

The output of the above query will be:

EmployeeManager
WilliamBob
AliceBob
BobCharlie

As we can see from the output, the SELF JOIN returns the name of the employee and the name of the employee's manager. The employee with ID 4 has no manager, so there's no matching row in the Employees table, and the result contains a NULL value for the Manager column.