Having clause in SQL

The HAVING clause in SQL is used to filter records that have been grouped by a GROUP BY clause. It is similar to the WHERE clause, but it is used for groups rather than individual rows. The HAVING clause is often used with aggregate functions such as COUNT, SUM, AVG, MAX, and MIN.

SQL Syntax

 SELECT column1, column2, aggregate_function(column3)
 FROM table_name
 WHERE condition
 GROUP BY column1, column2
 HAVING aggregate_function(column3) condition; 

Example: Let's say we have a table sales that records the sales made by employees in different regions.

Create a sales table and its columns.

SQL

CREATE TABLE sales (
    sale_id INT PRIMARY KEY,
    employee_id INT,
    region VARCHAR(50),
    amount DECIMAL(10, 2)
);  

Load the data into the Sales table.

SQL

INSERT INTO sales (
sale_id, employee_id, region, amount) 
VALUES
(1, 1, 'North', 500),
(2, 2, 'South', 800),
(3, 1, 'North', 700),
(4, 3, 'East', 200),
(5, 2, 'South', 400),
(6, 3, 'East', 600),
(7, 1, 'North', 300);   

By executing the below query we can see the data from the sales table.

SQL

Select * From Sales;

After running the above query, the result should be given below:

Table: sales

Sale IDEmployee IDRegionAmount
11North500
22South800
31North700
43East200
52South400
63East600
71North300

Example with GROUP BY Clause Suppose we want to find the total sales amount for each region where the total sales exceed 1000.

SQL

SELECT region, SUM(amount) AS total_sales
FROM sales
GROUP BY region
HAVING SUM(amount) > 1000;  

The result of the above query is shown below:

RegionTotal Sales
North1500
South1200

Example with GROUP BY and WHERE Clauses Suppose we want to find the total sales amount for each employee in the North region where the total sales exceed 1000.

SQL

SELECT employee_id, SUM(amount) AS total_sales
FROM sales
WHERE region = 'North'
GROUP BY employee_id
HAVING SUM(amount) > 1000;  

The result of the above query is shown below:

Employee IDTotal Sales
11500

In this example: