---
title: "The Relational Model, Relational Algebra and SQL"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 29
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/29-the-relational-model-relational-algebra-and-sql
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 29 — The Relational Model, Relational Algebra and SQL

The town’s library wants to write to the members who have never borrowed a book of poetry. Three colleagues each write a query. The first takes all the members and removes those who borrowed poetry; the second keeps each member for whom no poetry loan exists; the third joins members to poetry loans and keeps those left without a partner. All three print 28. Is that luck, or are they the same question? To answer, a query must be more than text: it must be a mathematical object, with laws that say when two of them are equal. That object is [relational algebra](#def-b1-relational-model-algebra), and this chapter reads SQL through it. It ends with the other half of the work, designing the tables in the first place.

**You already know.**

A [relation](#def-b1-relational-model-relation) between sets is a subset of their [Cartesian product](#def-b1-relational-model-join) (mathematics book, Year 1). The second book used the town’s tables in SQLite with `SELECT`, joins and keys; [valuations](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-valuation) of formulas are in [Definition 10.3](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-valuation). Every query here runs on the town’s `books`, `members` and `loans`, through the series’ SQL runner, which prints each statement after `sql>`.

## 29.1 Relations, keys and integrity constraints

**Definition 29.1 (Relation schema, attribute, domain).**

A *relation schema* $R(A_1, \dots, A_n)$ is a name and a finite set of *attributes* $A_1, \dots, A_n$, each with a *domain* $D_i$, the set of values it may take.

**Definition 29.2 (Tuple, relation).**

A *tuple* over the schema gives each attribute $A_i$ a value in $D_i$. A *relation* over the schema (an instance) is a finite set of tuples: a subset of $D_1
\times \dots \times D_n$, the [attributes](#def-b1-relational-model-schema) naming the positions.

A [relation](#def-b1-relational-model-relation) is a set: its [tuples](#def-b1-relational-model-relation) have no order and no duplicates. A table in a database is close to that, but not quite, and the differences (order, duplicates, NULL) are where SQL surprises.

**Definition 29.3 (Superkey, candidate key, primary key, foreign key).**

A *superkey* of a schema is a set of [attributes](#def-b1-relational-model-schema) on which no two [tuples](#def-b1-relational-model-relation) of any allowed instance agree. A *candidate key* is a superkey none of whose proper subsets is one. The *primary key* is the candidate key chosen to identify [tuples](#def-b1-relational-model-relation). A *foreign key* of $R$ is a set of [attributes](#def-b1-relational-model-schema) whose values must appear as the primary key of some [tuple](#def-b1-relational-model-relation) of another [relation](#def-b1-relational-model-relation) $S$: it *references* $S$.

**Definition 29.4 (Integrity constraint, referential integrity).**

An *integrity constraint* is a condition that every instance of a database must satisfy: a key, a NOT NULL, a CHECK on the values of a [tuple](#def-b1-relational-model-relation). *Referential integrity* is the constraint that every [foreign key](#def-b1-relational-model-keys) value appears in the [relation](#def-b1-relational-model-relation) it references.

**Definition 29.5 (Null marker).**

The *null marker* `NULL` stands in a [tuple](#def-b1-relational-model-relation) for a value that is missing or unknown. It is not a value of the [domain](#def-b1-relational-model-schema): it equals nothing, not even itself.

The library’s own schema, designed in [Section 29.4](#sec-29-4), writes each of these in SQL’s data definition language: `PRIMARY KEY`, `UNIQUE` (another [candidate key](#def-b1-relational-model-keys)), `REFERENCES` (a [foreign key](#def-b1-relational-model-keys)), `NOT NULL` and `CHECK`.

```sql
CREATE TABLE loan (                        -- the association table of borrows: *--*
  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,
  due_date    TEXT NOT NULL,
  return_date TEXT,                        -- NULL while the book is out
  CHECK (due_date > out_date),
  CHECK (return_date IS NULL OR return_date >= out_date)
);
```

***Listing 29.1.** The table of loans and its constraints code/bachelor-1/29-relational-model/listings/schema.sql*

```
$ python sqlrun.py constraints.sql
sql> INSERT INTO person VALUES (1, 'Iris', 'Brook'), (2, 'Ben', 'Holt');
OK (2 rows changed)

sql> INSERT INTO member VALUES (10, 1, '2024-05-01');
OK (1 row changed)

sql> INSERT INTO book VALUES (100, 'The Silent Code', 'Fatou Dalewell', 65);
OK (1 row changed)

sql> INSERT INTO loan VALUES (1, 100, 10, '2025-01-01', '2025-01-22', NULL);
OK (1 row changed)

sql> INSERT INTO book VALUES (100, 'Another Book', 'Somebody', 90);
Error: UNIQUE constraint failed: book.book_id

sql> INSERT INTO member VALUES (11, 1, '2025-02-01');
Error: UNIQUE constraint failed: member.person_id

sql> INSERT INTO loan VALUES (2, 999, 10, '2025-01-02', '2025-01-23', NULL);
Error: FOREIGN KEY constraint failed

sql> INSERT INTO book VALUES (101, NULL, 'Nobody', 40);
Error: NOT NULL constraint failed: book.title

sql> INSERT INTO loan VALUES (3, 100, 10, '2025-01-05', '2025-01-01', NULL);
Error: CHECK constraint failed: due_date > out_date

sql> DELETE FROM book WHERE book_id = 100;
Error: FOREIGN KEY constraint failed
```

***Output 29.1.** Four statements accepted (five rows), then six refused, one per constraint; the last would leave a loan pointing at nothing.*

The database is the guardian of its own consistency: no program can store a loan of a book that does not exist, however it is written. One trap is SQLite’s alone: for compatibility with old databases, it checks [foreign keys](#def-b1-relational-model-keys) only after `PRAGMA foreign_keys = ON`, on each connection, and the series’ runner sends it.

```
$ python sqlrun.py fk_off.sql
sql> PRAGMA foreign_keys = OFF;
OK

sql> INSERT INTO loan VALUES (2, 999, 10, '2025-01-02', '2025-01-23', NULL);
OK (1 row changed)

sql> PRAGMA foreign_key_check;
+-------+-------+--------+------+
| table | rowid | parent | fkid |
+-------+-------+--------+------+
| loan  | 2     | member | 0    |
| loan  | 2     | book   | 1    |
+-------+-------+--------+------+
(2 rows)
```

***Output 29.2.** With the check off, a loan of book 999 by member 10, who do not exist, is accepted; `foreign_key_check` finds it afterwards.*

![Two relations of the town, with some of their attributes (books also has a year and a number of pages, loans a due date). The primary keys are underlined; each value of loans.book_id must be the key of a tuple of books. A NULL return date means the book is still out.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-relational-model/fig-681389a01d0f.svg)

*Two [relations](#def-b1-relational-model-relation) of the town, with some of their [attributes](#def-b1-relational-model-schema) (`books` also has a year and a number of pages, `loans` a due date). The [primary keys](#def-b1-relational-model-keys) are underlined; each value of `loans.book_id` must be the key of a [tuple](#def-b1-relational-model-relation) of `books`. A NULL return date means the book is still out.*

![A library’s card catalogue was a relation on paper: one card per book, the same fields on every card, and drawers kept in the order of one attribute, so that a search by another attribute meant reading every card.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-relational-model/img-4133a485f4d5.jpg)

*A library’s card catalogue was a [relation](#def-b1-relational-model-relation) on paper: one card per book, the same fields on every card, and drawers kept in the order of one attribute, so that a search by another attribute meant reading every card.*

## 29.2 Relational algebra

**Definition 29.6 (Relational algebra).**

*Relational algebra* is the set of operators that take [relations](#def-b1-relational-model-relation) and return a [relation](#def-b1-relational-model-relation), and of the expressions built from them and from named [relations](#def-b1-relational-model-relation). A query is an expression.

**Definition 29.7 (Selection, projection, renaming).**

For a [relation](#def-b1-relational-model-relation) $r$ over [attributes](#def-b1-relational-model-schema) $U$: the *selection* $\sigma_c(r)$ is the set of [tuples](#def-b1-relational-model-relation) of $r$ that satisfy the condition $c$; the *projection* $\pi_X(r)$, for $X \subseteq U$, is the set of the restrictions $t[X]$ of the [tuples](#def-b1-relational-model-relation) of $r$ to $X$; the *renaming* $\rho_{B \leftarrow A}(r)$ is $r$ with the attribute $A$ called $B$.

The set operations $r \cup s$ and $r - s$ apply to [relations](#def-b1-relational-model-relation) over the same [attributes](#def-b1-relational-model-schema).

**Definition 29.8 (Cartesian product, natural join, theta join, left outer join).**

For $r$ over $U$ and $s$ over $V$: the *Cartesian product* $r \times s$, for disjoint $U$ and $V$, is the set of the [tuples](#def-b1-relational-model-relation) $t \cup u$, $t \in r$, $u \in s$. The *natural join* $r \bowtie s$ is the set of the [tuples](#def-b1-relational-model-relation) $w$ over $U \cup V$ with $w[U] \in r$ and $w[V] \in s$: the pairs that agree on the common [attributes](#def-b1-relational-model-schema), each kept once. A *theta join* is $r \bowtie_c s = \sigma_c(r \times s)$. The *left outer join* keeps, in addition, each [tuple](#def-b1-relational-model-relation) of $r$ that matches nothing, its [attributes](#def-b1-relational-model-schema) from $V - U$ set to NULL.

The [natural join](#def-b1-relational-model-join) is a product followed by a [selection](#def-b1-relational-model-selection) and a [projection](#def-b1-relational-model-selection), and the intersection is $r \cap s = r - (r -
s)$: six operators, $\sigma$, $\pi$, $\rho$, $\cup$, $-$ and $\times$, are enough for the rest. The next one is the algebra’s “for all”.

**Definition 29.9 (Division).**

For $r$ over $X \cup Y$ and $s$ over $Y$, with $X$ and $Y$ disjoint, the *division* $r \div s$ is the set of the [tuples](#def-b1-relational-model-relation) $x$ over $X$ such that $x \cup y \in r$ for every $y \in s$. It equals $\pi_X(r) - \pi_X\big((\pi_X(r) \times s) - r\big)$: the candidates, minus those missing some pair.

```python
def select(r, condition):  # sigma: the tuples that satisfy the condition
    return Relation(r.schema, [t for t, d in zip(r.rows, r.dicts()) if condition(d)])


def project(r, attrs):  # pi: keep some attributes; duplicates merge
    idx = [r.schema.index(a) for a in attrs]
    return Relation(attrs, [tuple(t[i] for i in idx) for t in r.rows])


def rename(r, mapping):  # rho: new names for some attributes
    return Relation([mapping.get(a, a) for a in r.schema], r.rows)


def union(r, s):
    assert set(r.schema) == set(s.schema), "union needs the same attributes"
    return Relation(r.schema, r.rows | project(s, r.schema).rows)


def difference(r, s):
    assert set(r.schema) == set(s.schema), "difference needs the same attributes"
    return Relation(r.schema, r.rows - project(s, r.schema).rows)


def product(r, s):
    assert not set(r.schema) & set(s.schema), "rename the common attributes first"
    return Relation(r.schema + s.schema, [t + u for t in r.rows for u in s.rows])


def natural_join(r, s):
    """Pairs of tuples that agree on the common attributes, each attribute kept once."""
    common = [a for a in r.schema if a in s.schema]
    rest = [a for a in s.schema if a not in common]
    by_key = defaultdict(list)  # the tuples of s, grouped by their common values
    for d in s.dicts():
        by_key[tuple(d[a] for a in common)].append(tuple(d[a] for a in rest))
    rows = [t + u for t, d in zip(r.rows, r.dicts())
            for u in by_key[tuple(d[a] for a in common)]]
    return Relation(r.schema + tuple(rest), rows)
```

***Listing 29.2.** [Relational algebra](#def-b1-relational-model-algebra) on Python sets: each operator as its definition code/bachelor-1/29-relational-model/listings/algebra.py*

```python
# 1. Titles and years of the poetry written before 2000.
old_poetry = project(select(books, lambda t: t["genre"] == "poetry"
                            and t["year"] < 2000), ("title", "year"))
# 2. Members who never borrowed poetry: all members minus those who did.
poetry_readers = project(select(natural_join(loans, books),
                                lambda t: t["genre"] == "poetry"), ("member_id",))
never = difference(project(members, ("member_id",)), poetry_readers)
# 3. Members who borrowed every book by Kofi Elmwick: a division.
by_elmwick = project(select(books, lambda t: t["author"] == "Kofi Elmwick"),
                     ("book_id",))
every = division(project(loans, ("member_id", "book_id")), by_elmwick)
```

***Listing 29.3.** Three questions, as algebra on the town’s tables code/bachelor-1/29-relational-model/listings/algebra_demo.py*

```
$ python algebra_demo.py
old poetry      8 tuple(s), the same as SQL: True
never poetry   28 tuple(s), the same as SQL: True
all of Elmwick  1 tuple(s), the same as SQL: True
members who borrowed all 2 books by Kofi Elmwick: [3]
```

***Output 29.3.** Each algebra answer compared with the SQL query written next to it in the program.*

An algebra has laws. Two of them are the basis of every query optimiser.

**Proposition 29.10 (Selection laws).**

For [relations](#def-b1-relational-model-relation) $r, r'$ over $U$, $s$ over $V$, and conditions $c, c'$: (i) $\sigma_c(\sigma_{c'}(r)) = \sigma_{c \wedge c'}(r)$; (ii) $\sigma_c(r \cup r') = \sigma_c(r) \cup \sigma_c(r')$; (iii) if $c$ mentions only [attributes](#def-b1-relational-model-schema) of $U$, then $\sigma_c(r \bowtie s) = \sigma_c(r) \bowtie s$.

**Proof.** (i) Both sides are the [tuples](#def-b1-relational-model-relation) of $r$ satisfying $c$ and $c'$. (ii) A [tuple](#def-b1-relational-model-relation) is on the left iff it is in $r$ or $r'$ and satisfies $c$, which is the right. (iii) Let $w$ be over $U \cup V$. $w$ is on the left iff $w[U] \in r$, $w[V] \in s$ and $w$ satisfies $c$. Since $c$ mentions only $U$, $w$ satisfies $c$ iff $w[U]$ does; so the condition reads $w[U] \in
\sigma_c(r)$ and $w[V] \in s$, the definition of the right side. ∎

The [natural join](#def-b1-relational-model-join) is also commutative and associative ([Exercise 29.11](#exo-b1-relational-model-11)), so a query engine may reorder joins. Pushing a [selection](#def-b1-relational-model-selection) below a join is what makes the reordering pay.

```python
def check_laws(trials=2000, seed=29):
    rng = random.Random(seed)
    for _ in range(trials):
        r, r2 = random_relation("ab", rng), random_relation("ab", rng)
        s = random_relation("bc", rng)
        k = rng.randrange(4)
        def c(t, k=k):
            return t["a"] == k  # mentions only attributes of r
        assert select(union(r, r2), c) == union(select(r, c), select(r2, c))
        assert select(natural_join(r, s), c) == natural_join(select(r, c), s)
    return trials
```

***Listing 29.4.** The laws on random [relations](#def-b1-relational-model-relation) code/bachelor-1/29-relational-model/listings/laws.py*

```
$ python laws.py
sigma over union, sigma through a join: 2000 random cases, all equal
select after the join: join builds 400 tuples, keeps 49
select pushed down: select keeps 8 books, join builds 49 tuples
same answer: True | poetry readers: 32
```

***Output 29.4.** The laws hold on 2000 random cases; on the town, the pushed-down plan builds 49 [tuples](#def-b1-relational-model-relation) instead of 400.*

![The members who borrowed poetry, as two algebra trees evaluated from the leaves up. By (iii) they are equal; the right one handles far fewer tuples.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-relational-model/fig-ecc56831bae5.svg)

*The members who borrowed poetry, as two algebra trees evaluated from the leaves up. By [Proposition 29.10](#prop-b1-relational-model-pushdown) (iii) they are equal; the right one handles far fewer [tuples](#def-b1-relational-model-relation).*

## 29.3 SQL read as algebra

A query `SELECT $A_1$, ..., $A_k$ FROM $r_1$, ..., $r_m$ WHERE $c$` is read

$$
\pi_{A_1, \dots, A_k}\big(\sigma_c(r_1 \times \dots \times r_m)\big),
$$

with one difference: SQL keeps duplicates. Its tables are *multisets*, and `DISTINCT` turns the answer into a set. `AS` renames, a column or a table. `ORDER BY`, `LIMIT` and `OFFSET` act on the answer after everything else, since a [relation](#def-b1-relational-model-relation) has no order to begin with.

```
$ python sqlrun.py select_project.sql
sql> SELECT title, year FROM books WHERE genre = 'poetry' AND year < 2000;
+--------------------------+------+
| title                    | year |
+--------------------------+------+
| A Map of the Lighthouse  | 1967 |
| The Hidden Machine       | 1961 |
| The Silent Machine       | 1966 |
| The Clockwork Code       | 1957 |
| The Lost Code            | 1976 |
| The Silent Valley        | 1958 |
| A Year by the Lighthouse | 1955 |
| The Last Lighthouse      | 1986 |
+--------------------------+------+
(8 rows)

sql> SELECT genre FROM books WHERE pages > 480;
+-----------+
| genre     |
+-----------+
| science   |
| science   |
| adventure |
| adventure |
| mystery   |
+-----------+
(5 rows)

sql> SELECT DISTINCT genre FROM books WHERE pages > 480;
+-----------+
| genre     |
+-----------+
| science   |
| adventure |
| mystery   |
+-----------+
(3 rows)
```

***Output 29.5.** [Selection](#def-b1-relational-model-selection) and [projection](#def-b1-relational-model-selection); the [projection](#def-b1-relational-model-selection) on `genre` keeps duplicates until `DISTINCT`. Some lines are left out.*

```
$ python sqlrun.py order_limit.sql
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)

sql> SELECT title, pages FROM books ORDER BY pages DESC, title LIMIT 3 OFFSET 3;
+------------------+-------+
| title            | pages |
+------------------+-------+
| Seven Forest     | 500   |
| The Last Engine  | 499   |
| The Lost Library | 478   |
+------------------+-------+
(3 rows)
```

***Output 29.6.** The longest books, three at a time: `OFFSET` skips rows of the sorted answer. The second sort key, `title`, makes the order total, so the pages are well defined.*

`JOIN ... ON $c$` is the [theta join](#def-b1-relational-model-join), and `LEFT JOIN` the [left outer join](#def-b1-relational-model-join). The `ON` condition decides which pairs match; a `WHERE` condition then filters the result, padded [tuples](#def-b1-relational-model-relation) included, so a condition on the right table moved from `ON` to `WHERE` turns a left join back into a join.

```
$ python sqlrun.py joins.sql
sql> SELECT b.title, l.out_date, l.return_date
...> FROM books AS b JOIN loans AS l ON l.book_id = b.book_id
...> WHERE b.author = 'Vera Ashley' AND l.out_date >= '2025-11-01';
+-----------------+------------+-------------+
| title           | out_date   | return_date |
+-----------------+------------+-------------+
| The Lost Forest | 2025-11-11 | 2025-11-23  |
| The Lost Forest | 2025-11-25 | 2026-01-11  |
+-----------------+------------+-------------+
(2 rows)

sql> SELECT b.title, l.out_date, l.return_date
...> FROM books AS b LEFT JOIN loans AS l
...>   ON l.book_id = b.book_id AND l.out_date >= '2025-11-01'
...> WHERE b.author = 'Vera Ashley';
+------------------+------------+-------------+
| title            | out_date   | return_date |
+------------------+------------+-------------+
| The Lost Forest  | 2025-11-11 | 2025-11-23  |
| The Lost Forest  | 2025-11-25 | 2026-01-11  |
| Under the Garden | NULL       | NULL        |
| The Lost Code    | NULL       | NULL        |
| Under the Engine | NULL       | NULL        |
+------------------+------------+-------------+
(5 rows)
```

***Output 29.7.** The books by one author and their loans since November: the join drops the books that were not borrowed; the left join keeps them, padded with NULL.*

![The left join of , reduced to two columns: book 9 meets its two loans; books 20, 40 and 48 meet none and are kept, their loan attributes padded with NULL. A plain join would drop them.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-relational-model/fig-abaecac3fbf5.svg)

*The left join of [Output 29.7](#out-b1-relational-model-joins), reduced to two columns: book 9 meets its two loans; books 20, 40 and 48 meet none and are kept, their loan [attributes](#def-b1-relational-model-schema) padded with NULL. A plain join would drop them.*

NULL forces a third [truth value](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-valuation). A comparison with NULL is neither true nor false but *unknown*, and `WHERE` keeps a [tuple](#def-b1-relational-model-relation) only when its condition is true.

**Definition 29.11 (Three-valued logic).**

*Three-valued logic* has the [truth values](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-valuation) $0$, $1$ and *unknown*, $u$, ordered $0 < u
< 1$, with $x \wedge y = \min(x, y)$, $x \vee y = \max(x, y)$, $\neg u = u$, and $\neg 0 = 1$, $\neg 1 = 0$. Any comparison with NULL is $u$.

On 0 and 1 these are the [valuations](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-valuation) of [Chapter 10](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#ch-b1-propositional-logic); the law of the excluded middle fails, since $u
\vee \neg u = u$.

```
$ python sqlrun.py null_logic.sql
sql> SELECT NULL = NULL, NULL <> 1, NULL AND 0, NULL AND 1, NULL OR 1, NOT NULL;
+-------------+-----------+------------+------------+-----------+----------+
| NULL = NULL | NULL <> 1 | NULL AND 0 | NULL AND 1 | NULL OR 1 | NOT NULL |
+-------------+-----------+------------+------------+-----------+----------+
| NULL        | NULL      | 0          | NULL       | 1         | NULL     |
+-------------+-----------+------------+------------+-----------+----------+
(1 row)

sql> SELECT count(*), count(return_date), count(DISTINCT member_id) FROM loans;
+----------+--------------------+---------------------------+
| count(*) | count(return_date) | count(DISTINCT member_id) |
+----------+--------------------+---------------------------+
| 400      | 378                | 60                        |
+----------+--------------------+---------------------------+
(1 row)

sql> SELECT count(*) FROM loans WHERE return_date > due_date;
+----------+
| count(*) |
+----------+
| 87       |
+----------+
(1 row)

sql> SELECT count(*) FROM loans WHERE NOT (return_date > due_date);
+----------+
| count(*) |
+----------+
| 291      |
+----------+
(1 row)
```

***Output 29.8.** [Three-valued logic](#def-b1-relational-model-three-valued) in SQLite, which prints $u$ as NULL; `count(*)` counts rows and `count(return_date)` non-NULL values; a condition and its negation together miss the 22 loans still out.*

The set operations are `UNION`, `INTERSECT` and `EXCEPT`, on answers with the same columns; they return sets (`UNION ALL` keeps duplicates).

```
$ python sqlrun.py set_ops.sql
sql> SELECT count(*) FROM (
...>   SELECT author FROM books WHERE genre = 'poetry'
...>   UNION SELECT author FROM books WHERE genre = 'science');
+----------+
| count(*) |
+----------+
| 12       |
+----------+
(1 row)

sql> SELECT author FROM books WHERE genre = 'poetry'
...> INTERSECT SELECT author FROM books WHERE genre = 'science';
+----------------+
| author         |
+----------------+
| Caio Lakeby    |
| Fatou Fernwell |
| Fatou Oakham   |
| Zoe Stoneton   |
+----------------+
(4 rows)

sql> SELECT author FROM books WHERE genre = 'poetry'
...> EXCEPT SELECT author FROM books WHERE genre = 'science';
+----------------+
| author         |
+----------------+
| Ivo Northworth |
| Vera Ashley    |
+----------------+
(2 rows)
```

***Output 29.9.** The authors of poetry and of science: 12 in all, four who write both, two who write poetry only.*

**Definition 29.12 (Aggregation operator).**

The *aggregation operator* $\gamma_{G; f(A)}(r)$ groups the [tuples](#def-b1-relational-model-relation) of $r$ by their values on the [attributes](#def-b1-relational-model-schema) $G$ and gives one [tuple](#def-b1-relational-model-relation) per group: the values of $G$ and $f$ applied to the multiset of the values of $A$ in the group, $f$ being `count`, `sum`, `avg`, `min` or `max`.

`GROUP BY` is $\gamma$; `WHERE` selects [tuples](#def-b1-relational-model-relation) before the grouping and `HAVING` selects groups after it, so only `HAVING` may mention an aggregate.

```
$ python sqlrun.py aggregates.sql
sql> SELECT genre, count(*) AS books, round(avg(pages)) AS pages
...> FROM books GROUP BY genre ORDER BY books DESC;
+-----------+-------+-------+
| genre     | books | pages |
+-----------+-------+-------+
| science   | 13    | 289.0 |
| adventure | 12    | 359.0 |
| history   | 11    | 265.0 |
| comics    | 10    | 196.0 |
| sport     | 9     | 284.0 |
| mystery   | 9     | 292.0 |
| poetry    | 8     | 262.0 |
| nature    | 8     | 251.0 |
+-----------+-------+-------+
(8 rows)

sql> SELECT genre, count(*) AS books FROM books
...> WHERE pages > 200 GROUP BY genre HAVING count(*) >= 7;
+-----------+-------+
| genre     | books |
+-----------+-------+
| adventure | 10    |
| history   | 7     |
| science   | 10    |
| sport     | 7     |
+-----------+-------+
(4 rows)
```

***Output 29.10.** One row per genre; then only the books of more than 200 pages, grouped, and only the groups of at least seven.*

A query may contain queries. `$x$ IN (SELECT ...)` tests membership in the inner answer, `EXISTS (SELECT ...)` tests that it is not empty, and a *correlated* subquery mentions the outer [tuple](#def-b1-relational-model-relation), so it is evaluated once per outer [tuple](#def-b1-relational-model-relation), as a nested loop would be.

```
$ python sqlrun.py nested.sql
sql> SELECT title FROM books
...> WHERE book_id IN (SELECT book_id FROM loans WHERE return_date IS NULL)
...>   AND genre = 'science';
+--------------------+
| title              |
+--------------------+
| The Last Engine    |
| The Paper Bridge   |
| The Hidden Library |
+--------------------+
(3 rows)

sql> SELECT b.title, b.genre, b.pages FROM books AS b
...> WHERE b.pages > (SELECT 1.7 * avg(pages) FROM books AS c WHERE c.genre = b.genre);
+-----------------------+---------+-------+
| title                 | genre   | pages |
+-----------------------+---------+-------+
| Seven Library         | comics  | 346   |
| The Last Engine       | science | 499   |
| A Year by the Harbour | science | 506   |
| The Paper River       | mystery | 513   |
+-----------------------+---------+-------+
(4 rows)

sql> SELECT count(*) FROM members AS m
...> WHERE EXISTS (SELECT * FROM loans AS l
...>               WHERE l.member_id = m.member_id AND l.return_date IS NULL);
+----------+
| count(*) |
+----------+
| 17       |
+----------+
(1 row)
```

***Output 29.11.** The science books still out; the books more than 1.7 times as long as the average of their genre (correlated); the members with a book still out.*

**Definition 29.13 (View).**

A *view* is a named query, used like a table; its rows are computed from the tables whenever it is read.

```
$ python sqlrun.py views.sql
sql> CREATE VIEW late AS
...>   SELECT member_id, book_id, julianday(return_date) - julianday(due_date) AS days
...>   FROM loans WHERE return_date > due_date;
OK

sql> SELECT count(*), max(days), round(avg(days), 1) FROM late;
+----------+-----------+---------------------+
| count(*) | max(days) | round(avg(days), 1) |
+----------+-----------+---------------------+
| 87       | 30.0      | 15.8                |
+----------+-----------+---------------------+
(1 row)

sql> SELECT member_id, count(*) AS times FROM late
...> GROUP BY member_id ORDER BY times DESC, member_id LIMIT 3;
+-----------+-------+
| member_id | times |
+-----------+-------+
| 37        | 4     |
| 38        | 4     |
| 41        | 4     |
+-----------+-------+
(3 rows)
```

***Output 29.12.** A [view](#def-b1-relational-model-view) of the late returns, with the number of days late, then queried twice.*

SQL is *declarative*: a query says what the answer is, as a formula says what a set is, and leaves the order of the work to the engine, which rewrites the algebra by laws such as [Proposition 29.10](#prop-b1-relational-model-pushdown) and chooses the cheapest plan. The same idea, programs as logical statements, has a whole paradigm of programming languages built on it.

## 29.4 Entity–relationship modelling

Before the tables, the world: what the database must remember. Chen proposed in 1976 to draw it.

**Definition 29.14 (Entity, relationship, multiplicity, entity–relationship model).**

An *entity* is a kind of thing the database records, with [attributes](#def-b1-relational-model-schema), one set of which identifies each thing. A *relationship* associates entities, possibly with [attributes](#def-b1-relational-model-schema) of its own. Its *multiplicity* says how many entities of one side may be associated with one entity of the other: one-to-one (1–1), one-to-many (1–*) or many-to-many (*–*). An *entity–relationship model* is the diagram of the entities and relationships of a [domain](#def-b1-relational-model-schema).

**Definition 29.15 (Association table).**

An *association table* represents a many-to-many [relationship](#def-b1-relational-model-er): one [tuple](#def-b1-relational-model-relation) per pair of associated entities, with a [foreign key](#def-b1-relational-model-keys) to each side and the [relationship](#def-b1-relational-model-er)’s own [attributes](#def-b1-relational-model-schema).

The translation follows rules. Each [entity](#def-b1-relational-model-er) becomes a table, its identifier the [primary key](#def-b1-relational-model-keys). A 1–* [relationship](#def-b1-relational-model-er) becomes a [foreign key](#def-b1-relational-model-keys) on the “many” side; a 1–1 [relationship](#def-b1-relational-model-er), a [foreign key](#def-b1-relational-model-keys) that is also `UNIQUE`; a *–* [relationship](#def-b1-relational-model-er), an [association table](#def-b1-relational-model-association-table), which splits it into two 1–* [relationships](#def-b1-relational-model-er).

![The library as an entity–relationship diagram, and its translation into the four tables of : the 1–1 relationship becomes a UNIQUE foreign key, the *–* one the association table loan.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-relational-model/fig-55c71899cbbe.svg)

*The library as an entity–relationship diagram, and its translation into the four tables of [Listing 29.1](#lst-b1-relational-model-schema): the 1–1 [relationship](#def-b1-relational-model-er) becomes a `UNIQUE` [foreign key](#def-b1-relational-model-keys), the *–* one the [association table](#def-b1-relational-model-association-table) `loan`.*

The `loan` table carries a key of its own, `loan_id`, rather than the pair (member, book): a member may borrow the same book twice, and the dates belong to each loan. The town’s tables follow the same design, with fewer constraints: `members.person_id` is not declared `UNIQUE`, and nothing checks that a return comes after the loan. A design also has to avoid storing a fact twice, which a later volume studies with normal forms.

**History — The relational model.**

Edgar Codd proposed in 1970 to describe the data of a bank or a company as mathematical [relations](#def-b1-relational-model-relation) and to query them by operations on [relations](#def-b1-relational-model-relation), leaving to the system the question of how the data are stored on disk. The databases of the time made programs follow [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) from record to record, and changing the storage meant rewriting the programs. Peter Chen’s [entity–relationship model](#def-b1-relational-model-er) followed in 1976. Relational systems and SQL came to dominate databases within two decades.

## 29.5 Exercises

**Exercise 29.1 ★.**

A [relation](#def-b1-relational-model-relation) $r(\text{name}, \text{city}, \text{age})$ holds $(\text{Ana}, \text{Lyon}, 31)$, $(\text{Bo}, \text{Oslo},
25)$, $(\text{Cy}, \text{Lyon}, 25)$, $(\text{Di}, \text{Oslo}, 40)$. Compute $\pi_{\text{city}}(\sigma_{\text{age} <
35}(r))$ and $\sigma_{\text{age} < 35}(\pi_{\text{city}, \text{age}}(r))$.

**Solution of Exercise 29.1.**

$\sigma_{\text{age} < 35}(r)$ keeps Ana, Bo and Cy, so the first answer is $\{(\text{Lyon}), (\text{Oslo})\}$, two [tuples](#def-b1-relational-model-relation), the duplicate Lyon merged. The second is $\{(\text{Lyon}, 31), (\text{Oslo}, 25), (\text{Lyon}, 25)\}$. The two expressions differ because the second projects on $\text{age}$ too; with the same final [projection](#def-b1-relational-model-selection) they would be equal, since a [selection](#def-b1-relational-model-selection) on age commutes with a [projection](#def-b1-relational-model-selection) that keeps age.

**Exercise 29.2 ★.**

$a(x, y) = \{(1, p), (2, q), (3, r)\}$ and $b(y, z) = \{(p, 10), (p, 20), (s, 30)\}$. Give $a \bowtie b$ and the [left outer join](#def-b1-relational-model-join) of $a$ with $b$.

**Solution of Exercise 29.2.**

$a \bowtie b = \{(1, p, 10), (1, p, 20)\}$ over $(x, y, z)$. The [left outer join](#def-b1-relational-model-join) adds $(2, q, \text{NULL})$ and $(3, r,
\text{NULL})$; $(s, 30)$ matches nothing and, $b$ being the right side, disappears.

**Exercise 29.3 ★.**

With $x =$ NULL and $y = 3$, give the [truth value](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-valuation) of $x = 3$, $y = 3 \vee x = 3$, $y = 4 \wedge x = 3$, $\neg(x = 3)$ and `x IS NULL`. Which rows does `WHERE` keep?

**Solution of Exercise 29.3.**

$x = 3$ is $u$; $y = 3 \vee x = 3$ is $\max(1, u) = 1$; $y = 4 \wedge x = 3$ is $\min(0, u) = 0$; $\neg(x = 3)$ is $u$; `x IS NULL` is 1, since `IS NULL` is never unknown. `WHERE` keeps a row only for the second and the last conditions.

**Exercise 29.4 ★.**

Using [Output 29.10](#out-b1-relational-model-aggregates), what does `SELECT genre FROM books GROUP BY genre HAVING avg(pages) > 280` print?

**Solution of Exercise 29.4.**

The genres whose average is above 280: science (289), adventure (359), sport (284) and mystery (292), in an order SQL does not promise without `ORDER BY`.

**Exercise 29.5 ★★.**

This query is refused. Why, and how should it be written?

```
$ python sqlrun.py exo_where_aggregate.sql
sql> SELECT genre, count(*) FROM books WHERE count(*) >= 10 GROUP BY genre;
Error: misuse of aggregate: count()
```

***Output 29.13.** An aggregate in `WHERE`.*

**Solution of Exercise 29.5.**

`WHERE` selects [tuples](#def-b1-relational-model-relation) before the grouping, when there is no group to count. The condition is on groups: `SELECT genre, count(*) FROM books GROUP BY genre HAVING count(*) >= 10`, which keeps science, adventure, history and comics ([Output 29.10](#out-b1-relational-model-aggregates)).

**Exercise 29.6 ★★.**

The two queries below should count the same days. Explain why the first finds none, and why `NOT EXISTS` does not have the problem.

```sql
SELECT count(DISTINCT out_date) FROM loans
WHERE out_date NOT IN (SELECT return_date FROM loans);
SELECT count(DISTINCT out_date) FROM loans AS l
WHERE NOT EXISTS (SELECT * FROM loans AS r WHERE r.return_date = l.out_date);
```

***Listing 29.5.** Two anti-joins code/bachelor-1/29-relational-model/listings/exo_not_in_null.sql*

```
$ python sqlrun.py exo_not_in_null.sql
sql> SELECT count(DISTINCT out_date) FROM loans
...> WHERE out_date NOT IN (SELECT return_date FROM loans);
+--------------------------+
| count(DISTINCT out_date) |
+--------------------------+
| 0                        |
+--------------------------+
(1 row)

sql> SELECT count(DISTINCT out_date) FROM loans AS l
...> WHERE NOT EXISTS (SELECT * FROM loans AS r WHERE r.return_date = l.out_date);
+--------------------------+
| count(DISTINCT out_date) |
+--------------------------+
| 81                       |
+--------------------------+
(1 row)
```

***Output 29.14.** 0 against 81.*

**Solution of Exercise 29.6.**

The subquery’s answer contains NULL, the return dates of the 22 loans still out. For a date $d$ that is no return date, `d NOT IN (...)` is $\neg(d = v_1 \vee \dots \vee d = \text{NULL})$, that is $\neg(0 \vee \dots \vee u) = \neg u =
u$: never true, so no row is kept. `NOT EXISTS` asks whether a set of rows is empty; the rows whose return date is NULL make the inner condition $u$, so they are not in that set, which is what the question means. Writing `WHERE return_date IS NOT NULL` inside the `NOT IN` repairs the first query.

**Exercise 29.7 ★★.**

Find the members with more than three late returns, in SQL and in [relational algebra](#def-b1-relational-model-algebra) with $\gamma$, and check that the answers agree.

**Solution of Exercise 29.7.**

```python
def late_members():
    loans = table("loans")
    late = select(loans, lambda t: t["return_date"] is not None
                  and t["return_date"] > t["due_date"])
    counts = group(late, ("member_id",), "late", len, "loan_id")
    return project(select(counts, lambda t: t["late"] > 3), ("member_id", "late"))
```

*Late returns, grouped and selected code/bachelor-1/29-relational-model/exercises/late_members.py*

The late loans are $\ell = \sigma_{\text{return\_date} > \text{due\_date}}(\text{loans})$, and the answer is

$$
\sigma_{\text{late} > 3}\big(\gamma_{\text{member\_id};\ \text{count}(\text{loan\_id}) \to \text{late}}(\ell)\big).
$$

Both the program and the SQL of `late_members.sql` find seven members, 37, 38, 41, 42, 46, 50 and 51, with four late returns each.

**Exercise 29.8 ★★.**

For each author of at least two books, find the members who borrowed every one of them, by a [division](#def-b1-relational-model-division).

**Solution of Exercise 29.8.**

```python
def every_book_of(author):
    books, loans = table("books"), table("loans")
    theirs = project(select(books, lambda t: t["author"] == author), ("book_id",))
    return theirs, division(project(loans, ("member_id", "book_id")), theirs)
```

*One [division](#def-b1-relational-model-division) per author code/bachelor-1/29-relational-model/exercises/division.py*

$\pi_{\text{member\_id}, \text{book\_id}}(\text{loans}) \div \pi_{\text{book\_id}}(\sigma_{\text{author} = a}(\text{books}))$ for each author $a$. Only two answers are not empty: member 39 read both books by Ivo Northworth, member 3 both by Kofi Elmwick.

**Exercise 29.9 ★★.**

A schema has $n$ [attributes](#def-b1-relational-model-schema) and a single [candidate key](#def-b1-relational-model-keys) of $k$ [attributes](#def-b1-relational-model-schema). How many [superkeys](#def-b1-relational-model-keys) does it have? How many if it has two disjoint [candidate keys](#def-b1-relational-model-keys) of $k$ and $l$ [attributes](#def-b1-relational-model-schema)?

**Solution of Exercise 29.9.**

A [superkey](#def-b1-relational-model-keys) is a set of [attributes](#def-b1-relational-model-schema) containing the key; the other $n - k$ [attributes](#def-b1-relational-model-schema) may be added or not: $2^{n - k}$. With two disjoint keys $K$ and $L$, the [superkeys](#def-b1-relational-model-keys) contain $K$ or $L$; by inclusion–exclusion there are $2^{n - k} + 2^{n - l}
- 2^{n - k - l}$. The program `superkeys.py` checks the first count by [brute force](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-exhaustive) for $n \leq 6$.

**Exercise 29.10 ★★★.**

Does [Proposition 29.10](#prop-b1-relational-model-pushdown) (iii) hold for the [left outer join](#def-b1-relational-model-join) of $r$ with $s$ when $c$ mentions only [attributes](#def-b1-relational-model-schema) of $r$? When it mentions only [attributes](#def-b1-relational-model-schema) of $s$? Prove it or give a counterexample.

**Solution of Exercise 29.10.**

When $c$ mentions only [attributes](#def-b1-relational-model-schema) of $r$, yes. Each [tuple](#def-b1-relational-model-relation) of the [left outer join](#def-b1-relational-model-join) comes from one [tuple](#def-b1-relational-model-relation) $t$ of $r$, joined or padded, and whether it satisfies $c$ depends on $t$ alone; so selecting before or after keeps the same [tuples](#def-b1-relational-model-relation) of $r$, with the same partners. When $c$ mentions only [attributes](#def-b1-relational-model-schema) of $s$, no. Take $r = \{(1)\}$ over $(x)$, $s = \{(1, 5)\}$ over $(x,
y)$, and $c$: $y > 9$. The [left outer join](#def-b1-relational-model-join) is $\{(1, 5)\}$, and $\sigma_c$ of it is empty; but $\sigma_c(s)$ is empty and the [left outer join](#def-b1-relational-model-join) of $r$ with it is $\{(1, \text{NULL})\}$. This is the `ON` versus `WHERE` difference of [Section 29.3](#sec-29-3).

**Exercise 29.11 ★★★.**

Prove that the [natural join](#def-b1-relational-model-join) is commutative and associative.

**Solution of Exercise 29.11.**

With $r$ over $U$ and $s$ over $V$, $r \bowtie s$ is the set of [tuples](#def-b1-relational-model-relation) $w$ over $U \cup V$ with $w[U] \in r$ and $w[V] \in
s$; the definition is symmetric in $r$ and $s$, and [attributes](#def-b1-relational-model-schema) are named, not ordered: $r \bowtie s = s \bowtie r$. For $t$ over $W$, $w$ over $U \cup V \cup W$ is in $(r \bowtie s) \bowtie t$ iff $w[U \cup V] \in r \bowtie s$ and $w[W] \in
t$, iff $w[U] \in r$, $w[V] \in s$ and $w[W] \in t$, since $w[U \cup V][U] = w[U]$. The same steps give the same condition for $r \bowtie (s \bowtie t)$.

**Exercise 29.12 ★★★.**

A school has teachers, each with one office (1–1); classes, each taught by one teacher (1–*); and students, who attend many classes (*–*). Translate the diagram into tables with constraints, and write inserts that each constraint must refuse.

**Solution of Exercise 29.12.**

```sql
CREATE TABLE office (office_id INTEGER PRIMARY KEY, room TEXT NOT NULL);
CREATE TABLE teacher (
  teacher_id INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  office_id  INTEGER NOT NULL UNIQUE REFERENCES office(office_id));
CREATE TABLE class (
  class_id   INTEGER PRIMARY KEY,
  subject    TEXT NOT NULL,
  teacher_id INTEGER NOT NULL REFERENCES teacher(teacher_id));
CREATE TABLE student (student_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE attends (
  student_id INTEGER REFERENCES student(student_id),
  class_id   INTEGER REFERENCES class(class_id),
  PRIMARY KEY (student_id, class_id));
```

*The school code/bachelor-1/29-relational-model/exercises/er_schema.sql*

The 1–1 [relationship](#def-b1-relational-model-er) is a `UNIQUE NOT NULL` [foreign key](#def-b1-relational-model-keys) in `teacher`; the 1–* one a `NOT NULL` [foreign key](#def-b1-relational-model-keys) in `class`; the *–* one the [association table](#def-b1-relational-model-association-table) `attends`, whose [primary key](#def-b1-relational-model-keys) is the pair. The five inserts at the end of the file are refused: a second teacher in office 1 (UNIQUE), a class of teacher 7 ([foreign key](#def-b1-relational-model-keys)), a student attending the same class twice ([primary key](#def-b1-relational-model-keys)), student 3 ([foreign key](#def-b1-relational-model-keys)), a class with no teacher (NOT NULL).

## 29.6 Problem: The library’s missing readers

**Problem 29.1.**

Weekend problem — The library’s missing readers

The question of the opening, “the members who have never borrowed a book of poetry”, written three ways over a [view](#def-b1-relational-model-view) of the poetry loans.

```sql
-- Members who have never borrowed a book of poetry, three ways.
CREATE VIEW poetry_loans AS
  SELECT l.member_id FROM loans AS l JOIN books AS b ON b.book_id = l.book_id
  WHERE b.genre = 'poetry';
SELECT count(*) FROM (
  SELECT member_id FROM members EXCEPT SELECT member_id FROM poetry_loans);
SELECT count(*) FROM members AS m
WHERE NOT EXISTS (SELECT * FROM poetry_loans AS p WHERE p.member_id = m.member_id);
SELECT count(*) FROM members AS m
  LEFT JOIN poetry_loans AS p ON p.member_id = m.member_id
WHERE p.member_id IS NULL;
```

***Listing 29.6.** Three anti-joins code/bachelor-1/29-relational-model/listings/never_borrowed.sql*

```
$ python sqlrun.py never_borrowed.sql
sql> CREATE VIEW poetry_loans AS
...>   SELECT l.member_id FROM loans AS l JOIN books AS b ON b.book_id = l.book_id
...>   WHERE b.genre = 'poetry';
OK

sql> SELECT count(*) FROM (
...>   SELECT member_id FROM members EXCEPT SELECT member_id FROM poetry_loans);
+----------+
| count(*) |
+----------+
| 28       |
+----------+
(1 row)

sql> SELECT count(*) FROM members AS m
...> WHERE NOT EXISTS (SELECT * FROM poetry_loans AS p WHERE p.member_id = m.member_id);
+----------+
| count(*) |
+----------+
| 28       |
+----------+
(1 row)

sql> SELECT count(*) FROM members AS m
...>   LEFT JOIN poetry_loans AS p ON p.member_id = m.member_id
...> WHERE p.member_id IS NULL;
+----------+
| count(*) |
+----------+
| 28       |
+----------+
(1 row)
```

***Output 29.15.** The three counts.*

**Part I — Keys and constraints.**

1. What are the [primary keys](#def-b1-relational-model-keys) of `books` , `members` and `loans` ? Are there other [candidate keys](#def-b1-relational-model-keys) ?
2. Which [foreign keys](#def-b1-relational-model-keys) does `loans` have, and what do they reference?
3. Why is ( `member_id` , `book_id` ) not a key of `loans` ?
4. Which constraint would stop a loan from being returned before it went out?
5. Which column of `loans` may be NULL, and what does NULL mean there?
6. Why does deleting a book that has loans fail in [Output 29.1](#out-b1-relational-model-constraints) ?

**Part II — Algebra.**

7. Write the loans still out in algebra.
8. Write the late returns in algebra. What happens to the loans still out?
9. Write the members who borrowed poetry as an algebra expression, and draw its tree.
10. Push the [selection](#def-b1-relational-model-selection) down, and say which law allows it.
11. Write “never borrowed poetry” with the difference.
12. Why must both sides of the difference be projected on `member_id` ?

**Part III — Three SQL formulations.**

13. Read the `EXCEPT` query as algebra.
14. Read the `NOT EXISTS` query: what is evaluated once per member?
15. Read the `LEFT JOIN` query: what does `p.member_id IS NULL` select?
16. Why would `WHERE p.member_id = NULL` select nothing?
17. Write the fourth formulation with `NOT IN` . When is it wrong?
18. How many members borrowed poetry, and how does that check the answer 28?

**Part IV — Equivalence.**

19. Show that, for $m = \pi_{\text{member\_id}}(\text{members})$ and $p = \pi_{\text{member\_id}}(\text{poetry\_loans})$ , the `EXCEPT` query computes $m - p$ .
20. Show that the `NOT EXISTS` query computes $\{t \in m : \neg \exists u \in p,\ u = t\} = m - p$ .
21. Show that the `LEFT JOIN` query computes $m - p$ : which members get a NULL partner?
22. Why do duplicates in `poetry_loans` (a member borrowing two poetry books) not change any of the three?
23. Why can `p.member_id` be NULL in the left join only through padding?
24. When does `NOT IN` differ from the other three?
25. State the named result, *the three anti-joins are equivalent* , with the count they print.

**Solution of Problem 29.1.**

**1.** `book_id`, `member_id`, `loan_id`. `members.person_id` could be a second key of `members`, if a person may join only once; the town’s schema does not say so.

**2.** `book_id` references `books` and `member_id` references `members`.

**3.** A member may borrow the same book twice; it happens 12 times in the town.

**4.** `CHECK (return_date IS NULL OR return_date >= out_date)`, as in [Listing 29.1](#lst-b1-relational-model-schema).

**5.** `return_date`: NULL means the book has not come back.

**6.** Loan 1 references book 100; deleting the book would break [referential integrity](#def-b1-relational-model-integrity).

**7.** $\sigma_{\text{return\_date IS NULL}}(\text{loans})$, the condition read with `IS NULL`.

**8.** $\sigma_{\text{return\_date} > \text{due\_date}}(\text{loans})$. For a loan still out the condition is unknown and the loan is left out, even if its due date has passed: lateness of those loans needs today’s date.

**9.** $\pi_{\text{member\_id}}(\sigma_{\text{genre} = \text{poetry}}(\text{loans} \bowtie \text{books}))$, the left tree of the figure in [Section 29.2](#sec-29-2).

**10.** $\pi_{\text{member\_id}}(\text{loans} \bowtie \sigma_{\text{genre} = \text{poetry}}(\text{books}))$, by [Proposition 29.10](#prop-b1-relational-model-pushdown) (iii), the condition mentioning only [attributes](#def-b1-relational-model-schema) of `books`.

**11.** $\pi_{\text{member\_id}}(\text{members}) - \pi_{\text{member\_id}}(\sigma_{\text{genre} =
\text{poetry}}(\text{loans} \bowtie \text{books}))$.

**12.** The difference is defined for [relations](#def-b1-relational-model-relation) over the same [attributes](#def-b1-relational-model-schema).

**13.** It is $m - p$ with the [projections](#def-b1-relational-model-selection) of question 11, `EXCEPT` being the difference of sets.

**14.** The subquery: it mentions `m.member_id`, so it is evaluated, at least in principle, once per member.

**15.** The members padded with NULL: those with no poetry loan.

**16.** `= NULL` is unknown on every row; only `IS NULL` tests for the marker.

**17.** `WHERE member_id NOT IN (SELECT member_id FROM poetry_loans)`. It is wrong if the subquery may contain NULL; here `loans.member_id` is never NULL, so it also prints 28.

**18.** [Output 29.4](#out-b1-relational-model-laws) counts 32 poetry readers; $32 + 28 = 60$, all the members.

**19.** `EXCEPT` returns the set of the rows of the first answer that are not rows of the second: $m - p$.

**20.** The inner query is empty iff no $u \in p$ equals $t$, the comparison being true or false, never unknown, since neither side is NULL. So the outer [tuple](#def-b1-relational-model-relation) is kept iff $t \notin p$.

**21.** A member $t$ with partners in $p$ gives one row per partner, each with a non-NULL `p.member_id`, all removed by the `WHERE`; a member with none gives one padded row, kept. The kept rows are those of $m - p$, once each.

**22.** `EXCEPT` works on sets; `NOT EXISTS` only tests emptiness; the left join multiplies only members that are then removed.

**23.** `loans.member_id` is never NULL and is the join attribute, so a NULL in the result can only come from padding.

**24.** When the subquery’s answer contains NULL: then `NOT IN` is never true, as in [Exercise 29.6](#exo-b1-relational-model-6).

**25.** *The three anti-joins are equivalent*: `EXCEPT`, `NOT EXISTS` and `LEFT JOIN ... IS NULL` all compute $m - p$ (questions 19–21), and `NOT IN` does too as long as the subquery has no NULL. All three print 28.
