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
| Clause | Filters... | Works With Aggregates? |
|---|---|---|
WHERE | Individual rows | ❌ Not used with aggregates |
HAVING | Groups after aggregation | ✅ Yes |
- Use
WHEREfor raw row-level filters. - Use
HAVINGwhen filtering aggregated results.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.