Reading history

SQL GROUP BY and HAVING Explained With Examples

3 min read 0 views

Learn SQL GROUP BY and HAVING: per-group counts and averages, filtering groups, WHERE vs HAVING, and the order SQL runs each clause.

Aggregate functions on their own give one answer for the whole table. GROUP BY splits the rows into groups first (one per department, one per city) and then runs the aggregate on each group, so you get a summary per group. HAVING then filters those groups, for example “only departments with more than two students”.

In this lesson you will learn

  • How GROUP BY forms groups
  • Which columns you may select alongside aggregates
  • How to filter groups with HAVING
  • The difference between WHERE and HAVING
  • The order in which SQL actually runs a query

GROUP BY

SELECT dept, COUNT(*) AS students, ROUND(AVG(cgpa), 2) AS avg_cgpa
FROM students
GROUP BY dept
ORDER BY students DESC;

SELECT city, COUNT(*) AS students
FROM students
GROUP BY city
ORDER BY students DESC, city;

Output

+------+----------+----------+
| dept | students | avg_cgpa |
+------+----------+----------+
| CSE  | 4        | 3.81     |
| EEE  | 2        | 3.2      |
| BBA  | 2        | 3.33     |
+------+----------+----------+
(3 rows)

+------------+----------+
| city       | students |
+------------+----------+
| Dhaka      | 3        |
| Chattogram | 2        |
| Khulna     | 1        |
| Rajshahi   | 1        |
| Sylhet     | 1        |
+------------+----------+
(5 rows)
  • Rows with the same dept are collected into one group, and COUNT and AVG run once per group.
  • Every column in the SELECT list must either be in GROUP BY or be inside an aggregate. Selecting name here would make no sense, because each group contains several names.
  • The CSE average (3.81) uses three values, since Nadia’s CGPA is NULL.
  • ORDER BY can sort by an aggregate alias such as students.

Filtering Groups with HAVING

-- Departments with more than two students
SELECT dept, COUNT(*) AS students
FROM students
GROUP BY dept
HAVING COUNT(*) > 2;

-- WHERE filters rows first, HAVING filters groups after
SELECT dept, ROUND(AVG(cgpa), 2) AS avg_cgpa
FROM students
WHERE city <> 'Dhaka'
GROUP BY dept
HAVING AVG(cgpa) >= 3.4;

Output

+------+----------+
| dept | students |
+------+----------+
| CSE  | 4        |
+------+----------+
(1 row)

+------+----------+
| dept | avg_cgpa |
+------+----------+
| CSE  | 3.67     |
| EEE  | 3.41     |
+------+----------+
(2 rows)
  • HAVING COUNT(*) > 2 keeps only groups with more than two rows. Only CSE qualifies.
  • In the second query, WHERE city <> 'Dhaka' first removes Dhaka students, then the remaining rows are grouped, then HAVING drops groups averaging below 3.4. BBA (3.33) is dropped.

How SQL Runs a Query

StepClauseWhat happens
1FROM / JOINPick the tables
2WHEREFilter rows
3GROUP BYForm groups
4HAVINGFilter groups
5SELECTCompute the output columns
6ORDER BYSort
7LIMITCut the result

This order explains why WHERE cannot use aggregates (groups do not exist yet) and why HAVING can.

Common Mistakes

  1. Selecting a column that is neither grouped nor aggregated.
  2. Using HAVING for row filters that belong in WHERE. It works but is slower, because the database groups rows it then throws away.
  3. Using WHERE with an aggregate, such as WHERE COUNT(*) > 2, which is an error.

Practice Exercises

Exercise 1. Show the average marks per course id, highest first.

Show answer
SELECT course_id, ROUND(AVG(marks), 1) AS avg_marks
FROM enrollments
GROUP BY course_id
ORDER BY avg_marks DESC;

Exercise 2. List cities with exactly one student.

Show answer
SELECT city FROM students GROUP BY city HAVING COUNT(*) = 1;
-- Khulna, Rajshahi, Sylhet

Frequently Asked Questions

Can I group by more than one column?

Yes. GROUP BY dept, city makes one group for each department-and-city combination.

Is GROUP BY the same as DISTINCT?

For selecting unique values they give the same rows, but only GROUP BY lets you compute aggregates for each group.

Summary

  • GROUP BY runs aggregates once per group.
  • Selected columns must be grouped or aggregated.
  • WHERE filters rows before grouping; HAVING filters groups after.
  • SQL runs FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.

Next: SQL JOINs.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *