http://www.sqlservercentral.com/blogs/vivekssqlnotes/2010/01/31/difference-between-having-and-where-clause-in-sql-server/

Printed 2014/08/30 08:29PM

Difference Between Having and Where Clause in Sql Server

By Vivek Johari, 2010/01/31


Both Having Clause and Where clause is used to filter the data coming from the Select statement, but still there are some differences between them. These difference are given below:-

To show the difference between the Where Clause and the Having clause we will going to use the table EmployeeDeptInfo whose create query statement  is given below :-

Create table EmployeeDeptInfo ( Employeeid int, Departmentid int)

and it contains the following data 

Employeeid              Departmentid
1                                  1
2                                  2
3                                  2
4                                  3
3                                  2
2                                  2
5                                  4
2                                  2

1) Where clause can be used with Select, Update and Delete Statement Clause but having clause can be used only with Select statement.

For example, the sql query
         Update EmployeeDeptInfo Set departmentid =7 Where employeeid=4 
will work fine but the query
         Update EmployeeDeptInfo Set departmentid =7 Having employeeid=4
will not work

2) We can't use aggregate functions in the where clause unless it is in a subquery contained in a HAVING clause whereas  we can use aggregate function in Having clause. We can use column name in Having clause but the column must be contained in the group by clause.

For example,  the sql query
select * from EmployeeDeptInfo where count(employeeid)>1 
will not  work but the query
Select Employeeid, Departmentid from EmployeeDeptInfo Group By Employeeid, DepartmentId having (count(employeeid) >1)
will work fine

3) Where Clause is used on the individual records whereas Having Clause in conjunction with Group By Clause work on the record sets ( group of records ).

For Example, in the below sql Query
 select employeeid, departmentid from EmployeeDeptInfo where employeeid=5

the where clause will  search the table EmployeeDeptInfo for the record whose employeeid is 5 and then show the output.

but in the below query,
Select Employeeid, Departmentid from EmployeeDeptInfo Group By Employeeid, DepartmentId having  employeeid=5

the result are  first grouped by the Group By Clause and then they become again filtered by the condition defined in the having clause. Sometime , like above both queries, we get the same result with the help of Where clause and having clause but which way is best is determined automatically by the optimizer and it select the best way of executing it.



   


Copyright © 2002-2014 Simple Talk Publishing. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.