The HAVING clause in SQL is used to filter groups of data after an aggregation operation. Unlike the WHERE clause, which filters rows before grouping, the HAVING clause applies conditions to aggregated data. In aggregation operations like SUM(), MAX() and etc, the WHERE clause does not worked. That's why we use HAVING to perform the same function as WHERE in MS SQL.

  • Syntax:

    SELECT column_name, aggregate_function(column_name)
    FROM table_name
    GROUP BY column_name
    HAVING condition;

Example

ProductAmount
Pen200
Notebook150
Marker350
Pen300
Notebook200
Marker100
SELECT Product, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Product
HAVING SUM(Amount) > 500;

Output:

ProductTotalSales
Pen500
Marker450