Skip to main content
The 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

  1. Filtering Groups: HAVING is used to filter groups of rows based on conditions.
  2. Use with GROUP BY: It is typically used with the GROUP BY clause to filter groups after aggregation.
  3. Aggregate Functions: Conditions in the HAVING clause often involve aggregate functions like COUNT, SUM, AVG, MIN, and MAX.
  4. Order of Execution: HAVING is executed after the GROUP BY clause and before the ORDER BY clause.

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 named Employees that stores employee details. Table: Employees To find departments with more than 1 employee:

HAVING with SUM

Suppose you have a table named Sales that stores sales data. Table: Sales To find cities with total sales greater than ₹10,000:

HAVING with AVG

Suppose you have a table named Orders 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 named Students that stores student details. Table: Students To find states with an average percentage greater than 90:

Key Takeaways

  1. The HAVING clause is used to filter groups of rows based on specified conditions.
  2. It is typically used with the GROUP BY clause to filter groups after aggregation.
  3. Conditions in the HAVING clause often involve aggregate functions like COUNT, SUM, AVG, MIN, and MAX.
  4. HAVING is executed after the GROUP BY clause and before the ORDER BY clause.
  5. Use HAVING to filter groups and generate meaningful summaries and reports.