Sub topic 1
What the database needs to answer
A schema is easier to get right when you start from the questions it must answer. This chapter lists those questions for the book-tracking database, derives the tables and relationships from them, and records the design decisions the rest of the tutorial builds on. No tables are created yet.
Prerequisites
This chapter assumes you have:
- Basic SQL:
SELECT,INSERT,UPDATE, andDELETE. - A running PostgreSQL 12 or newer instance, and
psqlor another SQL client connected to it. - A working idea of tables, rows, and columns.
Later chapters use generated columns (PostgreSQL 12 and newer), so check your server version now:
SHOW server_version_num;A result of 120000 or higher is enough. For example, 160002 means version 16.2.
Start from the questions
Many schemas fail because the designer started from a form or a spreadsheet and never asked what the data is for. A spreadsheet row such as "Title, Author, Date finished, Rating" works until you meet a book with two authors or a book you read twice. Starting from questions shows you which of those cases the design must handle.
This database tracks one person's reading. It should answer these questions:
- Which books do I own or plan to read, and what is each one's status?
- Who wrote a given book? Books can have several authors.
- Which books did a given author write?
- What did I finish in a given year, and how many books was that?
- What is my average rating per year?
- When did I start and finish a given book?
- Which books match a word in the title?
- Can I add the same book twice by accident?
Each question constrains the design. Question 2 means authors cannot be a text column on books. Question 8 means something must identify a book uniquely. Question 5 means a rating must be stored somewhere you can average by date.
From questions to nouns
Underline the nouns in the questions and decide which are things you store and which are properties of those things.
| Noun in the questions | Stored as | Reason |
|---|---|---|
| Book | Table `books` | Has its own identity and several attributes (title, ISBN, year, page count). |
| Author | Table `authors` | Can be linked to many books, so it cannot live inside one book row. |
| Reading (a pass through a book) | Table `readings` | Has its own dates, status, and rating, and a book can be read more than once. |
| Title, year, page count | Columns on `books` | Single values that describe one book. |
| Status | Column on `readings` | One value per reading, from a fixed set. |
| Rating | Column on `readings` | Describes how you felt about one reading. |
| Year (in "books per year") | Not stored | Derived from the finish date at query time. |
The last row matters. "Year finished" is a function of finished_on, so storing it separately would create two values that can disagree. Chapter 10 shows how to compute it with extract.
Relationships and cardinality
Cardinality means how many rows on one side can relate to rows on the other. Three relationships follow from the questions.
- Book and reading, one to many. One book can have many readings (a re-read), but each reading belongs to exactly one book.
- Book and author, many to many. A book can have several authors, and an author can have several books.
- Author and reading. There is no direct relationship. You reach an author's readings through books.
A relational database cannot store a many-to-many relationship directly. It needs a third table, called a join table, with one row per book-author pair. That table is book_authors.
Read the notation as follows. || on one end means exactly one. o{ on the other end means zero or more. So each book_authors row points to exactly one book and one author, while a book may have zero or more rows in readings.
Decisions to make before writing DDL
DDL (data definition language) is the part of SQL that creates and changes tables. These choices are cheaper to settle now than to change after data exists.
What identifies a book
Question 8 needs a rule for "the same book." Titles are not unique. Many books share a title, and the same book appears with spelling variants. The ISBN-13 is a standard identifier, so it is the natural candidate for a uniqueness rule. It has two limits:
- An ISBN identifies an edition, not a work. A paperback and a hardcover of the same novel have different ISBNs. This design treats each edition you track as one book. That keeps the schema small. It would be wrong for a library catalog that must group editions.
- Older books may have no ISBN. The
isbn13column will therefore allowNULL. PostgreSQL lets aUNIQUEcolumn hold manyNULLvalues, because it treats twoNULLs as not equal. Books without an ISBN are not protected from duplicates, so you must be careful when adding them.
Because titles and ISBNs can both be missing or repeated, each table also gets a surrogate key. This is a meaningless generated number whose only job is to identify the row. Chapter 3 covers identity columns.
Where the rating lives
A rating is an opinion about a reading, not a fact about a book. If you re-read a novel five years later, you may rate it differently. Putting rating on readings keeps both opinions and lets question 5 average by finish date. Putting it on books would force you to overwrite the old rating.
Authors are not unique by name
Two different authors can have the same name, so a UNIQUE constraint on authors.name would reject valid data. The cost is that a person you enter twice becomes two rows, and the database cannot stop it. This tutorial accepts that. A larger system would add an external identifier such as an ORCID or a library authority ID.
Author order
Book credits have an order: the first author is not interchangeable with the third. A join table has no inherent row order, so book_authors carries an author_position column. Question 2's answer should list authors in that order.
Which rules belong in the database
Some rules are simple enough to enforce in the schema, and then no application can break them:
- A rating is between 1 and 5.
- A page count is positive.
- A book cannot finish before it starts.
- Only a finished reading can have a rating.
- A reading must refer to a book that exists.
The database enforces these rules with constraints, which later chapters introduce one at a time. The alternative is to rely on application code. That fails the first time someone inserts data from a script, a migration, or a second application.
Mapping questions to the schema
This table connects each question to the chapter that implements it. Use it as a checklist at the end of the tutorial.
| Question | What the schema must provide | Where it is built |
|---|---|---|
| 1. Status of each book | Enum `status` on `readings` | Chapter 7 |
| 2. Authors of a book | `book_authors` and a join | Chapters 6 and 9 |
| 3. Books by an author | Index on `book_authors (author_id)` | Chapters 9 and 13 |
| 4. Books finished per year | Aggregate on `finished_on` | Chapter 10 |
| 5. Average rating per year | `rating` on `readings`, `avg` | Chapter 10 |
| 6. Start and finish dates | `date` columns with a `CHECK` | Chapters 2 and 7 |
| 7. Search by title word | `tsvector` column with a GIN index | Chapter 16 |
| 8. No duplicate books | `UNIQUE` on `isbn13`, upsert | Chapters 4 and 11 |
What this model leaves out
Every model omits things, and the omissions should be deliberate. This one has no publishers, series, genres, tags, or separate edition records. It has no users, so it describes one reader's log. It also records no reading progress such as a current page, and it has no notes or quotes. Each of these is an additional table or column. None of them changes the core design, so you can add them later without reshaping the four tables.
Exercise
You want to add the question "Which genres do I read most?" Suppose a book can belong to several genres. Describe the tables you would add, the relationship each has to books, and why a genre text column on books would not work.
Show answer
Add a genres table (one row per genre) and a book_genres join table with book_id and genre_id, using a composite primary key. This is a many-to-many relationship, the same shape as books and authors. A genre text column on books can hold only one value per book, so it cannot represent several genres. Putting a comma-separated list in it would make counting books per genre require string parsing and would allow misspelled or inconsistent values.
Exercise
A friend suggests storing rating on books because it is simpler. Give one question from this chapter that the design could no longer answer correctly, and explain why.
Show answer
Question 5, the average rating per year, could not be answered correctly. A rating on books has no date of its own, so you could not tell which year it belongs to. A re-read would also overwrite the earlier rating, which loses data. Storing the rating on readings ties each rating to a finish date.