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:
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 }- 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.
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.
Suppose, the following rows are in table:
1, 2011-05-20, 100Now, we want to get the
1, 2011-05-21, 50
1, 2011-05-30, 10
2, 2011-05-30, 10
2, 2011-05-20, 20
userids and sum(dailyincome) whose sum(dailyincome)>100If 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:
Post a Comment