login

SQL Having

Summary: In this tutorial, you will learn how to use SQL HAVING clause to add conditions to groups of records returned from a GROUP BY.

SQL HAVING clause is used together with SQL GROUP BY clause to filter group of records based on certain conditions. SQL HAVING clause is similar to WHERE clause in in term of functionality . SQL WHERE clause filters record while SQL HAVING clause filters group of records.

Let’s take a look at several examples of using SQL HAVING to have a bettern understanding.

If you want to find all sale orders which have total sale more than $12.000, you can use HAVING together with the GROUP BY clause.

SELECT OrderID, SUM(unitPrice * quantity) Total
FROM Order_details
GROUP BY OrderID
HAVING total > 12000

 SQL HAVING Example 1

Suppose you want to find all orders that have a number of products sold more than 5 , you can use COUNT function together with HAVING and GROUP BY. Here is the query:

SELECT orderID, COUNT(productID) prd_count
FROM order_details
GROUP BY orderID
HAVING prd_count > 5

SQL HAVING

In this tutorial, you've learned how to use SQL HAVING clause to filter groups of records returned by GROUP BY.