Computer Science · Book 5 · Bachelor Year 3

University Computer Science — Year 3

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 σ\sigma, projection π\pi, renaming, product and join ⋈\bowtie, each taking relations to a relation; an equi-join R⋈a=bSR \bowtie_{a = b} S keeps the pairs of tuples with r.a=s.br.a = s.b (Year 1 volume). Comparison sorting needs Ω(nlog⁡n)\Omega(n \log n) 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 hh finds a key in hh 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
Listing 22.1. Scan, selection and projection as generators; materialise writes a stream out as pages. code/bachelor-3/22-query-optimisation/listings/exec.py

A relation larger than memory cannot be sorted by sorted. With BB pages of memory, it is sorted in passes over the file.

Definition 22.2 (External merge sort)

External merge sort sorts a file of NN pages with BB buffer pages. Pass 0 reads BB pages at a time, sorts them in memory and writes them as a sorted run, giving ⌈N/B⌉\lceil N/B \rceil runs. Each later pass merges groups of B−1B - 1 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 N>BN > B pages makes 1+⌈log⁡B−1⌈N/B⌉⌉1 + \lceil \log_{B-1} \lceil N/B \rceil \rceil passes and 2N(1+⌈log⁡B−1⌈N/B⌉⌉)2N(1 + \lceil \log_{B-1} \lceil N/B \rceil \rceil) page reads and writes.

Proof. Pass 0 leaves r0=⌈N/B⌉r_0 = \lceil N/B \rceil runs. A merge pass turns rr runs into ⌈r/(B−1)⌉\lceil r/(B-1) \rceil, so after kk merge passes there are ⌈r0/(B−1)k⌉\lceil r_0 / (B-1)^k \rceil runs (ceilings compose: ⌈⌈x⌉/m⌉=⌈x/m⌉\lceil \lceil x \rceil / m \rceil = \lceil x/m \rceil for an integer mm). One run is left exactly when (B−1)k≥r0(B-1)^k \ge r_0, so the least such kk is ⌈log⁡B−1r0⌉\lceil \log_{B-1} r_0 \rceil. Every pass reads every page once and writes every page once: 2N2N 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
Listing 22.2. External merge sort: runs of BB pages, then (B−1)(B-1)-way merges with 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
Output 22.1. Counted I/O equals the formula for every size. With 100 buffer pages, 10,000 pages sort in three passes; with 3, in thirteen.

The logarithm’s base is what memory buys: with B=100B = 100, two passes sort any file of up to 100×99=9,900100 \times 99 = 9{,}900 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 RR have MM pages and ∣R∣|R| tuples, SS have NN pages, and BB buffer pages be free. The nested-loop join scans SS once for each tuple of RR: M+∣R∣NM + |R| N page reads. The block nested-loop join loads B−2B - 2 pages of RR at a time and scans SS once per block: M+⌈M/(B−2)⌉NM + \lceil M/(B-2) \rceil N. The index nested-loop join searches an index on SS’s join column for each tuple of RR: M+∣R∣(h+1)M + |R|(h + 1) for an index of height hh and one matching tuple. The sort–merge join sorts both inputs on the join column and merges them: the two sorts plus M+NM + N. The hash join builds a hash table on the smaller input and probes it with the other: M+NM + N if the smaller fits in B−2B - 2 pages; otherwise the Grace variant first partitions both inputs into B−1B - 1 buckets on disk by a hash of the join column and joins bucket by bucket: 3(M+N)3(M + N).

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
Listing 22.3. The two nested loops: once per tuple, or once per block of B−2B - 2 pages. code/bachelor-3/22-query-optimisation/listings/joins.py
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
Listing 22.4. Sort–merge and hash joins. The merge advances in SS only, since SS’s column is a key. code/bachelor-3/22-query-optimisation/listings/joins.py
$ 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
Output 22.2. The five joins of 10,000 loans with 1,000 books, 12 buffer pages. Each counted cost equals its formula, except the Grace hash join, whose 22 bucket files end in part-filled pages.

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 h+1=3h + 1 = 3 reads per loan, which loses here because every loan matches; it wins when few tuples of RR 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.

Counted page I/O of four joins as R grows from 100 to 1,000 pages, S fixed at 100 pages, 12 buffer pages. The tuple nested loop is off the chart: 100,100 already at M = 100.
Counted page I/O of four joins as RR grows from 100 to 1,000 pages, SS fixed at 100 pages, 12 buffer pages. The tuple nested loop is off the chart: 100,100 already at M=100M = 100.

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, σc1∧c2(E)=σc1(σc2(E))\sigma_{c_1 \wedge c_2}(E) = \sigma_{c_1}(\sigma_{c_2}(E)); 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 cc uses only columns of E1E_1, then σc(E1⋈θE2)=σc(E1)⋈θE2\sigma_c(E_1 \bowtie_\theta E_2) = \sigma_c(E_1) \bowtie_\theta E_2.

