09/11/2024
The `HAVING` clause in MySQL is used to filter records after the `GROUP BY` operation has been applied. While the `WHERE` clause filters rows before any grouping, `HAVING` is used to filter groups based on aggregate values like `COUNT`, `SUM`, `AVG`, etc.
# # # Syntax
```sql
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
```
# # # Key Points
- **`WHERE` vs `HAVING`:** `WHERE` filters rows before grouping, whereas `HAVING` filters groups after grouping.
- **Used with Aggregate Functions:** `HAVING` is typically used with aggregate functions such as `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`, etc.
# # # Example Use Case
Consider a table `orders` with columns `customer_id` and `amount`. Suppose you want to find customers who have placed more than 5 orders.
```sql
SELECT customer_id, COUNT(order_id) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(order_id) > 5;
```
In this example:
- The `GROUP BY` groups orders by `customer_id`.
- `HAVING COUNT(order_id) > 5` filters these groups to only include customers with more than 5 orders.
# # # Another Example with `SUM`
Suppose you want to find customers whose total purchase amount exceeds $500.
```sql
SELECT customer_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 500;
```
This query:
- Groups orders by `customer_id`.
- Calculates the `SUM(amount)` for each customer.
- Uses `HAVING` to filter for customers with total purchase amounts greater than $500.
# # # Summary
`HAVING` is essential when you need to filter grouped results based on aggregate conditions, while `WHERE` filters rows before any aggregation happens.