Skip to main content
Practice

WHERE vs HAVING

In this lesson, you'll learn in detail the difference between WHERE and HAVING.

Both WHERE and HAVING are used to filter data, but they operate at different stages of a SQL query.


WHERE: Filter Rows Before Aggregation

The WHERE clause filters individual records before any aggregation or grouping takes place.

Filter before grouping
SELECT client_name, region, order_total
FROM client_orders
WHERE region = 'USA';

This returns all orders made by clients from the USA.


HAVING: Filter After Grouping

The HAVING clause filters groups after aggregation, which is often used with GROUP BY.

Filter groups after aggregation
SELECT region, AVG(order_total) AS avg_order
FROM client_orders
GROUP BY region
HAVING AVG(order_total) > 200;

This returns only the regions where the average order total is greater than 200.


Summary: When to Use Each

ClauseFilters...Works With Aggregates?
WHEREIndividual rows❌ Not used with aggregates
HAVINGGroups after aggregation✅ Yes

Use WHERE for raw row-level filters. Use HAVING when filtering aggregated results.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.