Algorithm Search⌘K

Algorithmcore

Greedy operator ordering

Also called GOO, greedy join ordering by result size.

A join ordering heuristic that repeatedly joins the two current subplans whose join has the smallest estimated result.

Time
O(n^3) worst
Space
O(n^2) extra
Where
n = the number of relations
Properties
deterministicnot exactgreedyiterative
Origin
Leonidas Fegaras, 1998

Greedy operator ordering (GOO) is a heuristic for join ordering. It starts with one plan per relation. In each step it looks at every pair of current plans that a join predicate links, estimates the size of their join, and joins the pair with the smallest result. After n−1n - 1 steps one bushy plan is left. GOO takes O(n3)O(n^3) time, so it works for queries with hundreds of relations, where exact dynamic programs such as DPccp are too slow. The price is that the plan may cost more than the optimum. Leonidas Fegaras gave it in 1998.

In plain words

Joining many tables in a bad order makes huge intermediate results. GOO follows a simple rule: keep the intermediate results small. At the start, every table is its own piece. At each step, look at every two pieces that a join condition connects, guess how many rows their join would give, and join the two pieces with the smallest guess. Repeat until one piece is left.

The rule can join any two pieces, not only a piece and a single table, so the plan can be bushy. The rule is fast, but it only looks one step ahead. A join that is small now can lead to large joins later, so GOO does not always find the best plan.

The problem

The input is a query graph on relations R0,…,Rn−1R_0, \ldots, R_{n-1} with the estimated size of each relation and a selectivity on each edge. The size of a set SS of relations is the product of the sizes of its relations and of the selectivities of the edges inside SS. Two sets are linked if an edge has one end in each. The cost of a plan is CoutC_{out}, the sum of the sizes of its joins. GOO does not solve this problem exactly; it builds some bushy plan without cross products, quickly, and tries to keep the cost low.

The algorithm

  1. GOO(relations R_0, ..., R_(n-1), sizes, selectivities)
  2. 1T ← {R_0, ..., R_(n-1)}
  3. 2while T has two or more trees do
  4. 3among the pairs {T_i, T_j} of trees in T that an edge links (all pairs if none is linked), choose one with the smallest |T_i ⋈ T_j|
  5. 4T ← T - {T_i, T_j} ∪ {T_i ⋈ T_j}
  6. 5|T_i ⋈ T_j| ← |T_i| · |T_j| · (the product of the selectivities of the edges between T_i and T_j)
  7. 6return the one tree in T

The code stores the size of each tree and, for each pair of trees, the product of the selectivities between them. When two trees join, the value between the new tree and another tree TkT_k is the product of the values of the two old trees with TkT_k. Each size then costs O(1)O(1) to compute. The code puts the larger input on the left of each join, so that a hash join that builds on the right input builds on the smaller one. It uses a cross product only when no two trees are linked, which happens only when the query graph is not connected.

Example

The chain AA-BB-CC-DD has relations of 20, 10, 1000 and 20 tuples and the selectivities 1/5 on AA-BB, 1/100 on BB-CC and 1/100 on CC-DD.

step candidate joins and their sizes chosen
1 A⋈BA \bowtie B: 40, B⋈CB \bowtie C: 100, C⋈DC \bowtie D: 200 A⋈BA \bowtie B, 40
2 (AB)⋈C(AB) \bowtie C: 400, C⋈DC \bowtie D: 200 C⋈DC \bowtie D, 200
3 (AB)⋈(CD)(AB) \bowtie (CD): 80 80

GOO returns (C⋈D)⋈(A⋈B)(C \bowtie D) \bowtie (A \bowtie B) with cost 40+200+80=32040 + 200 + 80 = 320. The optimal plan is A⋈((B⋈C)⋈D)A \bowtie ((B \bowtie C) \bowtie D), with cost 100+20+80=200100 + 20 + 80 = 200: it starts with a larger join, B⋈CB \bowtie C with 100 tuples, but then DD cuts the result to 20 tuples. GOO took the smallest join first and then had to pay 200 for C⋈DC \bowtie D.

Correctness

GOO is a heuristic, so its correctness is about what it builds, not about optimality. The invariant is that the trees in TT always partition the relations, and that the stored size of each tree and the stored selectivity between each two trees are exact for the estimates. So each step picks a candidate pair with the smallest estimated join size, the result is a join tree with every relation as a leaf exactly once, and its returned cost is the true CoutC_{out} of that tree. If the query graph is connected, some two trees are always linked, so no join is a cross product. With three or fewer relations GOO is optimal, because the last join has the same size in every plan. The example shows that with four relations it can cost 1.6 times the optimum. The proof file has the details.

Proof: Greedy operator ordering builds a valid join tree, without cross products on a connected query graph, and takes the smallest join in each stepfull

Setting. The query graph has the relations R0,…,Rn−1R_0, \ldots, R_{n-1} with sizes ∣Ri∣|R_i| and a selectivity fef_e on each edge ee. For a set SS of relations, ∣S∣=∏i∈S∣Ri∣⋅∏e⊆Sfe|S| = \prod_{i \in S} |R_i| \cdot \prod_{e \subseteq S} f_e is the estimated size of the join of SS. For two disjoint sets AA and BB, f(A,B)f(A, B) is the product of fef_e over the edges with one end in AA and the other in BB, and AA and BB are linked if there is at least one such edge. A candidate in a step is a pair of current trees that are linked, or any pair of current trees if no pair is linked or if cross products are allowed. The cost of a plan is CoutC_{out}, the sum of the sizes of its joins. GOO is a heuristic, so the statement to prove is what it builds, not that the result is optimal.

Lemma 1 (invariant). At the start of each iteration of line L2, the leaf sets of the trees in TT are disjoint and their union is all relations. For each tree tt with leaf set StS_t, the stored size is ∣St∣|S_t|, and for two trees ss and tt the stored value between them is f(Ss,St)f(S_s, S_t) if they are linked and empty if they are not.

Proof. Line L1 makes one tree per relation, with size ∣Ri∣|R_i|, and the stored values between trees are the selectivities of the edges. Suppose the invariant holds and line L3 picks trees aa and bb. The edges inside Sa∪SbS_a \cup S_b are those inside SaS_a, those inside SbS_b, and those between them, so ∣Sa∪Sb∣=∣Sa∣⋅∣Sb∣⋅f(Sa,Sb)|S_a \cup S_b| = |S_a| \cdot |S_b| \cdot f(S_a, S_b), where f(Sa,Sb)=1f(S_a, S_b) = 1 if they are not linked. This is the size that line L5 stores. For another tree cc, the edges between Sa∪SbS_a \cup S_b and ScS_c are those between SaS_a and ScS_c and those between SbS_b and ScS_c, so f(Sa∪Sb,Sc)=f(Sa,Sc)⋅f(Sb,Sc)f(S_a \cup S_b, S_c) = f(S_a, S_c) \cdot f(S_b, S_c), and the two sets are linked exactly when aa or bb is linked to cc. The code stores this value. Line L4 replaces aa and bb by their join, so the leaf sets still partition the relations. □\square

Lemma 2 (greedy choice). In each step, the pair that line L3 picks has the smallest estimated join size among all candidates, and ties go to the pair with the smallest tree numbers.

Proof. Line L3 looks at every pair of current trees once, skips the pairs that are not candidates, and computes the size of each candidate as ∣Sa∣⋅∣Sb∣⋅f(Sa,Sb)|S_a| \cdot |S_b| \cdot f(S_a, S_b), which is ∣Sa∪Sb∣|S_a \cup S_b| by Lemma 1. It keeps a pair only if its size is strictly smaller than the best so far, and it looks at the pairs in increasing order of tree numbers. □\square

Lemma 3 (no cross products). If the query graph is connected and cross products are not allowed, every join that GOO makes has an edge between its two inputs. Then the leaf set of every tree is connected in the query graph.

Proof. While TT has two or more trees, their leaf sets partition the relations into two or more parts (Lemma 1). The graph is connected, so some edge has its ends in two different parts, and the two trees are linked. So the candidates are the linked pairs, and the chosen pair is linked. A join of two connected leaf sets with an edge between them has a connected leaf set. □\square

Theorem. GOO stops after n−1n - 1 joins and returns a join tree whose leaves are R0,…,Rn−1R_0, \ldots, R_{n-1}, each once. Its returned cost is the CoutC_{out} cost of the tree. If the query graph is connected and cross products are not allowed, the tree has no cross product. Each join is a smallest candidate of its step.

Proof. Each iteration of line L2 reduces the number of trees by one, so after n−1n - 1 iterations one tree is left, and by Lemma 1 its leaf set is all relations, with each relation in exactly one leaf. The code adds the size of each new join to the cost, and by Lemma 1 this size is ∣Sa∪Sb∣|S_a \cup S_b|, the size of the join in the plan, so the sum is CoutC_{out}. The other two claims are Lemmas 3 and 2. ■\blacksquare

Small queries. On a connected query graph with at most three relations, GOO returns an optimal plan without cross products. With one relation there is no join, and with two there is one plan. With three relations, every plan has two joins, and the second one has the size ∣{R0,R1,R2}∣|\{R_0, R_1, R_2\}|, which is the same for all plans. The first join of a plan without cross products is a linked pair, and GOO takes a linked pair of smallest size, so no plan has a smaller cost.

