---
title: "Relational Databases and SQL"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 30
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/30-relational-databases-and-sql
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 30 — Relational 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](#def-g12-relational-databases-sql-relation); 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](#def-g12-relational-databases-sql-database), and a language, [SQL](#def-g12-relational-databases-sql-sql), asks it questions and changes it. A [database](#def-g12-relational-databases-sql-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](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#ch-g10-data-tables)). A join combines two tables on a shared field, and a [missing value](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#def-g10-data-tables-missing) 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.

```python
"""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")
```

***Listing 30.1.** The library as one wide table: one row per loan. code/grade-12/09-relational-databases-sql/listings/flat_table.py*

```
$ 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
```

***Output 30.1.** One fact written many times, and three kinds of trouble.*

**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](#def-g12-relational-databases-sql-relation), and missing one leaves the table contradicting itself; a *deletion anomaly*, when deleting some [rows](#def-g12-relational-databases-sql-relation) loses a fact that had nothing to do with them; an *insertion anomaly*, when a fact cannot be stored until some unrelated fact exists.

![Four rows of the wide table built by 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-relational-databases-sql/fig-b826a3c182d6.svg)

*Four [rows](#def-g12-relational-databases-sql-relation) of the wide table built by `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](#def-g12-relational-databases-sql-relation) is an attribute, or a group of [attributes](#def-g12-relational-databases-sql-relation), whose values are different in every row and chosen to identify the [rows](#def-g12-relational-databases-sql-relation). A *foreign key* is an attribute whose values must be values of the primary key of another [relation](#def-g12-relational-databases-sql-relation): it points to a row of that [relation](#def-g12-relational-databases-sql-relation).

**Definition 30.5 (Relational schema, integrity constraint).**

The *relational schema* of a [database](#def-g12-relational-databases-sql-database) lists its [relations](#def-g12-relational-databases-sql-relation), with for each one its [attributes](#def-g12-relational-databases-sql-relation), their domains, its [primary key](#def-g12-relational-databases-sql-keys) and its [foreign keys](#def-g12-relational-databases-sql-keys). An *integrity constraint* is a rule every state of the [database](#def-g12-relational-databases-sql-database) must satisfy. Three kinds come with the schema: *domain* constraints (each value lies in its attribute’s domain), *[relation](#def-g12-relational-databases-sql-relation)* constraints (no two [rows](#def-g12-relational-databases-sql-relation) share a [primary key](#def-g12-relational-databases-sql-keys)) and *reference* constraints (each [foreign key](#def-g12-relational-databases-sql-keys) points to a row that exists).

The schema is the *structure* of the [database](#def-g12-relational-databases-sql-database); the [rows](#def-g12-relational-databases-sql-relation) present at a given moment are its *content*. The structure changes rarely, by design; the content changes with every loan.

![Part of the town’s schema. Primary keys are underlined; each arrow goes from a foreign key to the relation whose primary key it names: a loan points to a book and to a member, a member to a person, a person to a street. Each fact now has one place: an address in streets, an author in books.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-relational-databases-sql/fig-6cc55dede00c.svg)

*Part of the town’s schema. [Primary keys](#def-g12-relational-databases-sql-keys) are underlined; each arrow goes from a [foreign key](#def-g12-relational-databases-sql-keys) to the [relation](#def-g12-relational-databases-sql-relation) whose [primary key](#def-g12-relational-databases-sql-keys) it names: a loan points to a book and to a member, a member to a person, a person to a street. Each fact now has one place: an address in `streets`, an author in `books`.*

In [SQL](#def-g12-relational-databases-sql-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](#def-g12-relational-databases-sql-keys), which SQLite leaves off unless asked.

```sql
-- 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
);
```

***Listing 30.2.** A small library: keys, [foreign keys](#def-g12-relational-databases-sql-keys), and two domain checks. code/grade-12/09-relational-databases-sql/listings/schema.sql*

```
$ 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
```

***Output 30.2.** Four [rows](#def-g12-relational-databases-sql-relation) accepted, then one change refused for each kind of constraint: domain, [relation](#def-g12-relational-databases-sql-relation), reference twice.*

## 30.3 Querying

**Definition 30.6 (Query, SQL).**

A *query* is a request for data, answered with a [relation](#def-g12-relational-databases-sql-relation). *SQL* (Structured Query Language) is the language in which relational [databases](#def-g12-relational-databases-sql-database) are queried and changed. A query names the columns wanted, the [relations](#def-g12-relational-databases-sql-relation) they come from and a condition on the [rows](#def-g12-relational-databases-sql-relation): `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)
```

***Output 30.3.** Selecting [rows](#def-g12-relational-databases-sql-relation) with `WHERE`: comparisons, `AND`, and `LIKE` with `%` for any letters.*

`DISTINCT` removes repeated [rows](#def-g12-relational-databases-sql-relation) from an answer; `ORDER BY` sorts it, by several columns if needed, `DESC` for decreasing order; `LIMIT` keeps the first [rows](#def-g12-relational-databases-sql-relation).

```
$ 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)
```

***Output 30.4.** The eight genres, one author’s books from the newest, and the three longest books.*

An aggregate function turns a whole selection into one value: `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`. `COUNT(*)` counts [rows](#def-g12-relational-databases-sql-relation); `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)
```

***Output 30.5.** One row per [query](#def-g12-relational-databases-sql-sql): $400$ loans, of which $378$ have a return date.*

A [missing value](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#def-g10-data-tables-missing) is written `NULL` in [SQL](#def-g12-relational-databases-sql-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)
```

***Output 30.6.** $22$ loans still out; the comparison `= 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)
```

***Output 30.7.** A join of two [relations](#def-g12-relational-databases-sql-relation), then of four: the oldest loans still out, with the names of the borrowers.*

![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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-relational-databases-sql/fig-113eac3e6845.svg)

*`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](#def-g12-relational-databases-sql-relation) 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](#def-g12-relational-databases-sql-relation), `UPDATE ... SET ... WHERE` changes the [rows](#def-g12-relational-databases-sql-relation) that satisfy a condition, and `DELETE FROM ... WHERE` removes them. The [database](#def-g12-relational-databases-sql-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)
```

***Output 30.8.** A book added and removed, a due date moved, eight books changed at once; deleting a member who has loans, and a loan of a book that does not exist, are refused.*

An `UPDATE` or a `DELETE` without `WHERE` applies to every row of the [relation](#def-g12-relational-databases-sql-relation). That is rarely what was meant, and a [database](#def-g12-relational-databases-sql-database) system does not ask for confirmation.

## 30.5 What a database system guarantees

A [database management system](#def-g12-relational-databases-sql-database) 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](#def-g12-relational-databases-sql-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](#def-g12-relational-databases-sql-relation) without reading every one. It *controls access*: each user may read or change only what the administrator allowed.

![The layers. Programs never touch the files of the database: they send SQL and receive answers. The system in between applies the constraints and lets several programs work on the same data.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-relational-databases-sql/fig-414de8cb4126.svg)

*The layers. Programs never touch the files of the [database](#def-g12-relational-databases-sql-database): they send [SQL](#def-g12-relational-databases-sql-sql) and receive answers. The system in between applies the constraints and lets several programs work on the same data.*

From Python, the module `sqlite3` opens a [database](#def-g12-relational-databases-sql-database), here in memory, and sends it [SQL](#def-g12-relational-databases-sql-sql). The values of a [query](#def-g12-relational-databases-sql-sql) are not pasted into its text: they are passed separately, and each `?` of the [query](#def-g12-relational-databases-sql-sql) takes one.

```python
"""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()
```

***Listing 30.3.** The town’s tables from Python, and a [query](#def-g12-relational-databases-sql-sql) with two parameters. code/grade-12/09-relational-databases-sql/listings/from_python.py*

```
$ 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
```

***Output 30.9.** Two loans since September by members named Stoneford.*

**Definition 30.7 (SQL injection).**

An *SQL injection* is an attack on a program that builds the text of a [query](#def-g12-relational-databases-sql-sql) by pasting text supplied by a user: the text closes the quotation and adds [SQL](#def-g12-relational-databases-sql-sql) of the attacker’s choice, which the [database](#def-g12-relational-databases-sql-database) runs.

```python
"""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))
```

***Listing 30.4.** A [query](#def-g12-relational-databases-sql-sql) built by pasting, attacked on a toy table; then the same [query](#def-g12-relational-databases-sql-sql) with a parameter. code/grade-12/09-relational-databases-sql/listings/injection.py*

```
$ 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: []
```

***Output 30.10.** The attack turns the condition into one that is always true and reads every note; with a parameter, it is only a strange name.*

**Safe use.**

Never build the text of an [SQL](#def-g12-relational-databases-sql-sql) [query](#def-g12-relational-databases-sql-sql) 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](#def-g12-relational-databases-sql-relation) `pets(name, kind, age)` holds the [rows](#def-g12-relational-databases-sql-relation) (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 of Exercise 30.1.**

One row: Max. Rex is a dog but only $4$; the condition needs both parts true.

**Exercise 30.2 ★.**

A [relation](#def-g12-relational-databases-sql-relation) `seats(train, coach, seat, passenger)` records the seats booked on a day’s trains. Which [attributes](#def-g12-relational-databases-sql-relation) form a [primary key](#def-g12-relational-databases-sql-keys)?

**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](#def-g12-relational-databases-sql-sql) that counts the different authors of the town library. (The answer is $23$.)

**Solution of Exercise 30.3.**

`SELECT COUNT(DISTINCT author) FROM books;` `DISTINCT` inside `COUNT` counts each author once.

**Exercise 30.4 ★.**

Write a [query](#def-g12-relational-databases-sql-sql) that lists the titles and years of the books by Caio Lakeby, oldest first.

**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 of Exercise 30.5.**

Every pair of a loan and a book, whether related or not: $400 \times 80 = 32\,000$ [rows](#def-g12-relational-databases-sql-relation). A join is this product filtered by the condition that the keys agree.

**Exercise 30.6 ★★.**

Write a [query](#def-g12-relational-databases-sql-sql) that lists, once each, the first and last names of the members who have a book still out.

**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;`

$17$ members hold the $22$ loans still out. The tests pin the number.

**Exercise 30.7 ★★.**

How many [rows](#def-g12-relational-databases-sql-relation) has `loans JOIN books ON loans.book_id = books.book_id`? Why exactly that many?

**Solution of Exercise 30.7.**

$400$, one per loan. `book_id` is a [foreign key](#def-g12-relational-databases-sql-keys), so each loan’s value is the key of some book; it is the [primary key](#def-g12-relational-databases-sql-keys) 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 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](#def-g12-relational-databases-sql-relation) where the condition is true. The test for a [missing value](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#def-g10-data-tables-missing) is `WHERE return_date IS NULL`.

**Exercise 30.9 ★★.**

Write an `UPDATE` that gives every loan still out $14$ more days. SQLite’s `date(d, '+14 days')` adds days to a date. How many [rows](#def-g12-relational-databases-sql-relation) change?

**Solution of Exercise 30.9.**

    `UPDATE loans SET due_date = date(due_date, '+14 days')`

    `WHERE return_date IS NULL;`

It changes the $22$ loans still out. Forgetting the `WHERE` would move all $400$ due dates.

**Exercise 30.10 ★★.**

With [foreign keys](#def-g12-relational-databases-sql-keys) checked, which of these are refused on the town’s tables, and why: deleting street $1$, loan $1$, person $1$, member $1$?

**Solution of Exercise 30.10.**

Street $1$: refused, people live there (their `street_id` points to it). Loan $1$: accepted, since no [relation](#def-g12-relational-databases-sql-relation) points to a loan. Person $1$: refused; that person is not a member, but appears in `friendships`, whose two [attributes](#def-g12-relational-databases-sql-relation) are [foreign keys](#def-g12-relational-databases-sql-keys) to `people`. Member $1$: 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](#def-g12-relational-databases-sql-anomaly), and a schema without them.

**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 $8$ and $17$.

**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](#def-g12-relational-databases-sql-keys) 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](#def-g12-relational-databases-sql-sql), and a test for it.

**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](#def-g12-relational-databases-sql-relation) has at least one key: a group of [attributes](#def-g12-relational-databases-sql-relation) whose values differ in every row.

**Solution of Exercise 30.14.**

A [relation](#def-g12-relational-databases-sql-relation) is a set of [rows](#def-g12-relational-databases-sql-relation), so no two of its [rows](#def-g12-relational-databases-sql-relation) are equal: they differ in at least one attribute. So the group of all the [attributes](#def-g12-relational-databases-sql-relation) takes different values in every row, which makes it a key. Removing [attributes](#def-g12-relational-databases-sql-relation) 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 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.

```sql
-- 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');
```

***Listing 30.5.** Four queries about the loans overdue on 1 September 2025. code/grade-12/09-relational-databases-sql/listings/overdue.sql*

```
$ 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)
```

***Output 30.11.** The number of loans overdue, then the loans themselves (the statements are in the listing). Some lines are left out.*

```
+------------+------------+---------------+
| 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)
```

***Output 30.12.** The members concerned, with their streets, and the days of lateness. Some lines are left out.*

**Part I — The schema.**

1. Which [relations](#def-g12-relational-databases-sql-relation) does the problem need? Draw them with their keys and [foreign keys](#def-g12-relational-databases-sql-keys) .
2. Why is the date of return allowed to be `NULL` , but not the date of loan?
3. Why does `loans` store `member_id` and not the member’s name?
4. What would go wrong in the last [query](#def-g12-relational-databases-sql-sql) if a member could appear in `loans` without existing in `members` ?

**Part II — Overdue on a given day.**

5. Explain each of the three parts of the condition: `out_date <= D` , `due_date < D` , and the part in brackets.
6. Why are the brackets necessary?
7. How many loans were overdue on 1 September? How many of them were returned later, and when?
8. Why does `ORDER BY l.due_date` put the longest-overdue loans first?

**Part III — Members and streets.**

9. The third [query](#def-g12-relational-databases-sql-sql) joins four [relations](#def-g12-relational-databases-sql-relation) . Follow the path of the joins from a loan to a street.
10. There are $18$ loans but $14$ members. Why fewer, and what does `DISTINCT` do here?
11. Which streets appear twice, and is that a [redundancy](#def-g12-relational-databases-sql-anomaly) in the [database](#def-g12-relational-databases-sql-database) ?
12. Without `DISTINCT` , how many [rows](#def-g12-relational-databases-sql-relation) would the [query](#def-g12-relational-databases-sql-sql) return?
13. A member moves to another street. How many [rows](#def-g12-relational-databases-sql-relation) of the [database](#def-g12-relational-databases-sql-database) change, and how many [rows](#def-g12-relational-databases-sql-relation) of this answer?

**Part IV — Days of lateness.**

14. What does `julianday(D) - julianday(due_date)` measure?
15. How many days of lateness had piled up on 1 September, in all? The longest single delay?
16. Which loan has the longest delay, and when was it due?
17. The average delay is not in the output. Compute it from the output, then write the [query](#def-g12-relational-databases-sql-sql) .
18. For the four loans returned in September, how many days late were they on the day they came back?
19. The library fines $10$ cents per day late. What did the overdue loans owe on 1 September?
20. State the result: the number of loans overdue on 1 September 2025, the members concerned, and the total days of lateness.

**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](#def-g12-relational-databases-sql-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](#def-g12-relational-databases-sql-anomaly) 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 $D$ would be kept, whatever its dates.

**7.** $18$. Four were returned in September: loans $236$ (on 4 September), $247$ (13 September), $258$ (18 September) and $260$ (23 September). The other $14$ are still out.

**8.** The earlier the due date, the longer the loan had been overdue on $D$.

**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: $14$ members.

**11.** Church Lane, Church Way, Mill Avenue and School Avenue, each with two members. It is not [redundancy](#def-g12-relational-databases-sql-anomaly): the answer repeats the name, but the [database](#def-g12-relational-databases-sql-database) stores each person’s street once, as a key.

**12.** $18$, 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 $D$: how late the loan was on that day.

**15.** $1696$ days in all; the longest $222$.

**16.** Loan $3$, *Under the Bridge*, due on 22 January 2025, and never returned.

**17.** $1696 / 18 \approx 94$ days. The [query](#def-g12-relational-databases-sql-sql) has the same `WHERE`, after

    `SELECT AVG(julianday('2025-09-01') - julianday(due_date))`

    `FROM loans`

**18.** Loan $236$: $26$ days; $247$: $25$; $258$: $23$; $260$: $26$.

**19.** $1696 \times 0.10 = 169.60$, in the town’s money.

**20.** **On 1 September 2025, $18$ loans of the town library were overdue, held by $14$ members on $10$ streets; together they were $1696$ days late, the longest $222$ days.**
