Grouping and Aggregating Rows
Summarise books by author without confusing missing values and empty groups.
database, sql, postgresql, aggregate, grouping, countTurn rows into summaries
An aggregate such as COUNT or SUM combines values. GROUP BY forms
groups so each result can describe one group. In a left join, an author with
no book still has one NULL-extended joined row. Which expression is counted
therefore matters.
SQL illustration
Use the fictional authors and books setup in the same session:
SELECT a.id, a.name,
COUNT(b.id) AS book_count,
COUNT(b.pages) AS known_pages,
SUM(b.pages) AS page_sum
FROM authors AS a
LEFT JOIN books AS b ON b.author_id = a.id
GROUP BY a.id, a.name
ORDER BY a.id;
Prepared result — not live execution:
| id | name | book_count | known_pages | page_sum |
|---|---|---|---|---|
| 1 | Ada | 2 | 1 | 120 |
| 2 | Bo | 1 | 1 | 200 |
| 3 | Cy | 0 | 0 | NULL |
Ada has two books but only one known page count. Cy has no matching book:
COUNT(b.id) is zero, while SUM(b.pages) is NULL because there are no
non-NULL inputs. COUNT(*) would count Cy's one NULL-extended row.
See the reasoning
Follow the example one step at a time
Count matching books and known page counts for each author. This is a prepared teaching demonstration, not live code execution.
Collect joined rows
Ada → Kite: 120, Oak: NULL
Bo → Tide: 200
Cy → no matching book
(NULL-extended row)The left join keeps Cy with a NULL-extended book row even though Cy has no matching book.
Filter and interpret
WHERE filters input rows before grouping; HAVING filters groups after
aggregation. SUM, AVG, MIN, and MAX generally ignore NULL inputs;
most return NULL when no non-NULL inputs exist, while COUNT returns
zero. COALESCE(SUM(b.pages), 0) can explicitly display zero, but decide
whether that misrepresents unknown information. Grouping by both ID and
name avoids merging different authors who share a name.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
