What is a Self-Join, and in what real-world scenario would you use one?
Last updated
A self-join is a join where a table is joined to itself, using table aliases to treat it as two logical copies. It is used to relate rows within the same table, typically for hierarchical or comparative relationships.
How it works: You give the table two aliases and join on a column that references another row in the same table.
Classic scenario: employee/manager hierarchy: An
employeestable has amanager_idpointing to another employee'sid; a self-join pairs each employee with their manager.Other uses: Finding pairs (e.g., customers in the same city) or comparing rows to each other (e.g., duplicate detection).
[lang:sql]
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
- https://medium.com/@quipoin04/sql-self-join-beginner-to-interview-level-0faf5f9b578e
- https://dev.to/markadel/a-practical-example-of-using-sql-self-joins-ndd
- https://snehagupta-contact.medium.com/self-join-explained-with-a-real-world-example-55581c543775
- https://interviewmaster.ai/content/sql/joins/self-join
- https://motherduck.com/glossary/self-join/
- https://dev.to/dbvismarketing/understanding-self-joins-in-sql-1nni
- https://dev.to/dbvismarketing/mastering-advanced-sql-queries-with-dbvisualizer-and-postgresql-3m7a