Not optimal in general. Take the chain AA-BB-CC-DD with sizes 20, 10, 1000 and 20 and selectivities 1/5, 1/100 and 1/100 on its edges. The joins of two relations have sizes ∣AB∣=40|AB| = 40, ∣BC∣=100|BC| = 100 and ∣CD∣=200|CD| = 200, so GOO first joins AA and BB. Then ∣ABC∣=400|ABC| = 400 and ∣CD∣=200|CD| = 200, so it joins CC and DD, and the last join has size 80. The total is 40+200+80=32040 + 200 + 80 = 320. The plan A⋈((B⋈C)⋈D)A \bowtie ((B \bowtie C) \bowtie D) costs 100+20+80=200100 + 20 + 80 = 200. The step that looked best, the join of size 40, led to a step of size 200, while the join of size 100 led to a step of size 20.

Work. With kk trees, line L3 looks at fewer than k2/2k^2/2 pairs, each in O(1)O(1) steps with the stored values, and the update after a join takes O(k)O(k) steps. Summed over k=nk = n down to 2, this is O(n3)O(n^3). The stored values between trees take O(n2)O(n^2) space.

Complexity

There are n−1n - 1 steps. With kk trees, a step looks at fewer than k2/2k^2/2 pairs in O(1)O(1) each, and the update after the join takes O(k)O(k). The total is O(n3)O(n^3) time. The table of selectivities between trees takes O(n2)O(n^2) space. If the query graph has few edges, it is enough to look at the linked pairs, which lowers the work of each step.

Properties

  • Heuristic. The plan has no guarantee of optimality, and the example shows a plan 1.6 times the optimum on four relations.
  • Bushy plans. It can join two intermediate results, unlike a greedy rule that adds one relation at a time to a left-deep plan.
  • No cross products on connected graphs. Every join has a predicate between its inputs when the query graph is connected.
  • Deterministic. With a fixed tie rule, the same input gives the same plan.
  • Depends on estimates. Every choice uses estimated sizes, so errors in cardinality estimation change the plan directly.

Variants and improvements

  • Other greedy criteria. A greedy rule can pick the pair with the smallest selectivity, or the smallest cost of the join operator, instead of the smallest result. The shape of the loop is the same.
  • Cross products. If cross products are allowed in every step, a join of two very small relations without a predicate can be chosen. The code of this page allows this with a flag.
  • Hypergraphs. With complex predicates, two trees are linked when a hyperedge has one side in each, as in DPhyp.
  • A start for other searches. The plan of GOO can be the start plan of a randomized search such as simulated annealing, or an upper bound for a search that prunes plans by cost.

When to use it

Use it when a query has too many relations for an exact join enumerator, for example more than about 15 to 20 relations, depending on the shape of the query graph, and a plan is needed quickly. For tree-shaped queries where a left-deep plan is acceptable, the IKKBZ algorithm gives the optimal left-deep order in polynomial time. For small queries, use an exact method such as DPccp.

Pitfalls

  • Treating it as optimal. The result can cost more than the optimum even on four relations.
  • Stale sizes. After a join, the size of the new tree and its selectivities to the other trees must be updated; using the old values of the inputs gives wrong choices.
  • Ties. Many queries have joins of equal estimated size. Without a fixed tie rule, the plan can change between runs.
  • Cross products by accident. If the code scores all pairs, a cross product of two tiny relations can look like the smallest join; restrict the candidates to linked pairs unless cross products are wanted.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dbrel.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.

This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.

Relations
    Relation(schema, rows, mode) holds a tuple of distinct attribute names and
    a collections.Counter from tuples to positive counts. mode is "bag" (the
    default, SQL semantics) or "set" (relational theory); in set mode every
    count is 1. rows may be an iterable of tuples (duplicates add up) or a
    mapping from tuples to counts. Two relations are equal when they have the
    same attributes (in any column order) and the same count for each tuple.
    The mode is not compared.

Operators (each returns a new Relation in the mode of its input)
    select(rel, pred)            keeps a row only when pred(row) is True
    where(rel, pred)             the same as select (the SQL WHERE filter)
    project(rel, attrs)          bag: counts add up; set: duplicates removed
    rename(rel, mapping)         mapping is {old: new}
    union(r, s)                  bag: UNION ALL (counts add); set: union
    difference(r, s)             bag: monus max(0, m - n); set: r - s
    intersection(r, s)           bag: min(m, n); set: intersection
    product(r, s)                attributes must be disjoint; counts multiply
    natural_join(r, s)           nested loops on the common attributes
    theta_join(r, s, pred)       select(product(r, s), pred)
    semijoin(r, s), antijoin(r, s)
    distinct(rel)                every count becomes 1
    aggregate(rel, group_attrs, aggs)
                                 aggs is a list of (func, attr, out) with func in
                                 count_star, count, count_distinct, sum, avg, min, max

A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.

