Sie sind auf Seite 1von 4

11/3/2016 Differencebetweenhavingandwhereclause

Differencebetweenhavingandwhereclause
1Votes Whereclausecanbeappliedtoasinglerow,whereasHavingclauseisappliedtothewholegroup.But,itdoesnot

meanthatwecannothavebothWhereandHavingclauseinasinglequery.Ifbothwhereandhavingclausesareusedtogetherinsingleaquery,
whereclausewillapplyfilterconditiontothelistofrecordsanditwillfilterthegroupofrecordsfromthetableandHavingclausewillbeappliedto
thisresultantgroupandgroupswhichmeetstheconditiongiveninhavingclausewillbefilteredintheresultanttable.

Havingclauseisused,whenwewanttouseselectquerytofilterdatafromatablebasedonaaggregatecondition.Aggregatefunctionsused
alongwiththehavingclauseareSum,Count,MaxandMin.So,HavingclauseshouldalwaysbeusedalongwithgroupbyclauseinSQL.Ifitis
notusedwithGroupByclauseitthrowsanerrorsayingColumn'Yourcolumn'isinvalidintheHAVINGclausebecauseitisnotcontainedin
eitheranaggregatefunctionortheGROUPBYclause.

START YOUR
EXTRAORDINARY
STORY

ExampleforWhereClauseandHavingClause
HavingclauseisbeenaddedinSQLbecauseWHEREclausecouldnotbeusedlikeanaggregatefunction.Letscreateamultipletablesfor
demonstratingthiswithanexample

TableNameCustomerTable

CustomerID CustomerName CustomerDOB CustomerAge

1 John 10/10/90 24

2 Martin 05/12/65 49

3 Darren 07/26/86 28

4 Derek 01/20/90 25


TableNameOrderTable

OrderID CustomerID OrderDate

100 1 03/20/15

101 1 03/22/15

http://a4academics.com/tutorials/24sqltutorial/727havingvswhereclause 1/4
11/3/2016 Differencebetweenhavingandwhereclause

102 2 01/29/14

103 3 06/22/14

104 3 08/24/14

105 3 01/19/15

NowletsfilterthelistofordersofthecustomerJohndone

SELECTo.OrderID,o.OrderDateFROMCustomerascINNERJOINOrderasoONc.CustomerID=o.CustomerIDWHEREc.Customer

Name=John

AboveisthestraightforwardquerytofilteralltheordersdonebythecustomerJohnanddisplayingtheorderdateandorderIDofthefiltered
records.SohereintheabovequerywecanuseGroupbyclauseandhavingclausealsoalongwiththeexistingwhereclauseasshownbelow

Sobelowqueryisusedtofiltertheordersofallthecustomersandgroupalltheordersofthecustomersandfilterthecustomerswhohasmore
thanoneorderusinghavingclause.

SELECTo.CustomerIDFROMCustomerascINNERJOINOrderasoONc.CustomerID=o.CustomerIDGROUPBYo.CustomerID

HAVINGCOUNT(o.CustomerID)>1

SoaswecanseeintheabovequeryIamtryingtochecknumberofoccurrenceofCustomerIDrecordsinOrdertable,whichmeansthenumber
ofordersdonebythecustomersandthenIamtryingtofetchtheCustomerIDwhichismatchingthefiltercriteriainhavingclause.Soincaseyou
wanttogetthenameofthecustomerinsteadofcustomerIDthenbelowquerycanbeused

SELECTc1.CustomerName
FROMCustomerasc1INNERJOIN

(
SELECTo.CustomerIDasCustomerID
FROMCustomerasc

INNERJOINOrderasoONc.CustomerID=o.CustomerID
GROUPBYo.CustomerID
HAVINGCOUNT(o.CustomerID)>1

)cinner
ONcinner.CustomerID=c1.CustomerID

Looksstraightforwardquery.NowmyfirstqueryhasbeenmovedtoinnerqueryandnownewjoinhasbeenintroducedtomatchtheCustomerID
fromthefiltereddataandCustomertablesCustomerID.SotheselectedcustomerIDsCustomerNamehasbeenfetched.Thisisnotonlytheway
tofetchtheCustomerNamebutthisisonewayoftheway.

