Bird
0
0

How can you use a scalar subquery to find employees whose salary is above the average salary in their department?

hard📝 Application Q9 of 15
PostgreSQL - Subqueries in PostgreSQL
How can you use a scalar subquery to find employees whose salary is above the average salary in their department?
ASELECT name FROM employees WHERE salary > (SELECT salary FROM employees);
BSELECT name FROM employees WHERE salary > AVG(salary);
CSELECT name FROM employees WHERE salary > ALL (SELECT AVG(salary) FROM employees GROUP BY department_id);
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 problem

    We want employees with salary greater than their department's average salary.
  2. Step 2: Analyze the scalar subquery usage

    SELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); uses a correlated scalar subquery to compute AVG(salary) per employee's department.
  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 scalar subquery compares salary to department average [OK]
Quick Trick: Correlate subquery to outer query for per-group calculations [OK]
Common Mistakes:
  • Using aggregate without GROUP BY or correlation
  • Comparing salary to unrelated averages
  • Using ALL incorrectly with scalar subqueries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes