Sub topic 18
Aggregation, GROUP BY and HAVING
This chapter assumes you can write a SELECT-FROM-WHERE query, you know that SQL tables are bags (they allow duplicate rows), and you have seen NULL. All examples use Student(sid, sname, age), Course(cid, cname) and Enrolled(sid, cid).
Aggregate functions
An aggregate function takes a column of values from many rows and returns one value. The five standard ones are COUNT, SUM, AVG, MIN and MAX.
Three rules decide most exam answers:
- Every aggregate except
COUNT(*)ignores NULLs. COUNT(*)counts rows.COUNT(col)counts rows wherecolis not NULL.DISTINCTinside an aggregate, as inCOUNT(DISTINCT age), removes duplicate values before counting.
Suppose Student has ages 18, 21 and NULL.
SELECT COUNT(*) FROM Student; -- 3
SELECT COUNT(age) FROM Student; -- 2
SELECT SUM(age) FROM Student; -- 39
SELECT AVG(age) FROM Student; -- 19.5, not 13, because the NULL row is skipped
SELECT MAX(age) FROM Student; -- 21An aggregate query with no GROUP BY always returns exactly one row, even if the input is empty. On an empty input, COUNT returns 0 and SUM, AVG, MIN and MAX return NULL.
GROUP BY
GROUP BY partitions the rows into groups that agree on the listed columns. Each group then produces one output row. In extended relational algebra this is the operator γ:
γ cid; COUNT(*) → num_students (Enrolled)Two details matter. NULLs in a grouping column form one group together, even though NULL = NULL is not true elsewhere. Also, the number of output rows equals the number of distinct combinations of the grouping columns that survive WHERE.
The logical order of evaluation explains most rules in this chapter.
WHERE versus HAVING
WHERE runs before grouping, so it sees single rows and cannot contain aggregates. HAVING runs after grouping, so it sees groups and can use aggregates.
SELECT cid, COUNT(*) AS num_students
FROM Enrolled
GROUP BY cid
HAVING COUNT(*) >= 10;Take Enrolled with the rows (1,10), (1,20), (2,10), (3,10), (3,20), (3,30). Group by sid and keep groups with at least two rows:
SELECT sid, COUNT(*) AS n
FROM Enrolled
GROUP BY sid
HAVING COUNT(*) >= 2;| sid | rows in group | n | kept by HAVING |
|---|---|---|---|
| 1 | 2 | 2 | yes |
| 2 | 1 | 1 | no |
| 3 | 3 | 3 | yes |
The result is (1, 2) and (3, 3).
A condition on a plain column belongs in WHERE even though HAVING would accept it when the column is a grouping column. Filtering early is cheaper and clearer. A condition on an aggregate must go in HAVING.
Groups never come from nothing
A group exists only if at least one row belongs to it. A course with no enrollments therefore never appears in GROUP BY cid over Enrolled. To report zero counts, group over the outer-joined result and count a column from the nullable side:
SELECT c.cid, COUNT(e.sid) AS num_students
FROM Course c
LEFT OUTER JOIN Enrolled e ON c.cid = e.cid
GROUP BY c.cid;Here COUNT(e.sid) gives 0 for an unenrolled course because its single joined row has e.sid NULL. COUNT(*) would give 1, which is wrong.
Maximum and minimum groups
SQL does not allow nested aggregates such as MAX(COUNT(*)). To find the courses with the most enrollments, compare each group's count against the counts of all groups:
SELECT cid
FROM Enrolled
GROUP BY cid
HAVING COUNT(*) >= ALL (
SELECT COUNT(*)
FROM Enrolled
GROUP BY cid
);Ties all qualify, so the query can return more than one course.
Counting result tuples
GATE questions often ask how many rows a grouped query returns. Work in this order:
- Apply the joins and the WHERE filter, and count the surviving rows.
- Count the distinct values (or combinations) of the GROUP BY columns among those rows. That is the number of groups.
- Apply HAVING to remove groups.
- If there is no GROUP BY, the answer is 1 row for an aggregate query, whatever the input.
For minimum and maximum, the group count lies between 1 and the number of surviving rows. It is at most the number of distinct grouping values the domain allows.
Common errors
- Writing
WHERE COUNT(*) > 1. Aggregates are not allowed in WHERE. - Selecting a column that is neither grouped nor aggregated.
- Using
COUNT(*)when the intent is to count non-NULL values. - Expecting
AVG(col)to divide by the total row count instead of the non-NULL count. - Expecting empty groups to appear without an outer join.
Exercise
Using the Enrolled rows (1,10), (1,20), (2,10), (3,10), (3,20), (3,30), what does SELECT cid, COUNT() FROM Enrolled GROUP BY cid HAVING COUNT() >= 2 return?
Show answer
Course 10 has 3 rows (sid 1, 2, 3), course 20 has 2 rows (sid 1, 3), and course 30 has 1 row. HAVING removes course 30, so the result is (10, 3) and (20, 2).
Exercise
Student has ages 18, 21, NULL, 21. Give COUNT(*), COUNT(age), COUNT(DISTINCT age) and AVG(age).
Show answer
COUNT(*) is 4, COUNT(age) is 3 because the NULL is skipped, and COUNT(DISTINCT age) is 2 because only 18 and 21 remain. AVG(age) is (18 + 21 + 21) / 3 = 20.