⚡0 XP🔥0

Aggregate Functions, GROUP BY and HAVING

Lesson 4 of 10 ⏱ 4 min read ✎ 3 exercises ❓ 4-question quiz ▶ Runs SQL

Summarise data with COUNT, SUM, AVG, MIN and MAX, group rows with GROUP BY, filter groups with HAVING, and understand how NULLs affect aggregates.

So far every query returned individual rows. Reports need summaries: how many students, the average CGPA, the highest salary, totals per department. That is what aggregate functions and GROUP BY do.

Aggregate functions#

Function Returns
COUNT(*) number of rows
COUNT(col) number of non-NULL values in col
COUNT(DISTINCT col) number of different values
SUM(col) total
AVG(col) average
MIN(col), MAX(col) smallest, largest
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Without GROUP BY, the whole table is one group, so you get one row. Notice with_email is 27, not 30: three students have a NULL email, and aggregates skip NULLs.

GROUP BY - one row per group#

GROUP BY col splits the rows into groups that share the same value, then computes the aggregates per group:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
हिंदी में समझें

GROUP BY city का मतलब है: एक जैसे city वाले students को एक ढेर (group) में रखो, फिर हर ढेर का COUNT, AVG निकालो। Result में हर city की एक row आती है। SELECT में सिर्फ़ वही columns रखें जो GROUP BY में हैं, या जिन पर aggregate function लगा है।

Group by several columns:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Common Mistake

Every column in SELECT must either appear in GROUP BY or be inside an aggregate. SELECT city, name, COUNT(*) ... GROUP BY city makes no sense (one city has many names). PostgreSQL and SQL Server reject it; SQLite and older MySQL silently pick one arbitrary name - a hidden bug.

WHERE vs HAVING#

  • WHERE filters rows before they are grouped.
  • HAVING filters groups after aggregation (so it can use COUNT, AVG...).
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

The logical order of a full query#

FROM        → pick table(s)
WHERE       → filter rows
GROUP BY    → form groups
HAVING      → filter groups
SELECT      → compute output columns
ORDER BY    → sort
LIMIT       → keep the first n

Remembering this order explains most "why doesn't my query work?" questions - for example, why WHERE COUNT(*) > 5 is an error (groups do not exist yet at the WHERE step).

Conditional aggregation with CASE#

A powerful reporting trick: count or sum only the rows that match a condition, side by side:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Tip

Use 100.0 * (not 100 *) when computing percentages: in SQLite and PostgreSQL, dividing two integers gives an integer.

Summary#

  • COUNT, SUM, AVG, MIN, MAX summarise; they ignore NULLs (except COUNT(*)).
  • GROUP BY returns one row per group; select only grouped columns or aggregates.
  • WHERE filters rows before grouping; HAVING filters groups after.
  • SUM(CASE WHEN ... THEN 1 ELSE 0 END) counts conditionally - great for reports.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Students per city

Show each city and the number of students as students, most students first.

Database: college (see the tables in this lesson)
2

Department average CGPA

For each dept_id (skip students with no department), show the number of students and the average CGPA rounded to 2 decimals as avg_cgpa.

Database: college (see the tables in this lesson)
3

Popular courses

From enrollments, show each course_id with its number of enrollments as enrolled and the average marks as avg_marks (rounded to 1 decimal), only for courses with at least 5 enrollments.

Database: college (see the tables in this lesson)

Quick Quiz

Q1.

What is the difference between COUNT(*) and COUNT(email)?

Q2.

Which clause filters groups after aggregation?

Q3.

In SELECT city, COUNT(*) FROM students GROUP BY city, how many rows come back?

Q4.

Which query is INVALID in standard SQL?