What does HAVING do? How does HAVING differ from WHERE?
HAVING is used to filter results after grouping (GROUP BY).
WHERE, on the other hand, is used to filter rows before grouping.
The difference in execution order
WHEREruns beforeGROUP BY, selecting individual rows;HAVINGruns after, selecting groups based on the results of aggregate functions.
Example
sql
SELECT department, SUM(salary)
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;Groups by department are formed first,
then only the ones where the salary sum exceeds 100,000 remain.
If WHERE were used instead of HAVING, SQL wouldn't understand SUM(salary),
because aggregates haven't been computed at that stage yet.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.