⬅ Previous Topic
GROUP BY Clause in SQLNext Topic ⮕
LIMIT / TOP Clause in SQL⬅ Previous Topic
GROUP BY Clause in SQLNext Topic ⮕
LIMIT / TOP Clause in SQLOnce you’ve grouped your data using GROUP BY
, you often want to apply conditions on those grouped results — for example, finding classes where the average score is above 90. The HAVING
clause makes that possible. Think of it as a WHERE for groups.
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
We’ll use this student marks table:
CREATE TABLE student_marks (
roll_no INT,
name VARCHAR(50),
class VARCHAR(10),
subject VARCHAR(30),
marks INT
);
INSERT INTO student_marks VALUES
(1, 'Aarav Sharma', '10A', 'Maths', 85),
(2, 'Diya Iyer', '9B', 'Maths', 90),
(3, 'Rohit Menon', '10A', 'Maths', 78),
(4, 'Sneha Patil', '8C', 'Maths', 88),
(5, 'Mehul Agarwal', '9B', 'Maths', 92),
(1, 'Aarav Sharma', '10A', 'Science', 91),
(2, 'Diya Iyer', '9B', 'Science', 87),
(3, 'Rohit Menon', '10A', 'Science', 85),
(4, 'Sneha Patil', '8C', 'Science', 89),
(5, 'Mehul Agarwal', '9B', 'Science', 93);
Let’s find subjects with average marks above 88:
SELECT subject, AVG(marks) AS avg_marks
FROM student_marks
GROUP BY subject
HAVING AVG(marks) > 88;
subject | avg_marks
--------+-----------
Science | 89.0
WHERE
filters rows before grouping. HAVING
filters after grouping.
SELECT class, AVG(marks) AS avg_maths
FROM student_marks
WHERE subject = 'Maths'
GROUP BY class
HAVING AVG(marks) > 85;
class | avg_maths
------+-----------
9B | 91.0
8C | 88.0
Let’s find classes that have more than 2 subject entries:
SELECT class, COUNT(*) AS entry_count
FROM student_marks
GROUP BY class
HAVING COUNT(*) > 2;
Find students whose total marks (across subjects) exceed 175:
SELECT name, SUM(marks) AS total_score
FROM student_marks
GROUP BY name
HAVING SUM(marks) > 175;
name | total_score
----------------+-------------
Mehul Agarwal | 185
Aarav Sharma | 176
Find subject-wise average where marks are greater than 85 and entry count is more than 3:
SELECT subject, AVG(marks) AS avg_marks, COUNT(*) AS total_entries
FROM student_marks
GROUP BY subject
HAVING AVG(marks) > 85 AND COUNT(*) > 3;
The HAVING
clause is what you reach for when WHERE
isn’t enough. When you want to filter based on totals, averages, counts — after you’ve grouped the data — HAVING makes it possible.
Now that you’ve mastered filtering grouped data, let’s move on to the LIMIT clause — which helps you fetch just the top results, such as the top 3 scorers per class or subject.
SELECT class, AVG(marks) FROM students GROUP BY class HAVING AVG(marks) > 75;
⬅ Previous Topic
GROUP BY Clause in SQLNext Topic ⮕
LIMIT / TOP Clause in SQLYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.