
- SQL - Home
- SQL - Roadmap
- SQL - Overview
- SQL - RDBMS Concepts
- SQL - Databases
- SQL - Syntax
- SQL - Data Types
- SQL - Operators
- SQL - Expressions
- SQL - Comments
- SQL Database
- SQL - Create Database
- SQL - Drop Database
- SQL - Select Database
- SQL - Rename Database
- SQL - Show Databases
- SQL - Backup Database
- SQL Table
- SQL - Create Table
- SQL - Show Tables
- SQL - Rename Table
- SQL - Truncate Table
- SQL - Clone Tables
- SQL - Temporary Tables
- SQL - Alter Tables
- SQL - Drop Table
- SQL - Delete Table
- SQL - Constraints
- SQL Queries
- SQL - Insert Query
- SQL - Select Query
- SQL - Select Into
- SQL - Insert Into Select
- SQL - Update Query
- SQL - Delete Query
- SQL - Sorting Results
- SQL Views
- SQL - Create Views
- SQL - Update Views
- SQL - Drop Views
- SQL - Rename Views
- SQL Operators and Clauses
- SQL - Where Clause
- SQL - Top Clause
- SQL - Distinct Clause
- SQL - Order By Clause
- SQL - Group By Clause
- SQL - Having Clause
- SQL - AND & OR
- SQL - BOOLEAN (BIT) Operator
- SQL - LIKE Operator
- SQL - IN Operator
- SQL - ANY, ALL Operators
- SQL - EXISTS Operator
- SQL - CASE
- SQL - NOT Operator
- SQL - NOT EQUAL
- SQL - IS NULL
- SQL - IS NOT NULL
- SQL - NOT NULL
- SQL - BETWEEN Operator
- SQL - UNION Operator
- SQL - UNION vs UNION ALL
- SQL - INTERSECT Operator
- SQL - EXCEPT Operator
- SQL - Aliases
- SQL Joins
- SQL - Using Joins
- SQL - Inner Join
- SQL - Left Join
- SQL - Right Join
- SQL - Cross Join
- SQL - Full Join
- SQL - Self Join
- SQL - Delete Join
- SQL - Update Join
- SQL - Left Join vs Right Join
- SQL - Union vs Join
- SQL Keys
- SQL - Unique Key
- SQL - Primary Key
- SQL - Foreign Key
- SQL - Composite Key
- SQL - Alternate Key
- SQL Indexes
- SQL - Indexes
- SQL - Create Index
- SQL - Drop Index
- SQL - Show Indexes
- SQL - Unique Index
- SQL - Clustered Index
- SQL - Non-Clustered Index
- Advanced SQL
- SQL - Wildcards
- SQL - Injection
- SQL - Hosting
- SQL - Min & Max
- SQL - Null Functions
- SQL - Check Constraint
- SQL - Default Constraint
- SQL - Stored Procedures
- SQL - NULL Values
- SQL - Transactions
- SQL - Sub Queries
- SQL - Handling Duplicates
- SQL - Using Sequences
- SQL - Auto Increment
- SQL - Date & Time
- SQL - Cursors
- SQL - Common Table Expression
- SQL - Group By vs Order By
- SQL - IN vs EXISTS
- SQL - Database Tuning
- SQL Function Reference
- SQL - Date Functions
- SQL - String Functions
- SQL - Aggregate Functions
- SQL - Numeric Functions
- SQL - Text & Image Functions
- SQL - Statistical Functions
- SQL - Logical Functions
- SQL - Cursor Functions
- SQL - JSON Functions
- SQL - Conversion Functions
- SQL - Datatype Functions
- SQL Useful Resources
- SQL - Questions and Answers
- SQL - Cheatsheet
- SQL - Quick Guide
- SQL - Useful Functions
- SQL - Useful Resources
- SQL - Discussion
SQL - Having Clause
The SQL HAVING Clause
The HAVING clause in SQL is used to filter grouped records based on a condition, involving aggregate functions such as COUNT(), SUM(), AVG(), MAX(), or MIN(). It works in conjunction with the GROUP BY clause and is applied after the data has been grouped.
While the WHERE clause filters individual rows before grouping, the HAVING clause filters groups after the aggregation has been completed. This makes HAVING important when you need to restrict the output of grouped data based on aggregate values.
The HAVING clause was introduced in SQL because the WHERE clause cannot be used with aggregate functions.
Syntax
Following is the basic syntax of the SQL HAVING clause:
SELECT column1, column2, aggregate_function(column) FROM table_name GROUP BY column1, column2 HAVING condition;
The following code block shows the position of the HAVING Clause in a query:
SELECT FROM WHERE GROUP BY HAVING ORDER BY
HAVING with GROUP BY Clause
We can use the HAVING clause with the GROUP BY clause to filter groups of rows that meet certain conditions. It is used to apply a filter to the result set after the aggregation has been performed.
Example
Assume we have created a table named CUSTOMERS, which contains the personal details of customers including their name, age, address and salary, using the following query:
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Now insert values into this table using the INSERT statement as follows:
INSERT INTO CUSTOMERS VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00), (2, 'Khilan', 25, 'Delhi', 1500.00), (3, 'Kaushik', 23, 'Kota', 2000.00), (4, 'Chaitali', 25, 'Mumbai', 6500.00), (5, 'Hardik', 27, 'Bhopal', 8500.00), (6, 'Komal', 22, 'Hyderabad', 4500.00), (7, 'Muffy', 24, 'Indore', 10000.00);
The table created is as shown below:
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
Now, we are grouping the records of the CUSTOMERS table based on the columns ADDRESS and AGE and filtering the groups where the AGE value is less than 25.
SELECT ADDRESS, AGE, MIN(SALARY) AS MIN_SUM FROM CUSTOMERS GROUP BY ADDRESS, AGE HAVING AGE > 25;
The result produced is as follows:
ADDRESS | AGE | MIN_SUM |
---|---|---|
Ahmedabad | 32 | 2000.00 |
Bhopal | 27 | 8500.00 |
HAVING with ORDER BY Clause
The ORDER BY clause is used to arrange/sort the records of the result of a SELECT query based on a specific column (either in ascending order or in descending order).
If we use the ORDER BY clause with the HAVING clause we can sort the filtered groups in the desired order.
Example
Following query groups the records of the CUSTOMERS table based on the columns AGE and ADDRESS, filters the groups where the SALARY value is less than 5000 and, arranges the remaining groups in descending order based the total salaries of each group.
SELECT ADDRESS, AGE, SUM(SALARY) AS TOTAL_SALARY FROM CUSTOMERS GROUP BY ADDRESS, AGE HAVING TOTAL_SALARY >=5000 ORDER BY TOTAL_SALARY DESC;
The result produced is as follows:
ADDRESS | AGE | TOTAL_SALARY |
---|---|---|
Indore | 24 | 10000.00 |
Bhopal | 27 | 8500.00 |
Mumbai | 25 | 6500.00 |
HAVING Clause with COUNT() Function
The HAVING clause can be used with the COUNT() function to filter groups based on the number of rows they contain.
Example
Following query groups the records of the CUSTOMERS table based on the AGE column and, retrieves the details of the group that has more than two entities:
SELECT AGE, COUNT(AGE) FROM CUSTOMERS GROUP BY AGE HAVING COUNT(age) > 2;
This would produce the following result:
Query OK, 0 rows affected (0.02 sec)
HAVING Clause with AVG() Function
The HAVING clause can also be used with the AVG() function to filter groups based on the average value of a specified column.
Example
Now, we are retrieving the city of the customers whose average salary is greater than 5240:
SELECT ADDRESS, AVG(SALARY) as AVG_SALARY FROM CUSTOMERS GROUP BY ADDRESS HAVING AVG(SALARY) > 5240;
Following is the output of the above query:
ADDRESS | AVG_SALARY |
---|---|
Mumbai | 6500.000000 |
Bhopal | 8500.000000 |
Indore | 10000.000000 |
HAVING Clause with MAX() Function
We can also use the HAVING clause with MAX() function to filter groups based on the maximum value of a specified column.
Example
Now, we are retrieving the city of the customers whose maximum salary is greater than 5240:
SELECT ADDRESS, MAX(SALARY) as MAX_SALARY FROM CUSTOMERS GROUP BY ADDRESS HAVING MAX(SALARY) > 5240;
The result obtained is as follows:
ADDRESS | MAX_SALARY |
---|---|
Mumbai | 6500.00 |
Bhopal | 8500.00 |
Indore | 10000.00 |
HAVING Clause with Multiple Conditions
The HAVING clause can also include multiple conditions combined using logical operators like AND, OR, and NOT.This helps to filter grouped data more accurately using conditions with functions like SUM, COUNT, or AVG.
Example
Now, we are retrieving the address and age of the customers where the total salary is greater than or equal to 5000 and the minimum salary in the group is greater than 1500:
SELECT ADDRESS, AGE, SUM(SALARY) AS TOTAL_SALARY, MIN(SALARY) AS MIN_SALARY FROM CUSTOMERS GROUP BY ADDRESS, AGE HAVING SUM(SALARY) >= 5000 AND MIN(SALARY) > 1500;
The result obtained is as follows:
ADDRESS | AGE | TOTAL_SALARY | MIN_SALARY |
---|---|---|---|
Mumbai | 25 | 6500.00 | 6500.00 |
Indore | 24 | 10000.00 | 10000.00 |
Bhopal | 27 | 8500.00 | 8500.00 |
HAVING Clause with Joins
The HAVING clause can also be used in conjunction with JOIN operations. When multiple tables are joined and the result is grouped, the HAVING clause can be applied to filter those grouped results based on aggregate values.
Example
Assume we have another table named ORDERS with the following structure and data:
CREATE TABLE ORDERS ( OID INT NOT NULL, DATE VARCHAR(20) NOT NULL, CUSTOMER_ID INT, AMOUNT DECIMAL(10, 2), PRIMARY KEY (OID) );
INSERT INTO ORDERS VALUES (101, '2023-07-01', 1, 3000.00), (102, '2023-07-02', 3, 1500.00), (103, '2023-07-03', 4, 2500.00), (104, '2023-07-04', 6, 4000.00), (105, '2023-07-05', 5, 4500.00), (106, '2023-07-06', 7, 1000.00);
Now, let us retrieve the customer addresses and total order amounts for each address, but only where the total order amount is more than 3000:
SELECT C.ADDRESS, SUM(O.AMOUNT) AS TOTAL_ORDERS FROM CUSTOMERS C JOIN ORDERS O ON C.ID = O.CUSTOMER_ID GROUP BY C.ADDRESS HAVING SUM(O.AMOUNT) > 3000;
The result obtained is as follows:
ADDRESS | TOTAL_ORDERS |
---|---|
Hyderabad | 4000.00 |
Bhopal | 4500.00 |
SQL HAVING vs WHERE Clause
Both HAVING and WHERE clauses are used to filter data in SQL queries. But they work differently and are used at different steps in the query process:
WHERE Clause | HAVING Clause |
---|---|
Filters rows before grouping occurs. | Filters groups after aggregation occurs. |
Cannot be used with aggregate functions. | Can be used with aggregate functions (e.g., COUNT, AVG). |
Used in SELECT, UPDATE, DELETE statements. | Used only with SELECT statements and usually after GROUP BY. |
Evaluates each row individually. | Evaluates each group of rows. |
Example
Following query uses both WHERE and HAVING clauses:
SELECT ADDRESS, COUNT(*) AS TOTAL_CUSTOMERS FROM CUSTOMERS WHERE SALARY > 2000 GROUP BY ADDRESS HAVING COUNT(*) >= 1;
This query first filters out customers with salary ⤠2000 using WHERE, groups the remaining records by address, and then filters the groups that have at least one customer using HAVING.