কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ

29The 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, 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 between sets is a subset of their Cartesian product (mathematics book, Year 1). The second book used the town’s tables in SQLite with SELECT, joins and keys; valuations of formulas are in Definition 10.3. 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(A1,…,An)R(A_1, \dots, A_n) is a name and a finite set of attributes A1,…,AnA_1, \dots, A_n, each with a domain DiD_i, the set of values it may take.

Definition 29.2 (Tuple, relation)

A tuple over the schema gives each attribute AiA_i a value in DiD_i. A relation over the schema (an instance) is a finite set of tuples: a subset of D1×⋯×DnD_1 \times \dots \times D_n, the attributes naming the positions.

A relation is a set: its tuples 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 on which no two tuples 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. A foreign key of RR is a set of attributes whose values must appear as the primary key of some tuple of another relation SS: it references SS.

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. Referential integrity is the constraint that every foreign key value appears in the relation it references.

Definition 29.5 (Null marker)

The null marker NULL stands in a tuple for a value that is missing or unknown. It is not a value of the domain: it equals nothing, not even itself.

The library’s own schema, designed in Section 29.4, writes each of these in SQL’s data definition language: PRIMARY KEY, UNIQUE (another candidate key), REFERENCES (a foreign key), NOT NULL and CHECK.

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 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.
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.
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.
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.

29.2 Relational algebra

Definition 29.6 (Relational algebra)

Relational algebra is the set of operators that take relations and return a relation, and of the expressions built from them and from named relations. A query is an expression.

Definition 29.7 (Selection, projection, renaming)

For a relation rr over attributes UU: the selection σc(r)\sigma_c(r) is the set of tuples of rr that satisfy the condition cc; the projection πX(r)\pi_X(r), for X⊆UX \subseteq U, is the set of the restrictions t[X]t[X] of the tuples of rr to XX; the renaming ρB←A(r)\rho_{B \leftarrow A}(r) is rr with the attribute AA called BB.

The set operations r∪sr \cup s and r−sr - s apply to relations over the same attributes.

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

For rr over UU and ss over VV: the Cartesian product r×sr \times s, for disjoint UU and VV, is the set of the tuples t∪ut \cup u, t∈rt \in r, u∈su \in s. The natural join r⋈sr \bowtie s is the set of the tuples ww over U∪VU \cup V with w[U]∈rw[U] \in r and w[V]∈sw[V] \in s: the pairs that agree on the common attributes, each kept once. A theta join is r⋈cs=σc(r×s)r \bowtie_c s = \sigma_c(r \times s). The left outer join keeps, in addition, each tuple of rr that matches nothing, its attributes from V−UV - U set to NULL.

The natural join is a product followed by a selection and a projection, and the intersection is r∩s=r−(r−s)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 rr over X∪YX \cup Y and ss over YY, with XX and YY disjoint, the division r÷sr \div s is the set of the tuples xx over XX such that x∪y∈rx \cup y \in r for every y∈sy \in s. It equals πX(r)−πX((πX(r)×s)−r)\pi_X(r) - \pi_X\big((\pi_X(r) \times s) - r\big): the candidates, minus those missing some pair.

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 on Python sets: each operator as its definition code/bachelor-1/29-relational-model/listings/algebra.py
# 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 r,r′r, r' over UU, ss over VV, and conditions c,c′c, c': (i) σc(σc′(r))=σc∧c′(r)\sigma_c(\sigma_{c'}(r)) = \sigma_{c \wedge c'}(r); (ii) σc(r∪r′)=σc(r)∪σc(r′)\sigma_c(r \cup r') = \sigma_c(r) \cup \sigma_c(r'); (iii) if cc mentions only attributes of UU, then σc(r⋈s)=σc(r)⋈s\sigma_c(r \bowtie s) = \sigma_c(r) \bowtie s.

