Skip to content
  • HAVING vs WHERE · SQL

HAVING vs WHERE

LearnViaNotes @learnvianotes· 2 min read

WHERE filters rows before grouping; HAVING filters groups after aggregation. Same idea, different stage.

WHEREHAVING
FiltersIndividual rowsGroups (aggregated rows)
RunsBefore GROUP BYAfter GROUP BY
Can use aggregatesNoYes
Can use indexesYesRarely — groups are computed first
Needs GROUP BYNoUsually (without it, the whole table is one group)
SQL
-- departments whose average salary exceeds 90000, counting only people hired before 2023
SELECT dept_id,
       COUNT(*)            AS staff,
       ROUND(AVG(salary))  AS avg_salary
FROM employees
WHERE hire_date < '2023-01-01'          -- rows
GROUP BY dept_id
HAVING AVG(salary) > 90000              -- groups
ORDER BY avg_salary DESC;
Output
dept_id | staff | avg_salary
--------+-------+-----------
1       | 4     | 115000.0

Customers with more than one order

SQL
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1
ORDER BY customer_id;
Output
customer_id | orders
------------+-------
1           | 3
2           | 2
3           | 2

Put row filters in WHERE

SQL
-- HAVING without GROUP BY: the whole table is one group
SELECT COUNT(*) AS products FROM products HAVING MIN(price) < 100;
SELECT COUNT(*) AS products FROM products HAVING MIN(price) < 10;
Output
products
--------
7

products
--------

What is the difference between WHERE and HAVING?

Find duplicate emails in a users table.

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report