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 level and total salary for their hierarchy.
💡 Model Answer
For Q1 we use a LEFT JOIN on the employee table to link each employee to their manager. The ISNULL (or COALESCE) function substitutes the string 'TBO' when the manager_id is NULL, ensuring a placeholder is shown. The query is: 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; This runs in O(n) time where n is the number of employees.
Q2 requires a subquery to compute the average salary. The outer query then filters employees whose salary exceeds that average: SELECT emp_name, salary FROM employee WHERE salary > (SELECT AVG(salary) FROM employee); The subquery scans the table once, and the outer query scans it again, giving O(n) overall.
Q3 is a hierarchical query. A recursive CTE starts with the top‑level managers and repeatedly joins to find direct reports. The CTE accumulates the hierarchy and sums salaries per manager level. Example: WITH RECURSIVE hierarchy AS (SELECT emp_id, mgr_id, emp_name, 0 AS level, salary FROM employee WHERE mgr_id IS NULL UNION ALL SELECT e.emp_id, e.mgr_id, e.emp_name, h.level + 1, e.salary FROM employee e JOIN hierarchy h ON e.mgr_id = h.emp_id) SELECT mgr_id, SUM(salary) AS total_salary, MAX(level) AS level FROM hierarchy GROUP BY mgr_id; This approach is O(n) and works in most SQL dialects 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