Proof. (i) Both sides are the tuples of rr satisfying cc and c′c'. (ii) A tuple is on the left iff it is in rr or r′r' and satisfies cc, which is the right. (iii) Let ww be over U∪VU \cup V. ww is on the left iff w[U]∈rw[U] \in r, w[V]∈sw[V] \in s and ww satisfies cc. Since cc mentions only UU, ww satisfies cc iff w[U]w[U] does; so the condition reads w[U]∈σc(r)w[U] \in \sigma_c(r) and w[V]∈sw[V] \in s, the definition of the right side. ∎

The natural join is also commutative and associative (Exercise 29.11), so a query engine may reorder joins. Pushing a selection below a join is what makes the reordering pay.

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 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 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.
The members who borrowed poetry, as two algebra trees evaluated from the leaves up. By Proposition 29.10 (iii) they are equal; the right one handles far fewer tuples.

29.3 SQL read as algebra

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

πA1,…,Ak(σc(r1×⋯×rm)),\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 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 and projection; the projection 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, and LEFT JOIN the left outer join. The ON condition decides which pairs match; a WHERE condition then filters the result, padded tuples 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.
The left join of Output 29.7, 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.

NULL forces a third truth value. A comparison with NULL is neither true nor false but unknown, and WHERE keeps a tuple only when its condition is true.

Definition 29.11 (Three-valued logic)

Three-valued logic has the truth values 00, 11 and unknown, uu, ordered 0<u<10 < u < 1, with x∧y=min⁡(x,y)x \wedge y = \min(x, y), x∨y=max⁡(x,y)x \vee y = \max(x, y), ¬u=u\neg u = u, and ¬0=1\neg 0 = 1, ¬1=0\neg 1 = 0. Any comparison with NULL is uu.

On 0 and 1 these are the valuations of Chapter 10; the law of the excluded middle fails, since u∨¬u=uu \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 in SQLite, which prints uu 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 γG;f(A)(r)\gamma_{G; f(A)}(r) groups the tuples of rr by their values on the attributes GG and gives one tuple per group: the values of GG and ff applied to the multiset of the values of AA in the group, ff being count, sum, avg, min or max.

GROUP BY is γ\gamma; WHERE selects tuples 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, so it is evaluated once per outer tuple, 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 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 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, one set of which identifies each thing. A relationship associates entities, possibly with attributes 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.

Definition 29.15 (Association table)

An association table represents a many-to-many relationship: one tuple per pair of associated entities, with a foreign key to each side and the relationship’s own attributes.

The translation follows rules. Each entity becomes a table, its identifier the primary key. A 1–* relationship becomes a foreign key on the “many” side; a 1–1 relationship, a foreign key that is also UNIQUE; a *–* relationship, an association table, which splits it into two 1–* relationships.

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.
The library as an entity–relationship diagram, and its translation into the four tables of Listing 29.1: the 1–1 relationship becomes a UNIQUE foreign key, the *–* one the 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 and to query them by operations on relations, leaving to the system the question of how the data are stored on disk. The databases of the time made programs follow pointers from record to record, and changing the storage meant rewriting the programs. Peter Chen’s entity–relationship model followed in 1976. Relational systems and SQL came to dominate databases within two decades.

29.5 Exercises

Exercise 29.1 ★

A relation r(name,city,age)r(\text{name}, \text{city}, \text{age}) holds (Ana,Lyon,31)(\text{Ana}, \text{Lyon}, 31), (Bo,Oslo,25)(\text{Bo}, \text{Oslo}, 25), (Cy,Lyon,25)(\text{Cy}, \text{Lyon}, 25), (Di,Oslo,40)(\text{Di}, \text{Oslo}, 40). Compute πcity(σage<35(r))\pi_{\text{city}}(\sigma_{\text{age} < 35}(r)) and σage<35(πcity,age(r))\sigma_{\text{age} < 35}(\pi_{\text{city}, \text{age}}(r)).

Solution

Solution of Exercise 29.1.

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

Exercise 29.2 ★

a(x,y)={(1,p),(2,q),(3,r)}a(x, y) = \{(1, p), (2, q), (3, r)\} and b(y,z)={(p,10),(p,20),(s,30)}b(y, z) = \{(p, 10), (p, 20), (s, 30)\}. Give a⋈ba \bowtie b and the left outer join of aa with bb.

