Difference Between WHERE AND HAVING Clauses

WHERE
WHERE clause can be used to filter with SELECT, DELETE, UPDATE statements.
WHERE clause can be used with or without GROUP BY clause or AGGREGATE FUNCTIONS.
WHERE condition will act before aggregation or grouping.
SELECT employee_name,Month ,SUM(salary) FROM employee_details WHERE employee_grade = 'A' GROUP BY employee_name,Month
HAVING
HAVING clause can be used with SELECT statement only.
HAVING clause should be used with GROUP BY clause or an AGGREGATE FUNCTION.
HAVING clause will act after aggregation or grouping.
SELECT employee_name,Month, SUM(salary) FROM employee_details WHERE employee_grade = 'A' GROUP BY employee_name,Month HAVING SUM(salary)>50000

Note
Some database developers assume that HAVING clause is impossible to use without GROUP BY. But it is incorrect.
SELECT 'Right' AS result FROM Table HAVING COUNT(DISTINCT name ) = COUNT(name);
However this is not a significant query.

No comments:

Post a Comment