✏️ Explanatory Question

What is the difference between the WHERE and HAVING clauses?

👁 12 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

20

What is the difference between the WHERE and HAVING clauses?

Level: Basic to Intermediate — A very common question testing your grasp of filtering vs grouping.

Both WHERE and HAVING filter data, but they operate at different stages of query execution.

  • WHERE: Filters individual rows before grouping happens. It cannot use aggregate functions like SUM() or COUNT().
  • HAVING: Filters groups after GROUP BY has been applied. It can use aggregate functions.
Golden rule: WHERE filters rows before aggregation; HAVING filters groups after aggregation. Use WHERE for raw column conditions and HAVING for conditions on aggregated results.

Logical Order of Execution

MySQL processes a query in this order — which is why WHERE runs before HAVING:

EXECUTION ORDER
FROMWHEREGROUP BYHAVINGSELECTORDER BY

Side-by-Side Comparison

Feature WHERE HAVING
Filters Rows Groups
Runs Before GROUP BY After GROUP BY
Aggregate functions Not allowed Allowed
Used with GROUP BY? Optional Usually yes
Performance Faster (reduces rows early) Runs on grouped data

Quick Example

-- WHERE filters individual rows BEFORE grouping
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
WHERE salary > 30000        -- row-level filter
GROUP BY dept_id;

-- HAVING filters groups AFTER aggregation
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;        -- group-level filter

-- Both together: WHERE first, then HAVING
SELECT dept_id, AVG(salary) AS avg_sal
FROM employees
WHERE status = 'Active'     -- filter rows first
GROUP BY dept_id
HAVING AVG(salary) > 50000; -- then filter groups
Interviewer tip: The one-liner they want — "WHERE filters rows before grouping and can't use aggregate functions, while HAVING filters groups after GROUP BY and can use aggregate functions."