SQL HAVING clause

HAVING Clause

The reason for adding the HAVING clause in SQL is that the WHERE keyword cannot be used with aggregate functions.

SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

SQL HAVING Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer
1 2008/12/29 1000 Bush
2 2008/11/23 1600 Carter
3 2008/10/05 700 Bush
4 2008/09/28 300 Bush
5 2008/08/06 2000 Adams
6 2008/07/21 100 Carter

Now, we want to find customers whose total order amount is less than 2000.

We use the following SQL statement:

SELECT Customer, SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000

The result set is similar:

Customer SUM(OrderPrice)
Carter 1700

Now we want to find that the total order amount of customer "Bush" or "Adams" is more than 1500.

We added a regular WHERE clause in the SQL statement:

SELECT Customer, SUM(OrderPrice) FROM Orders
WHERE Customer='Bush' OR Customer='Adams'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500

Result Set:

Customer SUM(OrderPrice)
Bush 2000
Adams 2000