Solution

Solution of Exercise 29.2.

a⋈b={(1,p,10),(1,p,20)}a \bowtie b = \{(1, p, 10), (1, p, 20)\} over (x,y,z)(x, y, z). The left outer join adds (2,q,NULL)(2, q, \text{NULL}) and (3,r,NULL)(3, r, \text{NULL}); (s,30)(s, 30) matches nothing and, bb being the right side, disappears.

Exercise 29.3 ★

With x=x = NULL and y=3y = 3, give the truth value of x=3x = 3, y=3∨x=3y = 3 \vee x = 3, y=4∧x=3y = 4 \wedge x = 3, ¬(x=3)\neg(x = 3) and x IS NULL. Which rows does WHERE keep?

Solution

Solution of Exercise 29.3.

x=3x = 3 is uu; y=3∨x=3y = 3 \vee x = 3 is max⁡(1,u)=1\max(1, u) = 1; y=4∧x=3y = 4 \wedge x = 3 is min⁡(0,u)=0\min(0, u) = 0; ¬(x=3)\neg(x = 3) is uu; 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, what does SELECT genre FROM books GROUP BY genre HAVING avg(pages) > 280 print?

Solution

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

Solution of Exercise 29.5.

WHERE selects tuples 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).

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.

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

Solution of Exercise 29.6.

The subquery’s answer contains NULL, the return dates of the 22 loans still out. For a date dd that is no return date, d NOT IN (...) is ¬(d=v1∨⋯∨d=NULL)\neg(d = v_1 \vee \dots \vee d = \text{NULL}), that is ¬(0∨⋯∨u)=¬u=u\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 uu, 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 with γ\gamma, and check that the answers agree.

Solution

Solution of Exercise 29.7.

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 ℓ=σreturn_date>due_date(loans)\ell = \sigma_{\text{return\_date} > \text{due\_date}}(\text{loans}), and the answer is

σlate>3(γmember_id; count(loan_id)→late(ℓ)).\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.

Solution

Solution of Exercise 29.8.

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 per author code/bachelor-1/29-relational-model/exercises/division.py

πmember_id,book_id(loans)÷πbook_id(σauthor=a(books))\pi_{\text{member\_id}, \text{book\_id}}(\text{loans}) \div \pi_{\text{book\_id}}(\sigma_{\text{author} = a}(\text{books})) for each author aa. 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 nn attributes and a single candidate key of kk attributes. How many superkeys does it have? How many if it has two disjoint candidate keys of kk and ll attributes?

Solution

Solution of Exercise 29.9.

A superkey is a set of attributes containing the key; the other n−kn - k attributes may be added or not: 2n−k2^{n - k}. With two disjoint keys KK and LL, the superkeys contain KK or LL; by inclusion–exclusion there are 2n−k+2n−l−2n−k−l2^{n - k} + 2^{n - l} - 2^{n - k - l}. The program superkeys.py checks the first count by brute force for n≤6n \leq 6.

Exercise 29.10 ★★★

Does Proposition 29.10 (iii) hold for the left outer join of rr with ss when cc mentions only attributes of rr? When it mentions only attributes of ss? Prove it or give a counterexample.

Solution

Solution of Exercise 29.10.

When cc mentions only attributes of rr, yes. Each tuple of the left outer join comes from one tuple tt of rr, joined or padded, and whether it satisfies cc depends on tt alone; so selecting before or after keeps the same tuples of rr, with the same partners. When cc mentions only attributes of ss, no. Take r={(1)}r = \{(1)\} over (x)(x), s={(1,5)}s = \{(1, 5)\} over (x,y)(x, y), and cc: y>9y > 9. The left outer join is {(1,5)}\{(1, 5)\}, and σc\sigma_c of it is empty; but σc(s)\sigma_c(s) is empty and the left outer join of rr with it is {(1,NULL)}\{(1, \text{NULL})\}. This is the ON versus WHERE difference of Section 29.3.

Exercise 29.11 ★★★

Prove that the natural join is commutative and associative.

Solution

Solution of Exercise 29.11.