Nulls
    NULL is None. Joins follow SQL: a common attribute that is None in either
    row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
    column in one group, every aggregate except count_star skips nulls, and
    sum, avg, min and max of no non-null value give None while count gives 0.
    With no grouping attributes, aggregate returns one row even for an empty
    input, as SQL does.

Expressions
    evaluate(expr, db, mode) evaluates a tree of nested tuples:
        ("scan", name)
        ("select", pred, e)          ("project", attrs, e)
        ("rename", mapping, e)       ("distinct", e)
        ("union", e1, e2)            ("difference", e1, e2)
        ("intersection", e1, e2)     ("product", e1, e2)
        ("join", e1, e2)             ("theta_join", pred, e1, e2)
        ("semijoin", e1, e2)         ("antijoin", e1, e2)
        ("aggregate", group_attrs, aggs, e)
    db maps a name to a Relation. Each scanned relation is first put in mode.

Three-valued logic
    tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
    and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
    returns None when x or y is None.

Disk
    Disk counts page reads and writes. load(rows, per_page) puts an existing
    input on the disk without counting it. paginate(rows, per_page) splits a
    list of rows into pages.

Random data
    random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""

from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random

BAG = "bag"
SET = "set"
MODES = (BAG, SET)


# ---------------------------------------------------------------- ordering

def value_key(v: object) -> tuple:
    """A total order on the values of one column: None first, then numbers, then strings."""
    if v is None:
        return (0, 0)
    if isinstance(v, Number):
        return (1, v)
    if isinstance(v, str):
        return (2, v)
    if isinstance(v, tuple):
        return (3, tuple(value_key(x) for x in v))
    return (4, repr(v))


def row_key(t: Sequence) -> tuple:
    """A total order on tuples that tolerates None. Use it to sort rows in tests."""
    return tuple(value_key(v) for v in t)


# ---------------------------------------------------------------- relations

class Relation:
    """A relation: a schema (tuple of names), a Counter of tuples and a mode."""

    __slots__ = ("schema", "rows", "mode")

    def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
        if mode not in MODES:
            raise ValueError("mode must be 'bag' or 'set'")
        schema = tuple(schema)
        if len(set(schema)) != len(schema):
            raise ValueError("duplicate attribute in schema %r" % (schema,))
        counts: Counter = Counter()
        items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
        for t, c in items:
            t = tuple(t)
            if len(t) != len(schema):
                raise ValueError("tuple %r does not fit schema %r" % (t, schema))
            if c < 0:
                raise ValueError("negative count for %r" % (t,))
            if c:
                counts[t] += c
        if mode == SET:
            counts = Counter({t: 1 for t in counts})
        self.schema = schema
        self.rows = counts
        self.mode = mode

    def index(self, attr: str) -> int:
        return self.schema.index(attr)

    def reorder(self, schema: Sequence[str]) -> "Relation":
        """The same relation with its columns in the order of schema."""
        schema = tuple(schema)
        if sorted(schema) != sorted(self.schema):
            raise ValueError("schemas %r and %r differ" % (self.schema, schema))
        pos = [self.schema.index(a) for a in schema]
        return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)

    def with_mode(self, mode: str) -> "Relation":
        return Relation(self.schema, self.rows, mode)

    def as_dict(self, t: Sequence) -> dict:
        return dict(zip(self.schema, t))

    def sorted_rows(self) -> list:
        """Every tuple, repeated by its count, in row_key order."""
        out = []
        for t in sorted(self.rows, key=row_key):
            out.extend([t] * self.rows[t])
        return out

    def __iter__(self):
        return iter(self.sorted_rows())

    def __len__(self) -> int:
        return sum(self.rows.values())

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Relation):
            return NotImplemented
        if sorted(self.schema) != sorted(other.schema):
            return False
        return self.rows == other.reorder(self.schema).rows

    def __repr__(self) -> str:
        body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
        return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)


def _mode2(r: Relation, s: Relation) -> str:
    if r.mode != s.mode:
        raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
    return r.mode


def _same_schema(r: Relation, s: Relation) -> Relation:
    """s with its columns in the order of r; the attribute sets must be equal."""
    if sorted(r.schema) != sorted(s.schema):
        raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
    return s.reorder(r.schema)


# ---------------------------------------------------------------- three-valued logic

def tv_and(a: bool | None, b: bool | None) -> bool | None:
    if a is False or b is False:
        return False
    if a is None or b is None:
        return None
    return True


def tv_or(a: bool | None, b: bool | None) -> bool | None:
    if a is True or b is True:
        return True
    if a is None or b is None:
        return None
    return False


def tv_not(a: bool | None) -> bool | None:
    return None if a is None else not a


_CMP = {
    "=": lambda x, y: x == y,
    "<>": lambda x, y: x != y,
    "!=": lambda x, y: x != y,
    "<": lambda x, y: x < y,
    "<=": lambda x, y: x <= y,
    ">": lambda x, y: x > y,
    ">=": lambda x, y: x >= y,
}


