Sub topic 15
Aggregation, GROUP BY and HAVING
Assume you know selection, projection, joins, and basic SELECT ... FROM ... WHERE queries. This chapter adds aggregate functions, which compute one value from several rows.
Aggregate functions
An aggregate function combines values from multiple rows into one result.
COUNTcounts rows or non-NULLvalues.SUMadds numeric values.AVGcomputes an average.MINandMAXfind extreme values.
For example, to count enrollments for each course:
WITH Enrolled(cid, sid) AS (
VALUES
(10, 1), (10, 2), (10, 3),
(20, 1), (20, 2),
(30, 4)
)
SELECT cid, COUNT(*) AS num_students
FROM Enrolled
GROUP BY cid
HAVING COUNT(*) >= 2
ORDER BY cid;The result is:
| cid | num_students |
|---|---|
| 10 | 3 |
| 20 | 2 |
GROUP BY cid forms one group for every distinct course identifier. The aggregate function then runs separately for each group.
WHERE and HAVING
WHERE filters individual rows before grouping. HAVING filters complete groups after aggregation.
Consider this query:
SELECT cid, COUNT(*) AS num_students
FROM Enrolled
WHERE sid <> 1
GROUP BY cid
HAVING COUNT(*) >= 2;The row for student sid = 1 is removed first. The remaining rows are grouped. Only groups with at least two remaining rows are returned.
A selected column must normally be either:
- included in the
GROUP BYlist, or - computed by an aggregate function.
Thus, SELECT cid, COUNT(*) ... GROUP BY cid is valid, but selecting sid as well is ambiguous because a course group can contain many student identifiers.
Relational algebra view
Extended relational algebra commonly writes grouping and aggregation with the γ operator:
γ_cid; COUNT(sid) → num_students (Enrolled)This means: group Enrolled by cid, count sid in each group, and call the result num_students. A condition on the aggregate, such as COUNT(sid) >= 10, is applied after grouping, just as HAVING is applied after GROUP BY.
GATE strategy
For an aggregation question:
- Apply
WHEREto the original rows. - Create groups using the
GROUP BYattributes. - Compute each aggregate, carefully handling duplicates and
NULL. - Apply
HAVING. - Count the remaining output rows.
Exercise
Which clause should contain the condition “return departments having an average salary greater than 50000”?
Show answer
Use HAVING AVG(salary) > 50000, because the condition tests a group-level aggregate.