Home › Interview Questions › How can I modify the query for Q3 to return only d…

How can I modify the query for Q3 to return only direct reports, not the entire hierarchy?

🟡 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

To retrieve only direct reports, you don't need a recursive CTE; a simple self‑join suffices. The query joins the employee table to itself on the manager_id field: SELECT e.emp_name AS employee, m.emp_name AS manager FROM employee e JOIN employee m ON e.mgr_id = m.emp_id; This returns each employee together with the name of the manager they report to. If you also want the manager's level, you can add a subquery or a window function to compute the depth of each manager. The key difference from a recursive CTE is that the join only follows one level of the hierarchy, so the result set is limited to direct relationships. Complexity is O(n) for the join, and it is supported by all major RDBMS without the overhead of recursion.

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