# HAVING vs WHERE — MySQL Fundamentals: SQL, Joins and Transactions

Source: https://www.skillbyai.com/en/mysql/sql-having-vs-where

> Filter rows before grouping with WHERE and filter groups after aggregation with HAVING.

## Filtering groups

`WHERE` filters rows **before** grouping; `HAVING` filters groups **after** aggregation.

```sql
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 2000;
```

Output:

```
customer_id | total
1           | 3200.00
```

## Can't use WHERE with aggregates

`WHERE SUM(amount) > 2000` is invalid — aggregates don't exist yet when `WHERE` runs. Use `HAVING` instead.
