Sub topic 7
Reading status, dates, and ratings
This chapter builds the readings table, which records your history with each book. It assumes you have the books and authors tables from earlier chapters, and that you know CHECK constraints and foreign keys at a basic level. The aim is to make the database refuse impossible histories, such as a book finished before it was started or a rating on a book you abandoned.
One row per reading, not per book
A book and a reading are different things. A book is a published work. A reading is one pass through it by you. Keeping them in separate tables allows several things:
- You can re-read a book and keep both histories.
- You can add a book to a "want to read" list before you own a start date.
- Book facts (title, page count) are stored once, however many times you read it.
So readings has a foreign key to books but no unique constraint on book_id. Many readings may point at one book.
Status as an enum
Reading status has a small, fixed set of values. An enum type stores them compactly and rejects anything else.
CREATE TYPE reading_status AS ENUM ('want_to_read', 'reading', 'finished', 'abandoned');The enum has three properties worth knowing:
- Order matters. Enum values compare in the order you declared them.
ORDER BY statussortswant_to_readfirst andabandonedlast, not alphabetically. - Values can be added, not removed.
ALTER TYPE reading_status ADD VALUE 'paused' BEFORE 'finished';works. Dropping a value is not supported, so choose names you can live with. - A new value is unusable until its transaction commits. On PostgreSQL 12 and newer you may run
ADD VALUEinside a transaction block, but you cannot use the new value until that transaction has committed.
If your statuses change often, a lookup table with a foreign key is easier to maintain than an enum. For four stable states, the enum is simpler and keeps queries short.
The readings table
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')
);Each column makes a choice:
| Column | Type | Reason |
|---|---|---|
| `status` | `reading_status`, `NOT NULL`, default `want_to_read` | Every row has a state, and a new row starts on the wishlist. |
| `started_on`, `finished_on` | `date` | You read on days, not at instants. `timestamptz` would add time zone questions you do not need. |
| `rating` | `smallint` with `BETWEEN 1 AND 5` | A small whole number. `NULL` means "not rated", which is different from any score. |
The foreign key to books has no ON DELETE clause, so the default NO ACTION applies. You cannot delete a book that still has readings, which protects your history.
How the CHECK constraints treat NULL
A CHECK constraint rejects a row only when its expression is false. If the expression evaluates to NULL, the row passes. This explains two behaviors:
rating BETWEEN 1 AND 5passes whenratingisNULL, which is what lets unrated rows exist. You do not need a separaterating IS NULL OR ...guard on that column.- The date check would also pass when either date is
NULL, becausefinished_on >= started_onbecomesNULL. The explicitIS NULLtests in the table definition do not change the result. They make the intent visible to the next reader.
The second table-level check, rating IS NULL OR status = 'finished', says a rating is allowed only on a finished reading. Without the IS NULL branch, every unrated row would fail it.
Status lifecycle
The table does not enforce the order in which statuses occur, only which combinations of columns are valid. The usual flow looks like this:
Enforcing transitions (for example, forbidding finished to reading) would need a trigger. For a personal log, the column-level rules are enough.
Watching the constraints work
First create a book to attach readings to, then add a valid finished reading.
INSERT INTO books (title, isbn13)
VALUES ('Example Title', '9780000000001')
ON CONFLICT (isbn13) DO NOTHING;
INSERT INTO readings (book_id, status, started_on, finished_on, rating)
SELECT book_id, 'finished'::reading_status, DATE '2025-01-03', DATE '2025-01-20', 5
FROM books
WHERE isbn13 = '9780000000001';Now try three invalid rows. Each statement fails and inserts nothing.
-- Unknown status: invalid input value for enum reading_status
INSERT INTO readings (book_id, status)
SELECT book_id, 'paused' FROM books WHERE isbn13 = '9780000000001';
-- Finished before it started: violates the date check
INSERT INTO readings (book_id, status, started_on, finished_on)
SELECT book_id, 'finished', DATE '2025-02-10', DATE '2025-02-01'
FROM books WHERE isbn13 = '9780000000001';
-- Rating on a book still being read: violates the rating check
INSERT INTO readings (book_id, status, started_on, rating)
SELECT book_id, 'reading', DATE '2025-03-01', 4
FROM books WHERE isbn13 = '9780000000001';The error for the last statement reads new row for relation "readings" violates check constraint "readings_check1". PostgreSQL generates that name because the constraint was unnamed. Names like readings_check1 tell you little at 2 a.m. When you write your own constraints, give them names:
ALTER TABLE readings
ADD CONSTRAINT readings_finished_has_date
CHECK (status <> 'finished' OR finished_on IS NOT NULL) NOT VALID;NOT VALID skips checking existing rows, so the command succeeds even if old data breaks the rule. New and updated rows are still checked. Fix the old rows, then run ALTER TABLE readings VALIDATE CONSTRAINT readings_finished_has_date;. This is the safe way to add a rule to a table that already holds data.
Updating a reading
A check is evaluated against the whole new row at the end of each statement. You can therefore change status, date, and rating in a single UPDATE:
UPDATE readings
SET status = 'finished',
finished_on = CURRENT_DATE,
rating = 4
WHERE reading_id = 2
AND status = 'reading';The reverse direction needs care. If you move a rated row back to reading and leave the rating alone, the rating check fails. Clear the rating in the same statement:
UPDATE readings
SET status = 'reading', finished_on = NULL, rating = NULL
WHERE reading_id = 1;Including status = 'reading' in the WHERE clause of the first update is a cheap guard. It stops you from overwriting a row that is already finished or abandoned.
Allowing at most one active reading per book
Re-reads are legitimate, but two simultaneous reading rows for the same book are almost certainly a mistake. A partial unique index enforces this without blocking re-reads:
CREATE UNIQUE INDEX readings_one_active_idx
ON readings (book_id)
WHERE status = 'reading';The index covers only rows where status = 'reading', so uniqueness applies only to those. Any number of finished or abandoned rows can share a book_id.
Edge cases to remember
- A
finishedrow with nofinished_onis valid under the table as written. Add the named constraint above if you want to forbid it. abandonedrows may carry a start date and no rating. That is intentional, because you did start the book.- Deleting a book fails while readings reference it. Delete or reassign the readings first.
- Rating scale changes (say, 1 to 10) require dropping and recreating the check. The column type does not need to change.
Exercise
You run UPDATE readings SET status = 'abandoned' WHERE reading_id = 1; on a row that is finished with rating 5, and it fails. Why does it fail, and what single statement fixes it?
Show answer
The check rating IS NULL OR status = 'finished' is false for the new row, because it would be abandoned with a rating of 5. Clear the rating in the same statement: UPDATE readings SET status = 'abandoned', rating = NULL WHERE reading_id = 1;.
Exercise
Why does rating smallint CHECK (rating BETWEEN 1 AND 5) accept a row whose rating is NULL, and what does that let you record?
Show answer
A CHECK constraint rejects a row only when its expression is false. With a NULL rating the expression evaluates to NULL, so the row passes. This lets you record a reading that has not been rated, which is distinct from any score from 1 to 5.