w3resource

PostgreSQL Subquery: Find all the information of the employees whose salary greater than the average salary for all departments


10. Write a SQL subquery to find all the information of the employees whose salary greater than the average salary of all departments.

Sample Solution:

Code:

-- This SQL query retrieves all columns of employees whose salary is greater than the average salary of all employees in their respective departments.

SELECT * -- Selects all columns from the employees table
FROM employees -- Specifies the table from which to retrieve data, in this case, the employees table
WHERE salary >ALL( -- Filters the rows to include only those where the salary is greater than ALL the average salaries obtained from the subquery
    SELECT avg(salary) -- Subquery: Calculates the average salary of employees for each department
    FROM employees 
    GROUP BY department_id -- Groups the employees by department_id to calculate average salary for each department
);

Explanation:

  • This SQL query retrieves all columns of employees whose salary is greater than the average salary of all employees in their respective departments.
  • The outermost SELECT statement selects all columns from the employees table.
  • The WHERE clause filters the rows to include only those where the salary is greater than ALL the average salaries obtained from the subquery.
  • The subquery calculates the average salary of employees for each department using the AVG() function and GROUP BY clause.
  • The ALL keyword is used to compare the salary with all the average salaries calculated for each department.

Sample table: employees


Output:

pg_exercises=# SELECT *
pg_exercises-# FROM employees
pg_exercises-# WHERE salary >
pg_exercises-# ALL(SELECT avg(salary)
pg_exercises(# FROM employees
pg_exercises(# GROUP BY department_id);
 employee_id | first_name | last_name |     email     | phone_number | hire_date  | job_id  |  salary  | commission_pct | manager_id | department_id
-------------+------------+-----------+---------------+--------------+------------+---------+----------+----------------+------------+---------------
         100 | Steven     | King      | not available | 515.123.4567 | 1987-06-17 | AD_PRES | 24000.00 |           0.00 |          0 |            90
(1 row)

Practice Online


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a SQL subquery to find all the information of the employees who draws the same salary as the minimum salary for all departments.
Next: Write a subquery to find the first_name, last_name, job_id and salary of the employees who draws a salary that is higher than the salary of all the Shipping Clerk (JOB_ID = 'SH_CLERK'). Sort the results on salary from the lowest to highest.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.