Question presented to candidate:
"Our employees table has a manager_id column that points at another row of the same table. Write a query that lists every employee next to their manager's name, and explain what a self join is and when you would reach for one."
What a strong answer should cover:
- A self join is an ordinary join (INNER, LEFT, and so on) in which both sides are the same table, so each copy needs its own alias
- The typical use: a self-referencing foreign key such as
manager_id REFERENCES employees(id), the adjacency list way of storing a hierarchy LEFT JOINkeeps the root row (the CEO, whosemanager_idis NULL);INNER JOINsilently drops it- Other patterns: comparing a row to a related row (earns more than the manager), and building pairs inside a group with
a.id < b.idto avoid self-pairs and mirror duplicates - Limits: one self join walks exactly one level; an unknown depth needs a recursive CTE
- Performance: the engine treats the two aliases as two independent inputs, so the join column (
manager_id) wants an index like any other join
Code / implementation expected: Yes β an employee/manager query with two aliases of the same table, and ideally one comparison or pairing query.
Schema used by the examples: