Sub topic 10
Summaries: books per year and average rating
This chapter turns the readings table into yearly summaries. It assumes you can write basic SELECT and JOIN queries. It also assumes the books, authors, book_authors, and readings tables from the earlier chapters exist, with the reading_status enum and the CHECK constraint that allows a rating only on finished books.
What an aggregate does
An aggregate function collapses many rows into one value. count, sum, avg, min, and max are the common ones. Without GROUP BY, the whole result is one group and you get one row. With GROUP BY, PostgreSQL forms one group per distinct combination of the grouped values and computes each aggregate once per group.
Every column in the SELECT list must be either inside an aggregate or listed in GROUP BY. PostgreSQL has one exception: if you group by a table's primary key, you may select any other column of that table. That is why GROUP BY b.book_id, b.title works in the earlier author-listing query.
Sample data
The queries below need a few finished readings. This script is safe to run more than once for the books, and it adds new readings each time you run it. Run it once.
INSERT INTO books (title, isbn13, page_count) VALUES
('Alpha', '9780000000011', 300),
('Beta', '9780000000012', 250),
('Gamma', '9780000000013', 400),
('Delta', '9780000000014', 180)
ON CONFLICT (isbn13) DO NOTHING;
INSERT INTO readings (book_id, status, started_on, finished_on, rating)
SELECT b.book_id, 'finished'::reading_status,
v.started_on, v.finished_on, v.rating
FROM (VALUES
('9780000000011', date '2023-01-05', date '2023-02-01', 4),
('9780000000012', date '2023-03-01', date '2023-03-20', 5),
('9780000000013', date '2024-01-10', date '2024-02-15', 3),
('9780000000014', date '2024-05-02', date '2024-05-09', NULL)
) AS v(isbn13, started_on, finished_on, rating)
JOIN books b USING (isbn13);The last reading is finished but unrated. That row will show how aggregates treat NULL.
Books per year and average rating
This is the query from the chapter plan.
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;With the sample data it returns:
| year | books_finished | avg_rating |
|---|---|---|
| 2023 | 2 | 4.50 |
| 2024 | 2 | 3.00 |
Three details matter here.
extract(year FROM finished_on)returnsnumericin PostgreSQL 14 and later, anddouble precisionbefore that. The::intcast gives a plain integer in both cases.GROUP BY 1refers to the firstSELECTcolumn by position. This avoids repeating the expression. Some teams prefer repeating it for readability, and both forms behave the same.avg(smallint)returnsnumeric, soround(avg(rating), 2)is valid. If you cast the average todouble precision,round(x, 2)no longer works, becauseroundwith a digits argument requiresnumeric.
How NULL behaves in aggregates
The 2024 average is 3.00, not 1.50. Aggregates other than count(*) skip NULL inputs. Delta has no rating, so avg averaged only Gamma's 3. Compare the counting forms.
| Expression | Counts or computes over |
|---|---|
| `count(*)` | every row in the group |
| `count(rating)` | rows where `rating` is not `NULL` |
| `count(DISTINCT book_id)` | distinct non-`NULL` book ids |
| `avg(rating)` | non-`NULL` ratings only; `NULL` if there are none |
| `sum(page_count)` | non-`NULL` values; `NULL` (not 0) if all are `NULL` |
Reporting the number of ratings next to the average makes the figure honest:
SELECT extract(year FROM finished_on)::int AS year,
count(*) AS books_finished,
count(rating) AS books_rated,
round(avg(rating), 2) AS avg_rating
FROM readings
WHERE status = 'finished'
GROUP BY 1
ORDER BY 1;For 2024 this shows 2 finished, 1 rated, average 3.00. A reader can see the average rests on one rating.
Because of the table's CHECK (rating IS NULL OR status = 'finished') constraint, only finished readings can have ratings. The WHERE status = 'finished' filter is still needed for books_finished, since the table also holds reading and want_to_read rows.
Rows with a missing date
A finished reading may have finished_on IS NULL, because the schema allows it. extract(year FROM NULL) is NULL, and GROUP BY puts all such rows in one group with a NULL year. You can either surface that group, which is useful when checking data quality, or exclude it:
WHERE status = 'finished' AND finished_on IS NOT NULLThe order PostgreSQL evaluates a query
The order of evaluation explains where each filter belongs.
WHERE filters rows before grouping, so it cannot reference an aggregate. HAVING filters groups after aggregation. To keep only years in which you finished at least two books:
SELECT extract(year FROM finished_on)::int AS year,
count(*) AS books_finished
FROM readings
WHERE status = 'finished'
GROUP BY 1
HAVING count(*) >= 2
ORDER BY 1;Put conditions on plain columns in WHERE. This discards rows early, and it lets PostgreSQL use an index on those columns.
Several measures with FILTER
The FILTER clause applies a condition to a single aggregate. It lets one pass over the table produce several counts:
SELECT extract(year FROM finished_on)::int AS year,
count(*) AS finished,
count(*) FILTER (WHERE rating >= 4) AS highly_rated,
round(100.0 * count(*) FILTER (WHERE rating >= 4) / count(*), 1)
AS pct_highly_rated
FROM readings
WHERE status = 'finished'
GROUP BY 1
ORDER BY 1;The 100.0 literal is numeric, so the division is not integer division. If you wrote 100 * count(...) / count(*), both operands would be bigint and the result would truncate toward zero.
Joining before you aggregate: the fan-out trap
Pages read per year needs page_count from books. This join has one row per reading, so the sum is correct:
SELECT extract(year FROM r.finished_on)::int AS year,
sum(b.page_count) AS pages_read
FROM readings r
JOIN books b USING (book_id)
WHERE r.status = 'finished'
GROUP BY 1
ORDER BY 1;Adding book_authors to this join would be a mistake. A book with three authors would produce three joined rows, and its pages would be counted three times. This is called fan-out: joining across a one-to-many relationship multiplies the rows that an aggregate sees.
You have two ways to deal with it:
- Join only the tables you need for the measure, as above.
- When you must group by something on the "many" side, such as author, count with
count(DISTINCT ...)and understand what the numbers mean. In the next query, each author is credited with each book they wrote, so the per-author numbers do not add up to the overall total.
SELECT a.name,
count(DISTINCT r.book_id) AS books_finished,
round(avg(r.rating), 2) AS avg_rating
FROM authors a
JOIN book_authors ba USING (author_id)
JOIN readings r USING (book_id)
WHERE r.status = 'finished'
GROUP BY a.author_id, a.name
ORDER BY books_finished DESC, a.name;If you read the same book twice, count(DISTINCT r.book_id) counts it once, while avg(r.rating) averages both ratings. Decide which behavior you want before you trust the figures.
Showing years with zero books
GROUP BY returns only groups that have rows. A year in which you finished nothing is missing from the earlier results. To list every year in a range, generate the years and LEFT JOIN the readings to them:
SELECT y.year,
count(r.reading_id) AS books_finished
FROM generate_series(2022, 2025) AS y(year)
LEFT JOIN readings r
ON r.status = 'finished'
AND extract(year FROM r.finished_on) = y.year
GROUP BY y.year
ORDER BY y.year;With the sample data, 2022 and 2025 show 0. Two points make this work:
count(r.reading_id)counts only matched rows.count(*)would report 1 for each empty year, because the unmatched row from the left side still exists.- The reading conditions sit in
ON, notWHERE. AWHERE r.status = 'finished'would remove the unmatched rows and turn the left join back into an inner join.
Common mistakes
- Selecting a non-aggregated column that is not in
GROUP BY. PostgreSQL raises "column must appear in the GROUP BY clause or be used in an aggregate function". - Putting an aggregate in
WHERE. UseHAVING. - Reading
avg(rating)without checkingcount(rating). - Using
count(*)after aLEFT JOINand getting 1 for empty groups. - Joining through a join table and summing a column from the parent table.
Exercise
A reader says "my 2024 average rating is 3.00, but I finished 5 books that year." Using the readings table, write a query that shows, for each year, the number of finished books, the number of rated books, and the average rating. Explain why the average can describe fewer books than the finished count.
Show answer
SELECT extract(year FROM finishedon)::int AS year, count(*) AS booksfinished, count(rating) AS booksrated, round(avg(rating), 2) AS avgrating FROM readings WHERE status = 'finished' GROUP BY 1 ORDER BY 1; The average is computed only over non-NULL ratings, because avg() skips NULL. count(*) counts every finished row, while count(rating) counts only the rated ones, so booksrated can be smaller than booksfinished.
Exercise
You add book_authors to the pages-per-year query and the totals jump for books with several authors. What happened, and how do you fix it?
Show answer
The join to bookauthors is one-to-many from books, so a book with three authors appears in three joined rows and sum(pagecount) counts its pages three times (fan-out). Remove book_authors from the query when the measure does not depend on authors. If you need authors, aggregate per book first in a subquery or CTE, or count with DISTINCT where that is meaningful.
Exercise
Why does a year with no finished books not appear in the books-per-year result, and which join and counting expression make it appear with a count of 0?
Show answer
GROUP BY only produces groups from rows that exist, so a year with no rows has no group. Generate the years with generateseries, LEFT JOIN readings to them (with the reading conditions in ON, not WHERE), and use count(r.readingid) instead of count(*), so unmatched rows count as 0.