The Wayback Machine - https://web.archive.org/web/20240727132444/https://www.geeksforgeeks.org/sql-having-clause-with-examples/
Open In App

SQL HAVING Clause with Examples

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The HAVING clause was introduced in SQL to allow the filtering of query results based on aggregate functions and groupings, which cannot be achieved using the WHERE clause that is used to filter individual rows.

In simpler terms MSSQL, the HAVING clause is used to apply a filter on the result of GROUP BY based on the specified condition. The conditions are Boolean type i.e. use of logical operators  (AND, OR). This clause was included in SQL as the WHERE keyword failed when we use it with aggregate expressions. Having is a very generally used clause in SQL. Similar to WHERE it helps to apply conditions, but HAVING works with groups. If you wish to filter a group, the HAVING clause comes into action.

Some important points:

  • Having clause is used to filter data according to the conditions provided.
  • Having a clause is generally used in reports of large data.  
  • Having clause is only used with the SELECT clause.
  • The expression in the syntax can only have constants.
  • In the query, ORDER BY  is to be placed after the HAVING clause, if any.
  • HAVING Clause is implemented in column operation.
  • Having clause is generally used after GROUP BY.                                                                                                                                                                                                                                                                  

Syntax:

SELECT col_1, function_name(col_2)

FROM tablename

WHERE condition

GROUP BY column1, column2

HAVING Condition

ORDER BY column1, column2;

Here, the function_name is the name of the function used, for example, SUM(), and AVG().

Example 1:

Here first we create a database name as “Company”, then we will create a table named “Employee” in the database. After creating a table we will execute the query.

Step 1: Creating a database

CREATE DATABASE Company;

Step 2: To use this database

USE Company;

Step 3: Creating a table

CREATE TABLE Employee (
  EmployeeId int,
  Name varchar(20),
  Gender varchar(20),
  Salary int,
  Department varchar(20),
  Experience varchar(20)
);

Add value to the table:

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department, Experience)
VALUES (5, 'Priya Sharma', 'Female', 45000, 'IT', '2 years');

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department, Experience)
VALUES (6, 'Rahul Patel', 'Male', 65000, 'Sales', '5 years');

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department, Experience)
VALUES (7, 'Nisha Gupta', 'Female', 55000, 'Marketing', '4 years');

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department, Experience)
VALUES (8, 'Vikram Singh', 'Male', 75000, 'Finance', '7 years');

INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department, Experience)
VALUES (9, 'Aarti Desai', 'Female', 50000, 'IT', '3 years');

The final table is:

SELECT * FROM Employee;

Output:

img3

 

Step 4: Execute the query

This employee table will help us understand the HAVING Clause. It contains employee IDs, Name, Gender, department, and salary. To Know the sum of salaries, we will write the query:

SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department;

Here is the result,

Output

img4

 

Now if we need to display the departments where the sum of salaries is 50,000 or more. In this condition, we will use the HAVING Clause.

SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;  

Output:

img5

 

Example 2:

Suppose, a teacher wants to announce the toppers in class. For this, she decides to reward every student who scored more than 95%. We need to group the database by name and their percentage and find out who scored more than 95% in that year. So for this first, we create a database name “School”, and then we will create a table named “Student” in the database. After creating a table we will execute the query.

Step 1: Creating a database

CREATE DATABASE School;

Step 2: To use this database

USE School;

Step 3: Creating a table

CREATE TABLE Student(
   student Varchar(20),
   percentage int
);

Add value to the table:

INSERT INTO Student VALUES ('Isha Patel', 98)
INSERT INTO Student VALUES ('Harsh Das', 94)
INSERT INTO Student VALUES ('Rachit Sha', 93)
INSERT INTO Student VALUES ('Sumedha', 98)
INSERT INTO Student VALUES ('Rahat Ali', 98)

The final table is:

SELECT * FROM Student;

Output:

 

Step 4: Execute Query

SELECT student, percentage
FROM Student
GROUP BY student, percentage
HAVING percentage > 95;

Here, three students named Isha, Sumedha, and Rahat Ali scored more than 95 %.

Output:

 

 

Further, we can also filter rows on multiple values using the HAVING clause. The HAVING clause also permits filtering rows using more than one aggregate condition.

Query:

SELECT student  
FROM Student
WHERE percentage > 90
GROUP BY student, percentage
HAVING SUM(percentage) < 1000 AND AVG(percentage) > 95;

This query returns the students who have more percentage than 95 and the sum of percentage is less than 1000. 

Output:

 

SQL Having vs WHERE

Having Where
In the HAVING clause it will check the condition in group of a row. In the WHERE condition it will check or execute at each row individual.
HAVING clause can only be used with aggregate function. The WHERE Clause cannot be used with aggregate function like Having
Priority Wise HAVING Clause is executed after Group By. Priority Wise WHERE is executed before  Group By.


Previous Article
Next Article

Similar Reads

Difference between Having clause and Group by clause
1. Having Clause : Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The
3 min read
Having clause in MS SQL Server
In this article, we will be discussing having clause in MS SQL Server. There are certain instances where the data to be extracted from the queries is done using certain conditions. To do this, having clause is used. Having clause extracts the rows based on the conditions given by the user in the query. Having clause has to be paired with the group
2 min read
Difference between Where and Having Clause in SQL
WHERE and HAVING clauses play an important role in refining the result set of a query. While both clauses are used for filtering data, they serve distinct purposes and are applied at different stages of query execution. Let's explore the details of each and their differences with examples. WHERE ClauseWHERE Clause is used to filter the records from
2 min read
PHP - Mysql GROUP BY HAVING Clause
Problem Statement :In this article, we are going to perform database operations with GROUP BY HAVING operation through PHP through xampp server. In this scenario, we are going to consider the food database. Requirements :xampp server Introduction :PHP is a server side scripting language that can communicate with Mysql web server through xampp tool.
3 min read
SQL | Intersect &amp; Except clause
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 â€Ķâ€Ķ FROM table 1 WHEREâ€Ķ.. INTERSECT SELECT column-1, column-2 â€Ķâ€Ķ FROM table 2 WHE
1 min read
SQL | USING Clause
If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN. USING Clause is used to match only one column when more than one column matches. NATURAL JOIN and USING Clause are mutually exclusive. It should not have a q
2 min read
SQL | With Ties Clause
This post is a continuation of SQL Offset-Fetch Clause Now, we understand that how to use the Fetch Clause in Oracle Database, along with the Specified Offset and we also understand that Fetch clause is the newly added clause in the Oracle Database 12c or it is the new feature added in the Oracle database 12c. Now consider the below example: Suppos
4 min read
SQL | Sub queries in From Clause
From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied. Sub queries in the from clause are supported by most of the SQL implementations.The correlation variables from the relations in from clause cannot be used in the sub-queries in
2 min read
SQL | ON Clause
The join condition for the natural join is basically an EQUIJOIN of all columns with same name. To specify arbitrary conditions or specify columns to join, the ON Clause is used. The join condition is separated from other search conditions. The ON Clause makes code easy to understand. ON Clause can be used to join columns that have different names.
2 min read
Combining aggregate and non-aggregate values in SQL using Joins and Over clause
Prerequisite - Aggregate functions in SQL, Joins in SQLAggregate functions perform a calculation on a set of values and return a single value. Now, consider an employee table EMP and a department table DEPT with following structure:Table - EMPLOYEE TABLE NameNullTypeEMPNONOT NULLNUMBER(4)ENAME VARCHAR2(10)JOB VARCHAR2(9)MGR NUMBER(4)HIREDATE DATESA
2 min read
three90RightbarBannerImg