MySQL HAVING Clause

MySQL | HAVING Clause: Learn about the MySQL HAVING Clause, with its explanation, syntax, and query examples.
Submitted by Apurva Mathur, on September 08, 2022

HAVING Clause

When we use an aggregate function in our queries there we cannot use WHERE conditions, in such case MySQL provides us HAVING clause, this clause is used wherever we are not able to use the WHERE clause. This clause is used with the GROUP BY clause and returns the rows where the condition is TRUE.

HAVING Clause Syntax

SELECT column_name
FROM table_name
WHERE condition
GROUP BY column_name
HAVING condition;

To understand this clause in deep, here are some cases;

HAVING Clause Examples

Suppose we have a table named "student_details" and inside that table, we have the following columns;

HAVING Clause (Example 1)

Case 1: Suppose we want to know in which department more than 4 students are there, in such case, we will write the following query;

SELECT COUNT (ID), student_department 
FROM student_details 
GROUP BY student_department 
HAVING COUNT (ID) > 4;
HAVING Clause (Example 2)

As you can see in the result the "CSE" and "ME" department has more than 4 students so they are displayed as a result.

Case 2: Suppose we need to find out the minimum marks in all the departments then in such case we will make our query in such a way that they are grouped by departments.

SELECT student_department, min(Marks) AS "Minimum marks" 
FROM student_details 
GROUP BY student_department 
HAVING min(Marks)>10;
HAVING Clause (Example 3)

As a result, it will give you the minimum marks in all the departments.





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.