The HAVING clause in SQL is used to filter records after a GROUP BY operation. It is similar to the WHERE clause but is specifically used to filter grouped rows, meaning it works with aggregate functions like COUNT(), SUM(), AVG(), MAX(), MIN(), etc.
Syntax:
SELECT column1, column2, AGGREGATE_FUNCTION(column3)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING aggregate_condition;
WHEREfilters rows before aggregation.HAVINGfilters rows after aggregation.
Example:
Suppose you have a sales table with columns product, amount, and date.
SELECT product, SUM(amount) AS total_sales
FROM sales
GROUP BY product
HAVING SUM(amount) > 500;
This query:
- Groups the data by the
productcolumn. - Calculates the sum of
amountfor each product. - Filters the groups where the total sales are greater than 500 using the
HAVINGclause.
Key Points:
WHEREworks with raw data (before grouping).HAVINGworks with grouped data (after aggregation).
No comments:
Post a Comment