Sub topic 10
Summaries: Books per Year and Average Rating
Assume you know basic SELECT, WHERE, and INSERT statements, and that the book-tracking tables already exist. This chapter uses PostgreSQL aggregation to summarize finished readings by year.
Why group reading data?
A reading log stores one row per reading. That format is useful for recording events, but reports usually need summaries:
- How many books did you finish each year?
- What was your average rating?
- Which years had no finished books?
SQL aggregate functions calculate values from multiple rows. count counts rows, and avg calculates an average. GROUP BY divides rows into groups before the aggregate functions run.
The readings table contains finished_on, status, and rating. We should use only rows whose status is finished.
Count books and average ratings by year
PostgreSQL's extract function gets part of a date. The expression extract(year FROM finished_on) returns the year as a numeric value. Casting it to int makes the result easier to use.
SELECT extract(year FROM finished_on)::int AS year,
count(*) AS books_finished,
round(avg(rating), 2) AS avg_rating
FROM readings
WHERE status = 'finished'
GROUP BY 1
ORDER BY 1;GROUP BY 1 means “group by the first expression in the SELECT list,” which is the extracted year. You can write the expression explicitly if you prefer:
GROUP BY extract(year FROM finished_on)Both forms produce one result row per year. ORDER BY 1 sorts by the first selected column, so the years appear in ascending order.
For example, the result might look like this:
| year | books_finished | avg_rating |
|---|---|---|
| 2024 | 12 | 4.08 |
| 2025 | 18 | 3.72 |
avg(rating) ignores NULL values. Therefore, the average uses only finished books that have a rating. The count(*) value still counts every finished reading, including one without a rating.
Add filters and more measures
You can filter rows before grouping. For example, this query reports only recent years and also calculates the total pages read:
SELECT extract(year FROM r.finished_on)::int AS year,
count(*) AS books_finished,
coalesce(round(avg(r.rating), 2), 0) AS avg_rating,
sum(b.page_count) AS pages_read
FROM readings AS r
JOIN books AS b USING (book_id)
WHERE r.status = 'finished'
AND r.finished_on >= DATE '2024-01-01'
GROUP BY 1
ORDER BY 1;The JOIN connects each reading to its book. sum adds the page counts. coalesce replaces a NULL average with zero when a year has no ratings. In this query, the filter happens before grouping, so older readings cannot affect the results.
How the query is processed
Exercise
Which function should you use to count every finished reading, including readings with no rating?
Show answer
Use count(*), because count(rating) ignores rows where rating is NULL.