I'm trying to retrieve employees who earn more than the department's average salary using a subquery in PostgreSQL.
SELECT
employee_id,
first_name,
salary
FROM
employees e
WHERE
e.salary > (
SELECT
AVG(salary)
FROM
employees
WHERE
department_id = e.department_id
);
ERROR: more than one row returned by a subquery used as an expression
I checked if AVG(salary) is returning multiple values.
I attempted using GROUP BY department_id, but I received a different error.
I expected to get a list of employees who earn more than the average salary of their respective departments.
Instead, I got an error preventing the query from executing.
How can I correctly structure this query to compare each employee’s salary with their department’s average?
... department_id = e.department_idis causing this ... more than one row returned by a subquery used as an expression. In other words there is more then onedepartment_id. Either make the subquery a CTE element or turn it into aJOINwith the other query.I attempted using GROUP BY department_id, but I received a different error.- what error? Assuming you added this to the sub-query, it seems the correct thing to do.