How do you retrieve each employee's manager name using a self-join?
💡 Model Answer
To list each employee with their manager's name, perform a self‑join on the employee table. Use a LEFT JOIN so that employees without a manager (NULL manager_id) are still returned. The query looks like this:
SELECT e.emp_name,
m.emp_name AS manager_nameFROM employee e
LEFT JOIN employee m
ON e.manager_id = m.emp_id;
This joins each employee row to the row of their manager. If manager_id is NULL, the manager_name will be NULL, preserving the employee in the result set. The LEFT JOIN ensures all employees appear, even those at the top of the hierarchy. This pattern is common for hierarchical data stored in a single table. If you need to include additional columns, simply add them to the SELECT clause. For deeper hierarchies, you might use recursive CTEs to traverse multiple levels.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500