---
title: "Database Design: Dependencies, Normal Forms and Transactions"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 30
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/30-database-design-dependencies-normal-forms-and-transactions
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 30 — Database Design: Dependencies, Normal Forms and Transactions

For years the library kept its loans in one spreadsheet: one line per loan, with the book’s title and author, the member’s name and street, everything a librarian might want to read on the line. Built as a table from the town’s database, it looks like this, and it shows what happens when member 55 moves house:

```sql
-- load: wide_build.sql
SELECT count(*) AS lines, count(DISTINCT member_id) AS members,
       count(DISTINCT book_id) AS books FROM wide;
SELECT street, postcode, count(*) AS lines FROM wide
WHERE member_id = 55 GROUP BY street, postcode;
UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'
WHERE member_id = 55
  AND loan_id < (SELECT max(loan_id) FROM wide WHERE member_id = 55);
SELECT street, postcode, count(*) AS lines FROM wide
WHERE member_id = 55 GROUP BY street, postcode;
```

***Listing 30.1.** The wide table, and a move recorded on every line but the last code/bachelor-2/30-database-design/listings/wide_table.sql*

```
$ python sqlrun.py wide_table.sql
sql> SELECT count(*) AS lines, count(DISTINCT member_id) AS members,
...>        count(DISTINCT book_id) AS books FROM wide;
+-------+---------+-------+
| lines | members | books |
+-------+---------+-------+
| 400   | 60      | 80    |
+-------+---------+-------+
(1 row)

sql> SELECT street, postcode, count(*) AS lines FROM wide
...> WHERE member_id = 55 GROUP BY street, postcode;
+--------------+----------+-------+
| street       | postcode | lines |
+--------------+----------+-------+
| River Avenue | B-120    | 12    |
+--------------+----------+-------+
(1 row)

sql> UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'
...> WHERE member_id = 55
...>   AND loan_id < (SELECT max(loan_id) FROM wide WHERE member_id = 55);
OK (11 rows changed)

sql> SELECT street, postcode, count(*) AS lines FROM wide
...> WHERE member_id = 55 GROUP BY street, postcode;
+--------------+----------+-------+
| street       | postcode | lines |
+--------------+----------+-------+
| Garden Lane  | B-110    | 11    |
| River Avenue | B-120    | 1     |
+--------------+----------+-------+
(2 rows)
```

***Output 30.1.** Eleven lines changed, one forgotten: the member now lives in two streets at once.*