WecanuseTemporarytableaswellforthesamepurpose.Groupbyclauseallowstoustousefunctionslikemax(),min(),sum()etc.whichare
veryusefulwhereaswhereclausedoesnotworkwiththesefunctions.Sohavingclausecanbeusedwithaggregatefunctionswhereaswhere
clausewillnotworkwithaggregatefunctions.

Letsdiscussonemoreexamplewithdifferentsetsoftables.LetscreateatablecalledEmployeewithlistofcolumnsasshownbelow

TableNameEmployee

EmployeeID EmployeeName EmployeeAge EmployeeSalary

1 Wayne 29 20000
http://a4academics.com/tutorials/24sqltutorial/727havingvswhereclause 2/4
11/3/2016 Differencebetweenhavingandwhereclause

2 Jack 26 15000

3 Danny 28 35000

4 Kieran 21 13500

5 John 36 40000

NowletscreateonemoretablecalledDepartmentasshownbelow

TableNameDepartment

Department EmployeeID DepartmentName

100 1 Dept1

200 1 Dept2

300 3 Dept3

400 4 Dept4

500 5 Dept5

SELECTd.DepartmentID,d.DepartmentName
FROMEmployeease
INNERJOINDepartmentasdONe.EmployeeID=d.EmployeeID

WHEREe.EmployeeName=John

AbovequeryisusedtofetchthedepartmentdetailsofemployeenamedJohn.Andnowtofilteralltheemployeeswhichbelongstomultiple
departments.

SELECTd.EmployeeID
FROMEmployeeasc
INNERJOINDepartmentasdONe.EmployeeID=d.EmployeeID

GROUPBYd.EmployeeID
HAVINGCOUNT(d.EmployeeID)>1

SQLServerCourses
LearnSQLServerin3simplesteps.Registertowatchfreevideos!Go
toveeam.com

<<Prev Next>>

Youarehere: Home > Tutorials > SQLTutorialforBeginners > Differencebetweenhavingandwhereclause

PopularPosts

HRInterviewQuestionsandAnswers

SQLInterviewQuestionsandAnswers

JavaInterviewQuestionsandAnswers

http://a4academics.com/tutorials/24sqltutorial/727havingvswhereclause 3/4
11/3/2016 Differencebetweenhavingandwhereclause

SQLQueryInterviewQuestionsandAnswers

CareersChoicesandJobOpportunitiesforElectronicsandCommunicationEngineers

RelatedArticles

RDBMSandDBMSIntroduction,ConceptsandBasics

PrimaryKey,ForeignKeyandUniqueKey

SQLCreateTable,DROPTableSyntaxandSQLDefaultCommand

SQLSelectwithOrderBy,Insert,UpdateandDeleteCommand

SQLOperatorsWhere,IN,AND,ORandBetween

SQLLikeandDistinctCommand

SQLJoinCommandInner,OuterandLeftJoin

SQLMathematicalFunctions,ConcatandTrimCommands

SQLGroupByandHavingCommand

DifferencebetweenInnerjoinandLeftjoin

ClusteredIndexvsNonClusteredIndex

BasicDroolsConcepts

StepstoinstallDROOLSpluginandcreateDROOLSProjectinEclipse

CreatingDroolsKnowledgebase,KnowledgesessionandFacts

PopularCategories

DatabaseInterviewQuestionsandAnswers

.NetInterviewQuestionsandAnswers

CoreJava&SwingInterviewQuestions

CInterviewQuestionsandAnswers

HRInterviewQuestionsandAnswers

AptitudeTestTips,TricksandShortcuts

SeminarTopicsforCSE,MCA,I.T

SeminarTopicsforECE

MBAafterEngineeringCourses&TopColleges

SearchourSite

EnterSearchTerm

EmailNewsletter

EnteryourEmailAddressandgetinterestingupdates

YouremailAddress...

Subscribe

FollowUs

http://a4academics.com/tutorials/24sqltutorial/727havingvswhereclause 4/4

Das könnte Ihnen auch gefallen