SQL HAVING

The HAVING clause is used in conjunction with the GROUP BY clause to filter the groups based on a specified condition. It is similar to the WHERE clause, but HAVING is used for groups, while WHERE is used for individual rows.

Syntax

The basic syntax for HAVING is:


SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1
HAVING condition;

        

Example

Suppose we have a table Sales with columns Product and Amount. To find products with total sales amount greater than 1000:


SELECT Product, SUM(Amount) as TotalSales
FROM Sales
GROUP BY Product
HAVING SUM(Amount) > 1000;