Sub topic 1
Building a Book-Tracking Database in PostgreSQL
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), have PostgreSQL 12 or newer running, and can connect with psql or another SQL client. You should understand tables, rows, and columns.
What the database needs to answer
Start with the questions the database must answer:
- Which books have I read, and who wrote them?
- When did I start and finish each book?
- What rating did I give each finished book?
- How many books did I finish each year?
Each question names facts to store. Books, authors, and reading entries are separate things, so each gets its own table.
Picking data types for books, authors, and dates
Choose types that match the data. Use text for names and titles, char(13) for a fixed-length ISBN-13 code, smallint for a publication year, integer for a page count, and date for reading dates. A date column rejects 2026-02-30, but a text column accepts it.
Primary keys and identity columns
A primary key is a column that uniquely identifies each row. GENERATED ALWAYS AS IDENTITY tells PostgreSQL to assign the next number automatically, so you never supply one yourself.
Constraints that keep the data honest
A constraint is a rule the database checks on every write. NOT NULL forbids missing values, UNIQUE forbids duplicates, and CHECK tests a condition on each row.
CREATE TABLE authors (
author_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE books (
book_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
isbn13 char(13) UNIQUE CHECK (isbn13 ~ '^[0-9]{13}$'),
published_year smallint CHECK (published_year BETWEEN 1400 AND 2100),
page_count integer CHECK (page_count > 0)
);Linking tables with foreign keys
A foreign key is a column whose values must match a primary key in another table. The reference below ensures that every reading points to a real book.
CREATE TABLE readings (
reading_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id bigint NOT NULL REFERENCES books (book_id),
started_on date,
finished_on date,
CHECK (finished_on IS NULL OR started_on IS NULL OR finished_on >= started_on)
);Exercise
What happens if you insert a reading with book_id 999 when no book has that ID?
Show answer
PostgreSQL rejects the insert with a foreign key violation, because book_id must match an existing books row.