SQL SELF JOIN
A SELF JOIN is a regular JOIN
where a table is joined with itself to compare rows within the same table.
Itβs commonly used for hierarchical data, like employees and managers, or products and related products.
πΉ Basic Syntax
SELECT A.column1, B.column2
FROM table_name A
JOIN table_name B
ON A.common_column = B.common_column;
πΉ Example: Employees and Their Managers
Assume each employee has a manager_id
referring to another employee’s employee_id
in the same table.
SELECT
e.employee_name AS employee,
m.employee_name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;
β This shows each employee and their manager’s name.
πΉ When to Use SELF JOIN
- Compare rows in the same table
- Analyze hierarchical or paired data
- Find duplicate or related records
π§ Quick Recap
Key Point | Explanation |
---|---|
SELF JOIN | A table joins with itself |
Use case | Hierarchies, comparisons, duplicates |
Aliases | Required to distinguish the same table used twice |
JOIN type | Can be INNER , LEFT , etc., depending on the need |
π Use SELF JOIN for comparing or relating data within a single table