本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
30Relational Databases and SQL
The town library once kept its loans in one wide spreadsheet: a row per loan, with the title and the author of the book, the name of the member, the street and the postcode. It was easy to read. Then a member moved, and her new address had to be typed into eight rows; one was missed, and the library had two addresses for her. A book whose loans were all deleted at the end of the year disappeared from the catalogue with them.
This chapter splits such a table into several, linked by keys, so that each fact is written once. The tables and their rules form a relational database, and a language, SQL, asks it questions and changes it. A database system then keeps the tables safe on disk, lets several programs use them at once, and refuses changes that break the rules.
You already know
A data table is a list of records with the same fields, its columns named by descriptors; the domain of a column is the set of values it may take (chapter 7). A join combines two tables on a shared field, and a missing value is an empty cell (the same chapter). The town of Brenmoor has its people, streets, books, members and loans in tables (Book 1, grade 8).
30.1 Why one wide table fails
The program rebuilds the wide table from the town’s tables, and looks at what changing it would cost.
"""The library kept as one wide table: every loan with its book, member and street."""
import town
books = {r["book_id"]: r for r in town.load("books")}
members = {r["member_id"]: r for r in town.load("members")}
people = {r["person_id"]: r for r in town.load("people")}
streets = {r["street_id"]: r for r in town.load("streets")}
flat = []
for loan in town.load("loans"): # one wide row per loan
member = members[loan["member_id"]]
person = people[member["person_id"]]
flat.append({"loan_id": loan["loan_id"], "out_date": loan["out_date"],
"title": books[loan["book_id"]]["title"],
"author": books[loan["book_id"]]["author"],
"member": person["first_name"] + " " + person["last_name"],
"street": streets[person["street_id"]]["name"],
"postcode": streets[person["street_id"]]["postcode"]})
print(len(flat), "rows of", len(flat[0]), "columns:", ", ".join(flat[0]))
name = flat[1]["member"]
rows = [r for r in flat if r["member"] == name]
print(f"update: if {name} moves, {len(rows)} rows must change")
title = flat[1]["title"]
copies = sum(r["title"] == title for r in flat)
print(f"redundancy: the author of {title!r} is written {copies} times")
print(f"deletion: removing the {copies} old loans of {title!r}",
"also removes the book and its author")
print("insertion: a new member with no loan has no row to go in;",
"a new book neither")
$ python flat_table.py
400 rows of 7 columns: loan_id, out_date, title, author, member, street, postcode
update: if Bea Stoneford moves, 8 rows must change
redundancy: the author of 'Seven Forest' is written 9 times
deletion: removing the 9 old loans of 'Seven Forest' also removes the book and its author
insertion: a new member with no loan has no row to go in; a new book neither
Definition 30.1 (Redundancy, anomalies)
A table has redundancy when the same fact is stored in several places. It then suffers anomalies: an update anomaly, when changing one fact requires changing several rows, and missing one leaves the table contradicting itself; a deletion anomaly, when deleting some rows loses a fact that had nothing to do with them; an insertion anomaly, when a fact cannot be stored until some unrelated fact exists.
flat_table.py. The shaded cells repeat a fact written in another row: the author of Seven Forest twice here (nine times in the whole table), the address of Bea Stoneford three times here (eight in all). Each repetition is a place where an update can be forgotten.The cure is to write each fact once, in a table about that kind of thing, and to let the loans point to books and members instead of copying them.
30.2 The relational model
Definition 30.2 (Database, database management system)
A database is a collection of data organised to be stored, queried and changed by programs. A database management system is the program that stores a database, answers the queries of other programs, and applies their changes.
Definition 30.3 (Relation, attribute, row)
In the relational model, a relation is a table: a set of rows, all with the same attributes, the named columns. Each attribute has a domain. A relation is a set: its rows have no order, and no two rows are equal.
Definition 30.4 (Primary key, foreign key)
A primary key of a relation is an attribute, or a group of attributes, whose values are different in every row and chosen to identify the rows. A foreign key is an attribute whose values must be values of the primary key of another relation: it points to a row of that relation.
Definition 30.5 (Relational schema, integrity constraint)
The relational schema of a database lists its relations, with for each one its attributes, their domains, its primary key and its foreign keys. An integrity constraint is a rule every state of the database must satisfy. Three kinds come with the schema: domain constraints (each value lies in its attribute’s domain), relation constraints (no two rows share a primary key) and reference constraints (each foreign key points to a row that exists).
The schema is the structure of the database; the rows present at a given moment are its content. The structure changes rarely, by design; the content changes with every loan.
streets, an author in books.In SQL, the schema is written as CREATE TABLE statements. The small library below declares its constraints; the runner turns on the checking of foreign keys, which SQLite leaves off unless asked.
-- A small library, with its keys and constraints.
CREATE TABLE street (
street_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
postcode TEXT NOT NULL CHECK (postcode LIKE 'B-___')
);
CREATE TABLE member (
member_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
street_id INTEGER NOT NULL REFERENCES street(street_id)
);
CREATE TABLE book (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER CHECK (year BETWEEN 1450 AND 2100)
);
CREATE TABLE loan (
loan_id INTEGER PRIMARY KEY,
book_id INTEGER NOT NULL REFERENCES book(book_id),
member_id INTEGER NOT NULL REFERENCES member(member_id),
out_date TEXT NOT NULL,
return_date TEXT
);
$ python sqlrun.py create.sql
sql> INSERT INTO street VALUES (1, 'Bridge Road', 'B-100');
OK (1 row changed)
sql> INSERT INTO member VALUES (1, 'Iris Hale', 1);
OK (1 row changed)
sql> INSERT INTO book VALUES (1, 'The Silent Code', 'Fatou Dalewell', 2002);
OK (1 row changed)
sql> INSERT INTO loan VALUES (1, 1, 1, '2025-03-02', NULL);
OK (1 row changed)
sql> SELECT * FROM loan;
+---------+---------+-----------+------------+-------------+
| loan_id | book_id | member_id | out_date | return_date |
+---------+---------+-----------+------------+-------------+
| 1 | 1 | 1 | 2025-03-02 | NULL |
+---------+---------+-----------+------------+-------------+
(1 row)
sql> INSERT INTO book VALUES (2, 'The Paper Forest', 'Zoe Stoneton', 3025);
Error: CHECK constraint failed: year BETWEEN 1450 AND 2100
sql> INSERT INTO book VALUES (1, 'The Paper Forest', 'Zoe Stoneton', 1996);
Error: UNIQUE constraint failed: book.book_id
sql> INSERT INTO loan VALUES (2, 1, 7, '2025-03-05', NULL);
Error: FOREIGN KEY constraint failed
sql> DELETE FROM street WHERE street_id = 1;
Error: FOREIGN KEY constraint failed
30.3 Querying
Definition 30.6 (Query, SQL)
A query is a request for data, answered with a relation. SQL (Structured Query Language) is the language in which relational databases are queried and changed. A query names the columns wanted, the relations they come from and a condition on the rows: SELECT columns FROM relation WHERE condition.
The files below are run by the book’s runner, sqlrun.py, which loads the town’s tables (-- load: town), prints each statement after sql>, and then its answer.
$ python sqlrun.py select_where.sql
sql> SELECT title, author, year FROM books WHERE year < 1955;
+--------------------+---------------+------+
| title | author | year |
+--------------------+---------------+------+
| The Silent Kingdom | Ines Yewwell | 1950 |
| The Paper Comet | Elif Pineford | 1951 |
| The Last Code | Kofi Elmwick | 1954 |
| Beyond the Code | Zoe Stoneton | 1951 |
+--------------------+---------------+------+
(4 rows)
sql> SELECT title, pages FROM books WHERE genre = 'poetry' AND pages > 300;
+--------------------+-------+
| title | pages |
+--------------------+-------+
| The Hidden Machine | 318 |
| The Clockwork Code | 380 |
| The Lost Code | 428 |
+--------------------+-------+
(3 rows)
sql> SELECT first_name, last_name FROM people WHERE last_name LIKE 'Stonew%';
+------------+------------+
| first_name | last_name |
+------------+------------+
| Leo | Stonewell |
| Kofi | Stonewick |
| Nils | Stoneworth |
| Vera | Stoneworth |
+------------+------------+
(4 rows)
WHERE: comparisons, AND, and LIKE with % for any letters.DISTINCT removes repeated rows from an answer; ORDER BY sorts it, by several columns if needed, DESC for decreasing order; LIMIT keeps the first rows.
$ python sqlrun.py distinct_order.sql
sql> SELECT DISTINCT genre FROM books ORDER BY genre;
+-----------+
| genre |
+-----------+
| adventure |
| comics |
| history |
| mystery |
| nature |
| poetry |
| science |
| sport |
+-----------+
(8 rows)
sql> SELECT title, year FROM books WHERE author = 'Zoe Stoneton' ORDER BY year DESC;
+----------------------+------+
| title | year |
+----------------------+------+
| The Last Tower | 2020 |
| A Year by the Bridge | 2015 |
| The Lost Library | 2003 |
| The Paper Forest | 1996 |
| The Paper Kingdom | 1986 |
| The Silent Machine | 1966 |
| Beyond the Code | 1951 |
+----------------------+------+
(7 rows)
sql> SELECT title, pages FROM books ORDER BY pages DESC, title LIMIT 3;
+-----------------------+-------+
| title | pages |
+-----------------------+-------+
| The Paper River | 513 |
| A Year by the Harbour | 506 |
| Notes on the Comet | 502 |
+-----------------------+-------+
(3 rows)
An aggregate function turns a whole selection into one value: COUNT, SUM, AVG, MIN, MAX. COUNT(*) counts rows; COUNT(column) counts the values that are not missing.
$ python sqlrun.py aggregates.sql
sql> SELECT COUNT(*), MIN(year), MAX(year), AVG(pages) FROM books;
+----------+-----------+-----------+------------+
| COUNT(*) | MIN(year) | MAX(year) | AVG(pages) |
+----------+-----------+-----------+------------+
| 80 | 1950 | 2023 | 277.7625 |
+----------+-----------+-----------+------------+
(1 row)
sql> SELECT COUNT(*), SUM(pages) FROM books WHERE genre = 'history';
+----------+------------+
| COUNT(*) | SUM(pages) |
+----------+------------+
| 11 | 2918 |
+----------+------------+
(1 row)
sql> SELECT COUNT(*), COUNT(return_date) FROM loans;
+----------+--------------------+
| COUNT(*) | COUNT(return_date) |
+----------+--------------------+
| 400 | 378 |
+----------+--------------------+
(1 row)
sql> SELECT COUNT(DISTINCT member_id) FROM loans WHERE out_date >= '2025-11-01';
+---------------------------+
| COUNT(DISTINCT member_id) |
+---------------------------+
| 24 |
+---------------------------+
(1 row)
A missing value is written NULL in SQL. It is not a value like the others: any comparison with it, even NULL = NULL, is neither true nor false, so a WHERE keeps no row on it. The test is IS NULL.
$ python sqlrun.py still_out.sql
sql> SELECT COUNT(*) FROM loans WHERE return_date IS NULL;
+----------+
| COUNT(*) |
+----------+
| 22 |
+----------+
(1 row)
sql> SELECT COUNT(*) FROM loans WHERE return_date = NULL;
+----------+
| COUNT(*) |
+----------+
| 0 |
+----------+
(1 row)
sql> SELECT COUNT(*) FROM loans WHERE return_date IS NOT NULL AND return_date > due_date;
+----------+
| COUNT(*) |
+----------+
| 87 |
+----------+
(1 row)
sql> SELECT MIN(out_date), MAX(out_date) FROM loans WHERE return_date IS NULL;
+---------------+---------------+
| MIN(out_date) | MAX(out_date) |
+---------------+---------------+
| 2025-01-01 | 2025-11-11 |
+---------------+---------------+
(1 row)
= NULL finds none.The titles of the books are in books, the dates in loans. A join puts together each loan and the book its book_id points to. Long names are shortened by AS.
$ python sqlrun.py joins.sql
sql> SELECT loans.loan_id, books.title, loans.out_date
...> FROM loans JOIN books ON loans.book_id = books.book_id
...> WHERE loans.loan_id <= 3;
+---------+-------------------+------------+
| loan_id | title | out_date |
+---------+-------------------+------------+
| 1 | The Hidden Valley | 2025-01-01 |
| 2 | Seven Forest | 2025-01-01 |
| 3 | Under the Bridge | 2025-01-01 |
+---------+-------------------+------------+
(3 rows)
sql> SELECT l.out_date, b.title, p.first_name, p.last_name
...> FROM loans AS l
...> JOIN books AS b ON l.book_id = b.book_id
...> JOIN members AS m ON l.member_id = m.member_id
...> JOIN people AS p ON m.person_id = p.person_id
...> WHERE l.return_date IS NULL AND l.out_date < '2025-04-01'
...> ORDER BY l.out_date;
+------------+----------------------+------------+------------+
| out_date | title | first_name | last_name |
+------------+----------------------+------------+------------+
| 2025-01-01 | Under the Bridge | Wen | Glenfield |
| 2025-01-29 | Under the Forest | Gil | Stoneton |
| 2025-02-03 | The Clockwork Engine | Ivo | Ivyfield |
| 2025-02-22 | The Last Tower | Dev | Stonefield |
| 2025-02-26 | Seven Forest | Hana | Brookwick |
| 2025-03-16 | The Paper Code | Omar | Oakmore |
+------------+----------------------+------------+------------+
(6 rows)
loans JOIN books ON loans.book_id = books.book_id: each loan is matched with the row of books whose key equals its book_id, and the two rows are written side by side as one row of the answer. Without the ON condition, every loan would be paired with every book.30.4 Changing the data
INSERT INTO adds rows, UPDATE ... SET ... WHERE changes the rows that satisfy a condition, and DELETE FROM ... WHERE removes them. The database system checks every change against the constraints and refuses the ones that would break them.
$ python sqlrun.py changes.sql
sql> INSERT INTO books (book_id, title, author, year, genre, pages)
...> VALUES (81, 'The Tides of Brenmoor', 'Nils Mossham', 2025, 'history', 240);
OK (1 row changed)
sql> UPDATE loans SET due_date = '2025-12-31' WHERE loan_id = 400;
OK (1 row changed)
sql> SELECT loan_id, book_id, out_date, due_date FROM loans WHERE loan_id = 400;
+---------+---------+------------+------------+
| loan_id | book_id | out_date | due_date |
+---------+---------+------------+------------+
| 400 | 50 | 2025-11-26 | 2025-12-31 |
+---------+---------+------------+------------+
(1 row)
sql> UPDATE books SET pages = pages + 16 WHERE genre = 'poetry';
OK (8 rows changed)
sql> DELETE FROM members WHERE member_id = 8;
Error: FOREIGN KEY constraint failed
sql> INSERT INTO loans VALUES (401, 99, 8, '2025-12-01', '2025-12-22', NULL);
Error: FOREIGN KEY constraint failed
sql> DELETE FROM books WHERE book_id = 81;
OK (1 row changed)
sql> SELECT COUNT(*) FROM books;
+----------+
| COUNT(*) |
+----------+
| 80 |
+----------+
(1 row)
An UPDATE or a DELETE without WHERE applies to every row of the relation. That is rarely what was meant, and a database system does not ask for confirmation.
30.5 What a database system guarantees
A database management system offers more than a place to keep tables. It gives persistence: a change it has accepted is on disk and survives a crash or a power cut. It allows concurrent access: many programs, on many machines, read and change the same database at once, and each change is applied entirely or not at all, never half. It answers queries efficiently: it keeps indexes, sorted structures over chosen columns, and finds rows without reading every one. It controls access: each user may read or change only what the administrator allowed.
From Python, the module sqlite3 opens a database, here in memory, and sends it SQL. The values of a query are not pasted into its text: they are passed separately, and each ? of the query takes one.
"""SQL from Python: the town's tables in sqlite3, and a query with parameters."""
import sqlite3
import town
conn = sqlite3.connect(":memory:") # a database in memory
conn.execute("PRAGMA foreign_keys = ON")
town.to_sqlite(conn) # create and fill the tables
def loans_of(conn, last_name, since):
"""Titles borrowed by members with this last name, from a date on."""
rows = conn.execute(
"""SELECT p.first_name, b.title, l.out_date
FROM loans AS l
JOIN books AS b ON l.book_id = b.book_id
JOIN members AS m ON l.member_id = m.member_id
JOIN people AS p ON m.person_id = p.person_id
WHERE p.last_name = ? AND l.out_date >= ?
ORDER BY l.out_date""",
(last_name, since)) # the values travel apart
return rows.fetchall()
for first, title, day in loans_of(conn, "Stoneford", "2025-09-01"):
print(day, first, "borrowed", title)
total = conn.execute("SELECT COUNT(*) FROM loans WHERE return_date IS NULL")
print("still out:", total.fetchone()[0])
conn.close()
$ python from_python.py
2025-09-08 Bea borrowed The Hidden Library
2025-11-02 Sami borrowed A Year by the Harbour
still out: 22
Definition 30.7 (SQL injection)
An SQL injection is an attack on a program that builds the text of a query by pasting text supplied by a user: the text closes the quotation and adds SQL of the attacker’s choice, which the database runs.
"""A query built by pasting text, attacked; then the same query with a parameter."""
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE notes (owner TEXT, note TEXT)")
conn.executemany("INSERT INTO notes VALUES (?, ?)",
[("bea", "renew The Paper Forest"), ("omar", "book the reading room"),
("wen", "my locker code is 4417")])
def notes_unsafe(owner):
query = f"SELECT note FROM notes WHERE owner = '{owner}'" # pasted text
print(" query sent:", query)
return conn.execute(query).fetchall()
def notes_safe(owner):
return conn.execute("SELECT note FROM notes WHERE owner = ?", (owner,)).fetchall()
print("unsafe, an honest name:", notes_unsafe("bea"))
attack = "bea' OR '1' = '1"
print("unsafe, the attack:", notes_unsafe(attack))
print("safe, an honest name:", notes_safe("bea"))
print("safe, the attack:", notes_safe(attack))
$ python injection.py
query sent: SELECT note FROM notes WHERE owner = 'bea'
unsafe, an honest name: [('renew The Paper Forest',)]
query sent: SELECT note FROM notes WHERE owner = 'bea' OR '1' = '1'
unsafe, the attack: [('renew The Paper Forest',), ('book the reading room',), ('my locker code is 4417',)]
safe, an honest name: [('renew The Paper Forest',)]
safe, the attack: []
Safe use
Never build the text of an SQL query by pasting text that came from outside the program: a form, a file, a web address. Pass every value as a parameter. The attack above was run on a table the program had just created in memory; trying it on someone else’s system is an offence.
History — Codd, 1970
Edgar F. Codd proposed the relational model in 1970, in an article of the Communications of the ACM titled “A relational model of data for large shared data banks”. Programs, he argued, should ask for data by its values, not by where it is stored.
30.6 Exercises
Exercise 30.1 ★
The relation pets(name, kind, age) holds the rows (Rex, dog, 4), (Tom, cat, 2), (Kiki, bird, 1), (Max, dog, 9). What does SELECT name FROM pets WHERE kind = 'dog' AND age > 5 return?
Solution
Solution of Exercise 30.1.
One row: Max. Rex is a dog but only ; the condition needs both parts true.
Exercise 30.2 ★
A relation seats(train, coach, seat, passenger) records the seats booked on a day’s trains. Which attributes form a primary key?
Solution
Solution of Exercise 30.2.
The group (train, coach, seat): a seat is identified by its train, its coach and its number, and holds one passenger. passenger is not part of it: one passenger may book two seats. Over several days, the date would join the key.
Exercise 30.3 ★
Write a query that counts the different authors of the town library. (The answer is .)
Solution
Solution of Exercise 30.3.
SELECT COUNT(DISTINCT author) FROM books; DISTINCT inside COUNT counts each author once.
Exercise 30.4 ★
Write a query that lists the titles and years of the books by Caio Lakeby, oldest first.
Solution
Solution of Exercise 30.4.
SELECT title, year FROM books WHERE author = 'Caio Lakeby' ORDER BY year; It returns four books, from A Year by the Lighthouse (1955) to The Last Forest (1995).
Exercise 30.5 ★
A student writes SELECT COUNT(*) FROM loans, books, forgetting the join condition. What does it count?
Solution
Solution of Exercise 30.5.
Every pair of a loan and a book, whether related or not: rows. A join is this product filtered by the condition that the keys agree.
Exercise 30.6 ★★
Write a query that lists, once each, the first and last names of the members who have a book still out.
Solution
Solution of Exercise 30.6.
SELECT DISTINCT p.first_name, p.last_name
FROM loans AS l JOIN members AS m ON l.member_id = m.member_id
JOIN people AS p ON m.person_id = p.person_id
WHERE l.return_date IS NULL;
members hold the loans still out. The tests pin the number.
Exercise 30.7 ★★
How many rows has loans JOIN books ON loans.book_id = books.book_id? Why exactly that many?
Solution
Solution of Exercise 30.7.
, one per loan. book_id is a foreign key, so each loan’s value is the key of some book; it is the primary key of books, so of exactly one book. Each loan therefore meets exactly one row.
Exercise 30.8 ★★
Why does WHERE return_date = NULL keep no row, even for the loans still out? Write the right condition.
Solution
Solution of Exercise 30.8.
NULL means “no value”. A comparison with it has no truth value, neither true nor false, and WHERE keeps only the rows where the condition is true. The test for a missing value is WHERE return_date IS NULL.
Exercise 30.9 ★★
Write an UPDATE that gives every loan still out more days. SQLite’s date(d, '+14 days') adds days to a date. How many rows change?
Solution
Solution of Exercise 30.9.
UPDATE loans SET due_date = date(due_date, '+14 days')
WHERE return_date IS NULL;
It changes the loans still out. Forgetting the WHERE would move all due dates.
Exercise 30.10 ★★
With foreign keys checked, which of these are refused on the town’s tables, and why: deleting street , loan , person , member ?
Solution
Solution of Exercise 30.10.
Street : refused, people live there (their street_id points to it). Loan : accepted, since no relation points to a loan. Person : refused; that person is not a member, but appears in friendships, whose two attributes are foreign keys to people. Member : refused, the member has loans. The tests run the four deletes.
Exercise 30.11 ★★
A school keeps marks(student, class, teacher, teacher_phone, subject, mark), a row per mark. Give an example of each of the three anomalies, and a schema without them.
Solution
Solution of Exercise 30.11.
Update: a teacher’s new phone number must be changed in every row of a mark that teacher gave. Deletion: deleting the only mark of a class loses who teaches it. Insertion: a new teacher’s phone cannot be recorded before the teacher gives a mark. A schema without them:
teachers(teacher_id, name, phone)
classes(class, subject, teacher_id)
marks(student, class, subject, mark)
Each fact is stored once, and the marks point to the rest by keys.
Exercise 30.12 ★★★
Write the schema of a school timetable: teachers, rooms, and lessons (day, hour, room, teacher, subject), with keys and constraints so that a room holds one lesson at a time, a teacher gives one lesson at a time, and lessons are on weekdays between and .
Solution
Solution of Exercise 30.12.
CREATE TABLE teacher (teacher_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE room (room TEXT PRIMARY KEY, seats INTEGER CHECK (seats > 0));
CREATE TABLE lesson (
day TEXT CHECK (day IN ('Mon', 'Tue', 'Wed', 'Thu', 'Fri')),
hour INTEGER CHECK (hour BETWEEN 8 AND 17),
room TEXT REFERENCES room(room),
teacher INTEGER REFERENCES teacher(teacher_id),
subject TEXT NOT NULL,
PRIMARY KEY (day, hour, room),
UNIQUE (day, hour, teacher));
The primary key allows one lesson per room and hour; UNIQUE does the same for teachers. The tests insert a lesson, then check that a second lesson in the same room at the same hour, a Sunday lesson and a lesson in an unknown room are all refused.
Exercise 30.13 ★★★
Write books_between(conn, first, last), which returns the titles of the books published between two years, with a parameterised query, and a test for it.
Solution
Solution of Exercise 30.13.
def books_between(conn, first, last):
return [row[0] for row in conn.execute(
"SELECT title FROM books WHERE year BETWEEN ? AND ?"
" ORDER BY year, title",
(first, last))]
A test: books_between(conn, 1950, 1951) on the town’s tables must give The Silent Kingdom, then Beyond the Code and The Paper Comet, the two of 1951 by title.
Exercise 30.14 ★★★
Prove that every relation has at least one key: a group of attributes whose values differ in every row.
Solution
Solution of Exercise 30.14.
A relation is a set of rows, so no two of its rows are equal: they differ in at least one attribute. So the group of all the attributes takes different values in every row, which makes it a key. Removing attributes one at a time while the group stays a key ends with a group from which nothing can be removed; that is the kind of key a designer usually picks.
Exercise 30.15 ★★★
A program runs conn.execute(f"DELETE FROM notes WHERE owner = '{name}'") with a name typed by a user. What name deletes every note? Rewrite the line safely.
Solution
Solution of Exercise 30.15.
The name x' OR '1' = '1 makes the condition owner = 'x' OR '1' = '1', true for every row: every note is deleted. The safe line passes the name as a parameter: conn.execute("DELETE FROM notes WHERE owner = ?", (name,)).
30.7 Problem: The Overdue Books of Brenmoor
Problem 30.1
Weekend problem — which books were late on the first of September?
The library wants a picture of its late books on 1 September 2025: which loans were overdue that day, who held them, where those members live, and how many days of lateness had piled up.
-- load: town
SELECT COUNT(*) FROM loans
WHERE out_date <= '2025-09-01' AND due_date < '2025-09-01'
AND (return_date IS NULL OR return_date > '2025-09-01');
SELECT l.loan_id, b.title, l.due_date, l.return_date
FROM loans AS l JOIN books AS b ON l.book_id = b.book_id
WHERE l.out_date <= '2025-09-01' AND l.due_date < '2025-09-01'
AND (l.return_date IS NULL OR l.return_date > '2025-09-01')
ORDER BY l.due_date;
SELECT DISTINCT p.first_name, p.last_name, s.name AS street
FROM loans AS l
JOIN members AS m ON l.member_id = m.member_id
JOIN people AS p ON m.person_id = p.person_id
JOIN streets AS s ON p.street_id = s.street_id
WHERE l.out_date <= '2025-09-01' AND l.due_date < '2025-09-01'
AND (l.return_date IS NULL OR l.return_date > '2025-09-01')
ORDER BY s.name, p.last_name;
SELECT SUM(julianday('2025-09-01') - julianday(due_date)) AS days_late,
MAX(julianday('2025-09-01') - julianday(due_date)) AS longest
FROM loans
WHERE out_date <= '2025-09-01' AND due_date < '2025-09-01'
AND (return_date IS NULL OR return_date > '2025-09-01');
$ python sqlrun.py overdue.sql
sql> SELECT COUNT(*) FROM loans
...> WHERE out_date <= '2025-09-01' AND due_date < '2025-09-01'
...> AND (return_date IS NULL OR return_date > '2025-09-01');
+----------+
| COUNT(*) |
+----------+
| 18 |
+----------+
(1 row)
+---------+-------------------------+------------+-------------+
| loan_id | title | due_date | return_date |
+---------+-------------------------+------------+-------------+
| 3 | Under the Bridge | 2025-01-22 | NULL |
| 27 | Under the Forest | 2025-02-19 | NULL |
| 35 | The Clockwork Engine | 2025-02-24 | NULL |
| 59 | The Last Tower | 2025-03-15 | NULL |
| 63 | Seven Forest | 2025-03-19 | NULL |
| 78 | The Paper Code | 2025-04-06 | NULL |
| 103 | The Paper Bridge | 2025-04-28 | NULL |
| 117 | The Silent Machine | 2025-05-08 | NULL |
| 129 | A Map of the Lighthouse | 2025-05-15 | NULL |
| 172 | The Lost Forest | 2025-06-20 | NULL |
| 197 | The Hidden Machine | 2025-07-09 | NULL |
| 208 | The Hidden Comet | 2025-07-18 | NULL |
| 233 | The Silent Kingdom | 2025-08-06 | NULL |
| 236 | Under the Forest | 2025-08-09 | 2025-09-04 |
| 247 | Beyond the Comet | 2025-08-19 | 2025-09-13 |
| 249 | The Lost Forest | 2025-08-20 | NULL |
| 258 | The Clockwork Machine | 2025-08-26 | 2025-09-18 |
| 260 | Seven Comet | 2025-08-28 | 2025-09-23 |
+---------+-------------------------+------------+-------------+
(18 rows)
+------------+------------+---------------+
| first_name | last_name | street |
+------------+------------+---------------+
| Bea | Stoneford | Bridge Road |
| Grace | Elmfield | Castle Row |
| Xavi | Oakham | Church Lane |
| Nils | Reedby | Church Lane |
| Ivo | Ivyfield | Church Way |
| Vera | Lakewick | Church Way |
| Hana | Brookwick | Market Road |
| Bea | Hartwick | Mill Avenue |
| Maya | Woodford | Mill Avenue |
| Dev | Stonefield | Mill Row |
| Gil | Stoneton | Orchard Lane |
| Omar | Oakmore | School Avenue |
| Xavi | Stoneby | School Avenue |
| Wen | Glenfield | Station Row |
+------------+------------+---------------+
(14 rows)
+-----------+---------+
| days_late | longest |
+-----------+---------+
| 1696.0 | 222.0 |
+-----------+---------+
(1 row)
Part I — The schema.
- Which relations does the problem need? Draw them with their keys and foreign keys.
- Why is the date of return allowed to be
NULL, but not the date of loan? - Why does
loansstoremember_idand not the member’s name? - What would go wrong in the last query if a member could appear in
loanswithout existing inmembers?
Part II — Overdue on a given day.
- Explain each of the three parts of the condition:
out_date <= D,due_date < D, and the part in brackets. - Why are the brackets necessary?
- How many loans were overdue on 1 September? How many of them were returned later, and when?
- Why does
ORDER BY l.due_dateput the longest-overdue loans first?
Part III — Members and streets.
- The third query joins four relations. Follow the path of the joins from a loan to a street.
- There are loans but members. Why fewer, and what does
DISTINCTdo here? - Which streets appear twice, and is that a redundancy in the database?
- Without
DISTINCT, how many rows would the query return? - A member moves to another street. How many rows of the database change, and how many rows of this answer?
Part IV — Days of lateness.
- What does
julianday(D) - julianday(due_date)measure? - How many days of lateness had piled up on 1 September, in all? The longest single delay?
- Which loan has the longest delay, and when was it due?
- The average delay is not in the output. Compute it from the output, then write the query.
- For the four loans returned in September, how many days late were they on the day they came back?
- The library fines cents per day late. What did the overdue loans owe on 1 September?
- State the result: the number of loans overdue on 1 September 2025, the members concerned, and the total days of lateness.
Solution
Solution of Problem 30.1.
1. loans, books, members, people and streets. Keys: loan_id, book_id, member_id, person_id, street_id. Foreign keys, as in the schema figure: the book and the member of a loan, the person of a member, the street of a person.
2. A book still out has no return date yet, so the value is missing; every loan has started, so its date is always known.
3. The name is a fact about the member, stored once in people; copying it into each loan would bring back the anomalies of the wide table.
4. The join with members would find no row for that loan, which would silently disappear from the answer. The reference constraint prevents it.
5. out_date <= D: the book had been borrowed by then. due_date < D: it was due before that day. The bracket: it had not come back by then, either not at all (NULL) or later.
6. AND binds more tightly than OR: without brackets, every loan returned after would be kept, whatever its dates.
7. . Four were returned in September: loans (on 4 September), (13 September), (18 September) and (23 September). The other are still out.
8. The earlier the due date, the longer the loan had been overdue on .
9. From a loan to its member by member_id, from the member to the person by person_id, from the person to the street by street_id.
10. Some members held several overdue loans. DISTINCT keeps one copy of each repeated row of the answer: members.
11. Church Lane, Church Way, Mill Avenue and School Avenue, each with two members. It is not redundancy: the answer repeats the name, but the database stores each person’s street once, as a key.
12. , one per loan.
13. One row of people (its street_id); the answer changes in one row, since DISTINCT merged that member’s loans.
14. The number of days from the due date to : how late the loan was on that day.
15. days in all; the longest .
16. Loan , Under the Bridge, due on 22 January 2025, and never returned.
17. days. The query has the same WHERE, after
SELECT AVG(julianday('2025-09-01') - julianday(due_date))
FROM loans
18. Loan : days; : ; : ; : .
19. , in the town’s money.
20. On 1 September 2025, loans of the town library were overdue, held by members on streets; together they were days late, the longest days.