Reading preferences
Concept

Grouping and Aggregating Rows

Summarise books by author without confusing missing values and empty groups.

database, sql, postgresql, aggregate, grouping, count

Turn 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:

idnamebook_countknown_pagespage_sum
1Ada21120
2Bo11200
3Cy00NULL

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.

1. Why count b.id rather than COUNT(*) for authors with no books?
2. How many known page counts does Ada have?
3. What does SUM(b.pages) return for Cy in this example?
4. What is HAVING used for?

References and further reading