SQL Self Join is used when a table needs to be joined with itself to compare rows within the same table. It helps in finding relationships between records in a single table by treating it as two separate instances using table aliases.
SELECT columns FROM table AS alias1 JOIN table AS alias2 ON alias1.column = alias2.related_column;
columns: Columns to retrieve in the result.
alias1: First reference (alias) of the table.
alias2: Second reference (alias) of the same table.
related_column: condition that links rows within same table (e.g., Employee.ManagerID = Manager.EmployeeID).
Example: Employees and Their Managers
Let's create a table GFGemployees with employee_id, employee_name and manager_id. Each employee is linked to their manager using manager_id. Our goal is to extract employees along with their respective managers’ names.