The listing loads `wide_build.sql`, which builds the table by joining loans, books, members, people and streets. Nothing in the table says that a member has one street: the fact is written twelve times, and the twelve copies can disagree. This chapter makes the intuition precise. Dependencies say which facts determine which; normal forms say when a table stores each fact once; [decompositions](#def-b2-database-design-decomposition) split a table without losing anything. The second half turns to the other way a database goes wrong, two programs changing it at the same moment, and ends with the [index](#def-b2-database-design-index) that makes a search fast.

**You already know.**

The Year 1 volume: relations, attributes, keys, candidate and primary keys, foreign keys, relational algebra and its natural join, SQL queries, entity–relationship modelling. The grade 12 volume: the anomalies of a badly designed table, seen on examples.

## 30.1 Functional dependencies

**Definition 30.1 (Functional dependency, trivial dependency).**

Let $R$ be a set of attributes and $X, Y \subseteq R$. A table over $R$ *satisfies* the *functional dependency* $X \to Y$ if any two rows that agree on every attribute of $X$ also agree on every attribute of $Y$. The dependency is *trivial* if $Y \subseteq X$; it is then satisfied by every table.

A dependency is a rule about the world the table describes, not an observation about today’s rows. The library’s rules are that a loan determines its book, its member and its dates; a book determines its title, author, genre and pages; a member determines the name and the street; a street determines its postcode. The 400 lines satisfy other dependencies by accident: no two books have the same title yet, so *title* $\to$ *book* holds in the data, but nothing forbids two books called the same ([Exercise 30.9](#exo-b2-database-design-9)).

![The library’s rules over the wide table’s fourteen attributes. Blue: a loan determines its dates, its book and its member. Red: a book determines its title, author, genre and pages. Orange: a member determines the name and the street. Green: a street determines its postcode. Only the blue arrows start from a key.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-database-design/fig-6d6163b8acce.svg)

*The library’s rules over the wide table’s fourteen attributes. Blue: a loan determines its dates, its book and its member. Red: a book determines its title, author, genre and pages. Orange: a member determines the name and the street. Green: a street determines its postcode. Only the blue arrows start from a key.*

From some dependencies others follow: if a member determines the street and a street the postcode, a member determines the postcode.

**Definition 30.2 (Implication, Armstrong’s axioms).**

A set $F$ of dependencies over $R$ *implies* $X \to Y$, written $F \models X \to
Y$, if every table over $R$ that satisfies all of $F$ satisfies $X \to Y$. *Armstrong’s axioms* are three rules to derive dependencies, written $F \vdash X \to Y$: *reflexivity*, $X \to Y$ whenever $Y \subseteq X$; *augmentation*, from $X \to Y$ derive $XZ \to YZ$; *transitivity*, from $X \to Y$ and $Y \to Z$ derive $X \to Z$. (We write $XZ$ for $X \cup Z$.)

The *union* rule, from $X \to Y$ and $X \to Z$ derive $X \to YZ$, and the *decomposition* rule, from $X \to YZ$ derive $X \to Y$, follow from the three ([Exercise 30.8](#exo-b2-database-design-8)).

**Definition 30.3 (Attribute closure).**

The *attribute closure* of $X$ under $F$ is $X^+ = \{A \in R : F \models X \to A\}$, the set of attributes that $X$ determines.

**Theorem 30.4 (Armstrong’s axioms are sound and complete).**

For every $F$, $X$ and $Y$: $F \vdash X \to Y$ if and only if $F \models X \to Y$.

**Proof.** *Soundness*: each rule turns satisfied dependencies into a satisfied one. Reflexivity: two rows that agree on $X$ agree on its subset $Y$. Augmentation: two rows that agree on $XZ$ agree on $X$, hence on $Y$, and on $Z$. Transitivity: two rows that agree on $X$ agree on $Y$, hence on $Z$. By induction on the length of a derivation, every derived dependency holds in every table satisfying $F$.

*Completeness*: suppose $F \models X \to Y$, and let $D = \{A : F \vdash X \to A\}$; by reflexivity $X \subseteq D$. Build a table of two rows over $R$: both rows are $0$ on $D$; outside $D$, the first is $0$ and the second $1$. It satisfies every $V \to W$ of $F$: if the rows agree on $V$, then $V \subseteq D$, so $F \vdash X \to V$ by the union rule, then $F \vdash X \to W$ by transitivity, so $W \subseteq D$ by decomposition and the rows agree on $W$. The table therefore satisfies $X \to Y$; its rows agree on $X \subseteq D$, so they agree on $Y$, and $Y \subseteq D$. By the union rule, $F \vdash X \to Y$. ∎

So the closure can be computed by derivation instead of by imagining every table, and there is a simple algorithm:

```python
def closure(xs, deps):
    """X+: every attribute that X determines under deps."""
    result, changed = set(xs), True
    while changed:
        changed = False
        for left, right in deps:
            if left <= result and not right <= result:
                result |= right  # X determines left, hence right
                changed = True
    return frozenset(result)
```

***Listing 30.2.** The closure of a set of attributes: apply every dependency whose left side is already in, until nothing changes code/bachelor-2/30-database-design/listings/fd.py*

**Proposition 30.5 (The closure algorithm).**

The function `closure` returns $X^+$, after at most $|F| + 1$ passes over $F$, so in time $O(|F|^2 \cdot |R|)$.

**Proof.** [Exercise 30.11](#exo-b2-database-design-11): every attribute added is derivable, and when the loop stops the set is closed under $F$, which forces it to contain $X^+$. Each pass but the last adds the right side of at least one dependency not used before. ∎

**Corollary 30.6 (A test for keys).**

$X$ is a superkey of $R$ under $F$ exactly when $X^+ = R$; it is a candidate key when moreover $(X \setminus \{A\})^+ \neq R$ for every $A \in X$.

**Proof.** $X$ is a superkey when it determines every attribute, that is $F \models X \to R$, that is $R \subseteq X^+$. A candidate key is a superkey with no proper subset that is one; since a superset of a superkey is a superkey, it suffices to remove one attribute at a time. ∎

**Definition 30.7 (Minimal cover).**

A *minimal cover* of $F$ is a set $G$ of dependencies equivalent to $F$ (each [implies](#def-b2-database-design-armstrong) every dependency of the other) in which every right side is a single attribute, no attribute can be removed from a left side, and no dependency can be removed, without losing the equivalence.

```python
def keys(attrs, deps):
    """The candidate keys: the minimal sets whose closure is every attribute."""
    attrs = frozenset(attrs)
    found = []
    for size in range(len(attrs) + 1):
        for xs in combinations(sorted(attrs), size):
            xs = frozenset(xs)
            if not any(k <= xs for k in found) and closure(xs, deps) >= attrs:
                found.append(xs)
    return found


def minimal_cover(deps):
    """An equivalent set with one attribute on each right side, no extraneous
    attribute on a left side, and no redundant dependency."""
    out = [(left, frozenset([a])) for left, right in deps for a in sorted(right)]
    for i, (left, right) in enumerate(out):
        for a in sorted(left):
            if len(left) > 1 and right <= closure(left - {a}, out):
                left = left - {a}  # a is extraneous on the left
        out[i] = (left, right)
    out = list(dict.fromkeys(out))
    for d in list(out):
        rest = [e for e in out if e != d]
        if implies(rest, *d):
            out = rest
    return out
```

***Listing 30.3.** Candidate keys by increasing size, and a [minimal cover](#def-b2-database-design-cover) code/bachelor-2/30-database-design/listings/fd.py*

```python
WIDE = ("loan out due ret book title author genre pages member first last street"
        " postcode").split()
RULES = fds("loan -> book member out due ret; book -> title author genre pages;"
            " member -> first last street; street -> postcode")
```

***Listing 30.4.** The wide table’s attributes and the library’s rules code/bachelor-2/30-database-design/listings/fd_demo.py*

```
$ python fd_demo.py
closure of {member}: {member, first, last, street, postcode}
closure of {book}: {book, title, author, genre, pages}
candidate keys: ['{loan}']
minimal cover: 13 dependencies, one attribute on each right side
in 3NF: False
  BCNF table {book, title, author, genre, pages} key {book}
  BCNF table {street, postcode} key {street}
  BCNF table {member, first, last, street} key {member}
  BCNF table {loan, out, due, ret, book, member} key {loan}
lossless: True | preserves the dependencies: True
```

***Output 30.2.** Closures, the key, the cover, and the BCNF tables of [Section 30.3](#sec-30-3).*

The key search tries the subsets in increasing size, skipping supersets of keys already found: exponential in general, fast here, where one attribute suffices. The wide table’s only candidate key is the loan.

## 30.2 Normal forms

**Definition 30.8 (Update, insertion and deletion anomaly).**

A table has an *update anomaly* when one fact is stored on several rows, so that changing it means changing them all; an *insertion anomaly* when a fact cannot be recorded without an unrelated one, as a member without a loan; a *deletion anomaly* when removing a row removes an unrelated fact with it, as the last loan of a book removes the book.

All three come from a dependency whose left side is not a key: *book* $\to$ *title* makes the title a fact about the book, stored once per loan of that book.

**Definition 30.9 (Third normal form, Boyce–Codd normal form).**

Let $F$ hold on $R$. $R$ is in *Boyce–Codd normal form* (BCNF) if for every [non-trivial](#def-b2-database-design-fd) $X \to A$ implied by $F$ with $X \cup \{A\} \subseteq R$, $X$ is a superkey of $R$. It is in *third normal form* (3NF) if for every such dependency, $X$ is a superkey or $A$ belongs to some candidate key of $R$.

BCNF says that every fact the table records is a fact about a key; 3NF tolerates one exception, attributes that are part of a key. The wide table is in neither: *book*, *member* and *street* determine other attributes and are not keys.

## 30.3 Decomposition

**Definition 30.10 (Decomposition, lossless join, dependency preservation).**

A *decomposition* of $R$ is a list of attribute sets $R_1, \dots, R_m$ whose union is $R$; a table $T$ over $R$ is stored as its projections $\pi_{R_i}(T)$. The decomposition is *lossless* for $F$ if $T = \pi_{R_1}(T) \bowtie \dots \bowtie \pi_{R_m}(T)$ for every $T$ satisfying $F$; it *preserves the dependencies* if the dependencies of $F$ that hold inside the parts imply all of $F$.

The join of the projections always contains $T$; a lossy [decomposition](#def-b2-database-design-decomposition) adds rows that were never there. Preservation matters for checking: a dependency that holds inside a part is enforced by that part’s key, while one that spans two parts can be checked only by a join.

**Theorem 30.11 (Heath’s theorem).**

Let $R = X \cup Y \cup Z$ with $X, Y, Z$ disjoint. If a table over $R$ satisfies $X \to Y$, it is the join of its projections on $XY$ and $XZ$.

**Proof.** [Exercise 30.10](#exo-b2-database-design-10). ∎

```python
def bcnf_violation(r, deps):
    """A dependency X -> Y that holds in r with X not a superkey of r, or None."""
    r = frozenset(r)
    for xs in subsets(r):
        c = closure(xs, deps) & r
        if c != xs and c != r:
            return xs, c - xs
    return None


def bcnf(r, deps):
    """Split r on a violating X -> Y into XY and r - Y, until no part has one."""
    v = bcnf_violation(r, deps)
    if v is None:
        return [frozenset(r)]
    xs, ys = v
    return bcnf(xs | ys, deps) + bcnf(frozenset(r) - ys, deps)
```

***Listing 30.5.** A BCNF violation, and the BCNF [decomposition](#def-b2-database-design-decomposition) by repeated splits code/bachelor-2/30-database-design/listings/fd.py*

**Theorem 30.12 (BCNF decomposition).**

The function `bcnf` stops, returns parts that are all in BCNF, and the [decomposition](#def-b2-database-design-decomposition) is [lossless](#def-b2-database-design-decomposition).

**Proof.** A split of $R$ on a violation $X \to Y$, with $Y = X^+ \cap R \setminus X$ non-empty and $X^+ \cap R \neq R$, produces $XY$ and $R \setminus Y$, both strictly smaller than $R$: the recursion stops. A part is returned only when it has no violation, so it is in BCNF. Each split is [lossless](#def-b2-database-design-decomposition) by Heath’s theorem with $Z = R \setminus XY$, since $X \to Y$ holds. By induction on the recursion, if $R \setminus Y$ is replaced by a [lossless](#def-b2-database-design-decomposition) [decomposition](#def-b2-database-design-decomposition) of it, the whole stays [lossless](#def-b2-database-design-decomposition), because a table satisfying $F$ projects onto $R \setminus Y$ as a table that satisfies the dependencies of $F$ that hold there, and the natural join is associative. ∎

![The BCNF decomposition of . Each split takes a violating dependency X Y and makes one table of X with everything it determines, and another of the rest with X kept as the link. The four leaves are the BCNF tables.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-database-design/fig-dc9b21c576cc.svg)

*The BCNF [decomposition](#def-b2-database-design-decomposition) of [Output 30.2](#out-b2-database-design-fd-demo). Each split takes a violating dependency $X \to Y$ and makes one table of $X$ with everything it determines, and another of the rest with $X$ kept as the link. The four leaves are the BCNF tables.*

The SQL counterpart builds the four tables from the wide one and joins them back:

```sql
-- load: wide_build.sql
CREATE TABLE d_loans AS
  SELECT DISTINCT loan_id, out_date, due_date, return_date, book_id, member_id FROM wide;
CREATE TABLE d_books AS SELECT DISTINCT book_id, title, author, genre, pages FROM wide;
CREATE TABLE d_members AS
  SELECT DISTINCT member_id, first_name, last_name, street FROM wide;
CREATE TABLE d_streets AS SELECT DISTINCT street, postcode FROM wide;
SELECT (SELECT count(*) FROM d_loans) AS loans,
       (SELECT count(*) FROM d_books) AS books,
       (SELECT count(*) FROM d_members) AS members,
       (SELECT count(*) FROM d_streets) AS streets,
       (SELECT count(DISTINCT member_id) FROM d_members) AS member_ids,
       (SELECT count(DISTINCT street) FROM d_streets) AS street_names;
CREATE VIEW joined AS
  SELECT l.loan_id, l.out_date, l.due_date, l.return_date,
         b.book_id, b.title, b.author, b.genre, b.pages,
         m.member_id, m.first_name, m.last_name, s.street, s.postcode
  FROM d_loans AS l NATURAL JOIN d_books AS b
  NATURAL JOIN d_members AS m NATURAL JOIN d_streets AS s;
SELECT (SELECT count(*) FROM (SELECT * FROM wide EXCEPT SELECT * FROM joined))
         AS lost,
       (SELECT count(*) FROM (SELECT * FROM joined EXCEPT SELECT * FROM wide))
         AS invented;
```

***Listing 30.6.** The four BCNF tables, and the join that should give back the wide table code/bachelor-2/30-database-design/listings/decomposed.sql*

```
$ python sqlrun.py decomposed.sql
sql> CREATE TABLE d_loans AS
...>   SELECT DISTINCT loan_id, out_date, due_date, return_date, book_id, member_id FROM wide;
OK

sql> CREATE TABLE d_books AS SELECT DISTINCT book_id, title, author, genre, pages FROM wide;
OK

sql> CREATE TABLE d_members AS
...>   SELECT DISTINCT member_id, first_name, last_name, street FROM wide;
OK

sql> CREATE TABLE d_streets AS SELECT DISTINCT street, postcode FROM wide;
OK

sql> SELECT (SELECT count(*) FROM d_loans) AS loans,
...>        (SELECT count(*) FROM d_books) AS books,
...>        (SELECT count(*) FROM d_members) AS members,
...>        (SELECT count(*) FROM d_streets) AS streets,
...>        (SELECT count(DISTINCT member_id) FROM d_members) AS member_ids,
...>        (SELECT count(DISTINCT street) FROM d_streets) AS street_names;
+-------+-------+---------+---------+------------+--------------+
| loans | books | members | streets | member_ids | street_names |
+-------+-------+---------+---------+------------+--------------+
| 400   | 80    | 60      | 23      | 60         | 23           |
+-------+-------+---------+---------+------------+--------------+
(1 row)

sql> CREATE VIEW joined AS
...>   SELECT l.loan_id, l.out_date, l.due_date, l.return_date,
...>          b.book_id, b.title, b.author, b.genre, b.pages,
...>          m.member_id, m.first_name, m.last_name, s.street, s.postcode
...>   FROM d_loans AS l NATURAL JOIN d_books AS b
...>   NATURAL JOIN d_members AS m NATURAL JOIN d_streets AS s;
OK

sql> SELECT (SELECT count(*) FROM (SELECT * FROM wide EXCEPT SELECT * FROM joined))
...>          AS lost,
...>        (SELECT count(*) FROM (SELECT * FROM joined EXCEPT SELECT * FROM wide))
...>          AS invented;
+------+----------+
| lost | invented |
+------+----------+
| 0    | 0        |
+------+----------+
(1 row)
```

***Output 30.3.** No row lost, none invented, and each key unique in the data.*

Only 23 streets appear because no member lives on the 24th. BCNF cannot always keep the dependencies inside the parts.

**Example 30.13 (No BCNF decomposition preserves the dependencies).**

An address table over *street*, *town* and *postcode* with the rules *street town* $\to$ *postcode* and *postcode* $\to$ *town*. The keys are {street, town} and {street, postcode}, so *postcode* $\to$ *town* violates BCNF; every attribute belongs to a key, so the table is in 3NF. Any BCNF [decomposition](#def-b2-database-design-decomposition) must separate the three attributes, and *street town* $\to$ *postcode* then lies in no part.

```
$ python no_preserving.py
keys: {postcode, street} {street, town} | in 3NF: True
BCNF         : {postcode, town} {postcode, street} | lossless True, preserving False
3NF synthesis: {postcode, street, town} | lossless True, preserving True
```

***Output 30.4.** The address table: BCNF loses a dependency, 3NF keeps the table whole.*

```python
def synthesis_3nf(r, deps):
    """One table per left side of a minimal cover, plus a key if none holds one."""
    groups = {}
    for left, right in minimal_cover(deps):
        groups[left] = groups.get(left, left) | right
    parts = list(dict.fromkeys(groups.values()))
    parts = [p for p in parts if not any(p < q for q in parts)]
    if not any(closure(p, deps) >= frozenset(r) for p in parts):
        parts.append(keys(r, deps)[0])
    return parts
```

***Listing 30.7.** 3NF synthesis from a [minimal cover](#def-b2-database-design-cover) code/bachelor-2/30-database-design/listings/fd.py*

**Theorem 30.14 (3NF synthesis).**

The [decomposition](#def-b2-database-design-decomposition) of [Listing 30.7](#lst-b2-database-design-synthesis), one table for each left side of a [minimal cover](#def-b2-database-design-cover) with the attributes it determines in the cover, plus a candidate key if no table contains one, [preserves the dependencies](#def-b2-database-design-decomposition), is [lossless](#def-b2-database-design-decomposition), and has every table in 3NF.

**Proof.** Every dependency of the [minimal cover](#def-b2-database-design-cover) lies inside the table of its left side, and the cover is equivalent to $F$: the dependencies are preserved. For losslessness, let $K$ be a table containing a key and run the chase of [Exercise 30.5](#exo-b2-database-design-5): the row of $K$ starts with the symbol $a$ on $K$, and the cover’s dependencies, applied in the order in which the closure algorithm adds attributes to $K^+ = R$, give it $a$ on each attribute in turn, since each such dependency lies inside a table whose own row has $a$ everywhere. A row with $a$ everywhere means the join is [lossless](#def-b2-database-design-decomposition). That each table is in 3NF uses the minimality of the cover; we admit it. ∎

So 3NF can always be reached without losing a dependency, and BCNF without losing information but perhaps a dependency. The synthesis often gives BCNF tables anyway, as for the library: its four 3NF tables are the four BCNF tables.

One more kind of redundancy escapes functional dependencies. If a book has several authors and several subject keywords, unrelated to each other, a table (*book*, *author*, *keyword*) must hold every pair: two authors and three keywords make six rows, with each author written three times.

**Definition 30.15 (Multivalued dependency, fourth normal form).**

A table over $R$ satisfies the *multivalued dependency* $X \twoheadrightarrow Y$ if, with $Z = R \setminus XY$, whenever two rows agree on $X$, the row that takes $X$ and $Y$ from the first and $Z$ from the second is also in the table. $R$ is in *fourth normal form* if for every [non-trivial](#def-b2-database-design-fd) $X \twoheadrightarrow Y$ that holds, $X$ is a superkey.

Here *book* $\twoheadrightarrow$ *author*: every author of a book appears with every keyword of it. The table is in BCNF, its only key being all three attributes, but not in 4NF, and splitting it into (*book*, *author*) and (*book*, *keyword*) is [lossless](#def-b2-database-design-decomposition) by the same argument as Heath’s theorem. A [functional dependency](#def-b2-database-design-fd) is a special multivalued one; the chase of [Exercise 30.5](#exo-b2-database-design-5) extends to both, and we leave it at that.

**History.**

Edgar Codd published the relational model in 1970 and defined [third normal form](#def-b2-database-design-normal-forms) in 1971. Raymond Boyce and Codd formally developed the normal form that bears their names in 1974; Ian Heath had described it in 1971.

## 30.4 Transactions

Design removes the anomalies of one table. The other dangers come from time: a change made of several statements that stops in the middle, or two programs that change the same row at once.

**Definition 30.16 (Transaction, commit, rollback).**

A *transaction* is a sequence of reads and writes that the database treats as one unit. It ends with a *commit*, which makes all its writes permanent and visible to others, or a *rollback*, which cancels all of them.

**Definition 30.17 (Atomicity, consistency, isolation, durability).**

A database system guarantees *atomicity* if a [transaction](#def-b2-database-design-transaction)’s writes take effect all or none; *consistency* if a [transaction](#def-b2-database-design-transaction) that starts from a state satisfying the declared constraints and [commits](#def-b2-database-design-transaction) leaves one; *isolation* if concurrent [transactions](#def-b2-database-design-transaction) do not see each other’s partial work, to a degree fixed by the [isolation level](#def-b2-database-design-isolation-level); *durability* if a committed [transaction](#def-b2-database-design-transaction) survives a crash.

In SQLite, `BEGIN` starts a [transaction](#def-b2-database-design-transaction); without it, each statement is a [transaction](#def-b2-database-design-transaction) of its own. The book’s SQL runner [commits](#def-b2-database-design-transaction) after every statement, as an interactive tool does, so the [transactions](#def-b2-database-design-transaction) of this section are written in Python, which controls them explicitly:

```python
def record_return(day, amount):
    conn.execute("BEGIN")
    try:
        conn.execute("UPDATE loans SET return_date = ? WHERE loan_id = ?", (day, loan))
        conn.execute("INSERT INTO fines VALUES (?, ?)", (loan, amount))
        conn.execute("COMMIT")
        print(f"returned on {day}, fine {amount}: committed")
    except sqlite3.Error as e:
        conn.execute("ROLLBACK")
        print(f"returned on {day}, fine {amount}: {e}; rolled back")
```

***Listing 30.8.** A late return recorded in two tables as one [transaction](#def-b2-database-design-transaction) code/bachelor-2/30-database-design/listings/rollback.py*

```
$ python rollback.py
   loan 3 (due 2025-01-22): return_date None, fines 0
returned on 2026-02-03, fine 0: CHECK constraint failed: amount > 0; rolled back
   loan 3 (due 2025-01-22): return_date None, fines 0
returned on 2026-02-03, fine 2: committed
   loan 3 (due 2025-01-22): return_date 2026-02-03, fines 1
```

***Output 30.5.** The fine of 0 breaks a constraint after the loan was already updated: the [rollback](#def-b2-database-design-transaction) undoes the update too.*

Without the [transaction](#def-b2-database-design-transaction), the first attempt would have left a loan returned with no fine recorded: the two tables would disagree, the very thing the design was meant to prevent.

**History.**

Theo Härder and Andreas Reuter coined the acronym ACID for these four properties in 1983, in a survey of [transaction](#def-b2-database-design-transaction) recovery.

## 30.5 Isolation

**Definition 30.18 (Schedule).**

A *schedule* of a set of [transactions](#def-b2-database-design-transaction) is the order in time of all their reads, writes, [commits](#def-b2-database-design-transaction) and [rollbacks](#def-b2-database-design-transaction), each [transaction](#def-b2-database-design-transaction)’s own operations in their order. It is *serial* if the [transactions](#def-b2-database-design-transaction) do not overlap.

**Definition 30.19 (The anomalies of isolation).**

In a [schedule](#def-b2-database-design-schedule) of two [transactions](#def-b2-database-design-transaction) $T_1$ and $T_2$: a *dirty read* is $T_2$ reading a value written by $T_1$ that $T_1$ has not committed; a *non-repeatable read* is $T_1$ reading the same row twice and getting two values, because $T_2$ changed it and committed in between; a *phantom read* is $T_1$ running the same query with a condition twice and getting different sets of rows, because $T_2$ inserted or deleted a matching row; a *lost update* is $T_1$ and $T_2$ both reading a value and both writing a new value computed from it, so that one write erases the other; a *write skew* is $T_1$ and $T_2$ each reading the same rows, checking a rule over them, and each writing a different row, so that both checks pass and the result breaks the rule.

**Definition 30.20 (Isolation level).**

An *isolation level* is a promise about which of these anomalies a database system lets [transactions](#def-b2-database-design-transaction) see. The SQL standard names four: *read uncommitted*, *read committed*, *repeatable read* and *serializable*, the last promising that every [schedule](#def-b2-database-design-schedule) has the same effect as some serial one.

| [isolation level](#def-b2-database-design-isolation-level) | [dirty read](#def-b2-database-design-anomalies) | [non-repeatable read](#def-b2-database-design-anomalies) | [phantom read](#def-b2-database-design-anomalies) |
| --- | --- | --- | --- |
| read uncommitted | possible | possible | possible |
| read committed | no | possible | possible |
| repeatable read | no | no | possible |
| serializable | no | no | no |

*The standard [isolation levels](#def-b2-database-design-isolation-level), and the anomalies each allows. A system may give more than a level promises: PostgreSQL’s repeatable read shows no phantoms, and its read uncommitted behaves as read committed.*

SQLite takes the simplest road: its [transactions](#def-b2-database-design-transaction) are serializable, and it allows a single writer at a time. The one way to see an uncommitted change is to share a cache between two connections and turn on `read_uncommitted`.

**In practice.**

SQLite’s documentation states that its [transactions](#def-b2-database-design-transaction) are serializable except for connections that share a cache with `read_uncommitted` on, and that one connection writes at a time: the others wait their turn.

```python
URI = "file:shelf?mode=memory&cache=shared"
writer = sqlite3.connect(URI, uri=True, isolation_level=None)
reader = sqlite3.connect(URI, uri=True, isolation_level=None)
writer.execute("CREATE TABLE shelf (book_id INTEGER PRIMARY KEY, available INTEGER)")
writer.execute("INSERT INTO shelf VALUES (7, 3)")


def read(label):
    try:
        row = reader.execute("SELECT available FROM shelf WHERE book_id = 7").fetchone()
        n = row[0]
        print(f"{label}: the reader sees {n}")
    except sqlite3.OperationalError as e:
        print(f"{label}: the reader gets an error: {e}")


writer.execute("BEGIN")
writer.execute("UPDATE shelf SET available = 0 WHERE book_id = 7")
read("3 changed to 0, not committed")
reader.execute("PRAGMA read_uncommitted = 1")
read("the same, read_uncommitted on")
writer.execute("ROLLBACK")
read("writer rolled back")
```

***Listing 30.9.** Two connections to one shared in-memory database code/bachelor-2/30-database-design/listings/dirty_read.py*

```
$ python dirty_read.py
3 changed to 0, not committed: the reader gets an error: database table is locked: shelf
the same, read_uncommitted on: the reader sees 0
writer rolled back: the reader sees 3
```

***Output 30.6.** Refused, then a [dirty read](#def-b2-database-design-anomalies), then the value the writer never committed is gone.*

The [lost update](#def-b2-database-design-anomalies) needs no concurrency inside the database at all: it is enough that a program reads a value, computes, and writes, while another does the same. Two lending desks, each with its own connection to the library’s file:

```python
with tempfile.TemporaryDirectory() as folder:
    # 1. Read, then write what was read minus one: each statement on its own.
    a, b = fresh(folder)
    na, nb = available(a), available(b)  # both read 3
    a.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (na - 1,))
    b.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (nb - 1,))
    print("read, then write: two copies lent, available =", available(a))
    a.close()
    b.close()

    # 2. The same inside BEGIN IMMEDIATE: the second desk must wait for the first.
    a, b = fresh(folder)
    a.execute("BEGIN IMMEDIATE")
    na = available(a)
    try:
        b.execute("BEGIN IMMEDIATE")
    except sqlite3.OperationalError as e:
        print("BEGIN IMMEDIATE: the second desk is refused:", e)
    a.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (na - 1,))
    a.execute("COMMIT")
    b.execute("BEGIN IMMEDIATE")  # the desk tries again
    nb = available(b)
    b.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (nb - 1,))
    b.execute("COMMIT")
    print("BEGIN IMMEDIATE: two copies lent, available =", available(a))
    a.close()
    b.close()

    # 3. One statement that reads and writes: nothing to interleave.
    a, b = fresh(folder)
    for conn in (a, b):
        conn.execute("UPDATE shelf SET available = available - 1 WHERE book_id = 7")
    print("update expression: two copies lent, available =", available(a))
    a.close()
    b.close()
```

***Listing 30.10.** Read then write, unprotected, inside `BEGIN IMMEDIATE`, then as one `UPDATE` code/bachelor-2/30-database-design/listings/lost_update.py*

```
$ python lost_update.py
read, then write: two copies lent, available = 2
BEGIN IMMEDIATE: the second desk is refused: database is locked
BEGIN IMMEDIATE: two copies lent, available = 1
update expression: two copies lent, available = 1
```

***Output 30.7.** Three copies, two lent: only the first way records 2 instead of 1.*

![The lost update of , one step per line. Each write is correct for the value its desk read; the second erases the first. Inside BEGIN IMMEDIATE, desk B could not have started before A committed, and it would have read 2.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-database-design/fig-023423491bbf.svg)

*The [lost update](#def-b2-database-design-anomalies) of [Output 30.7](#out-b2-database-design-lost-update), one step per line. Each write is correct for the value its desk read; the second erases the first. Inside `BEGIN IMMEDIATE`, desk B could not have started before A committed, and it would have read 2.*

There are two fixes. `BEGIN IMMEDIATE` takes the right to write at the start of the [transaction](#def-b2-database-design-transaction), so the second desk is refused until the first [commits](#def-b2-database-design-transaction), and then reads the new value. Or the read and the write become one statement, `UPDATE shelf SET available = available - 1`, which the database executes as a whole ([Exercise 30.6](#exo-b2-database-design-6)).

**In practice.**

`BEGIN IMMEDIATE` starts a write [transaction](#def-b2-database-design-transaction) at once, and may fail with “database is locked” (`SQLITE_BUSY`) while another connection has one; a program then waits and tries again. A plain `BEGIN` waits for the first write, and may fail there instead, after reading.

Since SQLite never shows the other anomalies, a small simulator shows them: it runs a [schedule](#def-b2-database-design-schedule) of reads and writes under three rules for answering a read, the latest write even if uncommitted, the latest committed value, or a snapshot of the committed values when the [transaction](#def-b2-database-design-transaction) began. Under snapshots, a [transaction](#def-b2-database-design-transaction) that wants to [commit](#def-b2-database-design-transaction) a row that another [transaction](#def-b2-database-design-transaction) committed since it began is refused, the rule of “first committer wins”.

```python
def lost_update(db):  # both read x, both write what they read minus one
    a, b = db.read(1, "x"), db.read(2, "x")
    db.write(1, "x", a - 1)
    db.write(2, "x", b - 1)
    if not (db.commit(1) and db.commit(2)):
        return "refused"
    return db.committed["x"] != 1


def write_skew(db):  # the rule a + b >= 1; each checks it, each removes one copy
    s1 = db.read(1, "a") + db.read(1, "b")
    s2 = db.read(2, "a") + db.read(2, "b")
    if s1 >= 2:
        db.write(1, "a", 0)
    if s2 >= 2:
        db.write(2, "b", 0)
    if not (db.commit(1) and db.commit(2)):
        return "refused"
    return db.committed["a"] + db.committed["b"] < 1


```

***Listing 30.11.** Two of the five staged [schedules](#def-b2-database-design-schedule): the [lost update](#def-b2-database-design-anomalies) and the [write skew](#def-b2-database-design-anomalies) code/bachelor-2/30-database-design/listings/schedules.py*

```
$ python schedules.py
                       uncommitted     committed      snapshot
dirty read                    seen             -             -
non-repeatable read           seen          seen             -
phantom                       seen          seen             -
lost update                   seen          seen       refused
write skew                    seen          seen          seen
```

***Output 30.8.** Which anomaly each rule lets through.*

Reading committed values removes [dirty reads](#def-b2-database-design-anomalies) only; snapshots remove the three anomalies of the standard’s table and turn the [lost update](#def-b2-database-design-anomalies) into a refusal. [Write skew](#def-b2-database-design-anomalies) survives snapshots: the two [transactions](#def-b2-database-design-transaction) write different rows, so no write conflicts with another, yet the rule “at least one copy stays” is broken. Only a serializable level prevents it, for example by detecting that each read what the other wrote.

## 30.6 Using an index

**Definition 30.21 (Index).**

An *index* on columns of a table is a separate structure, kept up to date by the database system on every change, that maps values of those columns to the rows that hold them, in sorted order, so that the rows with a given value or in a given range are found without reading the whole table.

The database chooses for each query whether to use an [index](#def-b2-database-design-index). `EXPLAIN QUERY PLAN` shows the choice:

```sql
-- load: town
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id = 55;
CREATE INDEX loans_member ON loans (member_id);
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id = 55;
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id + 0 = 55;
```

***Listing 30.12.** The plan of the same query before and after an [index](#def-b2-database-design-index) code/bachelor-2/30-database-design/listings/explain.sql*

```
$ python sqlrun.py explain.sql
sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id = 55;
+----+--------+---------+------------+
| id | parent | notused | detail     |
+----+--------+---------+------------+
| 2  | 0      | 0       | SCAN loans |
+----+--------+---------+------------+
(1 row)

sql> CREATE INDEX loans_member ON loans (member_id);
OK

sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id = 55;
+----+--------+---------+-----------------------------------------------------+
| id | parent | notused | detail                                              |
+----+--------+---------+-----------------------------------------------------+
| 3  | 0      | 0       | SEARCH loans USING INDEX loans_member (member_id=?) |
+----+--------+---------+-----------------------------------------------------+
(1 row)

sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id + 0 = 55;
+----+--------+---------+------------+
| id | parent | notused | detail     |
+----+--------+---------+------------+
| 2  | 0      | 0       | SCAN loans |
+----+--------+---------+------------+
(1 row)
```

***Output 30.9.** SCAN reads every row; SEARCH reads only the matching ones, through the [index](#def-b2-database-design-index).*

The last query hides the column inside an expression, and the [index](#def-b2-database-design-index) no longer applies: `member_id + 0` is not a value that the [index](#def-b2-database-design-index) sorts.

**In practice.**

SQLite’s documentation says that SCAN is a full-table scan and SEARCH visits a subset of the rows, and warns that the format of `EXPLAIN QUERY PLAN` may change between releases: it is for people to read, not for programs to parse.

On 400 loans either way is instant. On generated tables of growing size:

```python
def timed(conn, members, rng):
    """Mean time in microseconds of one query, over 200 random members."""
    ids = [rng.randrange(members) for _ in range(200)]
    t0 = time.perf_counter()
    for m in ids:
        conn.execute("SELECT count(*), max(out_day) FROM loans WHERE member_id = ?",
                     (m,)).fetchone()
    return (time.perf_counter() - t0) / len(ids) * 1e6


rng = random.Random(30)
print("     rows   scan (us)   index (us)   speed-up   index built in (ms)")
for n in [10_000, 100_000, 1_000_000]:
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE loans (loan_id INTEGER PRIMARY KEY, member_id INTEGER,"
                 " book_id INTEGER, out_day INTEGER)")
    members = n // 20
    rows = ((i, rng.randrange(members), rng.randrange(5000), rng.randrange(365))
            for i in range(n))
    conn.executemany("INSERT INTO loans VALUES (?, ?, ?, ?)", rows)
    scan = timed(conn, members, rng)
    t0 = time.perf_counter()
    conn.execute("CREATE INDEX loans_member ON loans (member_id)")
    built = (time.perf_counter() - t0) * 1e3
    seek = timed(conn, members, rng)
    print(f"{n:9} {scan:11.0f} {seek:12.1f} {scan / seek:10.0f} {built:21.0f}")
    conn.close()
```

***Listing 30.13.** The loans of a member, by scan and by [index](#def-b2-database-design-index), timed on generated tables code/bachelor-2/30-database-design/listings/index_timing.py*

```
$ python index_timing.py
     rows   scan (us)   index (us)   speed-up   index built in (ms)
    10000         623         12.3         51                     6
   100000        5977         18.7        320                    69
  1000000       63714         66.3        961                   744
```

***Output 30.10.** Mean time of one query on the author’s laptop, in microseconds.*

![on logarithmic axes, measured on a laptop. The scan grows in proportion to the table; the search through the index grows slowly, with the height of a tree, and with the cost of reaching rows scattered in memory.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-database-design/fig-15c7cdbb479f.svg)

*[Output 30.10](#out-b2-database-design-index-timing) on logarithmic axes, measured on a laptop. The scan grows in proportion to the table; the search through the [index](#def-b2-database-design-index) grows slowly, with the height of a tree, and with the cost of reaching rows scattered in memory.*

The scan time grows tenfold with each tenfold table; the [index](#def-b2-database-design-index) time grows about fivefold over a table a hundred times larger, and on a million rows the [index](#def-b2-database-design-index) is about a thousand times faster. It is not free: building it took close to a second, and each later insertion or update of a loan must update it too. How the [index](#def-b2-database-design-index) is organised, a balanced tree with many keys per node, and how the system chooses among plans, are the subject of the Year 3 volume. An [index](#def-b2-database-design-index) does not always help either: a query that selects a large fraction of the table reads it faster in order ([Exercise 30.12](#exo-b2-database-design-12)).

## 30.7 Exercises

**Exercise 30.1 ★.**

With $F = \{a \to b,\ bc \to d,\ d \to e,\ ea \to c\}$, compute by hand the closures of $\{a\}$, $\{b, c\}$ and $\{c, e\}$, then check with `exo_closure.py`. Is $\{a, d\}$ a superkey of $\{a, b, c, d, e\}$?

**Solution of Exercise 30.1.**

From $\{a\}$: $a \to b$ adds $b$; no other left side is contained in $\{a, b\}$, so $\{a\}^+ = \{a, b\}$. From $\{b, c\}$: $bc \to d$ adds $d$, then $d \to e$ adds $e$; $ea \to c$ needs $a$, so $\{b, c\}^+ = \{b, c, d, e\}$. From $\{c, e\}$ no left side applies. For $\{a, d\}$: $a \to b$, $d \to e$, $ea \to c$ give $\{a, b, c, d, e\}$, so it is a superkey; neither $\{a\}^+$ nor $\{d\}^+ = \{d, e\}$ is everything, so it is even a candidate key.

```
$ python exo_closure.py
['a'] -> ['a', 'b']
['b', 'c'] -> ['b', 'c', 'd', 'e']
['c', 'e'] -> ['c', 'e']
```

***Output 30.12.** The three closures.*

**Exercise 30.2 ★.**

A BCNF step on the wide table’s violation *book* $\to$ *title author genre pages* splits off only {book, title}. What is wrong with the other part? Compare with the step that splits off the whole closure, using `exo_bcnf_step.py`.

**Solution of Exercise 30.2.**

```
$ python exo_bcnf_step.py
split off {book, title}
    2 attributes; still violated by nothing
    13 attributes; still violated by {book} -> {author, genre, pages}
split off {book, title, author, genre, pages}
    5 attributes; still violated by nothing
    10 attributes; still violated by {member} -> {first, last, street, postcode}
```

***Output 30.13.** A step that splits off too little, and one that splits off the closure.*

The part {book, title} is fine, but the other part keeps *book* together with *author*, *genre* and *pages*: *book* $\to$ *author genre pages* still violates BCNF there, and a second and third step will be needed for the same left side. Splitting off $X^+$ removes every attribute that $X$ determines in one step; what remains in the other part are other violations, such as the member’s.

**Exercise 30.3 ★.**

The reading room’s bookings have attributes *seat*, *day*, *slot*, *member* and *desk*, with *seat day slot* $\to$ *member*, *member day slot* $\to$ *seat* and *seat* $\to$ *desk*. Find all the candidate keys by hand, then with `exo_keys.py`.

**Solution of Exercise 30.3.**

*day* and *slot* appear on no right side, so every key contains them; *desk* appears on no left side and is determined by *seat*, so no key needs it. {day, slot} alone determines nothing more. Adding *seat*: *seat day slot* $\to$ *member*, *seat* $\to$ *desk*: everything. Adding *member*: *member day slot* $\to$ *seat*, then the rest. Both are minimal, since {day, slot} is not a key, and any other key would have to contain *seat* or *member*, hence one of these.

```
$ python exo_keys.py
key: ['day', 'member', 'slot']
key: ['day', 'seat', 'slot']
```

***Output 30.14.** The two candidate keys.*

**Exercise 30.4 ★.**

A schema with $n$ attributes has exactly one candidate key, of size $k$. Prove that it has exactly $2^{n-k}$ superkeys.

**Solution of Exercise 30.4.**

Let $K$ be the key. A set $S$ is a superkey exactly when $S \supseteq K$: if $S \supseteq K$, then $S^+ \supseteq K^+ = R$; conversely, a superkey contains a candidate key, obtained by removing attributes while it stays a superkey, and $K$ is the only one. The supersets of $K$ are $K \cup T$ for the $2^{n-k}$ subsets $T$ of the other $n - k$ attributes.

**Exercise 30.5 ★★.**

Split the wide table into the member’s attributes and the rest, keeping in both, in turn, the member, the street, or the last name. Which splits are [lossless](#def-b2-database-design-decomposition) by Heath’s theorem? For the others, explain how a join could invent rows. Check with `exo_heath.py`, which runs the *chase*: one row per part, with the symbol $a$ on the part’s attributes and distinct symbols elsewhere; the dependencies force equal symbols where two rows agree on a left side; the [decomposition](#def-b2-database-design-decomposition) is [lossless](#def-b2-database-design-decomposition) exactly when some row ends with $a$ everywhere.

**Solution of Exercise 30.5.**

```
$ python exo_heath.py
split on member   : lossless True
split on street   : lossless False
split on last name: lossless False
```

***Output 30.15.** Only the split that keeps the member in both parts is [lossless](#def-b2-database-design-decomposition).*

Keeping *member* in both parts: the common attribute determines the whole member part, *member* $\to$ *first last street postcode*, so Heath’s theorem applies. Keeping *street*: the street determines only the postcode, not the member, and two members on the same street become interchangeable; the join pairs each loan with every member of its borrower’s street, inventing rows. Keeping *last*: a last name determines nothing, and the join pairs a loan with every member of that name. In the chase, the row of the second part never gets $a$ on the loan’s attributes, nor the first row on the member’s.

**Exercise 30.6 ★★.**

In the first part of [Listing 30.10](#lst-b2-database-design-lost-update), explain the bug as a [schedule](#def-b2-database-design-schedule), and say why each of the two fixes prevents it. Which fix still works if the program must check that a copy is available before lending it?

**Solution of Exercise 30.6.**

As a [schedule](#def-b2-database-design-schedule): $r_A(\mathit{available}) = 3$, $r_B(\mathit{available}) = 3$, $w_A(2)$, $w_B(2)$, each statement committed on its own. $B$’s write is computed from a value that $A$’s write made stale: a [lost update](#def-b2-database-design-anomalies). With `BEGIN IMMEDIATE`, the read and the write are in one [transaction](#def-b2-database-design-transaction) that holds the right to write from its start, so $B$’s [transaction](#def-b2-database-design-transaction) cannot begin between $A$’s read and $A$’s write: the [schedule](#def-b2-database-design-schedule) becomes serial. With `available = available - 1`, the read and the write are one statement, executed by the database as a whole. To check that a copy is available first, the check and the change must be in one unit: either the [transaction](#def-b2-database-design-transaction) with `BEGIN IMMEDIATE`, or the condition inside the statement, `UPDATE shelf SET available = available - 1 WHERE book_id = 7 AND available > 0`, whose count of changed rows says whether the copy was lent.

**Exercise 30.7 ★★.**

Add a *name* determined by the member to the bookings of [Exercise 30.3](#exo-b2-database-design-3), and let *seat day slot* determine *desk* as well. Compute a [minimal cover](#def-b2-database-design-cover) and the 3NF synthesis by hand, then check with `exo_synthesis.py`.

**Solution of Exercise 30.7.**

Split the right sides: *seat day slot* $\to$ *member*, *seat day slot* $\to$ *desk*, *member day slot* $\to$ *seat*, *seat* $\to$ *desk*, *member* $\to$ *name*. No left side has an extraneous attribute: {day, slot} determines nothing, and neither {seat, day} nor {seat, slot} determines the member. The dependency *seat day slot* $\to$ *desk* is redundant, implied by *seat* $\to$ *desk*: remove it. The synthesis makes one table per left side: (seat, desk), (seat, day, slot, member), (member, day, slot, seat), the same set as the previous one, so kept once, and (member, name). The second contains a key, so no table is added.

```
$ python exo_synthesis.py
minimal cover: seat -> desk; day seat slot -> member; day member slot -> seat; member -> name
table ['desk', 'seat'] | 3NF: True
table ['day', 'member', 'seat', 'slot'] | 3NF: True
table ['member', 'name'] | 3NF: True
lossless: True | preserving: True
```

***Output 30.16.** The cover, the three tables, and the checks.*

**Exercise 30.8 ★★.**

Derive the union rule and the [decomposition](#def-b2-database-design-decomposition) rule from Armstrong’s three axioms.

**Solution of Exercise 30.8.**

Union: from $X \to Y$, augmentation with $X$ gives $X \to XY$; from $X \to Z$, augmentation with $Y$ gives $XY \to YZ$; transitivity gives $X \to YZ$. Decomposition: $YZ \to Y$ by reflexivity, and transitivity with $X \to YZ$ gives $X \to Y$.

**Exercise 30.9 ★★.**

Find, with `exo_extra_fds.py`, the dependencies between two single attributes that the town’s 400 lines satisfy but the library’s rules do not imply. Which of them would you add to the schema, and what would change?

**Solution of Exercise 30.9.**

```
$ python exo_extra_fds.py
out      -> due
due      -> out
title    -> book, author, genre, pages
```

***Output 30.17.** Dependencies of the data that are not rules.*

*out* $\to$ *due* is a rule of the library, every loan being due 21 days later: it could be added, and then *due* is better not stored at all but computed, since a table (*out*, *due*) would only store the rule. *due* $\to$ *out* follows from the same rule. *title* $\to$ *book* is an accident of 80 titles that happen to differ; making it a rule would forbid a second copy of a book with another number, or two books with the same title, and should not be added.

**Exercise 30.10 ★★★.**

Prove [Theorem 30.11](#thm-b2-database-design-heath).

**Solution of Exercise 30.10.**

Let $T$ satisfy $X \to Y$. Every row of $T$ is in the join, since its projections on $XY$ and $XZ$ are in the two projections and agree on $X$. Conversely, let $(x, y, z)$ be in the join: there are rows $(x, y, z_1)$ and $(x, y_1, z)$ in $T$, the first giving the part on $XY$, the second the part on $XZ$. They agree on $X$, so by $X \to Y$ they agree on $Y$: $y_1 = y$, and the second row is $(x, y, z)$, which is therefore in $T$.

**Exercise 30.11 ★★★.**

Prove [Proposition 30.5](#prop-b2-database-design-closure-algo).

**Solution of Exercise 30.11.**

Let $S_0 = X$ and $S_i$ the set after the $i$-th addition. *Every attribute added is in $X^+$*: by induction, $F \vdash X \to S_i$; an addition uses some $V \to W$ of $F$ with $V \subseteq S_i$, so $X \to V$ by decomposition, $X \to W$ by transitivity, and $X \to S_i W$ by union. By soundness, $S_i \subseteq X^+$. *At the end, $X^+ \subseteq
S$*: when the loop stops, $S$ contains $X$ and, for every $V \to W$ in $F$ with $V \subseteq S$, also $W$. The two-row table of the proof of [Theorem 30.4](#thm-b2-database-design-armstrong), equal on $S$ and different elsewhere, then satisfies $F$; it satisfies $X \to A$ for every $A \in X^+$, its rows agree on $X \subseteq S$, so they agree on $A$, and $A \in S$. *Time*: a pass that adds nothing ends the loop; every other pass applies at least one dependency, whose right side then stays in the set for good, so that it is never applied again; so there are at most $|F| + 1$ passes, each of $|F|$ dependencies tested in $O(|R|)$.

**Exercise 30.12 ★★★.**

A query selects the loans with `out_day` below a bound, through an [index](#def-b2-database-design-index) on `out_day` or by a full scan. Measure both as the fraction selected grows, with `exo_selectivity.py`, find where the [index](#def-b2-database-design-index) stops helping, and explain why.

**Solution of Exercise 30.12.**

```
$ python exo_selectivity.py
selected   index (ms)   scan (ms)
    0.1%          0.4        19.9
    1.0%          4.8        22.2
    5.0%         22.4        23.8
   10.0%         43.3        26.9
   20.0%         99.0        25.6
   30.0%        131.9        28.8
   50.0%        206.4        33.0
  100.0%        423.9        37.2
```

***Output 30.18.** Range queries on 400,000 rows on the author’s laptop: best of three runs, in milliseconds.*

The scan reads the whole table in order, at a nearly fixed cost, a little more as more rows are summed. The [index](#def-b2-database-design-index) finds the first matching entry quickly and then, for each matching entry, fetches its row from the table, at a place that has nothing to do with the order of `out_day`: one random access per row. Its cost grows in proportion to the number of rows selected, about 4 ms per 1 % here, while the scan’s grows by less than 20 ms from one end to the other. On this laptop the two meet between 5 % and 10 % of the table; beyond, the [index](#def-b2-database-design-index) loses, by a factor of more than ten when everything is selected. A query planner estimates the fraction from statistics on the column and chooses the scan for large ranges.

## 30.8 Problem: Redesigning the library’s spreadsheet

**Problem 30.1.**

Weekend problem — Redesigning the library’s spreadsheet

The library replaces its spreadsheet by a database. The program below measures the old design, checks the new one and replays member 55’s move in both; [Output 30.10](#out-b2-database-design-index-timing) measures the [index](#def-b2-database-design-index) the desks will need.

```python
# Part I: each fact is stored once per loan line.
for det, column in [("book", "book_id"), ("member", "member_id"), ("street", "street")]:
    sql = f"SELECT count(*), count(DISTINCT {column}) FROM wide"
    lines, values = conn.execute(sql).fetchone()
    print(f"facts of a {det:6}: {values:3} distinct, stored on {lines} lines,"
          f" {lines - values} copies too many")

# Part II: the left sides of the minimal cover that are not keys of the wide table.
bad = sorted({left for left, _ in minimal_cover(RULES)
              if closure(left, RULES) != frozenset(WIDE)}, key=sorted)
print("dependencies violating BCNF, by left side:", ", ".join(show(b) for b in bad))

# Part III: the BCNF tables; each checked, and the decomposition as a whole.
parts = bcnf(WIDE, RULES)
print(len(parts), "tables, violations left:",
      sum(bcnf_violation(p, RULES) is not None for p in parts),
      "| lossless:", lossless(WIDE, parts, RULES),
      "| preserving:", preserves(parts, RULES))

# Part IV: member 55 moves; one UPDATE in each design.
conn.execute("CREATE TABLE d_members AS SELECT DISTINCT member_id, first_name,"
             " last_name, street FROM wide")
wide = conn.execute("UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'"
                    " WHERE member_id = 55").rowcount
one = conn.execute("UPDATE d_members SET street = 'Garden Lane'"
                   " WHERE member_id = 55").rowcount
print(f"the move: {wide} lines changed in the wide table, {one} in the members table")
```

***Listing 30.14.** The old design measured, the new one checked code/bachelor-2/30-database-design/listings/redesign.py*

```
$ python redesign.py
facts of a book  :  80 distinct, stored on 400 lines, 320 copies too many
facts of a member:  60 distinct, stored on 400 lines, 340 copies too many
facts of a street:  23 distinct, stored on 400 lines, 377 copies too many
dependencies violating BCNF, by left side: {book}, {member}, {street}
4 tables, violations left: 0 | lossless: True | preserving: True
the move: 12 lines changed in the wide table, 1 in the members table
```

***Output 30.11.** Redundancy, violations, the four tables, and the move in each design.*

**Part I — The dependencies of the wide table.**

1. List the library’s rules as functional dependencies, and say which are about loans, books, members and streets.
2. Explain the 320 copies too many of the books’ facts: what is stored 400 times, and what should be stored 80 times?
3. Give an [update anomaly](#def-b2-database-design-anomaly) , an [insertion anomaly](#def-b2-database-design-anomaly) and a [deletion anomaly](#def-b2-database-design-anomaly) of the wide table, with the library’s own facts.
4. Why is *title* $\to$ *book* , which the data satisfy, not one of the rules?
5. Does *out* $\to$ *due* hold? Should it be a rule, and what would that mean for the schema?
6. Compute the closure of {member} and of {street}.

**Part II — Keys and normal forms.**

7. Prove with the closure that {loan} is a candidate key of the wide table, and that it is the only one.
8. Which dependencies violate BCNF? Why exactly three left sides?
9. Is the wide table in 3NF? Use the definition.
10. Is the table ( *member* , *first* , *last* , *street* ) in BCNF? And ( *street* , *postcode* )?
11. What would a table ( *member* , *street* , *postcode* ) violate?
12. Give the number of violations before and after the redesign, as the program prints them.

**Part III — A lossless decomposition.**

13. Draw the splits that lead to the four tables, naming the dependency used at each.
14. Prove that each split is [lossless](#def-b2-database-design-decomposition) with Heath’s theorem.
15. Is the [decomposition](#def-b2-database-design-decomposition) dependency-preserving? Check each rule.
16. What did [Output 30.3](#out-b2-database-design-decomposed) check on the town’s data, and why are both counts needed?
17. Why does the streets table have 23 rows and not 24?
18. State the problem’s result for the design.

**Part IV — Transactions and an index.**

19. How many rows does the move change in each design, and why can the new design not forget one?
20. A loan and its fine are recorded together. Why must they be one [transaction](#def-b2-database-design-transaction) ?
21. Two desks lend the last copy of a book at the same moment. Which anomaly threatens, and how do you prevent it in SQLite?
22. Which [index](#def-b2-database-design-index) do the desks need to list a member’s loans, and what does `EXPLAIN QUERY PLAN` show before and after it?
23. From [Output 30.10](#out-b2-database-design-index-timing) , how much faster is the [index](#def-b2-database-design-index) on a million loans, and what does it cost?
24. Complete the problem’s result: from one wide table with three violating dependencies to four BCNF tables with none, and an [index](#def-b2-database-design-index) that is how many times faster on a million loans?

**Solution of Problem 30.1.**

**1.** Loans: *loan* $\to$ *book member out due ret*. Books: *book* $\to$ *title author genre pages*. Members: *member* $\to$ *first last street*. Streets: *street* $\to$ *postcode*.

**2.** Each of the 400 lines carries its book’s title, author, genre and pages: the facts of 80 books are written 400 times, 320 times more than needed.

**3.** Update: member 55’s move must change 12 lines, as in the hook. Insertion: a new member, or a newly bought book, cannot be recorded before a first loan, since every line is a loan. Deletion: removing the loans of a book, say to forget old loans, removes the book’s title and author with them.

**4.** The data satisfy it because the 80 titles happen to be different. The library could buy a second book with the same title, by another author, and the rule would then be false; a rule describes what must always hold.

**5.** It holds in the data, and it is a rule of the library: every loan is due 21 days after it goes out. Then *due* need not be stored; if it is, a table (*out*, *due*) would be the BCNF answer, which only stores the rule. Most designs compute it instead.

**6.** $\{\mathit{member}\}^+ = \{\mathit{member}, \mathit{first}, \mathit{last}, \mathit{street}, \mathit{postcode}\}$; $\{\mathit{street}\}^+ = \{\mathit{street}, \mathit{postcode}\}$.

**7.** $\{\mathit{loan}\}^+$ contains the book and the member, hence their closures, hence all fourteen attributes. *loan* appears on no right side, so every key contains it, and every set containing it is a superkey: {loan} is the only candidate key.

**8.** The dependencies with left side *book*, *member* or *street*: those are the three left sides of the cover besides *loan*, and none of them is a key.

**9.** No: *member* $\to$ *street* has a left side that is not a superkey, and *street* is in no candidate key, the only one being {loan}.

**10.** Yes for both: in (*member*, *first*, *last*, *street*) the only [non-trivial](#def-b2-database-design-fd) dependencies have *member*, a key, on the left; in (*street*, *postcode*), *street* is the key.

**11.** *street* $\to$ *postcode* with *street* not a key of that table, whose key is *member*: BCNF, and 3NF too since *postcode* is in no key. A move would again have to change two attributes.

**12.** Three violating left sides before, none after.

**13.** On *book*: {book, title, author, genre, pages} and the rest; the rest on *member*: {member, first, last, street, postcode} and the loans; the member part on *street*: {street, postcode} and {member, first, last, street}. This is the [decomposition](#def-b2-database-design-decomposition) tree of the chapter.

**14.** At each split on $X \to Y$, the part $XY$ and the rest share exactly $X$, and $X \to Y$ holds: Heath’s theorem applies, with $Z$ the rest minus $X$. The composition of [lossless](#def-b2-database-design-decomposition) splits is [lossless](#def-b2-database-design-decomposition), as in [Theorem 30.12](#thm-b2-database-design-bcnf-lossless).

**15.** Yes: each rule lies inside one table, *loan* $\to \dots$ in the loans, *book* $\to \dots$ in the books, *member* $\to$ *first last street* in the members, *street* $\to$ *postcode* in the streets.

**16.** That the join of the four tables gives back exactly the 400 lines: no line of the wide table is missing (`lost`) and no line appears that was not there (`invented`). A join always contains the original, so the second count is the one that tests losslessness; the first guards against an error in the SQL. It also checked that each table’s key is unique in the data.

**17.** The streets table is built from the wide table, which only knows the streets of members; one street has no member living on it. A real design would load the streets from their own source.

**18.** From one wide table with three violating dependencies, and 320, 340 and 377 extra copies of facts, to four BCNF tables with none; the [decomposition](#def-b2-database-design-decomposition) is [lossless](#def-b2-database-design-decomposition) and preserves every rule.

**19.** Twelve lines in the wide table, one row in the members table. The street is stored once per member, so there is nothing to forget.

**20.** If the program stops between the two writes, the loan is marked returned and the fine is missing, or the reverse: [atomicity](#def-b2-database-design-acid) makes the pair all or nothing, as in [Output 30.5](#out-b2-database-design-rollback).

**21.** A [lost update](#def-b2-database-design-anomalies): both desks read one copy available and both lend it. In SQLite, take the write right at the start with `BEGIN IMMEDIATE`, or make the check part of the update, `SET available = available - 1 WHERE available > 0`, and look at the count of changed rows.

**22.** An [index](#def-b2-database-design-index) on `loans(member_id)`. Before it, the plan says `SCAN loans`, every row read; after it, `SEARCH loans USING INDEX loans_member (member_id=?)`.

**23.** On the laptop of [Output 30.10](#out-b2-database-design-index-timing), about a thousand times faster on a million rows. It costs the time to build it, close to a second there, the space of a second sorted structure, and some work on each insertion or update of a loan.

**24.** From one wide table with three violating dependencies to four BCNF tables with none, and an [index](#def-b2-database-design-index) about a thousand times faster than a scan on a million loans, as measured on that laptop.
