AnalystPracticeGuides
DashboardSign up

SQL WHERE vs HAVING: what's the difference?

WHERE filters individual rows before they are grouped. HAVING filters whole groups after GROUP BY, so it can use aggregates such as SUM and COUNT. If a condition is about a single row, put it in WHERE. If it is about a total, put it in HAVING.

Watch it solved. Task 1: filter totals with HAVING, from 0:31, in our video “Data Analyst Interview Questions and Answers: 10 SQL + Excel Tasks, Solved”. Pressing play loads the video from YouTube (privacy). Open on YouTube

Quick comparison

WHEREHAVING
FiltersRowsGroups
RunsBefore GROUP BYAfter GROUP BY
Can use SUM, COUNT, AVGNoYes
Typical question"Only orders from 2026""Only customers with more than 5 orders"

What does a query with both look like?

Customers who spent more than 1,000 in 2026, counting only completed orders:

SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'completed' AND order_date >= '2026-01-01'
GROUP BY customer_id
HAVING SUM(amount) > 1000;

WHERE first removes cancelled orders and older dates. GROUP BY then builds one row per customer, and HAVING keeps only the customers whose total is over 1,000.

Why can't you use SUM in WHERE?

Because WHERE runs before the groups exist, so there is no total yet to compare. WHERE SUM(amount) > 1000 returns an error. The logical order of a query explains it:

FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY

This order also explains a follow-up question: an alias defined in SELECT (like total) is not available in WHERE. Some databases, such as MySQL and SQLite, accept it in HAVING, but PostgreSQL and SQL Server do not, so repeating the expression SUM(amount) is the safe habit.

Can you filter row-level conditions in HAVING instead?

Often it gives the same result, but it is slower and harder to read, because the database groups rows it was going to throw away anyway. Interviewers notice this. Row conditions belong in WHERE.

Typical interview questions

"Find departments with more than 10 employees" uses GROUP BY department HAVING COUNT(*) > 10. "Find products that sold more than 100 units in March" filters March in WHERE and the units in HAVING. "Find duplicate emails" uses GROUP BY email HAVING COUNT(*) > 1.

Try it yourself. Write these queries against a real database in your browser and get instant feedback.
Practise GROUP BY and HAVING Practise WHERE

← All free guides