Forum

Write an SQL query ...
 
Share:
Notifications
Clear all

Write an SQL query to find employees who have a higher salary than the average salary of their department.


Posts: 71
Guest
Topic starter
(@Vinay Kumar)
Trusted Member
Joined: 4 years ago

To find employees whose salary is higher than the average salary of their department, you can use a subquery that calculates the average salary for each department.

SQL Statement:

sql
 
SELECT employee_id, name, department_id, salary
FROM employees e
WHERE salary > (SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id);

Explanation:

  • The subquery (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id) calculates the average salary for each department.
  • The WHERE clause in the main query compares the salary of each employee to the average salary of their respective department.
  • The query returns employees who earn more than the average salary of their department.

Example Scenario: Consider an employees table:

employee_id name department_id salary
1 John 101 80000
2 Alice 102 90000
3 Bob 101 85000
4 Carol 103 95000
5 Dave 101 75000
6 Eve 102 88000

Query Result: This query would return:

employee_id name department_id salary
3 Bob 101 85000
2 Alice 102 90000
4 Carol 103 95000

Employees John, Dave, and Eve are excluded because their salaries are not higher than their department's average.

Leave a reply

Author Name

Author Email

Title *

 
Preview 0 Revisions Saved
Share: