HomeInterview QuestionsExplain the recursive CTE query that calculates to…

Explain the recursive CTE query that calculates total salary per employee hierarchy, line by line.

🟡 Medium Conceptual Mid level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

The query starts with a recursive CTE named Recursive_hierarchy. The anchor part selects all employees whose mgr_id is NULL (the top of the org chart) and assigns them a level of 1. The recursive part joins each employee e to the CTE r on e.mgr_id = r.emp_id, which means it finds employees whose manager is already in the hierarchy. It then increments the level by 1 for each subordinate. This builds a tree where each row represents an employee and the depth of their position. After the CTE is fully populated, the outer SELECT groups by emp_name and sums the salary column from the hierarchy. Because the hierarchy contains every employee in the subtree of each manager, the SUM aggregates the salaries of all subordinates under that manager. The HAVING clause filters out managers whose total salary is 100,000 or less. The query effectively calculates the total compensation cost for each manager’s team, including themselves.

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