SQL Exercise: Managers salary exceeds the average of their employees
SQL subqueries on employee Database: Exercise-35 with Solution
[An editor is available at the bottom of the page to write and execute the scripts.]
35. From the following table, write a SQL query to find those managers whose salary is more than the average salary of his employees. Return complete information about the employees.
Sample table: employees
Sample Solution:
SELECT *
FROM employees m
WHERE m.emp_id IN
(SELECT manager_id
FROM employees)
AND m.salary >
(SELECT avg(e.salary)
FROM employees e
WHERE e.manager_id = m.emp_id );
Sample Output:
emp_id | emp_name | job_name | manager_id | hire_date | salary | commission | dep_id --------+----------+-----------+------------+------------+---------+------------+-------- 67832 | CLARE | MANAGER | 68319 | 1991-06-09 | 2550.00 | | 1001 69062 | FRANK | ANALYST | 65646 | 1991-12-03 | 3100.00 | | 2001 68319 | KAYLING | PRESIDENT | | 1991-11-18 | 6000.00 | | 1001 67858 | SCARLET | ANALYST | 65646 | 1997-04-19 | 3100.00 | | 2001 66928 | BLAZE | MANAGER | 68319 | 1991-05-01 | 2750.00 | | 3001 (5 rows)
Explanation:
The given query in SQL that retrieves all columns from the employees table for all employees who are also managers and whose salary is greater than the average salary of the employees they manage.
The WHERE clause includes the emp_id in the list who are also managers obtained from a subquery.
The subquery that selects the manager id from the employees table.
The query then filters the rows to only those where the salary of the manager is greater than the average salary of the employees they manage obtained from another subquery.
The subquery calculates the average salary of employees managed by each manager.
Practice Online
Structure of employee Database:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Average of the maximum and minimum salary of employees.
Next SQL Exercise: Salary is less than manager but more than colleagues.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/sql-exercises/employee-database-exercise/sql-subqueries-exercise-employee-database-35.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics