Wednesday, December 18, 2024

SQL HAVING Clause

 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;
  • WHERE filters rows before aggregation.
  • HAVING filters 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:

  1. Groups the data by the product column.
  2. Calculates the sum of amount for each product.
  3. Filters the groups where the total sales are greater than 500 using the HAVING clause.

Key Points:

  • WHERE works with raw data (before grouping).
  • HAVING works with grouped data (after aggregation).

No comments:

Post a Comment