Show contents
Chapter 6 of 7 · 30 min
Project: a library's database
By the end of this chapter, you'll be able to
- Design a schema of four linked tables, with its constraints
- Distinguish a work from its physical copies
- Compute delays with SQLite's date functions
- Combine joins, subqueries and CTEs to produce indicators
Step 1: the schema
The first idea would be a books table and a loans table. But the library owns two copies of The Little Prince: you don't borrow a work, you borrow a copy. Hence four tables:
| Table | Role | Notable constraints |
|---|---|---|
members | registered readers | |
books | the works: title, author, genre | |
copies | the physical items, with their state | state IN ('good', 'damaged', 'lost') |
loans | who borrowed which copy, and when | due date after the loan date; returned is NULL until the book comes back |
PRAGMA foreign_keys = ON;
CREATE TABLE members (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
joined TEXT NOT NULL
);
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
genre TEXT NOT NULL
);
CREATE TABLE copies (
id INTEGER PRIMARY KEY,
book_id INTEGER NOT NULL REFERENCES books(id),
state TEXT NOT NULL CHECK (state IN ('good', 'damaged', 'lost'))
);
CREATE TABLE loans (
id INTEGER PRIMARY KEY,
copy_id INTEGER NOT NULL REFERENCES copies(id),
member_id INTEGER NOT NULL REFERENCES members(id),
out_date TEXT NOT NULL,
due_date TEXT NOT NULL,
returned TEXT,
CHECK (due_date > out_date),
CHECK (returned IS NULL OR returned >= out_date)
);
Dates are text in ISO format (2026-11-12): they compare and sort correctly as text. A CHECK on several columns verifies that they are consistent: a loan due back before it went out is rejected.
INSERT INTO loans (copy_id, member_id, out_date, due_date) VALUES (5, 5, '2026-11-12', '2026-11-05');
CHECK constraint failed: due_date > out_date
On 12 November, the due date has passed and the book hasn't been returned: it's overdue.
Text description of the animation
- Adjoa is a member of the library.
- She borrows copy 4 on 1 October. The returned column is NULL: the book is still at her place.
- Copy 4 is an item of book 3.
- Three joins link Adjoa to her book's title.
- On 12 November, the due date has passed and the book hasn't been returned: it's overdue.
Step 2: the queries
The examples use a fixed date, 12 November 2026, so the results don't change from one day to the next. In an application, you would write date('now').
Overdue loans, with how late they are. julianday turns a date into a number of days, which lets you subtract two dates:
SELECT m.name, b.title, l.due_date,
CAST(julianday('2026-11-12') - julianday(l.due_date) AS INTEGER) AS days_late
FROM loans AS l
JOIN members AS m ON m.id = l.member_id
JOIN copies AS c ON c.id = l.copy_id
JOIN books AS b ON b.id = c.book_id
WHERE l.returned IS NULL AND l.due_date < '2026-11-12'
ORDER BY days_late DESC;
name | title | due_date | days_late
Adjoa | One Hundred Years of Solitude | 2026-10-22 | 21
Santiago | The Dark Child | 2026-11-10 | 2
Each book's availability. A copy is available if it isn't lost and no ongoing loan concerns it. COUNT(…) FILTER (WHERE …) counts only the rows that meet a condition:
SELECT b.title,
COUNT(c.id) FILTER (WHERE c.state <> 'lost') AS copies,
COUNT(c.id) FILTER (WHERE c.state <> 'lost' AND NOT EXISTS (
SELECT 1 FROM loans AS l WHERE l.copy_id = c.id AND l.returned IS NULL)) AS available
FROM books AS b
LEFT JOIN copies AS c ON c.book_id = b.id
GROUP BY b.id
ORDER BY b.title;
title | copies | available
A Brief History of Time | 0 | 0
Cosmos | 1 | 1
One Hundred Years of Solitude | 1 | 0
Sophie's World | 1 | 0
The Dark Child | 2 | 1
The Little Prince | 2 | 1
Books never borrowed, candidates for a display… or for weeding out:
SELECT b.title
FROM books AS b
WHERE NOT EXISTS (
SELECT 1 FROM copies AS c
JOIN loans AS l ON l.copy_id = c.id
WHERE c.book_id = b.id
)
ORDER BY b.title;
title
A Brief History of Time
Choices worth noticing:
- Separating work and copy lets you know that one Little Prince is still available while the other is on loan.
returnedset toNULLrepresents an ongoing loan. It's simpler and safer than a separateongoingcolumn, which could contradict thereturnedcolumn.- The lost book still has its row in
copies: the history is kept, and theloststate excludes it from availability. Deleting the row would break the past loans that refer to it, and the foreign key would forbid it. NOT EXISTSrather thanNOT IN, to avoid theNULLtrap seen in the subqueries chapter.
Your turn
Mini-lab: favourite genresSQLite
Result
Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.
A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: the members' record
Display, for each member (including those who have never borrowed), their number of loans and their number of late returns. A loan is late if it was returned after the due date, or if it hasn't been returned and the due date has passed on 12 November 2026. Sort by decreasing number of loans, then by name.
Hint 1
member_id in an activity CTE. In SQLite, a comparison is 1 when true and 0 otherwise: SUM(condition) therefore counts the rows that meet it.Hint 2
members to activity with a LEFT JOIN, and replace Olga's NULL values with 0 using COALESCE.Show the solution and common mistakes
WITH activity AS (
SELECT member_id, COUNT(*) AS loans,
SUM(returned IS NOT NULL AND returned > due_date) + SUM(returned IS NULL AND due_date < '2026-11-12') AS late
FROM loans
GROUP BY member_id
)
SELECT m.name, COALESCE(a.loans, 0) AS loans, COALESCE(a.late, 0) AS late
FROM members AS m
LEFT JOIN activity AS a ON a.member_id = m.id
ORDER BY loans DESC, m.name;
name | loans | late
Adjoa | 3 | 1
Ibrahim | 2 | 1
Mei | 2 | 0
Santiago | 1 | 1
Olga | 0 | 0
Computing the activity in a CTE before joining the members avoids the multiple-count trap: each member is linked to only one row of results.
Common mistakes:
- Forgetting ongoing loans when computing late returns: Adjoa and Santiago look punctual when they have an overdue book.
- Starting from
loansinstead ofmembers: Olga, who has never borrowed, disappears from the record.
Summary
- 1You borrow a copy, not a work: separating the two tables reflects reality.
- 2NULL in returned represents an ongoing loan; multi-column CHECKs keep the dates consistent.
- 3julianday turns a date into a number of days, to compute durations.
- 4COUNT(…) FILTER (WHERE …) and SUM(condition) count the rows that meet a condition.
- 5A multiple join multiplies rows: COUNT(DISTINCT …) or separate CTEs avoid double counting.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.