When working with grouped data in SQL, it is sometimes necessary to filter the groups based on certain conditions. While the WHERE clause filters rows before grouping, the HAVING clause filters groups after the GROUP BY operation.
The HAVING clause is mainly used with aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX() to specify conditions on grouped data.
The HAVING clause is used in SQL to apply conditions on grouped records created using the GROUP BY clause.
It filters groups based on aggregate values.
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Where:
Suppose we have a table named students.
| id | name | age | course |
|---|---|---|---|
| 1 | Rahul | 20 | BCA |
| 2 | Anita | 21 | BBA |
| 3 | Rohit | 19 | BCA |
| 4 | Priya | 22 | BCom |
| 5 | Arjun | 20 | BCA |
SELECT course, COUNT(*)
FROM students
GROUP BY course
HAVING COUNT(*) > 1;
| course | COUNT(*) |
|---|---|
| BCA | 3 |
This query groups students by course and displays only the courses that have more than one student.
SELECT course, AVG(age)
FROM students
GROUP BY course
HAVING AVG(age) > 20;
| course | AVG(age) |
|---|---|
| BBA | 21 |
| BCom | 22 |
This query shows courses where the average age of students is greater than 20.
| WHERE | HAVING |
|---|---|
| Filters rows before grouping | Filters groups after grouping |
| Cannot use aggregate functions | Can use aggregate functions |
| Used with SELECT, UPDATE, DELETE | Used mainly with GROUP BY |
Example:
SELECT course, COUNT(*)
FROM students
WHERE age > 19
GROUP BY course
HAVING COUNT(*) > 1;
Here:
HAVING is used to filter grouped records.The HAVING clause is used to apply conditions on grouped data in SQL queries. It is especially useful when working with aggregate functions and grouped records. By filtering grouped results, the HAVING clause helps users analyze summarized data more effectively.