Junior — Middle
Explain what the use of Self Join in SQL queries means and in what case it is applied?
sobes.tech AI
Answer from AI
Self Join is an operation in SQL where a table is joined with itself. It is useful when you need to compare rows within the same table or retrieve related data from it.
For example, in an employees table, there is a manager_id field that references the id of another employee — the manager. To get a list of employees with their managers' names, a Self Join is used:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
Here, employees is used twice with different aliases (e and m) to link an employee with their manager.