×

How to use HAVING clause in SQL

In this article, we will learn about the HAVING clause concept and how to use it in SQL.

What is the HAVING clause?

In Structured Query Language, HAVING Clause used with GROUP BY Clause specifies the conditions that filter the results appearing in the output. It returns only those data from the group, which fulfills the conditions.

With the HAVING clause, we can use the WHERE clause also in the query. If we use Both Clauses together, WHERE clause will get executed first where it will filter the individual rows, then rows are grouped and at the end, HAVING Clause filters the groups.

HAVING clause conditions are placed after the GROUP BY clause. HAVING clause behaved same as WHERE clause in the Structured Query Language does not use the GROUP BY clause. We can use aggregate functions such as MIN, MAX, SUM, AVG, and COUNT. This function is only used with the SELECT clause and the HAVING clause.

Syntax of HAVING clause:

SELECT COLUMNS, AGGREGATE FUNCTION, FROM TABLENAME WHERE CONDITION GROUP BY COLUMN HAVING CONDITIONS; 

There are some steps we have to learn for how to use the HAVING clause in the SQL query:

1. Create a new database or use an existing database by selecting the database using the USE keyword followed by the database name.

2. Create a new table inside the selected database, or you can use an already created table.

3. If the table is created new, insert the records in the newly created database using the INSERT query and view the inserted data using the SELECT query without the HAVING clause.

4. Now, we are ready to use the HAVING clause in the SQL queries.

Step 1: Create a new database or use an already created database.

I have already created a database. I will use my existing created database name.

USE SCHOOL;

School is the database name.

Those who didn’t have created a database, follow the below query to create the database:

CREATE DATABASE database_name;

After creating the database, select the database using the USE keyword followed by the database name.

Step 2: Create a new table or use already existing table:

I have already created a table. I will use the existing table named Student.

To create the new tables follow below CREATE TABLE syntax:

CREATE TABLE table_name(

columnname1 datatype(column size),

columnname2 datatype(column size),

columnname3 datatype(column size)

);

Step 3: Insert the records in the newly created table using the INSERT query and view the records using the SELECT query.

Use below syntax to insert new records in the table:

INSERT INTO table_name VALUES(value1, value2, value3);

To view the records from the table using the below syntax:

SELECT * FROM table_name;

The following query will display the records of Employees

SELECT * FROM Student;

The output of the above SELECT query is:

STUDENT_IDSTUDENT_NAMEPHYSICS_MARKSCHEMISTRY_MARKSMATHS_MARKSTOTAL_MARKS
1NEHA8588100273
2VISHAL709082242
3SAMKEET758896259
4NIKHIL607580215
5YOGESH566578199
6ANKITA958596276
7SONAM9889100287
8VINEET8590100275
9SANKET867865229
10PRACHI908075245

Step 4: We are ready to use the HAVING clause in the Structured Query Language.

We will now take deep dive into the HAVING clause with the help of examples.

We have a table named Student that contains the following records.

STUDENT_IDSTUDENT_NAMEPHYSICS_MARKSCHEMISTRY_MARKSMATHS_MARKSTOTAL_MARKS
1NEHA8588100273
2VISHAL709082242
3SAMKEET758896259
4NIKHIL607580215
5YOGESH566578199
6ANKITA958596276
7SONAM9889100287
8VINEET8590100275
9SANKET867865229
10PRACHI908075245

Example 1: Write a query to display the sum of physics marks where the sum of physics marks is greater than 60 groups by student id.

SELECT STUDENT_ID, STUDENT_NAME, SUM(PHYSICS_MARKS) AS PHYSICS_MARKS FROM STUDENT GROUP BY STUDENT_ID  HAVING SUM(PHYSICS_MARKS) > 60;

In the above query, we have taken an aggregate function named SUM() followed by column name physics_marks, which will sum the column. First Sum(physics_marks) gets executed, then HAVING clause condition gets executed at the end, and the final result will be displayed. We have used the GROUP BY clause followed by the column name Student_Id to group the same values and consider them one group. If values aren't the same, no group will be formed for values. And at the end, we have used the HAVING clause where we put the condition that will help display only those student details where the sum of physics marks is greater than 60. If student physics marks are less than 60, it won't display the records.

