Sub topic 7
Reading Status, Dates, and Ratings
This chapter assumes you know basic SQL and have already created the books table with its book_id primary key. You will add a reading log that records what happened to each book and when.
Model a reading entry
A reading entry is one attempt to read a book. It has a status, optional dates, and an optional rating. A separate table keeps this changing information out of the stable book record.
PostgreSQL provides an enum, a type whose value must be one item from a fixed list. It fits a status column when the allowed values are known and unlikely to change.
CREATE TYPE reading_status AS ENUM (
'want_to_read',
'reading',
'finished',
'abandoned'
);
CREATE TABLE readings (
reading_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id bigint NOT NULL REFERENCES books (book_id),
status reading_status NOT NULL DEFAULT 'want_to_read',
started_on date,
finished_on date,
rating smallint CHECK (rating BETWEEN 1 AND 5),
CHECK (
finished_on IS NULL
OR started_on IS NULL
OR finished_on >= started_on
),
CHECK (
rating IS NULL
OR status = 'finished'
)
);The book_id foreign key connects every reading entry to an existing book. The date type stores a calendar date without a time zone. Both dates are nullable because a book may be on your list before you start it.
The first table-level CHECK constraint prevents a finish date from coming before a start date. The IS NULL tests allow incomplete entries. For example, a book can have a start date but no finish date while you are reading it.
The second constraint prevents ratings for unfinished books. A NULL rating means that no rating has been recorded. It does not mean zero.
Change status as reading progresses
A typical entry moves through the statuses in this order:
You can create an entry with the default status, then update it when reading begins.
INSERT INTO readings (book_id)
VALUES (1);
UPDATE readings
SET status = 'reading',
started_on = CURRENT_DATE
WHERE book_id = 1
AND status = 'want_to_read';
UPDATE readings
SET status = 'finished',
finished_on = CURRENT_DATE,
rating = 5
WHERE book_id = 1
AND status = 'reading';The WHERE conditions make each update narrower. They help prevent a statement from changing an entry that is already finished or abandoned.
Query the reading log
To inspect the current status and dates, join readings to books:
SELECT b.title,
r.status,
r.started_on,
r.finished_on,
r.rating
FROM readings AS r
JOIN books AS b USING (book_id)
ORDER BY r.reading_id;A book can have multiple reading entries if you want to record rereads. If your application allows only one entry per book, add UNIQUE (book_id) to readings. That is a policy choice, not a universal rule.
Exercise
What happens if you insert a reading with status 'finished', no dates, and rating 4?
Show answer
The insert succeeds. The constraints require a valid rating for a finished entry, but they do not require start or finish dates.