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 |
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:
GROUP BY city का मतलब है: एक जैसे city वाले students को एक ढेर (group) में रखो, फिर हर ढेर का COUNT, AVG निकालो। Result में हर city की एक row आती है। SELECT में सिर्फ़ वही columns रखें जो GROUP BY में हैं, या जिन पर aggregate function लगा है।
Group by several columns:
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#
WHEREfilters rows before they are grouped.HAVINGfilters groups after aggregation (so it can useCOUNT,AVG...).
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:
Use 100.0 * (not 100 *) when computing percentages: in SQLite and PostgreSQL, dividing two integers gives an integer.
Summary#
COUNT,SUM,AVG,MIN,MAXsummarise; they ignore NULLs (exceptCOUNT(*)).GROUP BYreturns one row per group; select only grouped columns or aggregates.WHEREfilters rows before grouping;HAVINGfilters groups after.SUM(CASE WHEN ... THEN 1 ELSE 0 END)counts conditionally - great for reports.