Monday, 6 October 2014

What is the diffrent between HAVING and WHERE clause?

1. WHERE is applied before GROUP BY, HAVING is applied after (and can filter on aggregates).
2.   HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
3.   HAVING is used to check conditions after the aggregation takes place.
4.   The HAVING clause was added to SQL because the WHERE keyword could not be used with       aggregate functions.


The difference between the two is in the relationship to the GROUP BY clause:
  • WHERE comes before GROUP BY; SQL evaluates the WHERE clause before it groups records.
  • HAVING comes after GROUP BY; SQL evaluates HAVING after it groups records.
WHERE is applied as a limitation on the set returned by SQL; it uses SQL's built-in set oeprations and indexes and therefore is the fastest way to filter result sets. Always use WHERE whenever possible.

HAVING is necessary for some aggregate filters. It filters the query AFTER sql has retrieved, assembled, and sorted the results. Therefore, it is much slower than WHERE and should be avoided except in those situations that require it.

HAVING checks the condition on the query result already found. But WHERE is for checking condition while query runs.
Let me give an example to illustrate this. Suppose you have a database table like this.
 usertable{ int userid, date datefield, int dailyincome }

Suppose, the following rows are in table:
1, 2011-05-20, 100
1, 2011-05-21, 50
1, 2011-05-30, 10
2, 2011-05-30, 10
2, 2011-05-20, 20
Now, we want to get the userids and sum(dailyincome) whose sum(dailyincome)>100
If we write:
SELECT userid, sum(dailyincome) FROM usertable WHERE sum(dailyincome)>100 GROUP BY userid
This will be an error. The correct query would be:
SELECT userid, sum(dailyincome) FROM usertable GROUP BY userid HAVING sum(dailyincome)>100

No comments:

How calulation total value for HTML input text?

<script> $j(document).ready(function(){ $j(":text").keyup(function(){ if (isNaN($j(this).val())) { alert(...