Question

Here is the schema Employee (name,sex,salary,deptName) and name is the primary key

SELECT deptname
FROM employee
WHERE sex=m
GROUP BY deptName HAVING avg(salary) >
  (SELECT avg(salary)
   FROM employee)

I want to understand the part having avg(salary) what does that part actually do? since we dont include the salary select clause,

SELECT deptname
FROM employee
WHERE sex=m
GROUP BY deptName

This part will give me group of deptName, just one column nothing else, I am wondering how having (avg(salary)) is working, it is taking avg of all employees from the table or what?

Anyone who can tell me Thanks

Was it helpful?

Solution

WHERE filters records before they are grouped; whereas HAVING filters the results after they have been grouped. Expressions, using functions or operators, can be used in either clause (although aggregate functions like AVG() cannot be used in the WHERE clause as the records would not have been grouped when that clause is evaluated).

Thus your query filters a list of departments for those where the average salary of that department's male workers is greater than the overall (company) average salary.

OTHER TIPS

SELECT AVG(salary)
   FROM employee

By above query first you will get avg salary of all employees.

Now you are getting only department whose avg salary is greater than avg salary of all employees.

The having clause works like a where condition for the 'group by deptName' clause. All rows are grouped by value of deptName column. For each group, the average is calculated on the values of salary for that particular group.

Therefore, for all groups, only if the average salary for that particular 'deptName' group is greater than the average salary for all employees, the row from that group would show.

having is like WHERE clause but its for aggregate functions Like AVG.

so your query will look for average of every deptname. BUT in your query

 having avg(salary) > (select  avg(salary) from employee)

you maybe want give an average to compare with.

like

   having avg(salary) > 25 

so this will select only those who have average > 25.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top