✏️ Explanatory Question
Level: Intermediate to Advanced — Tests your ability to handle hierarchical and comparative data.
A SELF JOIN is a join where a table is joined with itself. It's not a special keyword — it's a regular join (INNER or OUTER) where both sides reference the same table, distinguished by using different table aliases.
a and b) so MySQL can tell the two "copies" apart. Without them, the query is ambiguous.
Consider an employees table where each employee has a manager_id that points to another employee's emp_id in the same table:
| emp_id | name | manager_id |
|---|---|---|
| 1 | Ajay (Manager) | NULL |
| 2 | Rumman | 1 |
| 3 | Krushna | 1 |
-- Show each employee alongside their manager's name
SELECT
e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id;
-- 'e' = employee copy, 'm' = manager copy of the SAME table
-- Find pairs of employees in the same department
SELECT
a.name AS employee_1,
b.name AS employee_2,
a.dept_id
FROM employees a
INNER JOIN employees b
ON a.dept_id = b.dept_id
AND a.emp_id < b.emp_id; -- avoids duplicate pairs & self-match
a.emp_id < b.emp_id trick: It prevents an employee from matching themselves and stops the same pair from appearing twice (e.g., "A–B" and "B–A").