In SQL, What's The Difference Between The Having Clause and The Where Clause?
In SQL, What's The Difference Between The Having Clause and The Where Clause?
SQL:Havingvs.WhereClause
InSQL,whatsthedifferencebetweenthehavingclauseandthewhere
clause?
Thedifferencebetweenthehavingandwhereclauseisbestillustratedbyanexample.Supposewehaveatable
calledemp_bonusasshownbelow.NotethatthetablehasmultipleentriesforemployeesAandB.
emp_bonus
Employee Bonus
A
1000
2000
500
700
1250
Ifwewanttocalculatethetotalbonusthateachemployeereceived,thenwewouldwriteaSQLstatementlike
this:
selectemployee,sum(bonus)fromemp_bonusgroupbyemployee
TheGroupByClause
IntheSQLstatementabove,youcanseethatweusethe"groupby"clausewiththeemployeecolumn.What
thegroupbyclausedoesisallowustofindthesumofthebonusesforeachemployee.Usingthegroupbyin
combinationwiththesum(bonus)statementwillgiveusthesumofallthebonusesforemployeesA,B,andC.
Subscribetoournewsletterformorefreeinterviewquestions.
RunningtheSQLabovewouldreturnthis:
Employee Sum(Bonus)
A
1500
3250
700
Now, suppose we wanted to find the employees who received more than $1,000 in bonuses for the year of
2007.Youmightthinkthatwecouldwriteaquerylikethis:
BADSQL:
selectemployee,sum(bonus)fromemp_bonus
groupbyemployeewheresum(bonus)>1000
data:text/htmlcharset=utf8,%3Ctable%20width%3D%22100%25%22%20border%3D%220%22%20cellspacing%3D%220%22%20cellpadding%3D%220%22
1/2
1/18/2015
SQL:Havingvs.WhereClause
TheWHEREclausedoesnotworkwithaggregateslikeSUM
TheSQLabovewillnotwork,becausethewhereclausedoesntworkwithaggregateslikesum,avg,max,etc..
Instead, what we will need to use is the having clause. The having clause was added to sql just so we could
compareaggregatestoothervaluesjusthowthewhereclausecanbeusedwithnonaggregates.Now,the
correctsqlwilllooklikethis:
GOODSQL:
selectemployee,sum(bonus)fromemp_bonus
groupbyemployeehavingsum(bonus)>1000
Differencebetweenhavingandwhereclause
So we can see that the difference between the having and where clause in sql is that the where clause
cannotbeusedwithaggregates,butthehavingclausecan.Onewaytothinkofitisthatthehavingclauseisan
additionalfiltertothewhereclause.
data:text/htmlcharset=utf8,%3Ctable%20width%3D%22100%25%22%20border%3D%220%22%20cellspacing%3D%220%22%20cellpadding%3D%220%22
2/2