Sub topic 3
Summaries: books per year and average rating
This chapter assumes you have the books, authors, book_authors, and readings tables from earlier chapters, PostgreSQL 12 or newer, and working knowledge of SELECT, JOIN, and GROUP BY.
Books per year and average rating
Group finished readings by the year they ended:
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;avg() ignores NULL ratings. Unrated books still count toward books_finished.
Inserting or updating with ON CONFLICT
An INSERT with an ISBN that already exists fails, because isbn13 is UNIQUE. ON CONFLICT turns that failure into an update, so you can re-run the statement safely:
INSERT INTO books (title, isbn13, page_count)
VALUES ('Example Title', '9780000000001', 340)
ON CONFLICT (isbn13) DO UPDATE
SET title = EXCLUDED.title,
page_count = EXCLUDED.page_count;EXCLUDED refers to the row you tried to insert.
Grouping changes in a transaction
A transaction makes several statements succeed or fail as one unit:
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Another Example', '9780000000002');
INSERT INTO readings (book_id)
SELECT book_id FROM books WHERE isbn13 = '9780000000002';
COMMIT;Indexing for the queries you run
PostgreSQL does not index foreign key columns automatically. Add B-tree indexes on the columns your lookups filter by:
CREATE INDEX book_authors_author_id_idx ON book_authors (author_id);
CREATE INDEX readings_book_id_idx ON readings (book_id);Checking plans with EXPLAIN
EXPLAIN (ANALYZE) runs the query and reports the plan PostgreSQL used:
EXPLAIN (ANALYZE)
SELECT b.title
FROM books b
JOIN book_authors ba USING (book_id)
WHERE ba.author_id = 1;Look for an index scan on the new index. A sequential scan on a large table means the index was not used. Because ANALYZE executes the statement, wrap data-changing statements in a transaction you roll back.
Saving a query as a view
A view stores a query under a name:
CREATE VIEW finished_books AS
SELECT b.book_id, b.title, r.finished_on, r.rating
FROM readings r
JOIN books b USING (book_id)
WHERE r.status = 'finished';Query it like a table with SELECT * FROM finished_books;. The view stores the query, not the results, so it always reflects current data.
Searching titles with full-text search
A GIN index supports fast full-text search. Add a generated column, then index it:
ALTER TABLE books
ADD COLUMN search tsvector
GENERATED ALWAYS AS (to_tsvector('english', title)) STORED;
CREATE INDEX books_search_idx ON books USING gin (search);
SELECT title FROM books
WHERE search @@ websearch_to_tsquery('english', 'example');websearch_to_tsquery accepts plain search text, so users do not need to learn query operators.
Exercise
The books-per-year query filters on status = 'finished' before grouping. Why does the filter go in WHERE rather than HAVING?
Show answer
WHERE filters individual rows before they are grouped, so the aggregate only processes finished readings. HAVING filters groups after aggregation, which would do the same work on more rows.