Este livro ainda não está disponível em Português. Edições: English.
University Computer Science — Year 2 · Graduação — Ano 2
30Database Design: Dependencies, Normal Forms and Transactions
For years the library kept its loans in one spreadsheet: one line per loan, with the book’s title and author, the member’s name and street, everything a librarian might want to read on the line. Built as a table from the town’s database, it looks like this, and it shows what happens when member 55 moves house:
-- load: wide_build.sql
SELECT count(*) AS lines, count(DISTINCT member_id) AS members,
count(DISTINCT book_id) AS books FROM wide;
SELECT street, postcode, count(*) AS lines FROM wide
WHERE member_id = 55 GROUP BY street, postcode;
UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'
WHERE member_id = 55
AND loan_id < (SELECT max(loan_id) FROM wide WHERE member_id = 55);
SELECT street, postcode, count(*) AS lines FROM wide
WHERE member_id = 55 GROUP BY street, postcode;
$ python sqlrun.py wide_table.sql
sql> SELECT count(*) AS lines, count(DISTINCT member_id) AS members,
...> count(DISTINCT book_id) AS books FROM wide;
+-------+---------+-------+
| lines | members | books |
+-------+---------+-------+
| 400 | 60 | 80 |
+-------+---------+-------+
(1 row)
sql> SELECT street, postcode, count(*) AS lines FROM wide
...> WHERE member_id = 55 GROUP BY street, postcode;
+--------------+----------+-------+
| street | postcode | lines |
+--------------+----------+-------+
| River Avenue | B-120 | 12 |
+--------------+----------+-------+
(1 row)
sql> UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'
...> WHERE member_id = 55
...> AND loan_id < (SELECT max(loan_id) FROM wide WHERE member_id = 55);
OK (11 rows changed)
sql> SELECT street, postcode, count(*) AS lines FROM wide
...> WHERE member_id = 55 GROUP BY street, postcode;
+--------------+----------+-------+
| street | postcode | lines |
+--------------+----------+-------+
| Garden Lane | B-110 | 11 |
| River Avenue | B-120 | 1 |
+--------------+----------+-------+
(2 rows)
The listing loads wide_build.sql, which builds the table by joining loans, books, members, people and streets. Nothing in the table says that a member has one street: the fact is written twelve times, and the twelve copies can disagree. This chapter makes the intuition precise. Dependencies say which facts determine which; normal forms say when a table stores each fact once; decompositions split a table without losing anything. The second half turns to the other way a database goes wrong, two programs changing it at the same moment, and ends with the index that makes a search fast.
You already know
The Year 1 volume: relations, attributes, keys, candidate and primary keys, foreign keys, relational algebra and its natural join, SQL queries, entity–relationship modelling. The grade 12 volume: the anomalies of a badly designed table, seen on examples.
30.1 Functional dependencies
Definition 30.1 (Functional dependency, trivial dependency)
Let be a set of attributes and . A table over satisfies the functional dependency if any two rows that agree on every attribute of also agree on every attribute of . The dependency is trivial if ; it is then satisfied by every table.
A dependency is a rule about the world the table describes, not an observation about today’s rows. The library’s rules are that a loan determines its book, its member and its dates; a book determines its title, author, genre and pages; a member determines the name and the street; a street determines its postcode. The 400 lines satisfy other dependencies by accident: no two books have the same title yet, so title book holds in the data, but nothing forbids two books called the same (Exercise 30.9).
From some dependencies others follow: if a member determines the street and a street the postcode, a member determines the postcode.
Definition 30.2 (Implication, Armstrong’s axioms)
A set of dependencies over implies , written , if every table over that satisfies all of satisfies . Armstrong’s axioms are three rules to derive dependencies, written : reflexivity, whenever ; augmentation, from derive ; transitivity, from and derive . (We write for .)
The union rule, from and derive , and the decomposition rule, from derive , follow from the three (Exercise 30.8).
Definition 30.3 (Attribute closure)
The attribute closure of under is , the set of attributes that determines.
Theorem 30.4 (Armstrong’s axioms are sound and complete)
For every , and : if and only if .
Proof. Soundness: each rule turns satisfied dependencies into a satisfied one. Reflexivity: two rows that agree on agree on its subset . Augmentation: two rows that agree on agree on , hence on , and on . Transitivity: two rows that agree on agree on , hence on . By induction on the length of a derivation, every derived dependency holds in every table satisfying .
Completeness: suppose , and let ; by reflexivity . Build a table of two rows over : both rows are on ; outside , the first is and the second . It satisfies every of : if the rows agree on , then , so by the union rule, then by transitivity, so by decomposition and the rows agree on . The table therefore satisfies ; its rows agree on , so they agree on , and . By the union rule, . ∎
So the closure can be computed by derivation instead of by imagining every table, and there is a simple algorithm:
def closure(xs, deps):
"""X+: every attribute that X determines under deps."""
result, changed = set(xs), True
while changed:
changed = False
for left, right in deps:
if left <= result and not right <= result:
result |= right # X determines left, hence right
changed = True
return frozenset(result)
Proposition 30.5 (The closure algorithm)
The function closure returns , after at most passes over , so in time .
Proof. Exercise 30.11: every attribute added is derivable, and when the loop stops the set is closed under , which forces it to contain . Each pass but the last adds the right side of at least one dependency not used before. ∎
Corollary 30.6 (A test for keys)
is a superkey of under exactly when ; it is a candidate key when moreover for every .
Proof. is a superkey when it determines every attribute, that is , that is . A candidate key is a superkey with no proper subset that is one; since a superset of a superkey is a superkey, it suffices to remove one attribute at a time. ∎
Definition 30.7 (Minimal cover)
A minimal cover of is a set of dependencies equivalent to (each implies every dependency of the other) in which every right side is a single attribute, no attribute can be removed from a left side, and no dependency can be removed, without losing the equivalence.
def keys(attrs, deps):
"""The candidate keys: the minimal sets whose closure is every attribute."""
attrs = frozenset(attrs)
found = []
for size in range(len(attrs) + 1):
for xs in combinations(sorted(attrs), size):
xs = frozenset(xs)
if not any(k <= xs for k in found) and closure(xs, deps) >= attrs:
found.append(xs)
return found
def minimal_cover(deps):
"""An equivalent set with one attribute on each right side, no extraneous
attribute on a left side, and no redundant dependency."""
out = [(left, frozenset([a])) for left, right in deps for a in sorted(right)]
for i, (left, right) in enumerate(out):
for a in sorted(left):
if len(left) > 1 and right <= closure(left - {a}, out):
left = left - {a} # a is extraneous on the left
out[i] = (left, right)
out = list(dict.fromkeys(out))
for d in list(out):
rest = [e for e in out if e != d]
if implies(rest, *d):
out = rest
return out
WIDE = ("loan out due ret book title author genre pages member first last street"
" postcode").split()
RULES = fds("loan -> book member out due ret; book -> title author genre pages;"
" member -> first last street; street -> postcode")
$ python fd_demo.py
closure of {member}: {member, first, last, street, postcode}
closure of {book}: {book, title, author, genre, pages}
candidate keys: ['{loan}']
minimal cover: 13 dependencies, one attribute on each right side
in 3NF: False
BCNF table {book, title, author, genre, pages} key {book}
BCNF table {street, postcode} key {street}
BCNF table {member, first, last, street} key {member}
BCNF table {loan, out, due, ret, book, member} key {loan}
lossless: True | preserves the dependencies: True
The key search tries the subsets in increasing size, skipping supersets of keys already found: exponential in general, fast here, where one attribute suffices. The wide table’s only candidate key is the loan.
30.2 Normal forms
Definition 30.8 (Update, insertion and deletion anomaly)
A table has an update anomaly when one fact is stored on several rows, so that changing it means changing them all; an insertion anomaly when a fact cannot be recorded without an unrelated one, as a member without a loan; a deletion anomaly when removing a row removes an unrelated fact with it, as the last loan of a book removes the book.
All three come from a dependency whose left side is not a key: book title makes the title a fact about the book, stored once per loan of that book.
Definition 30.9 (Third normal form, Boyce–Codd normal form)
Let hold on . is in Boyce–Codd normal form (BCNF) if for every non-trivial implied by with , is a superkey of . It is in third normal form (3NF) if for every such dependency, is a superkey or belongs to some candidate key of .
BCNF says that every fact the table records is a fact about a key; 3NF tolerates one exception, attributes that are part of a key. The wide table is in neither: book, member and street determine other attributes and are not keys.
30.3 Decomposition
Definition 30.10 (Decomposition, lossless join, dependency preservation)
A decomposition of is a list of attribute sets whose union is ; a table over is stored as its projections . The decomposition is lossless for if for every satisfying ; it preserves the dependencies if the dependencies of that hold inside the parts imply all of .
The join of the projections always contains ; a lossy decomposition adds rows that were never there. Preservation matters for checking: a dependency that holds inside a part is enforced by that part’s key, while one that spans two parts can be checked only by a join.
Theorem 30.11 (Heath’s theorem)
Let with disjoint. If a table over satisfies , it is the join of its projections on and .
Proof. Exercise 30.10. ∎
def bcnf_violation(r, deps):
"""A dependency X -> Y that holds in r with X not a superkey of r, or None."""
r = frozenset(r)
for xs in subsets(r):
c = closure(xs, deps) & r
if c != xs and c != r:
return xs, c - xs
return None
def bcnf(r, deps):
"""Split r on a violating X -> Y into XY and r - Y, until no part has one."""
v = bcnf_violation(r, deps)
if v is None:
return [frozenset(r)]
xs, ys = v
return bcnf(xs | ys, deps) + bcnf(frozenset(r) - ys, deps)
Theorem 30.12 (BCNF decomposition)
The function bcnf stops, returns parts that are all in BCNF, and the decomposition is lossless.
Proof. A split of on a violation , with non-empty and , produces and , both strictly smaller than : the recursion stops. A part is returned only when it has no violation, so it is in BCNF. Each split is lossless by Heath’s theorem with , since holds. By induction on the recursion, if is replaced by a lossless decomposition of it, the whole stays lossless, because a table satisfying projects onto as a table that satisfies the dependencies of that hold there, and the natural join is associative. ∎
The SQL counterpart builds the four tables from the wide one and joins them back:
-- load: wide_build.sql
CREATE TABLE d_loans AS
SELECT DISTINCT loan_id, out_date, due_date, return_date, book_id, member_id FROM wide;
CREATE TABLE d_books AS SELECT DISTINCT book_id, title, author, genre, pages FROM wide;
CREATE TABLE d_members AS
SELECT DISTINCT member_id, first_name, last_name, street FROM wide;
CREATE TABLE d_streets AS SELECT DISTINCT street, postcode FROM wide;
SELECT (SELECT count(*) FROM d_loans) AS loans,
(SELECT count(*) FROM d_books) AS books,
(SELECT count(*) FROM d_members) AS members,
(SELECT count(*) FROM d_streets) AS streets,
(SELECT count(DISTINCT member_id) FROM d_members) AS member_ids,
(SELECT count(DISTINCT street) FROM d_streets) AS street_names;
CREATE VIEW joined AS
SELECT l.loan_id, l.out_date, l.due_date, l.return_date,
b.book_id, b.title, b.author, b.genre, b.pages,
m.member_id, m.first_name, m.last_name, s.street, s.postcode
FROM d_loans AS l NATURAL JOIN d_books AS b
NATURAL JOIN d_members AS m NATURAL JOIN d_streets AS s;
SELECT (SELECT count(*) FROM (SELECT * FROM wide EXCEPT SELECT * FROM joined))
AS lost,
(SELECT count(*) FROM (SELECT * FROM joined EXCEPT SELECT * FROM wide))
AS invented;
$ python sqlrun.py decomposed.sql
sql> CREATE TABLE d_loans AS
...> SELECT DISTINCT loan_id, out_date, due_date, return_date, book_id, member_id FROM wide;
OK
sql> CREATE TABLE d_books AS SELECT DISTINCT book_id, title, author, genre, pages FROM wide;
OK
sql> CREATE TABLE d_members AS
...> SELECT DISTINCT member_id, first_name, last_name, street FROM wide;
OK
sql> CREATE TABLE d_streets AS SELECT DISTINCT street, postcode FROM wide;
OK
sql> SELECT (SELECT count(*) FROM d_loans) AS loans,
...> (SELECT count(*) FROM d_books) AS books,
...> (SELECT count(*) FROM d_members) AS members,
...> (SELECT count(*) FROM d_streets) AS streets,
...> (SELECT count(DISTINCT member_id) FROM d_members) AS member_ids,
...> (SELECT count(DISTINCT street) FROM d_streets) AS street_names;
+-------+-------+---------+---------+------------+--------------+
| loans | books | members | streets | member_ids | street_names |
+-------+-------+---------+---------+------------+--------------+
| 400 | 80 | 60 | 23 | 60 | 23 |
+-------+-------+---------+---------+------------+--------------+
(1 row)
sql> CREATE VIEW joined AS
...> SELECT l.loan_id, l.out_date, l.due_date, l.return_date,
...> b.book_id, b.title, b.author, b.genre, b.pages,
...> m.member_id, m.first_name, m.last_name, s.street, s.postcode
...> FROM d_loans AS l NATURAL JOIN d_books AS b
...> NATURAL JOIN d_members AS m NATURAL JOIN d_streets AS s;
OK
sql> SELECT (SELECT count(*) FROM (SELECT * FROM wide EXCEPT SELECT * FROM joined))
...> AS lost,
...> (SELECT count(*) FROM (SELECT * FROM joined EXCEPT SELECT * FROM wide))
...> AS invented;
+------+----------+
| lost | invented |
+------+----------+
| 0 | 0 |
+------+----------+
(1 row)
Only 23 streets appear because no member lives on the 24th. BCNF cannot always keep the dependencies inside the parts.
Example 30.13 (No BCNF decomposition preserves the dependencies)
An address table over street, town and postcode with the rules street town postcode and postcode town. The keys are {street, town} and {street, postcode}, so postcode town violates BCNF; every attribute belongs to a key, so the table is in 3NF. Any BCNF decomposition must separate the three attributes, and street town postcode then lies in no part.
$ python no_preserving.py
keys: {postcode, street} {street, town} | in 3NF: True
BCNF : {postcode, town} {postcode, street} | lossless True, preserving False
3NF synthesis: {postcode, street, town} | lossless True, preserving True
def synthesis_3nf(r, deps):
"""One table per left side of a minimal cover, plus a key if none holds one."""
groups = {}
for left, right in minimal_cover(deps):
groups[left] = groups.get(left, left) | right
parts = list(dict.fromkeys(groups.values()))
parts = [p for p in parts if not any(p < q for q in parts)]
if not any(closure(p, deps) >= frozenset(r) for p in parts):
parts.append(keys(r, deps)[0])
return parts
Theorem 30.14 (3NF synthesis)
The decomposition of Listing 30.7, one table for each left side of a minimal cover with the attributes it determines in the cover, plus a candidate key if no table contains one, preserves the dependencies, is lossless, and has every table in 3NF.
Proof. Every dependency of the minimal cover lies inside the table of its left side, and the cover is equivalent to : the dependencies are preserved. For losslessness, let be a table containing a key and run the chase of Exercise 30.5: the row of starts with the symbol on , and the cover’s dependencies, applied in the order in which the closure algorithm adds attributes to , give it on each attribute in turn, since each such dependency lies inside a table whose own row has everywhere. A row with everywhere means the join is lossless. That each table is in 3NF uses the minimality of the cover; we admit it. ∎
So 3NF can always be reached without losing a dependency, and BCNF without losing information but perhaps a dependency. The synthesis often gives BCNF tables anyway, as for the library: its four 3NF tables are the four BCNF tables.
One more kind of redundancy escapes functional dependencies. If a book has several authors and several subject keywords, unrelated to each other, a table (book, author, keyword) must hold every pair: two authors and three keywords make six rows, with each author written three times.
Definition 30.15 (Multivalued dependency, fourth normal form)
A table over satisfies the multivalued dependency if, with , whenever two rows agree on , the row that takes and from the first and from the second is also in the table. is in fourth normal form if for every non-trivial that holds, is a superkey.
Here book author: every author of a book appears with every keyword of it. The table is in BCNF, its only key being all three attributes, but not in 4NF, and splitting it into (book, author) and (book, keyword) is lossless by the same argument as Heath’s theorem. A functional dependency is a special multivalued one; the chase of Exercise 30.5 extends to both, and we leave it at that.
History
Edgar Codd published the relational model in 1970 and defined third normal form in 1971. Raymond Boyce and Codd formally developed the normal form that bears their names in 1974; Ian Heath had described it in 1971.
30.4 Transactions
Design removes the anomalies of one table. The other dangers come from time: a change made of several statements that stops in the middle, or two programs that change the same row at once.
Definition 30.16 (Transaction, commit, rollback)
A transaction is a sequence of reads and writes that the database treats as one unit. It ends with a commit, which makes all its writes permanent and visible to others, or a rollback, which cancels all of them.
Definition 30.17 (Atomicity, consistency, isolation, durability)
A database system guarantees atomicity if a transaction’s writes take effect all or none; consistency if a transaction that starts from a state satisfying the declared constraints and commits leaves one; isolation if concurrent transactions do not see each other’s partial work, to a degree fixed by the isolation level; durability if a committed transaction survives a crash.
In SQLite, BEGIN starts a transaction; without it, each statement is a transaction of its own. The book’s SQL runner commits after every statement, as an interactive tool does, so the transactions of this section are written in Python, which controls them explicitly:
def record_return(day, amount):
conn.execute("BEGIN")
try:
conn.execute("UPDATE loans SET return_date = ? WHERE loan_id = ?", (day, loan))
conn.execute("INSERT INTO fines VALUES (?, ?)", (loan, amount))
conn.execute("COMMIT")
print(f"returned on {day}, fine {amount}: committed")
except sqlite3.Error as e:
conn.execute("ROLLBACK")
print(f"returned on {day}, fine {amount}: {e}; rolled back")
$ python rollback.py
loan 3 (due 2025-01-22): return_date None, fines 0
returned on 2026-02-03, fine 0: CHECK constraint failed: amount > 0; rolled back
loan 3 (due 2025-01-22): return_date None, fines 0
returned on 2026-02-03, fine 2: committed
loan 3 (due 2025-01-22): return_date 2026-02-03, fines 1
Without the transaction, the first attempt would have left a loan returned with no fine recorded: the two tables would disagree, the very thing the design was meant to prevent.
History
Theo Härder and Andreas Reuter coined the acronym ACID for these four properties in 1983, in a survey of transaction recovery.
30.5 Isolation
Definition 30.18 (Schedule)
A schedule of a set of transactions is the order in time of all their reads, writes, commits and rollbacks, each transaction’s own operations in their order. It is serial if the transactions do not overlap.
Definition 30.19 (The anomalies of isolation)
In a schedule of two transactions and : a dirty read is reading a value written by that has not committed; a non-repeatable read is reading the same row twice and getting two values, because changed it and committed in between; a phantom read is running the same query with a condition twice and getting different sets of rows, because inserted or deleted a matching row; a lost update is and both reading a value and both writing a new value computed from it, so that one write erases the other; a write skew is and each reading the same rows, checking a rule over them, and each writing a different row, so that both checks pass and the result breaks the rule.
Definition 30.20 (Isolation level)
An isolation level is a promise about which of these anomalies a database system lets transactions see. The SQL standard names four: read uncommitted, read committed, repeatable read and serializable, the last promising that every schedule has the same effect as some serial one.
| isolation level | dirty read | non-repeatable read | phantom read |
|---|---|---|---|
| read uncommitted | possible | possible | possible |
| read committed | no | possible | possible |
| repeatable read | no | no | possible |
| serializable | no | no | no |
SQLite takes the simplest road: its transactions are serializable, and it allows a single writer at a time. The one way to see an uncommitted change is to share a cache between two connections and turn on read_uncommitted.
In practice
SQLite’s documentation states that its transactions are serializable except for connections that share a cache with read_uncommitted on, and that one connection writes at a time: the others wait their turn.
URI = "file:shelf?mode=memory&cache=shared"
writer = sqlite3.connect(URI, uri=True, isolation_level=None)
reader = sqlite3.connect(URI, uri=True, isolation_level=None)
writer.execute("CREATE TABLE shelf (book_id INTEGER PRIMARY KEY, available INTEGER)")
writer.execute("INSERT INTO shelf VALUES (7, 3)")
def read(label):
try:
row = reader.execute("SELECT available FROM shelf WHERE book_id = 7").fetchone()
n = row[0]
print(f"{label}: the reader sees {n}")
except sqlite3.OperationalError as e:
print(f"{label}: the reader gets an error: {e}")
writer.execute("BEGIN")
writer.execute("UPDATE shelf SET available = 0 WHERE book_id = 7")
read("3 changed to 0, not committed")
reader.execute("PRAGMA read_uncommitted = 1")
read("the same, read_uncommitted on")
writer.execute("ROLLBACK")
read("writer rolled back")
$ python dirty_read.py
3 changed to 0, not committed: the reader gets an error: database table is locked: shelf
the same, read_uncommitted on: the reader sees 0
writer rolled back: the reader sees 3
The lost update needs no concurrency inside the database at all: it is enough that a program reads a value, computes, and writes, while another does the same. Two lending desks, each with its own connection to the library’s file:
with tempfile.TemporaryDirectory() as folder:
# 1. Read, then write what was read minus one: each statement on its own.
a, b = fresh(folder)
na, nb = available(a), available(b) # both read 3
a.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (na - 1,))
b.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (nb - 1,))
print("read, then write: two copies lent, available =", available(a))
a.close()
b.close()
# 2. The same inside BEGIN IMMEDIATE: the second desk must wait for the first.
a, b = fresh(folder)
a.execute("BEGIN IMMEDIATE")
na = available(a)
try:
b.execute("BEGIN IMMEDIATE")
except sqlite3.OperationalError as e:
print("BEGIN IMMEDIATE: the second desk is refused:", e)
a.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (na - 1,))
a.execute("COMMIT")
b.execute("BEGIN IMMEDIATE") # the desk tries again
nb = available(b)
b.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (nb - 1,))
b.execute("COMMIT")
print("BEGIN IMMEDIATE: two copies lent, available =", available(a))
a.close()
b.close()
# 3. One statement that reads and writes: nothing to interleave.
a, b = fresh(folder)
for conn in (a, b):
conn.execute("UPDATE shelf SET available = available - 1 WHERE book_id = 7")
print("update expression: two copies lent, available =", available(a))
a.close()
b.close()
BEGIN IMMEDIATE, then as one UPDATE code/bachelor-2/30-database-design/listings/lost_update.py$ python lost_update.py
read, then write: two copies lent, available = 2
BEGIN IMMEDIATE: the second desk is refused: database is locked
BEGIN IMMEDIATE: two copies lent, available = 1
update expression: two copies lent, available = 1
BEGIN IMMEDIATE, desk B could not have started before A committed, and it would have read 2.There are two fixes. BEGIN IMMEDIATE takes the right to write at the start of the transaction, so the second desk is refused until the first commits, and then reads the new value. Or the read and the write become one statement, UPDATE shelf SET available = available - 1, which the database executes as a whole (Exercise 30.6).
In practice
BEGIN IMMEDIATE starts a write transaction at once, and may fail with “database is locked” (SQLITE_BUSY) while another connection has one; a program then waits and tries again. A plain BEGIN waits for the first write, and may fail there instead, after reading.
Since SQLite never shows the other anomalies, a small simulator shows them: it runs a schedule of reads and writes under three rules for answering a read, the latest write even if uncommitted, the latest committed value, or a snapshot of the committed values when the transaction began. Under snapshots, a transaction that wants to commit a row that another transaction committed since it began is refused, the rule of “first committer wins”.
def lost_update(db): # both read x, both write what they read minus one
a, b = db.read(1, "x"), db.read(2, "x")
db.write(1, "x", a - 1)
db.write(2, "x", b - 1)
if not (db.commit(1) and db.commit(2)):
return "refused"
return db.committed["x"] != 1
def write_skew(db): # the rule a + b >= 1; each checks it, each removes one copy
s1 = db.read(1, "a") + db.read(1, "b")
s2 = db.read(2, "a") + db.read(2, "b")
if s1 >= 2:
db.write(1, "a", 0)
if s2 >= 2:
db.write(2, "b", 0)
if not (db.commit(1) and db.commit(2)):
return "refused"
return db.committed["a"] + db.committed["b"] < 1
$ python schedules.py
uncommitted committed snapshot
dirty read seen - -
non-repeatable read seen seen -
phantom seen seen -
lost update seen seen refused
write skew seen seen seen
Reading committed values removes dirty reads only; snapshots remove the three anomalies of the standard’s table and turn the lost update into a refusal. Write skew survives snapshots: the two transactions write different rows, so no write conflicts with another, yet the rule “at least one copy stays” is broken. Only a serializable level prevents it, for example by detecting that each read what the other wrote.
30.6 Using an index
Definition 30.21 (Index)
An index on columns of a table is a separate structure, kept up to date by the database system on every change, that maps values of those columns to the rows that hold them, in sorted order, so that the rows with a given value or in a given range are found without reading the whole table.
The database chooses for each query whether to use an index. EXPLAIN QUERY PLAN shows the choice:
-- load: town
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id = 55;
CREATE INDEX loans_member ON loans (member_id);
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id = 55;
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id + 0 = 55;
$ python sqlrun.py explain.sql
sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id = 55;
+----+--------+---------+------------+
| id | parent | notused | detail |
+----+--------+---------+------------+
| 2 | 0 | 0 | SCAN loans |
+----+--------+---------+------------+
(1 row)
sql> CREATE INDEX loans_member ON loans (member_id);
OK
sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id = 55;
+----+--------+---------+-----------------------------------------------------+
| id | parent | notused | detail |
+----+--------+---------+-----------------------------------------------------+
| 3 | 0 | 0 | SEARCH loans USING INDEX loans_member (member_id=?) |
+----+--------+---------+-----------------------------------------------------+
(1 row)
sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id + 0 = 55;
+----+--------+---------+------------+
| id | parent | notused | detail |
+----+--------+---------+------------+
| 2 | 0 | 0 | SCAN loans |
+----+--------+---------+------------+
(1 row)
The last query hides the column inside an expression, and the index no longer applies: member_id + 0 is not a value that the index sorts.
In practice
SQLite’s documentation says that SCAN is a full-table scan and SEARCH visits a subset of the rows, and warns that the format of EXPLAIN QUERY PLAN may change between releases: it is for people to read, not for programs to parse.
On 400 loans either way is instant. On generated tables of growing size:
def timed(conn, members, rng):
"""Mean time in microseconds of one query, over 200 random members."""
ids = [rng.randrange(members) for _ in range(200)]
t0 = time.perf_counter()
for m in ids:
conn.execute("SELECT count(*), max(out_day) FROM loans WHERE member_id = ?",
(m,)).fetchone()
return (time.perf_counter() - t0) / len(ids) * 1e6
rng = random.Random(30)
print(" rows scan (us) index (us) speed-up index built in (ms)")
for n in [10_000, 100_000, 1_000_000]:
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE loans (loan_id INTEGER PRIMARY KEY, member_id INTEGER,"
" book_id INTEGER, out_day INTEGER)")
members = n // 20
rows = ((i, rng.randrange(members), rng.randrange(5000), rng.randrange(365))
for i in range(n))
conn.executemany("INSERT INTO loans VALUES (?, ?, ?, ?)", rows)
scan = timed(conn, members, rng)
t0 = time.perf_counter()
conn.execute("CREATE INDEX loans_member ON loans (member_id)")
built = (time.perf_counter() - t0) * 1e3
seek = timed(conn, members, rng)
print(f"{n:9} {scan:11.0f} {seek:12.1f} {scan / seek:10.0f} {built:21.0f}")
conn.close()
$ python index_timing.py
rows scan (us) index (us) speed-up index built in (ms)
10000 623 12.3 51 6
100000 5977 18.7 320 69
1000000 63714 66.3 961 744
The scan time grows tenfold with each tenfold table; the index time grows about fivefold over a table a hundred times larger, and on a million rows the index is about a thousand times faster. It is not free: building it took close to a second, and each later insertion or update of a loan must update it too. How the index is organised, a balanced tree with many keys per node, and how the system chooses among plans, are the subject of the Year 3 volume. An index does not always help either: a query that selects a large fraction of the table reads it faster in order (Exercise 30.12).
30.7 Exercises
Exercise 30.1 ★
With , compute by hand the closures of , and , then check with exo_closure.py. Is a superkey of ?
Solution
Solution of Exercise 30.1.
From : adds ; no other left side is contained in , so . From : adds , then adds ; needs , so . From no left side applies. For : , , give , so it is a superkey; neither nor is everything, so it is even a candidate key.
$ python exo_closure.py
['a'] -> ['a', 'b']
['b', 'c'] -> ['b', 'c', 'd', 'e']
['c', 'e'] -> ['c', 'e']
Exercise 30.2 ★
A BCNF step on the wide table’s violation book title author genre pages splits off only {book, title}. What is wrong with the other part? Compare with the step that splits off the whole closure, using exo_bcnf_step.py.
Solution
Solution of Exercise 30.2.
$ python exo_bcnf_step.py
split off {book, title}
2 attributes; still violated by nothing
13 attributes; still violated by {book} -> {author, genre, pages}
split off {book, title, author, genre, pages}
5 attributes; still violated by nothing
10 attributes; still violated by {member} -> {first, last, street, postcode}
The part {book, title} is fine, but the other part keeps book together with author, genre and pages: book author genre pages still violates BCNF there, and a second and third step will be needed for the same left side. Splitting off removes every attribute that determines in one step; what remains in the other part are other violations, such as the member’s.
Exercise 30.3 ★
The reading room’s bookings have attributes seat, day, slot, member and desk, with seat day slot member, member day slot seat and seat desk. Find all the candidate keys by hand, then with exo_keys.py.
Solution
Solution of Exercise 30.3.
day and slot appear on no right side, so every key contains them; desk appears on no left side and is determined by seat, so no key needs it. {day, slot} alone determines nothing more. Adding seat: seat day slot member, seat desk: everything. Adding member: member day slot seat, then the rest. Both are minimal, since {day, slot} is not a key, and any other key would have to contain seat or member, hence one of these.
$ python exo_keys.py
key: ['day', 'member', 'slot']
key: ['day', 'seat', 'slot']
Exercise 30.4 ★
A schema with attributes has exactly one candidate key, of size . Prove that it has exactly superkeys.
Solution
Solution of Exercise 30.4.
Let be the key. A set is a superkey exactly when : if , then ; conversely, a superkey contains a candidate key, obtained by removing attributes while it stays a superkey, and is the only one. The supersets of are for the subsets of the other attributes.
Exercise 30.5 ★★
Split the wide table into the member’s attributes and the rest, keeping in both, in turn, the member, the street, or the last name. Which splits are lossless by Heath’s theorem? For the others, explain how a join could invent rows. Check with exo_heath.py, which runs the chase: one row per part, with the symbol on the part’s attributes and distinct symbols elsewhere; the dependencies force equal symbols where two rows agree on a left side; the decomposition is lossless exactly when some row ends with everywhere.
Solution
Solution of Exercise 30.5.
$ python exo_heath.py
split on member : lossless True
split on street : lossless False
split on last name: lossless False
Keeping member in both parts: the common attribute determines the whole member part, member first last street postcode, so Heath’s theorem applies. Keeping street: the street determines only the postcode, not the member, and two members on the same street become interchangeable; the join pairs each loan with every member of its borrower’s street, inventing rows. Keeping last: a last name determines nothing, and the join pairs a loan with every member of that name. In the chase, the row of the second part never gets on the loan’s attributes, nor the first row on the member’s.
Exercise 30.6 ★★
In the first part of Listing 30.10, explain the bug as a schedule, and say why each of the two fixes prevents it. Which fix still works if the program must check that a copy is available before lending it?
Solution
Solution of Exercise 30.6.
As a schedule: , , , , each statement committed on its own. ’s write is computed from a value that ’s write made stale: a lost update. With BEGIN IMMEDIATE, the read and the write are in one transaction that holds the right to write from its start, so ’s transaction cannot begin between ’s read and ’s write: the schedule becomes serial. With available = available - 1, the read and the write are one statement, executed by the database as a whole. To check that a copy is available first, the check and the change must be in one unit: either the transaction with BEGIN IMMEDIATE, or the condition inside the statement, UPDATE shelf SET available = available - 1 WHERE book_id = 7 AND available > 0, whose count of changed rows says whether the copy was lent.
Exercise 30.7 ★★
Add a name determined by the member to the bookings of Exercise 30.3, and let seat day slot determine desk as well. Compute a minimal cover and the 3NF synthesis by hand, then check with exo_synthesis.py.
Solution
Solution of Exercise 30.7.
Split the right sides: seat day slot member, seat day slot desk, member day slot seat, seat desk, member name. No left side has an extraneous attribute: {day, slot} determines nothing, and neither {seat, day} nor {seat, slot} determines the member. The dependency seat day slot desk is redundant, implied by seat desk: remove it. The synthesis makes one table per left side: (seat, desk), (seat, day, slot, member), (member, day, slot, seat), the same set as the previous one, so kept once, and (member, name). The second contains a key, so no table is added.
$ python exo_synthesis.py
minimal cover: seat -> desk; day seat slot -> member; day member slot -> seat; member -> name
table ['desk', 'seat'] | 3NF: True
table ['day', 'member', 'seat', 'slot'] | 3NF: True
table ['member', 'name'] | 3NF: True
lossless: True | preserving: True
Exercise 30.8 ★★
Derive the union rule and the decomposition rule from Armstrong’s three axioms.
Solution
Solution of Exercise 30.8.
Union: from , augmentation with gives ; from , augmentation with gives ; transitivity gives . Decomposition: by reflexivity, and transitivity with gives .
Exercise 30.9 ★★
Find, with exo_extra_fds.py, the dependencies between two single attributes that the town’s 400 lines satisfy but the library’s rules do not imply. Which of them would you add to the schema, and what would change?
Solution
Solution of Exercise 30.9.
$ python exo_extra_fds.py
out -> due
due -> out
title -> book, author, genre, pages
out due is a rule of the library, every loan being due 21 days later: it could be added, and then due is better not stored at all but computed, since a table (out, due) would only store the rule. due out follows from the same rule. title book is an accident of 80 titles that happen to differ; making it a rule would forbid a second copy of a book with another number, or two books with the same title, and should not be added.
Exercise 30.10 ★★★
Prove Theorem 30.11.
Solution
Solution of Exercise 30.10.
Let satisfy . Every row of is in the join, since its projections on and are in the two projections and agree on . Conversely, let be in the join: there are rows and in , the first giving the part on , the second the part on . They agree on , so by they agree on : , and the second row is , which is therefore in .
Exercise 30.11 ★★★
Prove Proposition 30.5.
Solution
Solution of Exercise 30.11.
Let and the set after the -th addition. Every attribute added is in : by induction, ; an addition uses some of with , so by decomposition, by transitivity, and by union. By soundness, . At the end, : when the loop stops, contains and, for every in with , also . The two-row table of the proof of Theorem 30.4, equal on and different elsewhere, then satisfies ; it satisfies for every , its rows agree on , so they agree on , and . Time: a pass that adds nothing ends the loop; every other pass applies at least one dependency, whose right side then stays in the set for good, so that it is never applied again; so there are at most passes, each of dependencies tested in .
Exercise 30.12 ★★★
A query selects the loans with out_day below a bound, through an index on out_day or by a full scan. Measure both as the fraction selected grows, with exo_selectivity.py, find where the index stops helping, and explain why.
Solution
Solution of Exercise 30.12.
$ python exo_selectivity.py
selected index (ms) scan (ms)
0.1% 0.4 19.9
1.0% 4.8 22.2
5.0% 22.4 23.8
10.0% 43.3 26.9
20.0% 99.0 25.6
30.0% 131.9 28.8
50.0% 206.4 33.0
100.0% 423.9 37.2
The scan reads the whole table in order, at a nearly fixed cost, a little more as more rows are summed. The index finds the first matching entry quickly and then, for each matching entry, fetches its row from the table, at a place that has nothing to do with the order of out_day: one random access per row. Its cost grows in proportion to the number of rows selected, about 4 ms per 1 % here, while the scan’s grows by less than 20 ms from one end to the other. On this laptop the two meet between 5 % and 10 % of the table; beyond, the index loses, by a factor of more than ten when everything is selected. A query planner estimates the fraction from statistics on the column and chooses the scan for large ranges.
30.8 Problem: Redesigning the library’s spreadsheet
Problem 30.1
Weekend problem — Redesigning the library’s spreadsheet
The library replaces its spreadsheet by a database. The program below measures the old design, checks the new one and replays member 55’s move in both; Output 30.10 measures the index the desks will need.
# Part I: each fact is stored once per loan line.
for det, column in [("book", "book_id"), ("member", "member_id"), ("street", "street")]:
sql = f"SELECT count(*), count(DISTINCT {column}) FROM wide"
lines, values = conn.execute(sql).fetchone()
print(f"facts of a {det:6}: {values:3} distinct, stored on {lines} lines,"
f" {lines - values} copies too many")
# Part II: the left sides of the minimal cover that are not keys of the wide table.
bad = sorted({left for left, _ in minimal_cover(RULES)
if closure(left, RULES) != frozenset(WIDE)}, key=sorted)
print("dependencies violating BCNF, by left side:", ", ".join(show(b) for b in bad))
# Part III: the BCNF tables; each checked, and the decomposition as a whole.
parts = bcnf(WIDE, RULES)
print(len(parts), "tables, violations left:",
sum(bcnf_violation(p, RULES) is not None for p in parts),
"| lossless:", lossless(WIDE, parts, RULES),
"| preserving:", preserves(parts, RULES))
# Part IV: member 55 moves; one UPDATE in each design.
conn.execute("CREATE TABLE d_members AS SELECT DISTINCT member_id, first_name,"
" last_name, street FROM wide")
wide = conn.execute("UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'"
" WHERE member_id = 55").rowcount
one = conn.execute("UPDATE d_members SET street = 'Garden Lane'"
" WHERE member_id = 55").rowcount
print(f"the move: {wide} lines changed in the wide table, {one} in the members table")
$ python redesign.py
facts of a book : 80 distinct, stored on 400 lines, 320 copies too many
facts of a member: 60 distinct, stored on 400 lines, 340 copies too many
facts of a street: 23 distinct, stored on 400 lines, 377 copies too many
dependencies violating BCNF, by left side: {book}, {member}, {street}
4 tables, violations left: 0 | lossless: True | preserving: True
the move: 12 lines changed in the wide table, 1 in the members table
Part I — The dependencies of the wide table.
- List the library’s rules as functional dependencies, and say which are about loans, books, members and streets.
- Explain the 320 copies too many of the books’ facts: what is stored 400 times, and what should be stored 80 times?
- Give an update anomaly, an insertion anomaly and a deletion anomaly of the wide table, with the library’s own facts.
- Why is title book, which the data satisfy, not one of the rules?
- Does out due hold? Should it be a rule, and what would that mean for the schema?
- Compute the closure of {member} and of {street}.
Part II — Keys and normal forms.
- Prove with the closure that {loan} is a candidate key of the wide table, and that it is the only one.
- Which dependencies violate BCNF? Why exactly three left sides?
- Is the wide table in 3NF? Use the definition.
- Is the table (member, first, last, street) in BCNF? And (street, postcode)?
- What would a table (member, street, postcode) violate?
- Give the number of violations before and after the redesign, as the program prints them.
Part III — A lossless decomposition.
- Draw the splits that lead to the four tables, naming the dependency used at each.
- Prove that each split is lossless with Heath’s theorem.
- Is the decomposition dependency-preserving? Check each rule.
- What did Output 30.3 check on the town’s data, and why are both counts needed?
- Why does the streets table have 23 rows and not 24?
- State the problem’s result for the design.
Part IV — Transactions and an index.
- How many rows does the move change in each design, and why can the new design not forget one?
- A loan and its fine are recorded together. Why must they be one transaction?
- Two desks lend the last copy of a book at the same moment. Which anomaly threatens, and how do you prevent it in SQLite?
- Which index do the desks need to list a member’s loans, and what does
EXPLAIN QUERY PLANshow before and after it? - From Output 30.10, how much faster is the index on a million loans, and what does it cost?
- Complete the problem’s result: from one wide table with three violating dependencies to four BCNF tables with none, and an index that is how many times faster on a million loans?
Solution
Solution of Problem 30.1.
1. Loans: loan book member out due ret. Books: book title author genre pages. Members: member first last street. Streets: street postcode.
2. Each of the 400 lines carries its book’s title, author, genre and pages: the facts of 80 books are written 400 times, 320 times more than needed.
3. Update: member 55’s move must change 12 lines, as in the hook. Insertion: a new member, or a newly bought book, cannot be recorded before a first loan, since every line is a loan. Deletion: removing the loans of a book, say to forget old loans, removes the book’s title and author with them.
4. The data satisfy it because the 80 titles happen to be different. The library could buy a second book with the same title, by another author, and the rule would then be false; a rule describes what must always hold.
5. It holds in the data, and it is a rule of the library: every loan is due 21 days after it goes out. Then due need not be stored; if it is, a table (out, due) would be the BCNF answer, which only stores the rule. Most designs compute it instead.
6. ; .
7. contains the book and the member, hence their closures, hence all fourteen attributes. loan appears on no right side, so every key contains it, and every set containing it is a superkey: {loan} is the only candidate key.
8. The dependencies with left side book, member or street: those are the three left sides of the cover besides loan, and none of them is a key.
9. No: member street has a left side that is not a superkey, and street is in no candidate key, the only one being {loan}.
10. Yes for both: in (member, first, last, street) the only non-trivial dependencies have member, a key, on the left; in (street, postcode), street is the key.
11. street postcode with street not a key of that table, whose key is member: BCNF, and 3NF too since postcode is in no key. A move would again have to change two attributes.
12. Three violating left sides before, none after.
13. On book: {book, title, author, genre, pages} and the rest; the rest on member: {member, first, last, street, postcode} and the loans; the member part on street: {street, postcode} and {member, first, last, street}. This is the decomposition tree of the chapter.
14. At each split on , the part and the rest share exactly , and holds: Heath’s theorem applies, with the rest minus . The composition of lossless splits is lossless, as in Theorem 30.12.
15. Yes: each rule lies inside one table, loan in the loans, book in the books, member first last street in the members, street postcode in the streets.
16. That the join of the four tables gives back exactly the 400 lines: no line of the wide table is missing (lost) and no line appears that was not there (invented). A join always contains the original, so the second count is the one that tests losslessness; the first guards against an error in the SQL. It also checked that each table’s key is unique in the data.
17. The streets table is built from the wide table, which only knows the streets of members; one street has no member living on it. A real design would load the streets from their own source.
18. From one wide table with three violating dependencies, and 320, 340 and 377 extra copies of facts, to four BCNF tables with none; the decomposition is lossless and preserves every rule.
19. Twelve lines in the wide table, one row in the members table. The street is stored once per member, so there is nothing to forget.
20. If the program stops between the two writes, the loan is marked returned and the fine is missing, or the reverse: atomicity makes the pair all or nothing, as in Output 30.5.
21. A lost update: both desks read one copy available and both lend it. In SQLite, take the write right at the start with BEGIN IMMEDIATE, or make the check part of the update, SET available = available - 1 WHERE available > 0, and look at the count of changed rows.
22. An index on loans(member_id). Before it, the plan says SCAN loans, every row read; after it, SEARCH loans USING INDEX loans_member (member_id=?).
23. On the laptop of Output 30.10, about a thousand times faster on a million rows. It costs the time to build it, close to a second there, the space of a second sorted structure, and some work on each insertion or update of a loan.
24. From one wide table with three violating dependencies to four BCNF tables with none, and an index about a thousand times faster than a scan on a million loans, as measured on that laptop.
Termos definidos neste capítulo
- Atomicity, consistency, isolation, durability
- Attribute closure
- Decomposition, lossless join, dependency preservation
- Functional dependency, trivial dependency
- Implication, Armstrong’s axioms
- Index
- Isolation level
- Minimal cover
- Multivalued dependency, fourth normal form
- Schedule
- The anomalies of isolation
- Third normal form, Boyce–Codd normal form
- Transaction, commit, rollback
- Update, insertion and deletion anomaly