login

SQL Having

SQL HAVING clause is used together with SQL GROUP BY clause to filter group of records based on conditions. SQL HAVING clause is similar to WHERE clause in functionality manner but filter group of records not records.
Let’s take a look at several examples of using SQL HAVING.

You want to find all sale orders which have total sale greater than 120000$, you can use HAVING together with GROUP BY clause.

SELECT OrderID, SUM(unitPrice * quantity) total
FROM Order_details
GROUP BY OrderID
HAVING total > 12000
OrderID     total  
------- ----------
10372 12281.2000
10865 17250.0000
10981 15810.0000
11030 16321.9000

Suppose you want to find all orders which have a number of products greater than 5 , you can use COUNT function with HAVING and GROUP BY together. Her e is the query:

SELECT orderID, 
COUNT(productID) prd_count
FROM order_details
GROUP BY orderID
HAVING prd_count > 5
orderID  prd_count
------- ---------
10657 6
10847 6
10979 6
11077 25
Read On