What are the SQL queries to answer the following three questions: (1) Retrieve manager name, or 'TBD' if missing; (2) List employees earning more than the average salary; (3) Get manager name and total salary of their hierarchy, including the manager, but only if the total exceeds 100k.
💡 Model Answer
Q1 uses a LEFT JOIN and COALESCE to replace a missing manager with 'TBD': SELECT e.emp_name, COALESCE(m.emp_name, 'TBD') AS Manager_Name FROM employee e LEFT JOIN employee m ON e.mgr_id = m.emp_id; Q2 is identical to the previous average‑salary query: SELECT emp_name, salary FROM employee WHERE salary > (SELECT AVG(salary) FROM employee); Q3 requires a recursive CTE to walk the reporting tree. The CTE starts with each manager, then recursively joins to find all subordinates. After the recursion, we group by the manager and sum salaries. Finally, we filter the result to keep only those groups where the total salary exceeds 100,000: WITH RECURSIVE hierarchy AS (SELECT emp_id, mgr_id, emp_name, salary FROM employee WHERE mgr_id IS NULL UNION ALL SELECT e.emp_id, e.mgr_id, e.emp_name, e.salary FROM employee e JOIN hierarchy h ON e.mgr_id = h.emp_id) SELECT h.mgr_id, m.emp_name AS Manager_Name, SUM(h.salary) AS Total_Salary FROM hierarchy h JOIN employee m ON h.mgr_id = m.emp_id GROUP BY h.mgr_id, m.emp_name HAVING SUM(h.salary) > 100000; This pattern works in PostgreSQL, SQL Server, and other systems that support recursive CTEs.
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