What is the purpose of the HAVING
clause in SQL, and how does it differ from the WHERE
clause?
adminnewd Changed status to publish September 19, 2024
HAVING
Clause: TheHAVING
clause is used to filter records after theGROUP BY
clause has been applied. It is used with aggregate functions to filter groups of rows based on a condition.WHERE
Clause: TheWHERE
clause is used to filter records before any grouping occurs. It filters rows based on specified conditions before any grouping or aggregation is done.
Difference:
WHERE
is used for filtering individual rows before grouping.HAVING
is used for filtering groups of rows after grouping.
example:-
— Using WHERE to filter rows before grouping
SELECT department, COUNT(*) as employee_count
FROM employees
WHERE salary > 50000
GROUP BY department;
— Using HAVING to filter groups after grouping
SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
anonymous Answered question September 19, 2024