The output of the above query is:

STUDENT_IDSTUDENT_NAMEPHYSICS_MARKS
1NEHA85
2VISHAL70
3SAMKEET75
6ANKITA95
7SONAM98
8VINEET85
9SANKET86
10PRACHI90
How To Use HAVING Clause In SQL

As we can see in the output, only those student ids, names, and physics marks are displayed where the sum of physics marks is greater than 60. As we used GROUP BY clause and no values are similar, they are counted as a single group.

Example 2: Write a query to display the maximum marks of chemistry marks where a maximum mark of chemistry marks is less than 90 groups by student id.

SELECT STUDENT_ID, STUDENT_NAME, MAX(CHEMISTRY_MARKS) AS CHEMISTRY_MARKS FROM STUDENT GROUP BY STUDENT_ID  HAVING MAX(CHEMISTRY_MARKS) < 90;  

In the above query, we have taken an aggregate function named MAX() followed by column name chemistry_marks, which will find the maximum marks of the column. We have used the GROUP BY clause followed by the column name Student_Id to group the same values and consider them one group. If values aren't the same, then a separate group will be formed for values. And at the end, we have used the HAVING clause where we put the condition that will help display only those student details where the maximum mark of chemistry marks is less than 90. If the student chemistry marks are greater than 90, it won't display the records. First, MAX(chemistry_marks) gets executed, then the HAVING clause condition gets executed at the end, and the final result will be displayed. The output of the above query is:

STUDENT_IDSTUDENT_NAMECHEMISTRY_MARKS
1NEHA88
3SAMKEET88
4NIKHIL75
5YOGESH65
6ANKITA85
7SONAM89
9SANKET78
10PRACHI80
How To Use HAVING Clause In SQL

As we can see in the output, only those student ids, names, and chemistry marks are displayed where the maximum mark of chemistry marks is less than 90. As we used GROUP BY clause and no values are similar, they are counted as a single group.

Example 3: Write a query to display the mathematics marks where a minimum mark of mathematics marks is greater than 70 groups by student id.

SELECT STUDENT_ID, STUDENT_NAME, MIN(MATHS_MARKS) AS MATHS_MARKS FROM STUDENT GROUP BY STUDENT_ID  HAVING MIN(MATHS_MARKS) >70;

In the above query, we have taken an aggregate function named MIN() followed by column name maths_marks, which will find the minimum marks of the column. We have used the GROUP BY clause followed by the column name Student_Id to group the same values and consider them one group. If values aren't the same, then a separate group will be formed for values. And at the end, we have used the HAVING clause where we put the condition that will help display only those student details where the minimum mark of maths marks is greater than 70. If the Student's math marks are less than 70, it won't display the records. First, MIN(maths_marks) gets executed, then the HAVING clause condition gets executed at the end, and the final result will be displayed.

The output of the above query is:

STUDENT_IDSTUDENT_NAMEMATHS_MARKS
1NEHA100
2VISHAL82
3SAMKEET96
4NIKHIL80
5YOGESH78
6ANKITA96
7SONAM100
8VINEET100
10PRACHI75
How To Use HAVING Clause In SQL

As we can see in the output, only those student ids, names, and math marks are displayed where the minimum mark of math marks is greater than 70. As we used GROUP BY clause and no values are similar, they are counted as a single group.

Example 4: Write a query to display student details where minimum physics marks are greater than 56, AND maximum math marks are less than 98.

SELECT STUDENT_ID, STUDENT_NAME, MIN(PHYSICS_MARKS) AS PHYSICS_MARKS , MAX(MATHS_MARKS) AS MATHS_MARKS FROM STUDENT GROUP BY STUDENT_ID HAVING MIN(PHYSICS_MARKS) >58 AND MAX(MATHS_MARKS)<98;

We used double aggregate functions in a single query min() and max() in the above query. Min() is used to find out the minimum marks of physics, and Max() is used to find out the maximum math marks. First, the query will find the min() and max() marks of physics and math from the student table. As we used GROUP BY clause, so similar values mapped as one group, else values will be as separated. As no values are similar in the table, all values have separated. No values will be mapped as one group. Next, we used the HAVING clause, which works as WHERE clause difference only HAVING clause mapped into the group. First, the condition is MIN(PHYSICS_MARKS) > 58. As no values are similar, each value will be considered as minimum value, and compared with the condition, the same approach is used for MAX(MATHS_MARKS). As we used AND operator in the query, those conditions fulfill both conditions. Only those students' records are displayed in the final output.