def cmp3(op: str, x: object, y: object) -> bool | None:
    """SQL comparison: None (UNKNOWN) if either side is NULL."""
    if op not in _CMP:
        raise ValueError("unknown comparison %r" % (op,))
    if x is None or y is None:
        return None
    return bool(_CMP[op](x, y))


def is_true(v: bool | None) -> bool:
    """The WHERE test: only True passes; False and None (UNKNOWN) do not."""
    return v is True


# ---------------------------------------------------------------- operators

def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
    return Relation(rel.schema, out, rel.mode)


where = select


def project(rel: Relation, attrs: Sequence[str]) -> Relation:
    attrs = tuple(attrs)
    pos = [rel.index(a) for a in attrs]
    out: Counter = Counter()
    for t, c in rel.rows.items():
        out[tuple(t[i] for i in pos)] += c
    return Relation(attrs, out, rel.mode)


def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
    for a in mapping:
        if a not in rel.schema:
            raise ValueError("no attribute %r to rename" % (a,))
    return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)


def union(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = Counter(r.rows)
    out.update(s.rows)
    return Relation(r.schema, out, mode)


def difference(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def intersection(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def product(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    if common:
        raise ValueError("product needs disjoint schemas; common: %r" % (common,))
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            out[t + u] += c * d
    return Relation(r.schema + s.schema, out, mode)


def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
    for a in common:
        x, y = t[r.index(a)], u[s.index(a)]
        if x is None or y is None or x != y:
            return False
    return True


def natural_join(r: Relation, s: Relation) -> Relation:
    """Nested loops over both inputs. With no common attribute it is the product."""
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    rest = [a for a in s.schema if a not in common]
    rest_pos = [s.index(a) for a in rest]
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            if _matches(r, s, t, u, common):
                out[t + tuple(u[i] for i in rest_pos)] += c * d
    return Relation(r.schema + tuple(rest), out, mode)


def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    return select(product(r, s), pred)


def semijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with at least one row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def antijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with no row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def distinct(rel: Relation) -> Relation:
    return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)


AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")


def _avg(vals: list) -> object:
    total = sum(vals)
    if all(isinstance(v, (int, Fraction)) for v in vals):
        return Fraction(total, 1) / len(vals)
    return total / len(vals)


def agg_value(func: str, vals: list) -> object:
    """One SQL aggregate over a list of column values (with repeats). count_star counts all."""
    if func == "count_star":
        return len(vals)
    nn = [v for v in vals if v is not None]
    if func == "count":
        return len(nn)
    if func == "count_distinct":
        seen: list = []
        for v in nn:
            if v not in seen:
                seen.append(v)
        return len(seen)
    if not nn:
        return None
    if func == "sum":
        return sum(nn)
    if func == "avg":
        return _avg(nn)
    if func == "min":
        return min(nn)
    if func == "max":
        return max(nn)
    raise ValueError("unknown aggregate %r" % (func,))


def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
    """gamma_{G; f(A) -> B}(rel) by definition.

    aggs is a list of (func, attr, out); attr is ignored for count_star and may
    be None. For each distinct group key, in row_key order, the whole input is
    scanned. Each result row has count 1 in either mode.
    """
    group_attrs = tuple(group_attrs)
    gpos = [rel.index(a) for a in group_attrs]
    for func, attr, _ in aggs:
        if func not in AGG_FUNCS:
            raise ValueError("unknown aggregate %r" % (func,))
        if func != "count_star":
            rel.index(attr)
    keys: list = []
    for t in rel.rows:
        k = tuple(t[i] for i in gpos)
        if k not in keys:
            keys.append(k)
    if not group_attrs and not keys:
        keys = [()]
    out: Counter = Counter()
    for k in sorted(keys, key=row_key):
        row = list(k)
        for func, attr, _ in aggs:
            vals: list = []
            for t, c in rel.rows.items():
                if tuple(t[i] for i in gpos) == k:
                    vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
            row.append(agg_value(func, vals))
        out[tuple(row)] = 1
    schema = group_attrs + tuple(o for _, _, o in aggs)
    return Relation(schema, out, rel.mode)


# ---------------------------------------------------------------- evaluation

def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
    """Evaluate an expression tree of nested tuples over db, in mode."""
    if mode not in MODES:
        raise ValueError("mode must be 'bag' or 'set'")
    op = expr[0]
    ev = lambda e: evaluate(e, db, mode)
    if op == "scan":
        return db[expr[1]].with_mode(mode)
    if op == "select":
        return select(ev(expr[2]), expr[1])
    if op == "project":
        return project(ev(expr[2]), expr[1])
    if op == "rename":
        return rename(ev(expr[2]), expr[1])
    if op == "distinct":
        return distinct(ev(expr[1]))
    if op == "aggregate":
        return aggregate(ev(expr[3]), expr[1], expr[2])
    if op == "theta_join":
        return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
    binary = {
        "union": union, "difference": difference, "intersection": intersection,
        "product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
    }
    if op in binary:
        return binary[op](ev(expr[1]), ev(expr[2]))
    raise ValueError("unknown operator %r" % (op,))


# ---------------------------------------------------------------- disk

def paginate(rows: Sequence, per_page: int) -> list:
    """Split rows into pages of per_page rows; the last page may be shorter."""
    if per_page < 1:
        raise ValueError("per_page must be at least 1")
    rows = list(rows)
    return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]


class Disk:
    """Pages on a simulated disk. Each read_page and write_page call costs one I/O."""

    def __init__(self) -> None:
        self.pages: dict = {}
        self.reads = 0
        self.writes = 0
        self._next = 0

    def alloc(self) -> int:
        pid = self._next
        self._next += 1
        self.pages[pid] = ()
        return pid

    def write_page(self, pid: int, rows: Iterable) -> None:
        if pid not in self.pages:
            raise KeyError("page %r was not allocated" % (pid,))
        self.pages[pid] = tuple(rows)
        self.writes += 1

    def read_page(self, pid: int) -> list:
        self.reads += 1
        return list(self.pages[pid])

    def free(self, pid: int) -> None:
        del self.pages[pid]

    def load(self, rows: Sequence, per_page: int) -> list:
        """Store an input file without counting I/O; return its page ids in order."""
        ids = []
        for page in paginate(rows, per_page):
            pid = self.alloc()
            self.pages[pid] = tuple(page)
            ids.append(pid)
        return ids

    def io(self) -> int:
        return self.reads + self.writes

    def reset_counters(self) -> None:
        self.reads = 0
        self.writes = 0


# ---------------------------------------------------------------- random data

def random_relation(rng: random.Random, schema: Sequence[str], n: int,
                    domain: int | Sequence | Mapping = 4, mode: str = BAG,
                    null_rate: float = 0.0) -> Relation:
    """n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
    values, or a dict from attribute to either. Each value is None with
    probability null_rate. In set mode duplicates collapse, so there may be
    fewer than n rows."""
    schema = tuple(schema)

    def values(a: str) -> list:
        d = domain[a] if isinstance(domain, Mapping) else domain
        return list(range(d)) if isinstance(d, int) else list(d)

    doms = [values(a) for a in schema]
    rows = []
    for _ in range(n):
        t = []
        for d in doms:
            if null_rate and rng.random() < null_rate:
                t.append(None)
            else:
                t.append(rng.choice(d))
        rows.append(tuple(t))
    return Relation(schema, rows, mode)
greedy_operator_ordering.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-operator-ordering/. The authors are listed in prov/X0F4M8.jsonl.
"""Greedy operator ordering (GOO), a join ordering heuristic after Fegaras (1998).

The input is a query graph: the size of each relation and a selectivity on
each edge {i, j}. GOO keeps a set of join trees, one per relation at the
start. In each step it joins the two trees whose join has the smallest
estimated size. By default it only joins trees that an edge links, and it
uses a cross product only when no two trees are linked, which happens when
the query graph is not connected.

The size of a join of trees T1 and T2 is |T1| * |T2| * f, where f is the
product of the selectivities of the edges between them. The cost of the
result is C_out, the sum of the sizes of all joins. GOO is a heuristic: it
builds a bushy tree in O(n^3) time, and the tree may cost more than the
optimum.
"""

from fractions import Fraction
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union

Plan = Union[int, tuple]
Edges = Dict[Tuple[int, int], Fraction]


def _norm(sel: Edges, n: int) -> Edges:
    out: Edges = {}
    for (i, j), f in sel.items():
        if i == j or not (0 <= i < n and 0 <= j < n):
            raise ValueError("an edge needs two different relations")
        key = (min(i, j), max(i, j))
        out[key] = out.get(key, Fraction(1)) * Fraction(f)
    return out


def goo(card: Sequence, sel: Edges, cross_products: bool = False,
        on_step: Optional[Callable[[Plan, Plan, Fraction], None]] = None) -> Tuple[Fraction, Plan]:
    """Return (C_out cost, plan). A plan is a relation number or a pair (left, right).

    Ties are broken by the smallest pair of tree numbers. If cross_products is
    True, every pair of trees is a candidate in every step. on_step(T1, T2,
    size) is called for each join, with the larger input as T1.
    """
    n = len(card)
    if n == 0:
        raise ValueError("no relations")
    sel = _norm(sel, n)
    plan: Dict[int, Plan] = {}
    size: Dict[int, Fraction] = {}
    for i in range(n):  # @line L1
        plan[i], size[i] = i, Fraction(card[i])
    # between[a][b]: the product of the selectivities between trees a and b, or None if no edge.
    between: Dict[int, Dict[int, Optional[Fraction]]] = {a: {b: None for b in range(n) if b != a} for a in range(n)}
    for (i, j), f in sel.items():
        between[i][j] = between[j][i] = f
    cost = Fraction(0)
    nxt = n
    while len(plan) > 1:  # @line L2
        best = None
        ids = sorted(plan)
        linked = any(between[a][b] is not None for a in ids for b in ids if a < b)
        for x, a in enumerate(ids):  # @line L3
            for b in ids[x + 1:]:
                f = between[a][b]
                if f is None and linked and not cross_products:
                    continue
                s = size[a] * size[b] * (Fraction(1) if f is None else f)
                if best is None or s < best[0]:
                    best = (s, a, b)
        s, a, b = best
        left, right = (a, b) if size[a] >= size[b] else (b, a)
        if on_step is not None:
            on_step(plan[left], plan[right], s)
        new = nxt  # @line L4
        nxt += 1
        plan[new], size[new] = (plan[left], plan[right]), s  # @line L5
        cost += s
        between[new] = {}
        for c in plan:
            if c in (a, b, new):
                continue
            fa, fb = between[a][c], between[b][c]
            f = None
            if fa is not None or fb is not None:
                f = (Fraction(1) if fa is None else fa) * (Fraction(1) if fb is None else fb)
            between[new][c] = between[c][new] = f
            del between[c][a], between[c][b]
        for t in (a, b):
            del plan[t], size[t], between[t]
    (root,) = plan.values()
    return cost, root  # @line L6


def leaves(p: Plan) -> List[int]:
    return [p] if isinstance(p, int) else leaves(p[0]) + leaves(p[1])


def plan_size(card: Sequence, sel: Edges, rels: Sequence[int]) -> Fraction:
    s = Fraction(1)
    rs = set(rels)
    for i in rs:
        s *= Fraction(card[i])
    for (i, j), f in _norm(sel, len(card)).items():
        if i in rs and j in rs:
            s *= f
    return s


def plan_cost(card: Sequence, sel: Edges, p: Plan) -> Fraction:
    """The C_out cost of a plan: the sum of the sizes of its joins."""
    if isinstance(p, int):
        return Fraction(0)
    return plan_cost(card, sel, p[0]) + plan_cost(card, sel, p[1]) + plan_size(card, sel, leaves(p))
test_greedy_operator_ordering.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-operator-ordering/. The authors are listed in prov/X0F4M8.jsonl.

import random
import unittest
from fractions import Fraction

import dbrel
from greedy_operator_ordering import goo, leaves, plan_cost, plan_size


def linked(sel, A, B):
    return any((i in A and j in B) or (j in A and i in B) for i, j in sel)


def all_trees(sel, S, memo):
    """Every bushy tree over the set S whose joins all have an edge between their inputs."""
    if S in memo:
        return memo[S]
    if len(S) == 1:
        memo[S] = [next(iter(S))]
        return memo[S]
    out = []
    items = sorted(S)
    for mask in range(1, 1 << len(items)):
        A = frozenset(x for k, x in enumerate(items) if mask >> k & 1)
        B = S - A
        if B and linked(sel, A, B):
            for ta in all_trees(sel, A, memo):
                for tb in all_trees(sel, B, memo):
                    out.append((ta, tb))
    memo[S] = out
    return out


def random_query(rng, n, connected=True):
    sel = {}
    for i in range(1, n):
        if connected or rng.random() < 0.6:
            sel[(rng.randrange(i), i)] = Fraction(1, rng.choice([1, 2, 5, 10, 100]))
    for _ in range(rng.randint(0, n)):
        i, j = sorted(rng.sample(range(n), 2)) if n >= 2 else (0, 0)
        if i != j and (i, j) not in sel:
            sel[(i, j)] = Fraction(1, rng.choice([2, 10, 100]))
    card = [rng.choice([1, 10, 20, 100, 1000]) for _ in range(n)]
    return card, sel


class TestGOO(unittest.TestCase):
    def test_every_step_takes_the_smallest_join(self):
        rng = random.Random(1)
        for trial in range(300):
            n = rng.randint(1, 8)
            card, sel = random_query(rng, n, connected=trial % 3 != 0)
            cross = trial % 5 == 0
            trees = {frozenset([i]) for i in range(n)}

            def step(t1, t2, s):
                A, B = frozenset(leaves(t1)), frozenset(leaves(t2))
                self.assertIn(A, trees)
                self.assertIn(B, trees)
                self.assertNotEqual(A, B)
                cands = [(X, Y) for X in trees for Y in trees if X != Y]
                if not cross and any(linked(sel, X, Y) for X, Y in cands):
                    cands = [(X, Y) for X, Y in cands if linked(sel, X, Y)]
                    self.assertTrue(linked(sel, A, B))
                self.assertEqual(s, plan_size(card, sel, A | B))
                self.assertEqual(s, min(plan_size(card, sel, X | Y) for X, Y in cands))
                self.assertGreaterEqual(plan_size(card, sel, A), plan_size(card, sel, B))
                trees.difference_update((A, B))
                trees.add(A | B)

            cost, plan = goo(card, sel, cross_products=cross, on_step=step)
            self.assertEqual(len(trees), 1)
            self.assertEqual(sorted(leaves(plan)), list(range(n)))
            self.assertEqual(plan_cost(card, sel, plan), cost)

    def test_never_cheaper_than_the_optimum(self):
        rng = random.Random(2)
        worse = 0
        for _ in range(150):
            n = rng.randint(1, 5)
            card, sel = random_query(rng, n)
            cost, plan = goo(card, sel)
            trees = all_trees(sel, frozenset(range(n)), {})
            self.assertIn(plan, trees)
            best = min(plan_cost(card, sel, t) for t in trees)
            self.assertGreaterEqual(cost, best)
            if n <= 3:
                self.assertEqual(cost, best)
            worse += cost > best
        self.assertGreater(worse, 0)

    def test_counterexample(self):
        card = [20, 10, 1000, 20]
        sel = {(0, 1): Fraction(1, 5), (1, 2): Fraction(1, 100), (2, 3): Fraction(1, 100)}
        sizes = []
        cost, plan = goo(card, sel, on_step=lambda a, b, s: sizes.append(s))
        self.assertEqual(sizes, [40, 200, 80])
        self.assertEqual(cost, 320)
        self.assertEqual(plan, ((2, 3), (0, 1)))
        trees = all_trees(sel, frozenset(range(4)), {})
        best = min(trees, key=lambda t: plan_cost(card, sel, t))
        self.assertEqual(plan_cost(card, sel, best), 200)
        self.assertEqual(plan_cost(card, sel, (0, ((1, 2), 3))), 200)

    def test_cross_product_only_when_needed(self):
        card = [10, 10, 10, 10]
        sel = {(0, 1): Fraction(1, 2), (2, 3): Fraction(1, 2)}
        sizes = []
        cost, plan = goo(card, sel, on_step=lambda a, b, s: sizes.append(s))
        self.assertEqual(sizes, [50, 50, 2500])
        self.assertEqual(cost, 2600)
        card = [1, 1, 100]
        sel = {(0, 2): Fraction(1, 10), (1, 2): Fraction(1, 10)}
        self.assertEqual(goo(card, sel)[0], 10 + 1)
        self.assertEqual(goo(card, sel, cross_products=True), (Fraction(1 + 1), (2, (0, 1))))

    def test_plan_runs_and_gives_the_join(self):
        rng = random.Random(3)
        for _ in range(30):
            n = rng.randint(1, 5)
            card, sel = random_query(rng, n, connected=rng.random() < 0.8)
            attrs = {i: ["k%d" % i] + ["e%d_%d" % e for e in sel if i in e] for i in range(n)}
            db = {i: dbrel.random_relation(rng, attrs[i], rng.randint(0, 4), domain=2, null_rate=0.1)
                  for i in range(n)}
            _, plan = goo(card, sel)

            def run(p):
                if isinstance(p, int):
                    return db[p]
                return dbrel.natural_join(run(p[0]), run(p[1]))

            naive = db[0]
            for i in range(1, n):
                naive = dbrel.natural_join(naive, db[i])
            self.assertEqual(run(plan), naive)

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            goo([], {})
        with self.assertRaises(ValueError):
            goo([1, 2], {(1, 1): Fraction(1, 2)})
        with self.assertRaises(ValueError):
            goo([1, 2], {(0, 2): Fraction(1, 2)})
        self.assertEqual(goo([7], {}), (0, 0))
        self.assertEqual(goo([3, 4], {(1, 0): Fraction(1, 2)}), (6, (1, 0)))


if __name__ == "__main__":
    unittest.main()

History

Greedy rules for join order are older than GOO. The simpler ones add one relation at a time to a left-deep plan, and in 1997 Steinbrunn, Moerkotte and Kemper compared heuristics of this kind with randomized methods for large join queries. In 1998 Leonidas Fegaras described greedy operator ordering, which applies the greedy rule to any two subplans and so builds bushy plans for large queries.

References

  1. A new heuristic for optimizing large queries, the greedy operator ordering heuristic, which joins the pair of subplans with the smallest result size in each step
  2. Heuristic and randomized optimization for the join ordering problem, the comparison of earlier greedy heuristics and randomized methods for large join queries

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example