Middle
Is it possible to perform a self-join? Why is it needed?
sobes.tech AI
Answer from AI
Yes, in SQL, you can perform a JOIN of a table with itself — this is called a self-join.
A self-join is used when you need to compare rows within the same table or retrieve related data from the same table that are linked.
Example: there is an employees table with fields id, name, manager_id, where manager_id is a reference to the id of the manager in the same table. To get a list of employees along with their managers' names, a self-join is performed:
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.
Thus, a self-join helps work with hierarchical or related data within a single table.