HAVING clause in SQL is used to filter groups of rows based on specified conditions. It is often used with the GROUP BY clause to filter groups after aggregate functions have been applied. Unlike the WHERE clause, which filters rows before grouping, the HAVING clause filters groups after grouping and aggregation.
Key Points
- Filtering Groups:
HAVINGis used to filter groups of rows based on conditions. - Use with GROUP BY: It is typically used with the
GROUP BYclause to filter groups after aggregation. - Aggregate Functions: Conditions in the
HAVINGclause often involve aggregate functions likeCOUNT,SUM,AVG,MIN, andMAX. - Order of Execution:
HAVINGis executed after theGROUP BYclause and before theORDER BYclause.
Syntax
column1: The column(s) by which to group the rows.aggregate_function(column2): The aggregate function to apply to each group.table_name: The table from which to retrieve data.condition: The condition to filter groups.
Examples
HAVING with COUNT
Suppose you have a table namedEmployees that stores employee details.
Table: Employees
To find departments with more than 1 employee:
HAVING with SUM
Suppose you have a table namedSales that stores sales data.
Table: Sales
To find cities with total sales greater than ₹10,000:
HAVING with AVG
Suppose you have a table namedOrders that stores order details.
Table: Orders
To find states with an average order amount greater than ₹5,000:
Practical Use Case
Suppose you have a table namedStudents that stores student details.
Table: Students
To find states with an average percentage greater than 90:
Key Takeaways
- The
HAVINGclause is used to filter groups of rows based on specified conditions. - It is typically used with the
GROUP BYclause to filter groups after aggregation. - Conditions in the
HAVINGclause often involve aggregate functions likeCOUNT,SUM,AVG,MIN, andMAX. HAVINGis executed after theGROUP BYclause and before theORDER BYclause.- Use
HAVINGto filter groups and generate meaningful summaries and reports.