Proof. A tuple of the left side is a pair (t1,t2)(t_1, t_2) with t1∈E1t_1 \in E_1, t2∈E2t_2 \in E_2, θ(t1,t2)\theta(t_1, t_2) true and c(t1,t2)c(t_1, t_2) true. Since cc reads only columns of E1E_1, c(t1,t2)=c(t1)c(t_1, t_2) = c(t_1), so the conditions are t1∈E1t_1 \in E_1 and c(t1)c(t_1), that is t1∈σc(E1)t_1 \in \sigma_c(E_1), together with t2∈E2t_2 \in E_2 and θ(t1,t2)\theta(t_1, t_2): 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)
Listing 22.5. Push a selection into the side of a join that holds all the columns it reads. code/bachelor-3/22-query-optimisation/listings/rewrite.py
$ 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)
Output 22.3. Late mystery loans, as written and rewritten: the same 11 rows, with 1,331 intermediate rows reduced to 162.
The two trees of . On the left, every join carries all 400 loans and the conditions remove 389 of them at the end; on the right, the first join already has only 11 rows.
The two trees of Output 22.3. On the left, every join carries all 400 loans and the conditions remove 389 of them at the end; on the right, the first join already has only 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 VV distinct values selects 1/V1/V 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
Listing 22.6. An equi-depth histogram, and the estimate any histogram gives for a range or an equality. code/bachelor-3/22-query-optimisation/listings/histogram.py
$ 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
Output 22.4. Two histograms of 8 buckets on the same 731 values, three conditions, and two correlated columns of the loans.

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 c1∧c2c_1 \wedge c_2 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 V(R,a)V(R, a) and V(S,b)V(S, b) distinct values, the standard estimate assumes every value of the column with fewer values appears in the other:

∣R⋈a=bS∣≈∣R∣ ∣S∣max⁡(V(R,a),V(S,b)).|R \bowtie_{a = b} S| \approx \frac{|R|\,|S|}{\max(V(R, a), V(S, b))}.

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

For nn relations there are n!n! left-deep orders and (2n−2)!/(n−1)!(2n - 2)!/(n - 1)! 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 SS of relations ends by joining some r∈Sr \in S to a plan for S∖{r}S \setminus \{r\}, and that plan may as well be the cheapest one for S∖{r}S \setminus \{r\}: 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
Listing 22.7. Dynamic programming over sets of relations; each join is costed as a hash join and as a sort–merge join. code/bachelor-3/22-query-optimisation/listings/selinger.py
$ 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)
Output 22.5. Chain and star queries on generated relations: a few dozen plans costed instead of n!n! orders.
The sets of relations of a chain query R_1 - R_2 - R_3 - R_4. The dynamic programming fills the shaded sets from the bottom up; the grey ones, on the right, would need a Cartesian product and are skipped. Each line is a join that is costed.
The sets of relations of a chain query R1−R2−R3−R4R_1 - R_2 - R_3 - R_4. The dynamic programming fills the shaded sets from the bottom up; the grey ones, on the right, would need a Cartesian product and are skipped. Each line is a join that is costed.

The program keeps one plan per set. That is where interesting orders come in: a plan for {R1,R2}\{R_1, R_2\} 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)
Output 22.6. The late-loans report and a count of loans per person on the town’s library: every join is a loop, and each inner loop searches by rowid. Some lines are left out.
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)
Output 22.7. The same count after an index on 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 ★

RR has 2,000 pages and SS 300 pages. With 52 buffer pages, what does a block nested-loop join cost with RR outside, and with SS outside? Which should be the outer relation in general?

Solution

Solution of Exercise 22.1.

With 50 pages per block: RR outside, 2,000+40×300=14,0002{,}000 + 40 \times 300 = 14{,}000; SS outside, 300+6×2,000=12,300300 + 6 \times 2{,}000 = 12{,}300. The number of blocks times the inner size is about MN/(B−2)MN/(B-2) 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 B=11B = 11: ⌈5000/11⌉=455\lceil 5000/11 \rceil = 455 runs, then 46, 5 and 1 after three merge passes of 10 runs: 4 passes, 2×5,000×4=40,0002 \times 5{,}000 \times 4 = 40{,}000 page I/O. With B=101B = 101: 50 runs, merged in one pass of 100: 2 passes, 20,000. Two passes sort up to B(B−1)=110B(B-1) = 110 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 568/26≈21.8568/26 \approx 21.8. Equi-depth: four buckets hold only the value 0, 91+91+92+91=36591 + 91 + 92 + 91 = 365 days counted whole, and the fifth, [0,0.2][0, 0.2], has 91 days and 3 distinct values, 91/3≈30.391/3 \approx 30.3: 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 B−2=6B - 2 = 6 pages, it must partition both inputs: 3(20+5)=753(20 + 5) = 75, plus 10 pages from part-filled buckets. Building on the 5-page input, the table fits in memory and each input is read once: 20+5=2520 + 5 = 25. 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 RR meeting every tuple of the matching group in SS. 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 SS while its key is smaller than the current key of RR; on equal keys it outputs the product of the two groups. A group of SS is kept while several groups of RR 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 SS fits in memory; otherwise the group’s pages are read again for each page of the matching RR 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, πL(E1⋈θE2)=πL(πL1(E1)⋈θπL2(E2))\pi_L(E_1 \bowtie_\theta E_2) = \pi_L(\pi_{L_1}(E_1) \bowtie_\theta \pi_{L_2}(E_2)), where LiL_i is the set of columns of EiE_i that occur in LL or in θ\theta. Why must LiL_i contain the columns of θ\theta?

Solution

Solution of Exercise 22.7.

Facts used: a tuple of E1⋈θE2E_1 \bowtie_\theta E_2 is a pair (t1,t2)(t_1, t_2) with θ(t1,t2)\theta(t_1, t_2) true; πL\pi_L keeps the columns in LL.

Let (t1,t2)(t_1, t_2) be in the join. Then (t1[L1],t2[L2])(t_1[L_1], t_2[L_2]) is in the right-hand join, since θ\theta reads only columns in L1∪L2L_1 \cup L_2, and its projection on LL equals that of (t1,t2)(t_1, t_2), since L⊆L1∪L2L \subseteq L_1 \cup L_2. Conversely, a pair (u1,u2)(u_1, u_2) of the right-hand join comes from some t1∈E1t_1 \in E_1, t2∈E2t_2 \in E_2 with ui=ti[Li]u_i = t_i[L_i], and θ(t1,t2)=θ(u1,u2)\theta(t_1, t_2) = \theta(u_1, u_2) is true: so (t1,t2)(t_1, t_2) is in the left-hand join with the same projection. If LiL_i lacked a column of θ\theta, the right-hand join could not evaluate its condition: pushing πtitle\pi_{\mathit{title}} below the join on book_id would lose the column the join needs.

Exercise 22.8 ★★

Show that there are n!n! left-deep join orders of nn relations and (2n−2)!/(n−1)!(2n - 2)!/(n - 1)! 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 nn relations?

Solution

Solution of Exercise 22.8.

A left-deep plan is fixed by the order in which the relations enter: n!n! orders. A join tree of any shape is a binary tree with nn leaves, ordered children, labelled by the relations: there are Cn−1=(2n−2)!n! (n−1)!C_{n-1} = \frac{(2n-2)!}{n!\,(n-1)!} tree shapes with nn leaves (the Catalan number) and n!n! labellings, giving (2n−2)!/(n−1)!(2n-2)!/(n-1)!. 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 n−1n - 1 choices of end determines the order, and every sequence of ends determines a valid first relation. There are 2n−12^{n-1} such orders. A test counts the trees by recursion for n≤7n \le 7.

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, (∑vcv)2≤V∑vcv2(\sum_v c_v)^2 \le V \sum_v c_v^2 for VV numbers cvc_v.

The estimate is 400×400/60≈2,667400 \times 400/60 \approx 2{,}667 pairs; the true count is ∑vcv2=3,084\sum_v c_v^2 = 3{,}084, where cvc_v is the number of loans of member vv (pairs of a loan with itself included). For a self-join on a column with VV values and counts cvc_v, the result has ∑vcv2\sum_v c_v^2 tuples and the estimate is ∣R∣2/V=(∑vcv)2/V|R|^2/V = (\sum_v c_v)^2 / V. By Cauchy–Schwarz the estimate is at most the truth, with equality only when all cvc_v are equal: skew always makes a self-join larger than estimated.

Exercise 22.10 ★★★

Prove that the Grace hash join reads and writes 3(M+N)3(M + N) pages when every bucket of the smaller input fits in B−2B - 2 pages, and that with an even hash this holds when min⁡(M,N)≤(B−1)(B−2)\min(M, N) \le (B-1)(B-2). 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 B−1B - 1 output buffers; the join phase holds one bucket’s hash table in B−2B - 2 pages, with one page to read the other bucket and one for output.

Partitioning reads both inputs and writes them once, as buckets: 2(M+N)2(M + N). If each bucket of the smaller input fits in B−2B - 2 pages, the join phase reads every bucket of both inputs once: M+NM + N more, 3(M+N)3(M + N) in all. With an even hash, the smaller input of m=min⁡(M,N)m = \min(M, N) pages splits into buckets of m/(B−1)m/(B-1) pages, which fit when m/(B−1)≤B−2m/(B-1) \le B - 2, that is m≤(B−1)(B−2)m \le (B-1)(B-2). When a bucket is too large, it and its partner are partitioned again with another hash function, one more read and write of both: 5(M+N)5(M + N) if every bucket needs it, less if only some do. In Output 22.2, min⁡(M,N)=100≤11×10\min(M, N) = 100 \le 11 \times 10, 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 rr to a plan for SS depends on the plan only through its number of tuples, fixed by SS, and its output order.

exercises/ex12_orders.py keys its table by (set, order). For four relations of 50 tuples joined on kk, the plain search chooses three hash joins, 3×30=903 \times 30 = 90; the extended search chooses three merge joins, 30+20+20=7030 + 20 + 20 = 70: the first merge sorts both inputs, each later one finds its left input already sorted on kk and sorts only the 5-page relation. The plain search lost this because for {R3,R4}\{R_3, R_4\} 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 rr to a plan PP for S∖{r}S \setminus \{r\} with output order oo. Replacing PP by the cheapest plan for (S∖{r},o)(S \setminus \{r\}, o) keeps the cost of the last join (same tuples, same order) and does not increase the cost of PP; 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
Listing 22.8. Three physical plans; every intermediate result is written out and read back. code/bachelor-3/22-query-optimisation/listings/overdue.py
$ 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
Output 22.8. The three plans counted, and the plan chosen by selinger.py with the cost in its own model.

Part I — The query.

  1. Write the report in relational algebra, the selection last.
  2. To which table can late be pushed, and by which theorem?
  3. Why can it not be pushed into the books, members or people?
  4. Draw the query graph, one node per table and one edge per join condition. What shape is it?
  5. How many left-deep orders do four relations have, and how many avoid a Cartesian product here?
  6. Why does the projection on title, name and due date not go below the joins whole?

Part II — Costs by formula.

  1. 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.
  2. 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.
  3. 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.
  4. Why is plan C, the plan with indexes, the most expensive here?
  5. What would plan C cost if the three small tables and their indexes stayed in the buffer pool?
  6. Which plan would you choose for this database, and which if loans had a million rows and 1 % were late?

Part III — Measured.

  1. Check plan A’s counted reads and writes against question 7.
  2. Check plan C’s against question 8.
  3. Plan B counts 244 page I/O against the formula of question 9. Where do the extra pages come from?
  4. All three plans return the same 109 rows. Which theorems guarantee it?
  5. How many page reads does plan A spend joining loans that are not late?
  6. How would pipelining, passing tuples from join to join without writing them, change plans A and B?

Part IV — The optimisers.

  1. selinger.py chooses plan B’s order. Why does its model cost of 162 differ from the 244 counted?
  2. Why does it start from people and members rather than from the late loans?
  3. Which of the three plans is SQLite’s, in Output 22.6?
  4. Why is that plan a good choice for SQLite, though it is the worst in this chapter’s count?
  5. What did ANALYZE tell SQLite in Output 22.7, and why did the plan change?
  6. 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. πtitle,last_name,due_date σlate(((loans⋈books)⋈members)⋈people)\pi_{\mathit{title}, \mathit{last\_name}, \mathit{due\_date}}\, \sigma_{\mathit{late}}\bigl(((\mathit{loans} \bowtie \mathit{books}) \bowtie \mathit{members}) \bowtie \mathit{people}\bigr), 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. 4!=244! = 24 orders; 23=82^3 = 8 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, 40+14×8=15240 + 14 \times 8 = 152 reads, 40 written; with members, 40+14×6=12440 + 14 \times 6 = 124, 40 written; with people, 40+14×12=20840 + 14 \times 12 = 208, 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, 11+218=22911 + 218 = 229; the first two results are written, 11 pages each. Reads 40+3×229=72740 + 3 \times 229 = 727, writes 33: 760.

9. Selection 51. People with members: the smaller, 6 pages, exceeds B−2=3B - 2 = 3, so Grace: 3(12+6)=543(12 + 6) = 54, and 6 pages written. With the late loans: 3(6+11)=513(6 + 11) = 51, and 11 written. With the books: 3(11+8)=573(11 + 8) = 57. In all 51+54+6+51+11+57=23051 + 54 + 6 + 51 + 11 + 57 = 230.

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; 244−230=14244 - 230 = 14 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 152+124+208=484152 + 124 + 208 = 484 pages; with the selection first, the same block nested loops read 43+35+59=13743 + 35 + 59 = 137. 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, 2×28=562 \times 28 = 56 pages, and cost about 188 in all.

19. The model counts only the joins, 3(L+P)3(L + P) each: 54+51+57=16254 + 51 + 57 = 162. The count adds the selection, 51, the writes of two intermediates, 17, and the 14 part-filled pages: 162+51+17+14=244162 + 51 + 17 + 14 = 244.

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 51+69+57=17751 + 69 + 57 = 177.

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.

Terms defined in this chapter

See all 1050 terms in the glossary