University Computer Science — Year 3 · Bachelor Year 3
22Query Processing and Optimisation
An SQL query says what rows are wanted, never how to find them. Between the two stands the optimiser, which turns the query into a tree of algorithms and, among the many equivalent trees, picks one it expects to be cheap. This chapter builds both halves on the page files of Chapter 21: an executor whose operators count every page they read and write, the five ways to join two tables with their exact costs, the algebraic rewrites that keep a query’s meaning while shrinking its intermediate results, the statistics that estimate how many rows each step will produce, and the dynamic programming that searches the join orders. The library’s report of late loans is planned by hand, by the program and by SQLite, and the three are compared.
You already know
Relational algebra builds queries from selection , projection , renaming, product and join , each taking relations to a relation; an equi-join keeps the pairs of tuples with (Year 1 volume). Comparison sorting needs comparisons; a hash table finds a key in expected constant time; dynamic programming solves a problem from the solutions of its subproblems, each computed once (Year 1 volume). A B+ tree of height finds a key in page reads (Theorem 21.4).
22.1 Operators, sorting and joins
Definition 22.1 (Query plan, physical operator, access path)
A query plan is a tree whose leaves read stored relations and whose inner nodes are physical operators: algorithms implementing a relational operator, such as a block nested-loop join or an external sort, each with a cost in page reads and writes. An access path is a way to read the tuples of one stored relation: a full scan, or a search through an index.
The executor of this chapter follows the iterator model: each operator is a Python generator that pulls tuples from its children one at a time, so a plan runs without storing what passes between pipelined operators. It is the model of Goetz Graefe’s Volcano system of 1994, and his survey of 1993 describes it with the other techniques of query evaluation. A relation is a list of pages of ten tuples, and every page read or written goes through a Disk that counts it.
def scan(rel, disk):
for page in rel.pages:
disk.reads += 1
yield from page
def select(pred, child):
return (t for t in child if pred(t))
def project(cols, child):
return ({c: t[c] for c in cols} for t in child)
def materialise(child, disk, per_page=10):
"""Write a stream out as a relation: one page write per page."""
rel = Relation(child, per_page)
disk.writes += len(rel)
return rel
materialise writes a stream out as pages. code/bachelor-3/22-query-optimisation/listings/exec.pyA relation larger than memory cannot be sorted by sorted. With pages of memory, it is sorted in passes over the file.
Definition 22.2 (External merge sort)
External merge sort sorts a file of pages with buffer pages. Pass 0 reads pages at a time, sorts them in memory and writes them as a sorted run, giving runs. Each later pass merges groups of runs into one, reading each through one buffer page and writing through the last, until one run is left.
Theorem 22.3 (Cost of external merge sort)
External merge sort of pages makes passes and page reads and writes.
Proof. Pass 0 leaves runs. A merge pass turns runs into , so after merge passes there are runs (ceilings compose: for an integer ). One run is left exactly when , so the least such is . Every pass reads every page once and writes every page once: per pass. ∎
def external_sort(rel, key, B, disk):
runs = []
for s in range(0, len(rel), B): # pass 0: sorted runs of B pages
chunk = [t for page in rel.pages[s : s + B] for t in page]
disk.reads += len(rel.pages[s : s + B])
runs.append(materialise(sorted(chunk, key=key), disk, rel.per_page))
passes = 1
while len(runs) > 1: # merge B - 1 runs at a time, one output buffer
merged = []
for s in range(0, len(runs), B - 1):
group = runs[s : s + B - 1]
streams = [scan_run(r, disk) for r in group]
merged.append(
materialise(heapq.merge(*streams, key=key), disk, rel.per_page)
)
runs, passes = merged, passes + 1
return (runs[0] if runs else Relation([], rel.per_page)), passes
heapq.merge. code/bachelor-3/22-query-optimisation/listings/sort_ext.py$ python sort_ext.py
pages N buffers B passes page I/O 2N(1 + ceil(log_{B-1} ceil(N/B)))
10 3 3 60 60
10 10 1 20 20
10 100 1 20 20
100 3 7 1,400 1,400
100 10 3 600 600
100 100 1 200 200
1,000 3 10 20,000 20,000
1,000 10 4 8,000 8,000
1,000 100 2 4,000 4,000
10,000 3 13 260,000 260,000
10,000 10 5 100,000 100,000
10,000 100 3 60,000 60,000
The logarithm’s base is what memory buys: with , two passes sort any file of up to pages, and three passes almost a million. Most real sorts take two passes.
Definition 22.4 (Nested-loop, block nested-loop, index nested-loop, sort–merge and hash joins)
Let have pages and tuples, have pages, and buffer pages be free. The nested-loop join scans once for each tuple of : page reads. The block nested-loop join loads pages of at a time and scans once per block: . The index nested-loop join searches an index on ’s join column for each tuple of : for an index of height and one matching tuple. The sort–merge join sorts both inputs on the join column and merges them: the two sorts plus . The hash join builds a hash table on the smaller input and probes it with the other: if the smaller fits in pages; otherwise the Grace variant first partitions both inputs into buckets on disk by a hash of the join column and joins bucket by bucket: .
def nested_loop(R, S, a, b, disk):
"""For each tuple of R, scan all of S: M + |R| N."""
return [merge(r, s) for r in scan(R, disk) for s in scan(S, disk) if r[a] == s[b]]
def block_nested_loop(R, S, a, b, B, disk):
"""Load B - 2 pages of R, hash them, scan S once per block: M + ceil(M/(B-2)) N."""
out = []
for start in range(0, len(R), B - 2):
block = defaultdict(list)
for page in R.pages[start : start + B - 2]:
disk.reads += 1
for r in page:
block[r[a]].append(r)
out += [merge(r, s) for s in scan(S, disk) for r in block.get(s[b], ())]
return out
def sort_merge(R, S, a, b, B, disk):
"""Sort both, then merge; S.b is a key of S, as in a foreign-key join."""
Rs, _ = external_sort(R, lambda t: t[a], B, disk)
Ss, _ = external_sort(S, lambda t: t[b], B, disk)
out, it = [], scan(Ss, disk)
s = next(it, None)
for r in scan(Rs, disk):
while s is not None and s[b] < r[a]:
s = next(it, None)
if s is not None and s[b] == r[a]:
out.append(merge(r, s))
for _ in it: # read the rest of S, as a merge does
pass
return out
def hash_join(R, S, a, b, B, disk):
"""Build a hash table on the smaller input if it fits in B - 2 pages: M + N.
Otherwise partition both into B - 1 buckets on disk first (Grace): 3(M + N)."""
if len(R) < len(S):
R, S, a, b, swapped = S, R, b, a, True
else:
swapped = False
pairs = [(R, S)]
if len(S) > B - 2:
pairs = list(zip(partition(R, a, B, disk), partition(S, b, B, disk)))
out = []
for Rp, Sp in pairs:
table = defaultdict(list)
for s in scan(Sp, disk):
table[s[b]].append(s)
for r in scan(Rp, disk):
out += [
merge(s, r) if swapped else merge(r, s) for s in table.get(r[a], ())
]
return out
$ python join_demo.py
M = 1000 pages, N = 100 pages, B = 12, index height 2
join result page I/O formula
nested loop 10,000 1,001,000 1,001,000
block nested loop 10,000 11,000 11,000
index nested loop 10,000 31,000 31,000
sort-merge 10,000 7,500 7,500
hash (Grace) 10,000 3,328 3,300
The tuple-at-a-time nested loop costs a million page reads where the hash join costs 3,328: three hundred times more for the same 10,000 rows. The block nested loop divides it by the tuples per page and the block size. The index nested loop pays reads per loan, which loses here because every loan matches; it wins when few tuples of take part, after a selective condition. The sort–merge join pays for two sorts, but leaves its result sorted on the join column, which a later operator may use.
22.2 Algebraic rewriting
The same query has many algebra trees. The laws of the Year 1 volume say which trees are equal: a conjunction of conditions is a cascade of selections, ; joins are commutative and associative, up to the order of columns; and a selection can move through a join.
Theorem 22.5 (Pushing a selection through a join)
If the condition uses only columns of , then .
Proof. A tuple of the left side is a pair with , , true and true. Since reads only columns of , , so the conditions are and , that is , together with and : exactly the tuples of the right side. ∎
The rewrite never changes the result and almost always shrinks it early: a selection pushed down filters before the join instead of after. rewrite.py pushes every selection as far down as its columns allow and runs both trees on the town’s tables.
def push(node):
"""Move every selection as far down as its columns allow."""
if node[0] == "table":
return node
if node[0] == "join":
return ("join", node[1], node[2], push(node[3]), push(node[4]))
child = push(node[2])
if node[0] == "select" and child[0] == "join":
used = PREDICATES[node[1]][0]
for side in (3, 4):
if used <= columns(child[side]):
parts = list(child)
parts[side] = push(("select", node[1], child[side]))
return tuple(parts)
return (node[0], node[1], child)
$ python rewrite.py
as written: 1331 intermediate rows in all
project title, last_name, due_date [11 rows]
select mystery [11 rows]
select late [109 rows]
join person_id = person_id [400 rows]
join member_id = member_id [400 rows]
join book_id = book_id [400 rows]
loans [400 rows]
books [80 rows]
members [60 rows]
people [120 rows]
selections pushed down: 162 intermediate rows in all
project title, last_name, due_date [11 rows]
join person_id = person_id [11 rows]
join member_id = member_id [11 rows]
join book_id = book_id [11 rows]
select late [109 rows]
loans [400 rows]
select mystery [9 rows]
books [80 rows]
members [60 rows]
people [120 rows]
same result: True (11 rows)
Projections can be pushed down in the same way, provided each keeps the columns that later joins and selections need. A plan built from these rules alone, selections and projections as low as possible, is already good; what remains is to choose the order of the joins and an algorithm for each, and for that the optimiser needs numbers.
22.3 Estimating sizes
Definition 22.6 (Selectivity, cardinality estimate, equi-depth histogram)
The selectivity of a condition on a relation is the fraction of its tuples that satisfy it. A cardinality estimate is the optimiser’s prediction of the number of tuples an operator will output, computed from stored statistics. An equi-width histogram of a column cuts its range into buckets of equal width and stores each bucket’s count; an equi-depth histogram cuts it at quantiles, so that every bucket holds about the same number of tuples. Within a bucket, values are assumed evenly spread, and each distinct value equally frequent.
Without statistics, an optimiser assumes uniform values: an equality on a column with distinct values selects of the tuples. With histograms it does better where values are skewed. The town’s daily rain is very skewed: 447 of 731 days are dry.
def equi_depth(values, k):
"""k buckets of (almost) equal counts, cut at positions in sorted order."""
vs = sorted(values)
cuts = [len(vs) * i // k for i in range(k + 1)]
return [
(vs[a], vs[b - 1], b - a, len(set(vs[a:b]))) for a, b in zip(cuts, cuts[1:])
]
def estimate(hist, lo, hi):
"""Rows with lo <= v <= hi, assuming values spread evenly inside each bucket;
an equality (lo == hi) assumes each distinct value of the bucket equally often."""
total = 0.0
for a, b, count, distinct in hist:
if lo == hi:
total += count / distinct if a <= lo <= b else 0
elif a == b:
total += count if lo <= a <= hi else 0
else:
total += count * max(0.0, min(hi, b) - max(lo, a)) / (b - a)
return total
$ python histogram.py
bucket equi-width rows equi-depth rows
0 [ 0.00, 2.51] 568 [ 0.0, 0.0] 91
1 [ 2.51, 5.03] 84 [ 0.0, 0.0] 91
2 [ 5.03, 7.54] 35 [ 0.0, 0.0] 92
3 [ 7.54, 10.05] 17 [ 0.0, 0.0] 91
4 [10.05, 12.56] 13 [ 0.0, 0.2] 91
5 [12.56, 15.08] 6 [ 0.2, 2.0] 92
6 [15.08, 17.59] 6 [ 2.0, 4.5] 91
7 [17.59, 20.10] 2 [ 4.6, 20.1] 92
condition true equi-width equi-depth
rain = 0 447 21.8 395.3
1 <= rain <= 3 85 358.2 87.5
rain >= 10 27 27.3 59.9
loans out before March: 0.160, due before March: 0.100
both: independence estimates 6.4 rows, true 40
The equi-width histogram puts 568 days in its first bucket and spreads them over 2.5 mm: it estimates 22 dry days instead of 447, and 358 days between 1 and 3 mm instead of 85. The equi-depth histogram gives four buckets to the dry days and is close on both; it is worse only in the long tail, where its last bucket spreads 92 days from 4.6 to 20.1 mm. Each kind of histogram is good where it puts many buckets.
Conditions on several columns are combined by assuming independence: the selectivity of is the product of theirs. For two columns of the loans this fails badly: a loan is due 21 days after it goes out, so a loan due before March went out before March. The product predicts 6.4 such loans; there are 40. For a join on columns with and distinct values, the standard estimate assumes every value of the column with fewer values appears in the other:
For a join on a foreign key it is exact; for others the error can be large, and errors multiply along a plan, since each join’s estimate is built on the estimates below it. Yannis Ioannidis and Stavros Christodoulakis studied this propagation of errors through joins in 1991.
22.4 Searching for a plan
Definition 22.7 (Left-deep plan, interesting order, cost-based optimiser)
A left-deep plan joins one stored relation at a time: every join has a stored relation as its right input. A cost-based optimiser enumerates plans, estimates the cost of each from statistics, and keeps the cheapest. An interesting order is a sort order of an intermediate result that a later operator can use, such as the order on a join column needed by a later sort–merge join.
For relations there are left-deep orders and join trees of any shape (Exercise 22.8): 720 and 30,240 for six relations. Patricia Selinger and her colleagues described in 1979 the dynamic programming that follows. The cheapest left-deep plan for a set of relations ends by joining some to a plan for , and that plan may as well be the cheapest one for : so the best plans are computed for sets of increasing size, each from the best plans of the sets one smaller. Plans that would join two relations with no condition between them, a Cartesian product, are skipped.
def methods(left_pages, right_pages, left_order, col, B):
"""(name, cost, order of the output) of each way to join."""
sort_left = 0 if left_order == col else sort_cost(left_pages, B)
merge = sort_left + sort_cost(right_pages, B) + left_pages + right_pages
return [("hash", 3 * (left_pages + right_pages), None), ("merge", merge, col)]
def best_plan(sizes, preds, B=10):
"""sizes: {relation: tuples}; preds: {frozenset({x, y}): (column, selectivity)}.
Returns (cost, estimated tuples, plan) and the number of plans costed."""
best, costed = {}, 0
for r, t in sizes.items():
best[frozenset([r])] = (0, t, r, None)
for k in range(2, len(sizes) + 1):
for S in map(frozenset, combinations(sorted(sizes), k)):
for r in sorted(S):
left = S - {r}
ps = [preds[p] for p in preds if r in p and p - {r} <= left]
if left not in best or not ps:
continue # no cross products
cost, t, plan, order = best[left]
out = t * sizes[r] * math.prod(sel for _, sel in ps)
for name, c, new_order in methods(
pages(t), pages(sizes[r]), order, ps[0][0], B
):
costed += 1
if S not in best or cost + c < best[S][0]:
best[S] = (cost + c, out, f"({plan} {name} {r})", new_order)
cost, t, plan, _ = best[frozenset(sizes)]
return (cost, t, plan), costed
$ python selinger.py
chain of 4: 24 orders, 24 plans costed, best 30,690 page I/O
(((R3 hash R2) hash R1) hash R4)
star of 4: 24 orders, 30 plans costed, best 3,393 page I/O
(((R4 hash R1) hash R2) hash R3)
chain of 5: 120 orders, 40 plans costed, best 6,666 page I/O
((((R4 hash R3) hash R5) hash R2) hash R1)
star of 5: 120 orders, 72 plans costed, best 36,099 page I/O
((((R3 hash R1) hash R2) hash R5) hash R4)
chain of 6: 720 orders, 60 plans costed, best 33,780 page I/O
(((((R6 hash R5) hash R4) hash R3) hash R2) hash R1)
star of 6: 720 orders, 170 plans costed, best 39,990 page I/O
(((((R6 hash R1) hash R3) hash R5) hash R2) hash R4)
The program keeps one plan per set. That is where interesting orders come in: a plan for that costs a little more but leaves its result sorted on the next join column can make the whole plan cheaper. An optimiser can keep, for each set, the cheapest plan for every interesting order as well as the cheapest overall; Exercise 22.12 adds this and finds a query where it pays. Optimisers for many relations, where even the subsets are too many, fall back on greedy heuristics: join next the relation that gives the smallest intermediate result.
22.5 Reading SQLite’s plans
SQLite implements every join as nested scans, and EXPLAIN QUERY PLAN prints one line per loop, outermost first. Its optimiser chooses the order of the loops and the access path of each: a scan, a search by rowid, or a search through an index. ANALYZE gathers statistics on the tables and indexes into internal tables that the planner reads; it is never required, but it can change the plans. The table sqlite_stat1 has one row per index: the approximate number of rows, then the average number of rows sharing a value of the first column; a row with no index holds the table’s row count.
$ python sqlrun.py plans.sql
sql> EXPLAIN QUERY PLAN
...> SELECT b.title, p.last_name, l.due_date
...> FROM loans l JOIN books b ON b.book_id = l.book_id
...> JOIN members m ON m.member_id = l.member_id
...> JOIN people p ON p.person_id = m.person_id
...> WHERE l.return_date IS NULL OR l.return_date > l.due_date;
+----+--------+---------+----------------------------------------------+
| id | parent | notused | detail |
+----+--------+---------+----------------------------------------------+
| 5 | 0 | 0 | SCAN l |
| 12 | 0 | 0 | SEARCH b USING INTEGER PRIMARY KEY (rowid=?) |
| 15 | 0 | 0 | SEARCH m USING INTEGER PRIMARY KEY (rowid=?) |
| 18 | 0 | 0 | SEARCH p USING INTEGER PRIMARY KEY (rowid=?) |
+----+--------+---------+----------------------------------------------+
(4 rows)
sql> EXPLAIN QUERY PLAN
...> SELECT p.last_name, count(*) AS loans
...> FROM people p JOIN members m ON m.person_id = p.person_id
...> JOIN loans l ON l.member_id = m.member_id
...> GROUP BY p.person_id;
+----+--------+---------+----------------------------------------------+
| id | parent | notused | detail |
+----+--------+---------+----------------------------------------------+
| 8 | 0 | 0 | SCAN l |
| 10 | 0 | 0 | SEARCH m USING INTEGER PRIMARY KEY (rowid=?) |
| 13 | 0 | 0 | SEARCH p USING INTEGER PRIMARY KEY (rowid=?) |
| 16 | 0 | 0 | USE TEMP B-TREE FOR GROUP BY |
+----+--------+---------+----------------------------------------------+
(4 rows)
sql> CREATE INDEX loans_member ON loans(member_id);
OK
sql> EXPLAIN QUERY PLAN
...> SELECT p.last_name, count(*) AS loans
...> FROM people p JOIN members m ON m.person_id = p.person_id
...> JOIN loans l ON l.member_id = m.member_id
...> GROUP BY p.person_id;
+----+--------+---------+----------------------------------------------+
| id | parent | notused | detail |
+----+--------+---------+----------------------------------------------+
| 8 | 0 | 0 | SCAN l USING COVERING INDEX loans_member |
| 10 | 0 | 0 | SEARCH m USING INTEGER PRIMARY KEY (rowid=?) |
| 13 | 0 | 0 | SEARCH p USING INTEGER PRIMARY KEY (rowid=?) |
| 16 | 0 | 0 | USE TEMP B-TREE FOR GROUP BY |
+----+--------+---------+----------------------------------------------+
(4 rows)
sql> ANALYZE;
OK
sql> SELECT tbl, idx, stat FROM sqlite_stat1 WHERE tbl IN ('loans', 'members', 'people');
+---------+--------------+-------+
| tbl | idx | stat |
+---------+--------------+-------+
| people | NULL | 120 |
| members | NULL | 60 |
| loans | loans_member | 400 7 |
+---------+--------------+-------+
(3 rows)
sql> EXPLAIN QUERY PLAN
...> SELECT p.last_name, count(*) AS loans
...> FROM people p JOIN members m ON m.person_id = p.person_id
...> JOIN loans l ON l.member_id = m.member_id
...> GROUP BY p.person_id;
+----+--------+---------+----------------------------------------------------------+
| id | parent | notused | detail |
+----+--------+---------+----------------------------------------------------------+
| 8 | 0 | 0 | SCAN m |
| 10 | 0 | 0 | SEARCH l USING COVERING INDEX loans_member (member_id=?) |
| 14 | 0 | 0 | SEARCH p USING INTEGER PRIMARY KEY (rowid=?) |
| 17 | 0 | 0 | USE TEMP B-TREE FOR GROUP BY |
+----+--------+---------+----------------------------------------------------------+
(4 rows)
loans.member_id, then after ANALYZE: with the statistics, the outer loop moves to the 60 members, each searching about 7 loans in the index. Some lines are left out.Without statistics, SQLite scans the loans and looks up each loan’s member and person by rowid: the inner loops are index nested-loop joins on primary keys. The index on member_id first only changes the scan of the loans into a scan of the smaller index, which covers the query. Once ANALYZE has recorded that the index holds 400 rows, about 7 per member, the planner turns the loops round: 60 members on the outside, each with an index search. Statistics change the plan, not the result.
22.6 Exercises
Exercise 22.1 ★
has 2,000 pages and 300 pages. With 52 buffer pages, what does a block nested-loop join cost with outside, and with outside? Which should be the outer relation in general?
Solution
Solution of Exercise 22.1.
With 50 pages per block: outside, ; outside, . The number of blocks times the inner size is about either way; the outer relation is read once more, so the smaller relation should be outside, and rounding up the number of blocks also favours it.
Exercise 22.2 ★
How many passes and page I/O does external merge sort need for 5,000 pages with 11 buffer pages, and with 101? What is the largest file sorted in two passes with 11 pages?
Solution
Solution of Exercise 22.2.
With : runs, then 46, 5 and 1 after three merge passes of 10 runs: 4 passes, page I/O. With : 50 runs, merged in one pass of 100: 2 passes, 20,000. Two passes sort up to pages with 11 buffer pages: 10 runs of 11 pages, merged at once.
Exercise 22.3 ★
From the histograms of Output 22.4, compute by hand the two estimates of the number of dry days. Which assumption of Definition 22.6 makes the equi-width estimate so low?
Solution
Solution of Exercise 22.3.
Equi-width: the first bucket holds 568 days with 26 distinct values, so an equality is estimated at . Equi-depth: four buckets hold only the value 0, days counted whole, and the fifth, , has 91 days and 3 distinct values, : 395.3 in all. The assumption that every distinct value in a bucket is equally frequent makes the equi-width estimate low: 0 is one of 26 values but has 447 of the 568 days.
Exercise 22.4 ★
exercises/ex4_plan.sql lists the mystery books with their loans, before and after an index on loans.book_id. Predict SQLite’s two plans, then run it.
Solution
Solution of Exercise 22.4.
Before the index: SCAN l, then SEARCH b USING INTEGER PRIMARY KEY (rowid=?): each loan looks up its book by rowid and the genre is tested there. After it: SCAN b, then SEARCH l USING INDEX loans_book (book_id=?): the 80 books are scanned, the condition on the genre keeps the mysteries, and only their loans are found through the index. A test checks the four lines.
Exercise 22.5 ★★
exercises/ex5_hash.py always builds its hash table on its first input. Its results are correct. Join a relation of 20 pages with one of 5, with 8 buffer pages, and count its I/O against a join that builds on the smaller input. Explain the difference, and fix it.
Solution
Solution of Exercise 22.5.
The buggy join counts 85 page I/O, the fixed one 25. Building on the 20-page input, which does not fit in pages, it must partition both inputs: , plus 10 pages from part-filled buckets. Building on the 5-page input, the table fits in memory and each input is read once: . The fix compares the sizes and builds on the smaller, swapping the order of the columns back in each output tuple:
if len(S) < len(R): return join_building_on(S, R, b, a, B, disk, build_is_left=False)
Exercise 22.6 ★★
Write sort_merge_dup, a sort–merge join for join columns with duplicates on both sides, every tuple of a group of equal keys in meeting every tuple of the matching group in . It is tested against the nested loop on random relations.
Solution
Solution of Exercise 22.6.
exercises/ex6_sortmerge.py sorts both inputs, then reads each as a sequence of groups of equal keys. It advances the group of while its key is smaller than the current key of ; on equal keys it outputs the product of the two groups. A group of is kept while several groups of are compared with it, which is why groups, not single tuples, are the unit. The I/O is that of the merge join if every group of fits in memory; otherwise the group’s pages are read again for each page of the matching group. The test compares its output with the nested loop on random relations with many duplicates.
Exercise 22.7 ★★
Prove that a projection can be pushed through a join, , where is the set of columns of that occur in or in . Why must contain the columns of ?
Solution
Solution of Exercise 22.7.
Facts used: a tuple of is a pair with true; keeps the columns in .
Let be in the join. Then is in the right-hand join, since reads only columns in , and its projection on equals that of , since . Conversely, a pair of the right-hand join comes from some , with , and is true: so is in the left-hand join with the same projection. If lacked a column of , the right-hand join could not evaluate its condition: pushing below the join on book_id would lose the column the join needs.
Exercise 22.8 ★★
Show that there are left-deep join orders of relations and join trees of any shape, the two inputs of each join being ordered. How many left-deep orders avoid Cartesian products in a chain query of relations?
Solution
Solution of Exercise 22.8.
A left-deep plan is fixed by the order in which the relations enter: orders. A join tree of any shape is a binary tree with leaves, ordered children, labelled by the relations: there are tree shapes with leaves (the Catalan number) and labellings, giving . For a chain, an order avoids products exactly when the relations entered so far form a segment of the chain: the first relation is anywhere, and each next one extends the segment at its left or right end; the sequence of choices of end determines the order, and every sequence of ends determines a valid first relation. There are such orders. A test counts the trees by recursion for .
Exercise 22.9 ★★
Estimate the number of pairs of loans made by the same member, a join of the loans with themselves on member_id, from the 400 loans and 60 members, then count it on the town’s data. Prove that for a join of a relation with itself on one column, the estimate of Section 22.3 is never too high.
Solution
Solution of Exercise 22.9.
Facts used: Cauchy–Schwarz, for numbers .
The estimate is pairs; the true count is , where is the number of loans of member (pairs of a loan with itself included). For a self-join on a column with values and counts , the result has tuples and the estimate is . By Cauchy–Schwarz the estimate is at most the truth, with equality only when all are equal: skew always makes a self-join larger than estimated.
Exercise 22.10 ★★★
Prove that the Grace hash join reads and writes pages when every bucket of the smaller input fits in pages, and that with an even hash this holds when . What does one more round of partitioning cost when it does not?
Solution
Solution of Exercise 22.10.
Facts used: the partition phase uses one input buffer and output buffers; the join phase holds one bucket’s hash table in pages, with one page to read the other bucket and one for output.
Partitioning reads both inputs and writes them once, as buckets: . If each bucket of the smaller input fits in pages, the join phase reads every bucket of both inputs once: more, in all. With an even hash, the smaller input of pages splits into buckets of pages, which fit when , that is . When a bucket is too large, it and its partner are partitioned again with another hash function, one more read and write of both: if every bucket needs it, less if only some do. In Output 22.2, , and one round suffices.
Exercise 22.11 ★★★
In exercises/ex11_twocol.py, compare for four pairs of months the true number of loans out before one month and due before another with the estimate under independence, then build a two-column statistic that counts loans per (month out, month due) and estimate again. When is the two-column estimate exact, and what does it cost to store?
Solution
Solution of Exercise 22.11.
The program prints, for (out before, due before) = (3, 3), (6, 6), (6, 4) and (10, 12): true counts 40, 150, 73, 329; independence estimates 6.4, 65.2, 31.8, 311.7; two-column estimates equal to the true counts. Independence fails because the due date is the out date plus 21 days; it is close only when one condition holds for almost every row, as with a due date before December. The two-column statistic stores a count per pair of months, and its estimate is exact whenever the query’s boundaries fall on month boundaries, since the query is then a union of whole cells; for a boundary inside a month it must spread a cell’s count as a histogram does. Here it has 22 non-empty cells, the out month and the next one: at most 144 counts to store, against 12 for each column alone.
Exercise 22.12 ★★★
Extend best_plan to keep, for each set of relations, the cheapest plan for each order of its output. Find, for four relations of 50 tuples joined in a chain on one column, the plan it now chooses and the plan it chose before. Prove that the extended search finds the cheapest left-deep plan under the cost model.
Solution
Solution of Exercise 22.12.
Facts used: in the cost model, the cost of joining a relation to a plan for depends on the plan only through its number of tuples, fixed by , and its output order.
exercises/ex12_orders.py keys its table by (set, order). For four relations of 50 tuples joined on , the plain search chooses three hash joins, ; the extended search chooses three merge joins, : the first merge sorts both inputs, each later one finds its left input already sorted on and sorts only the 5-page relation. The plain search lost this because for the merge join costs as much as the hash join, 30, and only one was kept, the hash. Proof of optimality: take an optimal left-deep plan for all relations; its last join adds to a plan for with output order . Replacing by the cheapest plan for keeps the cost of the last join (same tuples, same order) and does not increase the cost of ; by induction on the size of the set, the table holds a plan as cheap as the optimum. A test compares the extended search with an exhaustive one on random queries.
22.7 Weekend problem
Problem 22.1
Weekend problem — The overdue books report
Every week the library prints its late loans, with the title of each book and the name of the borrower: a join of four tables and one condition, late, true when a book came back after its due date or is still out. With ten tuples to a page the tables have 40, 8, 6 and 12 pages, and 5 buffer pages are free. This problem plans the report three ways, costs the plans by formula, runs them, and compares the result with Selinger’s choice and SQLite’s.
def plan_a(disk): # as written: block nested loops, selection last
cur = T["loans"]
for col, table in KEYS:
cur = materialise(block_nested_loop(cur, T[table], col, col, B, disk), disk)
return list(select(late, scan(cur, disk))) # the last join's result is read back
def plan_b(disk): # selection pushed down, hash joins in the order Selinger picks
loans = materialise(select(late, scan(T["loans"], disk)), disk)
cur = materialise(
hash_join(T["people"], T["members"], "person_id", "person_id", B, disk), disk
)
cur = materialise(hash_join(cur, loans, "member_id", "member_id", B, disk), disk)
return hash_join(cur, T["books"], "book_id", "book_id", B, disk)
def plan_c(disk): # selection pushed down, then index nested loops on the keys
cur = materialise(select(late, scan(T["loans"], disk)), disk)
for col, table in KEYS:
rows = index_nested_loop(cur, T[table], col, col, INDEX[table], disk)
if table != "people":
cur = materialise(rows, disk)
return rows
$ python overdue.py
pages: loans 40, books 8, members 6, people 12; B = 5
A block nested loops, select last 109 rows, 524 reads, 120 writes, 644 page I/O
B select first, hash joins (Selinger) 109 rows, 155 reads, 89 writes, 244 page I/O
C select first, index nested loops 109 rows, 727 reads, 33 writes, 760 page I/O
same rows: True
Selinger: (((people hash members) hash late_loans) hash books)
model cost 162, estimated 109 rows, 24 plans costed for 24 orders
selinger.py with the cost in its own model.Part I — The query.
- Write the report in relational algebra, the selection last.
- To which table can late be pushed, and by which theorem?
- Why can it not be pushed into the books, members or people?
- Draw the query graph, one node per table and one edge per join condition. What shape is it?
- How many left-deep orders do four relations have, and how many avoid a Cartesian product here?
- Why does the projection on title, name and due date not go below the joins whole?
Part II — Costs by formula.
- Plan A joins with block nested loops in the order of the query and selects last. Compute its reads and writes, every join result having 400 tuples.
- Plan C selects first, writing 109 tuples, then joins by index nested loops on the three primary keys, whose indexes have height 1. Compute its reads and writes.
- Plan B selects first, then joins people with members, the result with the late loans and that with the books, all by Grace hash joins. Compute its cost by formula, the intermediate results having 60 and 109 tuples.
- Why is plan C, the plan with indexes, the most expensive here?
- What would plan C cost if the three small tables and their indexes stayed in the buffer pool?
- Which plan would you choose for this database, and which if loans had a million rows and 1 % were late?
Part III — Measured.
- Check plan A’s counted reads and writes against question 7.
- Check plan C’s against question 8.
- Plan B counts 244 page I/O against the formula of question 9. Where do the extra pages come from?
- All three plans return the same 109 rows. Which theorems guarantee it?
- How many page reads does plan A spend joining loans that are not late?
- How would pipelining, passing tuples from join to join without writing them, change plans A and B?
Part IV — The optimisers.
selinger.pychooses plan B’s order. Why does its model cost of 162 differ from the 244 counted?- Why does it start from people and members rather than from the late loans?
- Which of the three plans is SQLite’s, in Output 22.6?
- Why is that plan a good choice for SQLite, though it is the worst in this chapter’s count?
- What did
ANALYZEtell SQLite in Output 22.7, and why did the plan change? - Sum up: what does the chosen plan cost against the plan as written, and how many plans did the optimiser look at?
Solution
Solution of Problem 22.1.
1. , each join on the shared key.
2. To the loans: late reads only return_date and due_date, columns of the loans, so Theorem 22.5 applies at each join on the way down.
3. None of those tables has the dates: the condition cannot be evaluated there.
4. books – loans – members – people: a chain of four.
5. orders; avoid a Cartesian product (Exercise 22.8).
6. The joins need book_id, member_id and person_id, which the final projection drops; a pushed projection must keep them (Exercise 22.7).
7. Blocks of 3 pages: loans with books, reads, 40 written; with members, , 40 written; with people, , 40 written; then 40 read for the selection. 524 reads and 120 writes, 644 in all.
8. 40 read and 11 written for the selection; each join reads its 11 input pages and 2 pages per tuple, ; the first two results are written, 11 pages each. Reads , writes 33: 760.
9. Selection 51. People with members: the smaller, 6 pages, exceeds , so Grace: , and 6 pages written. With the late loans: , and 11 written. With the books: . In all .
10. Each of 109 tuples pays 2 page reads per join, 218, more than reading the three small tables many times over: the count has no buffer pool, so the same page of books is read again for every loan.
11. The probes then read nothing: 40 for the loans and 11 for each of the three intermediate inputs, 73 reads, and 33 writes: 106, the cheapest of the three.
12. Here plan B, or plan C if the small tables stay cached, as they would. With a million loans and 1 % late, the scan of the loans dominates every plan; the 10,000 late loans then probe three small key indexes held in memory almost for free, so plan C is best while those indexes fit in the buffer pool, and plan B when they do not.
13. The counts are 524 and 120, as in question 7.
14. 727 and 33, as in question 8.
15. The Grace partitions: 4 buckets per input, each ending in a part-filled page, written and read again; such pages.
16. Theorem 22.5 and the commutativity and associativity of joins make the three algebra trees equal; each physical join computes the equi-join exactly, as the tests check.
17. Its three joins read pages; with the selection first, the same block nested loops read . The other 347 reads carry loans that are not late.
18. Each intermediate result would no longer be written and read back. Plan A would save its 120 writes and the 120 reads of the second and third joins’ outer inputs and of the selection, 240 pages, and cost about 404 in all. Plan B would save the writes and first reads of its 11-, 6- and 11-page intermediates, pages, and cost about 188 in all.
19. The model counts only the joins, each: . The count adds the selection, 51, the writes of two intermediates, 17, and the 14 part-filled pages: .
20. Joining people and members first, the two smallest inputs, gives a 6-page result for 54; every order starting from the late loans joins their 11 pages first, and the cheapest of those costs .
21. Plan C: SCAN l, then searches of the books, members and people by rowid, index nested loops on the primary keys, with the selection applied as each loan is read.
22. SQLite’s tables are B-trees keyed by rowid, and the pages of these small tables stay in its page cache: each probe costs a few comparisons in memory, not a disk read. That is question 11’s situation, where plan C is the cheapest.
23. That loans_member holds 400 entries, about 7 per member, and that members has 60 rows. With these counts the planner estimated that 60 searches of about 7 index entries each cost less than a scan of all 400 entries with a search of the members for each, and it reversed the two loops. Without them it had to guess the sizes.
24. The plan chosen by selinger.py costs 244 page I/O as counted, 162 in its model, against 644 for the query as written: 2.6 times less. The search costed 24 plans; of the 24 orders of four relations, 8 avoid a Cartesian product.