The output of the above query is:

STUDENT_IDSTUDENT_NAMEPHYSICS_MARKSMATHS_MARKS
2VISHAL7082
3SAMKEET7596
4NIKHIL6080
6ANKITA9596
9SANKET8665
10PRACHI9075
How To Use HAVING Clause In SQL

As we can see in the output, only those student records are displayed where minimum marks of physics values are greater than 56, AND maximum math marks are less than 98.

In the above example, if used OR operator instead of AND operator, then all the ten records are displayed because OR operator says if one condition fails and other conditions are true, then table records fulfill the conditions.


Related Topics

SQL CREATE TABLE

In SQL tutorial, we learned and created different databases. To stores data in databases, we need to create a table. To create the table, we need to use CREATE TABLE...

5 minutes read.

How to drop a column in SQL?

How to drop a column in SQL Introduction To delete a column from an already created table, one needs to use the ALTER command along with the DROP COLUMN clause. Syntax: ALTER TABLE tablename...

4 minutes read.

SQL GROUP BY CLAUSE

The GROUP BY clause is used to arrange similar records into the groups in the Structured Query Language queries. The records are arranged with the help of functions which is...

4 minutes read.

How to Update Table in SQL?

How to Update Table in SQL Introduction UPDATE query is used to update a record in a table. UPDATE is a DML command, which operates on the data of the table and not...

4 minutes read.

SQL CRUD Operation

In any computer language, CRUD operation is a foundation. CRUD operation rules are applied in databases as well. These operations are the basic operations used to perform with any database...

7 minutes read.

How to add column in table in SQL ?

How to add column in table in SQL  Introduction To add a column in already created table, one needs to use the ALTER command along with the ADD clause.If in the query,...

7 minutes read.

SQL CONSTRAINTS

SQL Constraints specifies the rules/limitations/restrictions for data present in table. SQL Constraints are specified at the time of table creation or after table creation using ALTER command. There are two...

5 minutes read.

SQL Aggregate Functions

In this tutorial, we will learn and understand the SQL Aggregate Functions concept with the help of examples. SQL Aggregate Function is a function used to perform calculation operations on one...

4 minutes read.

SQL TABLE

SQL TABLE Structured Query Language (SQL) is a relational database (RDBMS) where data is stored in the form of tables, that is, in rows and columns. These tables are known as...

3 minutes read.

Check Constraint in SQL

The Check Constraint in SQL is the rule or set of rules used to limit the data range that can be entered in a table column. Check constraint is used...

8 minutes read.

SQL HAVING Clause

In this tutorial, we will understand the HAVING clause concept in SQL with the help of examples. The HAVING Clause in the SQL is used as we cannot use the WHERE...

3 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

SQL SELECT Database

In this tutorial, we will help you to understand and learn how to select the database in SQL with the help of examples. The database user or the administrator wants to...

3 minutes read.

GROUP BY vs ORDER BY

The GROUP BY clause and ORDER BY clause in SQL are used to arrange data obtained by SQL queries. The important difference between the GROUP BY clause and ORDER BY...

4 minutes read.

SQL Syntax

In this tutorial, we will help you understand about the different SQL Syntax concepts with the help of an example. Every Structured Query Language starts with Keywords like select, insert, update,...

5 minutes read.

SQL UNION ALL Operator

This page has all the information about UNION ALL operator, which is used to join all the values from the SELECT queries. Similar records were not considered in the result in...

3 minutes read.

How to delete column in table

Introduction In SQL, sometimes it is required to delete a column of a table.The use of ALTER TABLE command with DROP COLUMN clause will serve the purpose to delete/remove a column...

4 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.

Nth highest salary

The most common and important question asked in interviews that how we can find the Nth highest salary in a table (2nd highest salary, 3rd highest salary, or Nth highest...

6 minutes read.

SQL Except

In SQL, we probably use the JOIN clause to receive the combined result from one or more than one table. But sometimes, we want a result that contains data from...

4 minutes read.