Bird
0
0

You want to find employees who earn more than the average salary in their department. Which query correctly uses a subquery to achieve this?

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 subquery to achieve this?
ASELECT name FROM employees WHERE salary > ALL (SELECT salary FROM employees)
BSELECT name FROM employees WHERE salary > AVG(salary)
CSELECT name FROM employees WHERE salary > (SELECT salary FROM employees)
DSELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    We need to compare each employee's salary to the average salary of their own department.
  2. Step 2: Analyze each option

    SELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id) uses a correlated subquery referencing the employee's department_id to calculate average salary per department correctly.
  3. Final Answer:

    SELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id) -> Option D
  4. Quick Check:

    Correlated subquery filters by department average [OK]
Quick Trick: Use correlated subqueries to compare within groups [OK]
Common Mistakes:
MISTAKES
  • Using aggregate functions without GROUP BY
  • Not correlating subquery to outer query
  • Using ALL incorrectly for this case

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes