MySQL HAVING Clause
The HAVING clause in MySQL is used to filter the results of a GROUP BY operation based on aggregate function conditions. It is similar to the WHERE clause but specifically operates on grouped data.
Key Points
- The HAVING clause is used after the GROUP BY clause.
- It allows you to filter aggregated data, such as sums, averages, counts, etc.
- If no GROUP BY is present, HAVING behaves like a WHERE clause but can still use aggregate functions.
Syntax
column1
: The column to group by.aggregate_function(column2)
: An aggregate function likeSUM
,COUNT
,AVG
, etc.condition
: The filtering condition applied to the aggregated data.
Example Table
Table: sales
1. Using HAVING with GROUP BY
Find products with total sales greater than 800:
Result
2. HAVING Without GROUP BY
The HAVING clause can filter aggregate results even without a GROUP BY:
Result
3. Using HAVING with Multiple Conditions
Find products with total sales between 600 and 900:
Result
4. Combining WHERE and HAVING
- Use the WHERE clause to filter rows before grouping.
- Use the HAVING clause to filter aggregated data.
Find total sales per region where individual sales are greater than 300, and total sales are more than 800:
Result
5. Using Aggregate Functions in HAVING
Find regions with more than 1 product category having sales greater than 300:
Result
6. HAVING with Aliases
You can use column aliases in the HAVING clause. For example:
HAVING vs. WHERE
Feature | HAVING | WHERE |
---|---|---|
Purpose | Filters aggregated/grouped data | Filters rows before grouping |
Used With | GROUP BY | Any query |
Aggregate Funcs | Allowed (e.g., SUM , COUNT ) | Not allowed |
Performance Considerations
WHERE First, HAVING Later:
- Use WHERE to filter rows before grouping to reduce the amount of data processed.
Indexes:
- Indexes are used with the WHERE clause but do not optimize the HAVING clause since it works on grouped data.
Use Cases
- Filter summarized data (e.g., sales totals, averages).
- Enforce conditions on grouped results.
- Apply advanced filters combining WHERE and HAVING.
Let me know if you'd like additional examples or help crafting a query!