Home › Interview Questions › What are the SQL queries to answer the following t…

What are the SQL queries to answer the following three questions: (1) Retrieve employee and manager names, showing 'TBO' if no manager; (2) List employees earning more than the average salary; (3) Get manager salary at their level and total salary of their hierarchy.

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

💡 Model Answer

Q1: Use a LEFT JOIN and ISNULL/COALESCE to provide a placeholder for missing managers: SELECT e.emp_name, ISNULL(m.emp_name, 'TBO') AS Manager_Name FROM employee e LEFT JOIN employee m ON e.mgr_id = m.emp_id; Q2: Compute the average salary in a subquery and filter: SELECT emp_name, salary FROM employee WHERE salary > (SELECT AVG(salary) FROM employee); Q3: To get the manager’s salary at their level and the total salary of the entire hierarchy, a recursive CTE is appropriate. The CTE starts with the top‑level managers and recursively adds direct reports. After the recursion, we group by the manager and sum the salaries: 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, m.salary AS Manager_Salary, SUM(h.salary) AS Total_Hierarchy_Salary FROM hierarchy h JOIN employee m ON h.mgr_id = m.emp_id GROUP BY h.mgr_id, m.emp_name, m.salary; This query runs in linear time relative to the number of employees.

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