Lecture

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.

Quiz
0 / 1

In SQL, which clause would you use to filter groups after an aggregation has been applied?

To filter groups after aggregation, use the clause.
WHERE
HAVING
SELECT
GROUP BY

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result