Skip to main content
Practice

WHERE vs HAVING

In this lesson, you’ll explore the difference between WHERE and HAVING.

Both clauses are used to filter data, but they work at different stages of a SQL query.


WHERE: Filter Rows Before Aggregation

The WHERE clause filters individual rows before any aggregation or grouping happens.

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

This query returns all orders placed by clients in the USA.


HAVING: Filter After Grouping

The HAVING clause filters groups after aggregation and is typically 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 query returns regions where the average order total exceeds 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.