Saturday, July 24, 2010

What is Difference between HAVING and WHERE clause?

Though the HAVING clause specifies a condition that is similar to the purpose of a WHERE clause, the two clauses are not interchangeable. Listed below are some differences to help distinguish between the two:

  1. WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. HAVING clause cannot be used without the GROUP BY clause.
  2. WHERE clause selects rows before grouping. HAVING clause selects rows after grouping.
  3. WHERE clause cannot contain aggregate functions. HAVING clause can contain aggregate functions, such as COUNT() or AVG() or SUM(), or MAX() or MIN().
  4. Having is just an additional filter to Where clause.
  5. Where clause applies to the individual rows whereas 'Having' clause is used to test some condition on the group (usually aggregate methods) rather than on individual rows.
  6. WHERE clause is used for comparing values in the base table whereas HAVING clause can be used for filtering the results of aggregate functions in the result set of the query.
Here's a simple example of a WHERE clause --

SELECT * FROM tablename WHERE ID > 100

Here's a simple example of a HAVING clause that returns the count of workers with the same last names --

SELECT WorkerLastName, COUNT(WorkerLastName) AS WorkerCount FROM tblWorker

GROUP BY WorkerLastName HAVING COUNT(WorkerLastName) > 1

No comments:

Post a Comment


All Rights Reserved @ Raju Das