You want to find employees who earn more than the average salary in their department. Which query correctly uses a nested subquery?
hard📝 Application Q8 of 15
SQL - Subqueries
You want to find employees who earn more than the average salary in their department. Which query correctly uses a nested subquery?
ASELECT name FROM Employees WHERE salary > AVG(salary) GROUP BY dept_id
BSELECT name FROM Employees e WHERE salary > (SELECT AVG(salary) FROM Employees WHERE dept_id = e.dept_id)
CSELECT name FROM Employees WHERE salary > (SELECT salary FROM Employees WHERE dept_id = dept_id)
DSELECT name FROM Employees WHERE salary > ALL (SELECT salary FROM Employees)
Step-by-Step Solution
Solution:
Step 1: Understand the requirement
We need to compare each employee's salary to the average salary of their own department.
Step 2: Analyze each option
SELECT name FROM Employees e WHERE salary > (SELECT AVG(salary) FROM Employees WHERE dept_id = e.dept_id) uses a correlated subquery referencing the outer query's dept_id to calculate average salary per department.
Final Answer:
SELECT name FROM Employees e WHERE salary > (SELECT AVG(salary) FROM Employees WHERE dept_id = e.dept_id) -> Option B
Quick Check:
Correlated subquery compares salary to dept average [OK]
Quick Trick:Use correlated subqueries to compare within groups [OK]
Common Mistakes:
MISTAKES
Using aggregate without GROUP BY
Ignoring correlation with outer query
Using ALL without filtering by department
Master "Subqueries" in SQL
9 interactive learning modes - each teaches the same concept differently