With rr over UU and ss over VV, r⋈sr \bowtie s is the set of tuples ww over U∪VU \cup V with w[U]∈rw[U] \in r and w[V]∈sw[V] \in s; the definition is symmetric in rr and ss, and attributes are named, not ordered: r⋈s=s⋈rr \bowtie s = s \bowtie r. For tt over WW, ww over U∪V∪WU \cup V \cup W is in (r⋈s)⋈t(r \bowtie s) \bowtie t iff w[U∪V]∈r⋈sw[U \cup V] \in r \bowtie s and w[W]∈tw[W] \in t, iff w[U]∈rw[U] \in r, w[V]∈sw[V] \in s and w[W]∈tw[W] \in t, since w[U∪V][U]=w[U]w[U \cup V][U] = w[U]. The same steps give the same condition for r⋈(s⋈t)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

Solution of Exercise 29.12.

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 is a UNIQUE NOT NULL foreign key in teacher; the 1–* one a NOT NULL foreign key in class; the *–* one the association table attends, whose primary key 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), a student attending the same class twice (primary key), student 3 (foreign key), 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 of the poetry loans.

-- 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 of books, members and loans? Are there other candidate keys?
  2. Which foreign 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?

Part II — Algebra.

  1. Write the loans still out in algebra.
  2. Write the late returns in algebra. What happens to the loans still out?
  3. Write the members who borrowed poetry as an algebra expression, and draw its tree.
  4. Push the selection down, and say which law allows it.
  5. Write “never borrowed poetry” with the difference.
  6. Why must both sides of the difference be projected on member_id?

Part III — Three SQL formulations.

  1. Read the EXCEPT query as algebra.
  2. Read the NOT EXISTS query: what is evaluated once per member?
  3. Read the LEFT JOIN query: what does p.member_id IS NULL select?
  4. Why would WHERE p.member_id = NULL select nothing?
  5. Write the fourth formulation with NOT IN. When is it wrong?
  6. How many members borrowed poetry, and how does that check the answer 28?

Part IV — Equivalence.

  1. Show that, for m=πmember_id(members)m = \pi_{\text{member\_id}}(\text{members}) and p=πmember_id(poetry_loans)p = \pi_{\text{member\_id}}(\text{poetry\_loans}), the EXCEPT query computes m−pm - p.
  2. Show that the NOT EXISTS query computes {t∈m:¬∃u∈p, u=t}=m−p\{t \in m : \neg \exists u \in p,\ u = t\} = m - p.
  3. Show that the LEFT JOIN query computes m−pm - p: which members get a NULL partner?
  4. Why do duplicates in poetry_loans (a member borrowing two poetry books) not change any of the three?
  5. Why can p.member_id be NULL in the left join only through padding?
  6. When does NOT IN differ from the other three?
  7. State the named result, the three anti-joins are equivalent, with the count they print.
Solution

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.

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

6. Loan 1 references book 100; deleting the book would break referential integrity.

7. σreturn_date IS NULL(loans)\sigma_{\text{return\_date IS NULL}}(\text{loans}), the condition read with IS NULL.

8. σreturn_date>due_date(loans)\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. πmember_id(σgenre=poetry(loans⋈books))\pi_{\text{member\_id}}(\sigma_{\text{genre} = \text{poetry}}(\text{loans} \bowtie \text{books})), the left tree of the figure in Section 29.2.

10. πmember_id(loans⋈σgenre=poetry(books))\pi_{\text{member\_id}}(\text{loans} \bowtie \sigma_{\text{genre} = \text{poetry}}(\text{books})), by Proposition 29.10 (iii), the condition mentioning only attributes of books.

11. πmember_id(members)−πmember_id(σgenre=poetry(loans⋈books))\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 over the same attributes.

13. It is m−pm - p with the projections 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 counts 32 poetry readers; 32+28=6032 + 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−pm - p.

20. The inner query is empty iff no u∈pu \in p equals tt, the comparison being true or false, never unknown, since neither side is NULL. So the outer tuple is kept iff t∉pt \notin p.

21. A member tt with partners in pp 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−pm - 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.

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

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো