এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 is a name and a finite set of attributes , each with a domain , the set of values it may take.
Definition 29.2 (Tuple, relation)
A tuple over the schema gives each attribute a value in . A relation over the schema (an instance) is a finite set of tuples: a subset of , 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 is a set of attributes whose values must appear as the primary key of some tuple of another relation : it references .
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)
);
$ 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
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)
foreign_key_check finds it afterwards.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.
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 over attributes : the selection is the set of tuples of that satisfy the condition ; the projection , for , is the set of the restrictions of the tuples of to ; the renaming is with the attribute called .
The set operations and apply to relations over the same attributes.
Definition 29.8 (Cartesian product, natural join, theta join, left outer join)
For over and over : the Cartesian product , for disjoint and , is the set of the tuples , , . The natural join is the set of the tuples over with and : the pairs that agree on the common attributes, each kept once. A theta join is . The left outer join keeps, in addition, each tuple of that matches nothing, its attributes from set to NULL.
The natural join is a product followed by a selection and a projection, and the intersection is : six operators, , , , , and , are enough for the rest. The next one is the algebra’s “for all”.
Definition 29.9 (Division)
For over and over , with and disjoint, the division is the set of the tuples over such that for every . It equals : 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)
# 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)
$ 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]
An algebra has laws. Two of them are the basis of every query optimiser.
Proposition 29.10 (Selection laws)
For relations over , over , and conditions : (i) ; (ii) ; (iii) if mentions only attributes of , then .
Proof. (i) Both sides are the tuples of satisfying and . (ii) A tuple is on the left iff it is in or and satisfies , which is the right. (iii) Let be over . is on the left iff , and satisfies . Since mentions only , satisfies iff does; so the condition reads and , 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
$ 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
29.3 SQL read as algebra
A query SELECT $A_1$, ..., $A_k$ FROM $r_1$, ..., $r_m$ WHERE $c$ is read
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)
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)
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)
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 , and unknown, , ordered , with , , , and , . Any comparison with NULL is .
On 0 and 1 these are the valuations of Chapter 10; the law of the excluded middle fails, since .
$ 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)
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)
Definition 29.12 (Aggregation operator)
The aggregation operator groups the tuples of by their values on the attributes and gives one tuple per group: the values of and applied to the multiset of the values of in the group, being count, sum, avg, min or max.
GROUP BY is ; 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)
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)
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)
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.
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 holds , , , . Compute and .
Solution
Solution of Exercise 29.1.
keeps Ana, Bo and Cy, so the first answer is , two tuples, the duplicate Lyon merged. The second is . The two expressions differ because the second projects on 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 ★
and . Give and the left outer join of with .
Solution
Solution of Exercise 29.2.
over . The left outer join adds and ; matches nothing and, being the right side, disappears.
Exercise 29.3 ★
With NULL and , give the truth value of , , , and x IS NULL. Which rows does WHERE keep?
Solution
Solution of Exercise 29.3.
is ; is ; is ; is ; 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()
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);
$ 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)
Solution
Solution of Exercise 29.6.
The subquery’s answer contains NULL, the return dates of the 22 loans still out. For a date that is no return date, d NOT IN (...) is , that is : 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 , 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 , 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"))
The late loans are , and the answer is
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)
for each author . 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 attributes and a single candidate key of attributes. How many superkeys does it have? How many if it has two disjoint candidate keys of and attributes?
Solution
Solution of Exercise 29.9.
A superkey is a set of attributes containing the key; the other attributes may be added or not: . With two disjoint keys and , the superkeys contain or ; by inclusion–exclusion there are . The program superkeys.py checks the first count by brute force for .
Exercise 29.10 ★★★
Does Proposition 29.10 (iii) hold for the left outer join of with when mentions only attributes of ? When it mentions only attributes of ? Prove it or give a counterexample.
Solution
Solution of Exercise 29.10.
When mentions only attributes of , yes. Each tuple of the left outer join comes from one tuple of , joined or padded, and whether it satisfies depends on alone; so selecting before or after keeps the same tuples of , with the same partners. When mentions only attributes of , no. Take over , over , and : . The left outer join is , and of it is empty; but is empty and the left outer join of with it is . 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 over and over , is the set of tuples over with and ; the definition is symmetric in and , and attributes are named, not ordered: . For over , over is in iff and , iff , and , since . The same steps give the same condition for .
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 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;
$ 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)
Part I — Keys and constraints.
- What are the primary keys of
books,membersandloans? Are there other candidate keys? - Which foreign keys does
loanshave, and what do they reference? - Why is (
member_id,book_id) not a key ofloans? - Which constraint would stop a loan from being returned before it went out?
- Which column of
loansmay be NULL, and what does NULL mean there? - Why does deleting a book that has loans fail in Output 29.1?
Part II — Algebra.
- Write the loans still out in algebra.
- Write the late returns in algebra. What happens to the loans still out?
- Write the members who borrowed poetry as an algebra expression, and draw its tree.
- Push the selection down, and say which law allows it.
- Write “never borrowed poetry” with the difference.
- Why must both sides of the difference be projected on
member_id?
Part III — Three SQL formulations.
- Read the
EXCEPTquery as algebra. - Read the
NOT EXISTSquery: what is evaluated once per member? - Read the
LEFT JOINquery: what doesp.member_id IS NULLselect? - Why would
WHERE p.member_id = NULLselect nothing? - Write the fourth formulation with
NOT IN. When is it wrong? - How many members borrowed poetry, and how does that check the answer 28?
Part IV — Equivalence.
- Show that, for and , the
EXCEPTquery computes . - Show that the
NOT EXISTSquery computes . - Show that the
LEFT JOINquery computes : which members get a NULL partner? - Why do duplicates in
poetry_loans(a member borrowing two poetry books) not change any of the three? - Why can
p.member_idbe NULL in the left join only through padding? - When does
NOT INdiffer from the other three? - 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. , the condition read with IS NULL.
8. . 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. , the left tree of the figure in Section 29.2.
10. , by Proposition 29.10 (iii), the condition mentioning only attributes of books.
11. .
12. The difference is defined for relations over the same attributes.
13. It is 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; , all the members.
19. EXCEPT returns the set of the rows of the first answer that are not rows of the second: .
20. The inner query is empty iff no equals , the comparison being true or false, never unknown, since neither side is NULL. So the outer tuple is kept iff .
21. A member with partners in 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 , 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 (questions 19–21), and NOT IN does too as long as the subquery has no NULL. All three print 28.
এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ
- Aggregation operator
- Association table
- Cartesian product, natural join, theta join, left outer join
- Division
- Entity, relationship, multiplicity, entity–relationship model
- Integrity constraint, referential integrity
- Null marker
- Relation schema, attribute, domain
- Relational algebra
- Selection, projection, renaming
- Superkey, candidate key, primary key, foreign key
- Three-valued logic
- Tuple, relation
- View