Project: Library Database
In this project, you design and build a complete small database from a plain description, then use it to answer ten questions. Navika, Srihitha and Advitha keep their books on one shelf and lend them to each other, and they keep forgetting who has what. They want a database that records who owns each book, who borrowed it and when, and that refuses impossible data, such as one book lent to two people at once. You'll work the way you would on a real job: turn the description into tables, choose keys and constraints, load sample data, test that bad data is refused, and then write the queries. Everything uses skills from earlier in the course; each step points back to the lesson that taught it. Try to write each part yourself before opening the solution.
In One Minute
- Goal: a lending library for three people, built from scratch.
- Steps: requirements, design, tables with constraints, sample data, tests, ten questions.
- Tables:
members,authors,books,loans. - Key rule: a book can be out with only one person at a time, enforced by a partial unique index.
- Sample data loads with
db="library"in Try it, on top of the Fee Tracker; the file islibrary.sql. - "Today" in the questions is 2026-01-05, the same date the Fee Tracker uses.
Step 1: The Requirements
Every database starts as a description in ordinary words. Here is what the sisters asked for:
- Keep a list of members: the three sisters, their city and when they joined.
- Keep a list of books: title, author, year published, genre and which sister owns it.
- An author can write many books; store each author once, with the year they were born.
- Record every loan: which book, who borrowed it, when, when it's due, and when it came back.
- A book can be lent to one person at a time.
- A loan's due date must come after the day it was borrowed, and a return can't come before the loan.
- Answer questions like "What's overdue?" and "Which books has nobody borrowed?"
Rule 5 is the interesting one. It isn't a rule about one row, like a CHECK; it's a rule about how rows relate to each other. Keep it in mind for step 3.
Step 2: The Design
Find the nouns, and decide what is a table, what is a column, and how they connect (Data Modeling, Relationships):
| Table | One row is | Key | Connects to |
|---|---|---|---|
members | One sister | member_id | Owns books; borrows books |
authors | One author | author_id | Writes books (one author, many books) |
books | One physical book on the shelf | book_id | One author, one owner (a member) |
loans | One time a book was lent | loan_id | One book, one borrower (a member) |
loans is the table that links members and books: one member can borrow many books, and one book can be borrowed many times, so the many-to-many relationship gets its own table, with the dates that belong to each loan (Relationships). Authors are their own table so that "Frances Hodgson Burnett" is stored once, not typed again for each of her books (Normalization).
Step 3: Tables and Constraints
Now turn the design into CREATE TABLE statements, putting every rule you can into the database itself (Constraints). Try it before you look:
Show solution
CREATE TABLE members (
member_id INTEGER PRIMARY KEY,
first_name VARCHAR(40) NOT NULL,
city VARCHAR(40) NOT NULL,
joined_on DATE NOT NULL
);
CREATE TABLE authors (
author_id INTEGER PRIMARY KEY,
name VARCHAR(80) NOT NULL UNIQUE,
born_year INTEGER CHECK (born_year BETWEEN 1500 AND 2100)
);
CREATE TABLE books (
book_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR(120) NOT NULL,
author_id INTEGER NOT NULL REFERENCES authors (author_id),
published_year INTEGER NOT NULL CHECK (published_year BETWEEN 1450 AND 2100),
genre VARCHAR(20) NOT NULL CHECK (genre IN ('novel', 'fantasy', 'adventure')),
owner_id INTEGER NOT NULL REFERENCES members (member_id)
);
CREATE TABLE loans (
loan_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id INTEGER NOT NULL REFERENCES books (book_id),
member_id INTEGER NOT NULL REFERENCES members (member_id),
borrowed_on DATE NOT NULL,
due_on DATE NOT NULL,
returned_on DATE,
CHECK (due_on > borrowed_on),
CHECK (returned_on IS NULL OR returned_on >= borrowed_on)
);
-- Requirement 5: a book can be out with only one person at a time.
CREATE UNIQUE INDEX loans_one_open_per_book
ON loans (book_id) WHERE returned_on IS NULL;CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE INDEXExplanation: Each requirement maps to a constraint:
| Requirement | Enforced by |
|---|---|
| Every book has an author and an owner | NOT NULL + REFERENCES (FOREIGN KEY) |
| Authors stored once | UNIQUE (name) |
| Genre is one of three | CHECK (genre IN (...)) |
| Due after borrowed; returned not before borrowed | Two table CHECK constraints |
| One open loan per book | A partial unique index: unique book_id among rows where returned_on IS NULL |
The partial unique index is the trick for rule 5. A plain UNIQUE (book_id) would forbid lending a book twice ever. Adding WHERE returned_on IS NULL applies uniqueness only to loans that are still open: returned loans can repeat a book as often as needed, but two open loans for one book can't exist (Indexes). returned_on is NULL while the book is out; NULL here means "not yet", which is exactly what the column records (NULL Values).
Step 4: Load and Test the Data
The sample data, in library.sql, has 3 members, 7 authors, 9 books and 9 loans. In Try it, examples marked to use it load the file on top of the Fee Tracker, so every run starts with the full library. First, check the counts, then prove the rules work by trying to break them:
SELECT (SELECT count(*) FROM members) AS members,
(SELECT count(*) FROM authors) AS authors,
(SELECT count(*) FROM books) AS books,
(SELECT count(*) FROM loans) AS loans; members | authors | books | loans
---------+---------+-------+-------
3 | 7 | 9 | 9
(1 row)-- Treasure Island (book 8) is out with Srihitha. Lend it to Advitha too:
INSERT INTO loans (book_id, member_id, borrowed_on, due_on)
VALUES (8, 2, '2026-01-05', '2026-01-26');
-- A due date before the loan:
INSERT INTO loans (book_id, member_id, borrowed_on, due_on)
VALUES (4, 2, '2026-01-05', '2026-01-01');
-- A genre that isn't allowed:
INSERT INTO books (title, author_id, published_year, genre, owner_id)
VALUES ('Persuasion', 4, 1817, 'romance', 1);ERROR: duplicate key value violates unique constraint "loans_one_open_per_book"
DETAIL: Key (book_id)=(8) already exists.
ERROR: new row for relation "loans" violates check constraint "loans_check"
DETAIL: Failing row contains (11, 4, 2, 2026-01-05, 2026-01-01, null).
ERROR: new row for relation "books" violates check constraint "books_genre_check"
DETAIL: Failing row contains (10, Persuasion, 4, 1817, romance, 1).Explanation: All three bad rows are refused, each by the rule written for it: the partial unique index stops the second open loan, the CHECK stops the backwards dates, and the genre list stops 'romance'. These are the same kind of tests as in Testing SQL, and they're worth keeping: if someone later drops a constraint, they fail.
Step 5: Ten Questions
Now use the library. Each question is a real one the sisters asked; each solution says which lesson it draws on.
Q1. Which books are out right now, and with whom? (INNER JOIN, NULL Values)
SELECT b.title, m.first_name AS borrowed_by, l.borrowed_on, l.due_on
FROM loans AS l
JOIN books AS b ON b.book_id = l.book_id
JOIN members AS m ON m.member_id = l.member_id
WHERE l.returned_on IS NULL
ORDER BY l.due_on; title | borrowed_by | borrowed_on | due_on
-------------------------+-------------+-------------+------------
Pride and Prejudice | Advitha | 2025-12-01 | 2025-12-22
Treasure Island | Srihitha | 2025-12-20 | 2026-01-10
The Wind in the Willows | Navika | 2025-12-27 | 2026-01-17
(3 rows)Q2. What's overdue on 2026-01-05, and by how many days? (Date Functions)
SELECT b.title, m.first_name AS borrowed_by,
DATE '2026-01-05' - l.due_on AS days_overdue
FROM loans AS l
JOIN books AS b ON b.book_id = l.book_id
JOIN members AS m ON m.member_id = l.member_id
WHERE l.returned_on IS NULL
AND l.due_on < DATE '2026-01-05'
ORDER BY days_overdue DESC; title | borrowed_by | days_overdue
---------------------+-------------+--------------
Pride and Prejudice | Advitha | 14
(1 row)Q3. How many books does each sister own? (GROUP BY)
SELECT m.first_name, count(b.book_id) AS books_owned
FROM members AS m
LEFT JOIN books AS b ON b.owner_id = m.member_id
GROUP BY m.member_id, m.first_name
ORDER BY books_owned DESC, m.first_name; first_name | books_owned
------------+-------------
Advitha | 3
Navika | 3
Srihitha | 3
(3 rows)Q4. Which books has nobody ever borrowed? (EXISTS)
SELECT b.title, a.name AS author
FROM books AS b
JOIN authors AS a ON a.author_id = b.author_id
WHERE NOT EXISTS (SELECT 1 FROM loans AS l WHERE l.book_id = b.book_id)
ORDER BY b.title; title | author
-------------------+-------------------------
A Little Princess | Frances Hodgson Burnett
Emma | Jane Austen
(2 rows)Q5. How many times has each sister borrowed, including anyone who never has? (LEFT JOIN)
SELECT m.first_name, count(l.loan_id) AS loans
FROM members AS m
LEFT JOIN loans AS l ON l.member_id = m.member_id
GROUP BY m.member_id, m.first_name
ORDER BY loans DESC, m.first_name; first_name | loans
------------+-------
Advitha | 3
Navika | 3
Srihitha | 3
(3 rows)Q6. Rank the authors by how often their books were borrowed. (Ranking Functions)
SELECT a.name,
count(l.loan_id) AS times_borrowed,
RANK() OVER (ORDER BY count(l.loan_id) DESC) AS rank
FROM authors AS a
JOIN books AS b ON b.author_id = a.author_id
LEFT JOIN loans AS l ON l.book_id = b.book_id
GROUP BY a.author_id, a.name
ORDER BY rank, a.name; name | times_borrowed | rank
-------------------------+----------------+------
Frances Hodgson Burnett | 2 | 1
Louisa May Alcott | 2 | 1
Jane Austen | 1 | 3
Kenneth Grahame | 1 | 3
L. M. Montgomery | 1 | 3
Lewis Carroll | 1 | 3
Robert Louis Stevenson | 1 | 3
(7 rows)Q7. For returned loans, how long were books kept on average, and was each loan on time? (CASE Expressions, Aggregate Functions)
SELECT b.title, m.first_name,
l.returned_on - l.borrowed_on AS days_kept,
CASE WHEN l.returned_on <= l.due_on THEN 'on time' ELSE 'late' END AS status
FROM loans AS l
JOIN books AS b ON b.book_id = l.book_id
JOIN members AS m ON m.member_id = l.member_id
WHERE l.returned_on IS NOT NULL
ORDER BY l.borrowed_on;
SELECT round(avg(returned_on - borrowed_on), 1) AS avg_days_kept
FROM loans
WHERE returned_on IS NOT NULL; title | first_name | days_kept | status
----------------------------------+------------+-----------+---------
Little Women | Advitha | 17 | on time
Anne of Green Gables | Srihitha | 15 | on time
Little Women | Navika | 27 | late
The Secret Garden | Advitha | 19 | on time
Alice's Adventures in Wonderland | Navika | 16 | on time
The Secret Garden | Srihitha | 18 | on time
(6 rows)
avg_days_kept
---------------
18.7
(1 row)Q8. Who lends to whom? Each loan has a borrower and, through the book, an owner: two roles from the same members table (Self Join).
SELECT owner.first_name AS lender,
borrower.first_name AS borrower,
count(*) AS loans
FROM loans AS l
JOIN books AS b ON b.book_id = l.book_id
JOIN members AS owner ON owner.member_id = b.owner_id
JOIN members AS borrower ON borrower.member_id = l.member_id
GROUP BY owner.first_name, borrower.first_name
ORDER BY lender, borrower; lender | borrower | loans
----------+----------+-------
Advitha | Navika | 2
Advitha | Srihitha | 1
Navika | Advitha | 1
Navika | Srihitha | 2
Srihitha | Advitha | 2
Srihitha | Navika | 1
(6 rows)Q9. Which genre is most popular, by loans? (GROUP BY, ORDER BY)
SELECT b.genre, count(l.loan_id) AS loans, count(DISTINCT b.book_id) AS books
FROM books AS b
LEFT JOIN loans AS l ON l.book_id = b.book_id
GROUP BY b.genre
ORDER BY loans DESC, b.genre; genre | loans | books
-----------+-------+-------
novel | 6 | 6
fantasy | 2 | 2
adventure | 1 | 1
(3 rows)Q10. Return a book. Srihitha brings back Treasure Island on 2026-01-05. Record it, then show that the book can be lent again. (UPDATE, Transactions)
BEGIN;
UPDATE loans
SET returned_on = DATE '2026-01-05'
WHERE book_id = 8 AND returned_on IS NULL;
INSERT INTO loans (book_id, member_id, borrowed_on, due_on)
VALUES (8, 2, '2026-01-05', '2026-01-26');
COMMIT;
SELECT l.loan_id, m.first_name, l.borrowed_on, l.returned_on
FROM loans AS l
JOIN members AS m ON m.member_id = l.member_id
WHERE l.book_id = 8
ORDER BY l.loan_id;BEGIN
UPDATE 1
INSERT 0 1
COMMIT
loan_id | first_name | borrowed_on | returned_on
---------+------------+-------------+-------------
8 | Srihitha | 2025-12-20 | 2026-01-05
10 | Advitha | 2026-01-05 | NULL
(2 rows)Explanation: The UPDATE closes the open loan, so the partial unique index now allows a new open loan for book 8, and Advitha borrows it the same day. Doing both in one transaction means the book is never recorded as "returned but not lent" or "lent twice", even for a moment.
Common Mistakes
Making book_id unique in loans. That allows each book to be lent only once, ever. Use a partial unique index on open loans.
Storing the author's name in books. The same name gets typed differently ("L.M. Montgomery", "L. M. Montgomery"). Give authors their own table.
Using a status column instead of returned_on. A 'returned' flag and a missing date can disagree. Let returned_on IS NULL mean "out".
Counting with count(*) after a LEFT JOIN. A member with no loans would show 1. Count a column from the right-hand table, such as count(l.loan_id) (Aggregate Functions).
Hard-coding "today" as CURRENT_DATE in tests. Answers change every day. Pass the date in, as the questions here use DATE '2026-01-05'.
Interview Corner
How would you stop a library book being lent to two people at once?
A partial unique index on the loans table: CREATE UNIQUE INDEX ... ON loans (book_id) WHERE returned_on IS NULL. Returned loans can repeat; only one open loan per book can exist.
Why is loans a separate table?
Members and books have a many-to-many relationship, and each loan has its own facts (dates). A linking table holds one row per loan, with foreign keys to both.
How do you find rows with no match, such as books never borrowed?
NOT EXISTS with a correlated subquery, or a LEFT JOIN and WHERE loans.loan_id IS NULL.
Practice
Challenge: The sisters want a reading report: for each member, the number of different books they have borrowed, their most recent loan date, and how many of their loans are still open. Include every member.
Show solution
SELECT m.first_name,
count(DISTINCT l.book_id) AS different_books,
max(l.borrowed_on) AS last_borrowed,
count(l.loan_id) FILTER (WHERE l.returned_on IS NULL) AS open_loans
FROM members AS m
LEFT JOIN loans AS l ON l.member_id = m.member_id
GROUP BY m.member_id, m.first_name
ORDER BY m.first_name; first_name | different_books | last_borrowed | open_loans
------------+-----------------+---------------+------------
Advitha | 3 | 2025-12-01 | 1
Navika | 3 | 2025-12-27 | 1
Srihitha | 3 | 2025-12-20 | 1
(3 rows)count(DISTINCT l.book_id) counts each book once, even if borrowed twice; FILTER (WHERE ...) counts only open loans (Pivoting Data). The LEFT JOIN keeps every member, even one who has never borrowed.
Key Takeaways
Was this tutorial helpful?