Algorithm Search⌘K

Techniqueadvanced

Eager aggregation

Also called group-by pushdown, aggregation pushdown.

Move a grouping below a join when the conditions of Yan and Larson hold, so the join works on fewer rows.

Eager aggregation is the technique that computes part of a grouping before a join and finishes it after the join. A query such as SELECT R.g, SUM(S.v) FROM R JOIN S ON R.k = S.k GROUP BY R.g joins every row of SS with its rows of RR and only then adds up. If many rows of SS share a join value, it is cheaper to group SS by kk first, so that the join reads one row for each value of kk, and then to combine the partial results in a final grouping by gg. Yan and Larson named this move eager aggregation and its reverse lazy aggregation, and gave the conditions under which the two forms of the query are equal. Whether the move pays depends on the number of rows per group, so an optimizer makes the choice by cost, as Chaudhuri and Shim proposed.

In plain words

A shop wants the total amount of each customer's order lines. The direct way is to attach the customer to every order line, and then to add up the lines of each customer. If an order has a hundred lines, the customer is attached a hundred times.

The eager way first adds up the lines of each order. Then it attaches the customer to each order total, and adds up the order totals of each customer. Fewer rows go through the attach step.

This works for totals, counts, smallest and largest values. It needs care in three cases. A count of rows becomes a total of counts. A value from the customer side must be counted once for each order line it stands for. An average is not an average of averages, so the eager way keeps a total and a count and divides at the end.

When it applies

  • The query is SQL, so tables are bags. It is a grouping on top of an inner equijoin, γG; aggs(R⋈kS)\gamma_{G;\,\mathrm{aggs}}(R \bowtie_{k} S). The code of this page uses R(g,k,x)R(g, k, x) and S(k,v)S(k, v), with GG equal to {g}\{g\} or empty.
  • Each aggregate is decomposable: it can be computed from the results of the same or another aggregate on the parts of a partition of its input. COUNT, SUM, MIN and MAX are decomposable, and AVG is the quotient of a SUM and a COUNT. COUNT(DISTINCT) and the median are not decomposable in this way.
  • The lower grouping groups SS by all its join columns and by every column of SS in GG. Then every row of RR joins at most one partial row, and a final group never mixes two join values that the query keeps apart.
  • The final grouping stays above the join. It can be dropped only when each final group gets at most one row of the join with the partial results. That holds, for example, when GG holds a key of RR. Yan and Larson state conditions of this kind as functional dependencies that must hold in the join result.
  • A HAVING clause and an ORDER BY stay above the final grouping.

The template

Write cc for the number of rows of SS in a partial group, vv for a column of SS and xx for a column of RR. A join test with NULL on either side is UNKNOWN, so a row with a NULL join value has no match.

  1. EAGER(R, S, G, aggregates) ▷ the query γ_{G; aggregates}(R ⋈_k S), G a set of columns of R
  2. 1P ← γ_{k; c ← COUNT(*), and a partial aggregate for each aggregate of a column of S}(S)
  3. 2J ← R ⋈ P ▷ each row of R joins at most one row of P
  4. 3add to each row of J the columns x·c and c, or NULL and NULL if x is NULL
  5. 4F ← γ_{G; the final aggregates}(J)
  6. 5replace each NULL count of F by 0, and compute each AVG as its sum divided by its count

The partial and final aggregates are these.

aggregate of the query partial, in PP final, in FF
COUNT(*) cc SUM(cc)
COUNT(vv), SUM(vv) the same aggregate SUM
MIN(vv), MAX(vv) the same aggregate MIN, MAX
AVG(vv) SUM(vv) and COUNT(vv) SUM of each, then the quotient
SUM(xx) none SUM(x⋅cx \cdot c)
COUNT(xx) none SUM of cc over the rows with xx not NULL
MIN(xx), MAX(xx) none MIN(xx), MAX(xx)
AVG(xx) none SUM(x⋅cx \cdot c) divided by the final of COUNT(xx)

Why it works. Let SaS_a be the bag of rows of SS with k=ak = a. A row rr of RR joins exactly the rows of Sr.kS_{r.k}, and none if r.kr.k is NULL. So the joined rows of a final group are the union, over the rows rr of RR in the group and with their counts, of the parts {r}×Sr.k\{r\} \times S_{r.k}. Line L1 makes one row of PP for each aa with SaS_a not empty, and the row for a NULL key never joins. So line L2 gives one row of JJ for each row rr whose part is not empty, and the row carries the partial aggregates of its part. A final group of the query exists exactly when one of its parts is not empty, and so it exists in FF too. The final aggregates then combine the parts. A count of the union is the sum of the counts. A SUM, MIN or MAX of vv over the union is the SUM, MIN or MAX of the partial values, and NULL handling agrees: a partial value is NULL when its part has no non-null vv, the final aggregate skips it, and the result is NULL only when no part has a non-null vv. In the part of rr the value xx of rr appears cc times, which line L3 accounts for, and repeats do not change MIN and MAX. Line L5 handles the one case where the final aggregate differs from the count: with GG empty and no joined row, SQL returns one row with COUNT equal to 0, while SUM over no rows is NULL.

Cost. Line L1 is one grouping of SS, O(∣S∣)O(|S|) expected time with a hash table. Line L2 joins RR with at most ∣S∣|S| partial rows and returns at most ∣R∣|R| rows, while the original join can return ∣R∣⋅∣S∣|R| \cdot |S| rows. The move pays when the rows of SS repeat their join values, and it costs one extra grouping when they do not. The code of this page uses the dbrel helper, whose operators work by their definitions, so it shows that the results are equal, and it counts the join rows, but its time is not that of a real engine.

Example. Take R={(a,1,10),(a,2,20),(b,2,NULL),(b,NULL,5)}R = \{(a, 1, 10), (a, 2, 20), (b, 2, \mathrm{NULL}), (b, \mathrm{NULL}, 5)\} as (g,k,x)(g, k, x) and S={(1,3),(1,NULL),(2,4),(2,4),(2,6),(NULL,7)}S = \{(1, 3), (1, \mathrm{NULL}), (2, 4), (2, 4), (2, 6), (\mathrm{NULL}, 7)\} as (k,v)(k, v). The query asks for COUNT(*), SUM(vv), SUM(xx), COUNT(xx) and AVG(vv) for each gg. The join R⋈SR \bowtie S has 8 rows. Line L1 gives PP with the columns (k,c,SUM(v),COUNT(v))(k, c, \mathrm{SUM}(v), \mathrm{COUNT}(v)).

kk cc SUM(vv) COUNT(vv)
1 2 3 1
2 3 14 3
NULL 1 7 1

Line L2 gives 3 rows: (a,1,10)(a, 1, 10) with the row of k=1k = 1, and (a,2,20)(a, 2, 20) and (b,2,NULL)(b, 2, \mathrm{NULL}) with the row of k=2k = 2. The row of RR with a NULL key and the row of PP with a NULL key find no partner. Lines L3 to L5 give, for aa: COUNT(*) =2+3=5= 2 + 3 = 5, SUM(vv) =3+14=17= 3 + 14 = 17, SUM(xx) =10⋅2+20⋅3=80= 10 \cdot 2 + 20 \cdot 3 = 80, COUNT(xx) =5= 5 and AVG(vv) =17/4= 17/4. For bb: COUNT(*) =3= 3, SUM(vv) =14= 14, SUM(xx) is NULL, COUNT(xx) is 0 and AVG(vv) =14/3= 14/3. These are the values of the original query, and the tests check them and random tables with NULL values for every aggregate, with and without the grouping by gg.

Classic examples

  • Star schemas. A query joins a large fact table with a dimension table and groups by a column of the dimension. Grouping the fact rows by the foreign key first is eager group-by on the fact table.
  • Local and global aggregation. A parallel plan groups each partition before the exchange and finishes the grouping after it. The partial and final aggregates are those of the table above, and the exchange plays the part of the join.
  • Roll-up in a data cube. The data cube computes a coarse grouping from a finer one with the same pairs of partial and final aggregates.
  • After unnesting. Subquery unnesting turns a correlated aggregate into a grouping of the inner table followed by a join, which is eager aggregation already. Lazy aggregation can move that grouping above the join when that is cheaper.

Variations

  • Eager count. Group the side with no aggregate column, here RR by (g,k)(g, k) with a count dd, join with SS, and weight each value of vv by dd in the final grouping. Yan and Larson call this eager count.
  • Double eager. Group both sides by their join columns and combine the two counts in the final grouping.
  • Lazy aggregation. The reverse move pulls a grouping up above a join, which pays when the join removes many rows first.
  • Dropping the final grouping. If each final group gets one row of JJ, the final grouping is a projection. The code has this case as eager_without_final.
  • Partial pre-aggregation. An engine can run line L1 with a small hash table that sends a group on when the table is full. The final grouping still gives the right answer, so the lower grouping does not need to be complete.
  • Outer joins. For RR left outer join SS, a row of RR with no match has NULL partial values. Its COUNT(*) must be 1 and its count of SS columns 0, so the final aggregates need a case for the padded rows.

Pitfalls

  • COUNT(*) as a count of the join rows. After line L2 a row of JJ stands for cc joined rows. In the example, counting the rows of JJ gives 2 for aa, not 5.
  • Sums of the other side without weights. SUM(xx) over JJ without the factor cc gives 30 for aa, not 80.
  • The average of averages. The partial averages of aa are 3 and 14/314/3, and their average is 23/623/6, not 17/417/4. Keep a sum and a count.
  • NULL in place of 0. With no grouping columns and no joined rows, the final SUM of counts is NULL, but SQL returns 0 for COUNT. Line L5 fixes this.
  • Dropping the final grouping when GG is not a key. In the example, aa joins two partial rows, so the result without the final grouping has two rows for aa.
  • Too coarse a lower grouping. If SS is grouped by fewer columns than its join columns, one partial row mixes rows that join different rows of RR.
  • No reduction. If the join values of SS are almost all distinct, line L1 costs a pass and saves nothing. The decision needs an estimate of the number of groups from cardinality estimation.

Code

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)
eager_aggregation.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eager-aggregation/. The authors are listed in prov/B4N0ZP.jsonl.
"""Eager aggregation: a grouping below a join, with a final grouping above it.

The tables are R(g, k, x) and S(k, v), both bags. The query is

    SELECT G, agg_1, ..., agg_m FROM R JOIN S ON R.k = S.k GROUP BY G

where G is ["g"] or [] and each aggregate is (func, attr, out) with func one
of count_star, count, sum, min, max, avg and attr "v" (a column of S), "x" (a
column of R) or None for count_star. lazy() evaluates the query as written.
eager() groups S by its join column k first, joins the partial results with
R, and combines them with a final grouping. For an aggregate of a column of
R, each row of R stands for c joined rows, where c is the number of rows of S
in the partial group, so sums and counts of R columns are weighted by c. This
is eager group-by on S combined with eager count, in the terms of Yan and
Larson. eager_without_final() also drops the final grouping, which is right
only when g is a key of R.
"""

from fractions import Fraction
from typing import List, Sequence, Tuple

import dbrel
from dbrel import Relation

FUNCS = ("count_star", "count", "sum", "min", "max", "avg")
COUNTS = ("count_star", "count")


def _check(R: Relation, S: Relation, group: Sequence[str], aggs: Sequence[Tuple]) -> None:
    if sorted(R.schema) != ["g", "k", "x"] or sorted(S.schema) != ["k", "v"]:
        raise ValueError("R must have the attributes g, k, x and S the attributes k, v")
    if R.mode != dbrel.BAG or S.mode != dbrel.BAG:
        raise ValueError("SQL tables are bags")
    if list(group) not in (["g"], []):
        raise ValueError("the grouping is ['g'] or []")
    outs = set()
    for agg in aggs:
        if len(agg) != 3 or agg[0] not in FUNCS:
            raise ValueError("an aggregate is (func, attr, out) with func in %r" % (FUNCS,))
        func, attr, out = agg
        if (func == "count_star") != (attr is None) or attr not in (None, "v", "x"):
            raise ValueError("bad attribute %r for %s" % (attr, func))
        if out in outs or out in ("g", "k", "x", "v", "c"):
            raise ValueError("bad output name %r" % (out,))
        outs.add(out)


def lazy(R: Relation, S: Relation, group: Sequence[str], aggs: Sequence[Tuple]) -> Relation:
    """The query as written: the join first, then one grouping."""
    _check(R, S, group, aggs)
    return dbrel.aggregate(dbrel.natural_join(R, S), list(group), list(aggs))


def _partials(aggs: Sequence[Tuple]) -> List[Tuple]:
    """The partial aggregates of S, grouped by k. c counts the rows of each group."""
    out = [("count_star", None, "c")]
    for i, (func, attr, _) in enumerate(aggs):
        if attr != "v":
            continue
        if func == "avg":
            out += [("sum", "v", "p%d_s" % i), ("count", "v", "p%d_n" % i)]
        else:
            out.append((func, "v", "p%d" % i))
    return out


def _finals(aggs: Sequence[Tuple]) -> List[Tuple]:
    """The final aggregates over the join of R with the partial results."""
    out = []
    for i, (func, attr, _) in enumerate(aggs):
        if func == "count_star":
            out.append(("sum", "c", "f%d" % i))
        elif attr == "v" and func == "avg":
            out += [("sum", "p%d_s" % i, "f%d_s" % i), ("sum", "p%d_n" % i, "f%d_n" % i)]
        elif attr == "v":
            out.append(("min" if func == "min" else "max" if func == "max" else "sum", "p%d" % i, "f%d" % i))
        elif func in ("min", "max"):
            out.append((func, "x", "f%d" % i))  # copies of a row do not change MIN and MAX
        elif func == "sum":
            out.append(("sum", "xc", "f%d" % i))
        elif func == "count":
            out.append(("sum", "cx", "f%d" % i))
        else:
            out += [("sum", "xc", "f%d_s" % i), ("sum", "cx", "f%d_n" % i)]
    return out


def _weighted(J: Relation) -> Relation:
    """J with the columns xc = x * c and cx = c, both NULL where x is NULL."""
    xi, ci = J.index("x"), J.index("c")
    rows = {}
    for t, m in J.rows.items():
        x, c = t[xi], t[ci]
        u = t + ((None, None) if x is None else (x * c, c))
        rows[u] = rows.get(u, 0) + m
    return Relation(J.schema + ("xc", "cx"), rows)


def _finish(F: Relation, group: Sequence[str], aggs: Sequence[Tuple]) -> Relation:
    """Replace NULL counts by 0 and divide the sums of each AVG."""
    rows = {}
    for t, m in F.rows.items():
        r = F.as_dict(t)
        u = [r[a] for a in group]
        for i, (func, _, _) in enumerate(aggs):
            if func == "avg":
                s, n = r["f%d_s" % i], r["f%d_n" % i] or 0
                u.append(None if n == 0 else Fraction(s, 1) / n)
            elif func in COUNTS:
                u.append(r["f%d" % i] or 0)
            else:
                u.append(r["f%d" % i])
        rows[tuple(u)] = rows.get(tuple(u), 0) + m
    return Relation(tuple(group) + tuple(out for _, _, out in aggs), rows)


def eager(R: Relation, S: Relation, group: Sequence[str], aggs: Sequence[Tuple]) -> Relation:
    """The rewritten query: group S by k, join with R, then group by G."""
    _check(R, S, group, aggs)
    P = dbrel.aggregate(S, ["k"], _partials(aggs))  # @line L1
    J = dbrel.natural_join(R, P)  # @line L2
    J = _weighted(J)  # @line L3
    F = dbrel.aggregate(J, list(group), _finals(aggs))  # @line L4
    return _finish(F, group, aggs)  # @line L5


def eager_without_final(R: Relation, S: Relation, aggs: Sequence[Tuple]) -> Relation:
    """Eager aggregation with no grouping above the join, for GROUP BY g.

    Each row of the join of R with the partial results becomes one result row.
    This equals the query only when no two joined rows of R share a value of g,
    for example when g is a key of R.
    """
    _check(R, S, ["g"], aggs)
    J = _weighted(dbrel.natural_join(R, dbrel.aggregate(S, ["k"], _partials(aggs))))
    rows = {}
    for t, m in J.rows.items():
        one = Relation(J.schema, {t: 1})
        for u in _finish(dbrel.aggregate(one, ["g"], _finals(aggs)), ["g"], aggs).rows:
            rows[u] = rows.get(u, 0) + m
    return Relation(("g",) + tuple(out for _, _, out in aggs), rows)


def join_sizes(R: Relation, S: Relation) -> Tuple[int, int]:
    """The number of rows that the join reads from S, without and with the grouping below it."""
    P = dbrel.aggregate(S, ["k"], [("count_star", None, "c")])
    return len(dbrel.natural_join(R, S)), len(dbrel.natural_join(R, P))
test_eager_aggregation.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eager-aggregation/. The authors are listed in prov/B4N0ZP.jsonl.

import random
import unittest
from fractions import Fraction

import dbrel
from dbrel import Relation
from eager_aggregation import FUNCS, eager, eager_without_final, join_sizes, lazy

ALL = [("count_star", None, "n")] + [(f, a, "%s_%s" % (f, a)) for f in FUNCS if f != "count_star" for a in ("v", "x")]
R0 = Relation(("g", "k", "x"), [("a", 1, 10), ("a", 2, 20), ("b", 2, None), ("b", None, 5)])
S0 = Relation(("k", "v"), [(1, 3), (1, None), (2, 4), (2, 4), (2, 6), (None, 7)])


def random_tables(rng, key_g=False):
    n = rng.randint(0, 6)
    R = dbrel.random_relation(rng, ["g", "k", "x"], n, domain={"g": [0, 1, 2], "k": [1, 2, 3], "x": [0, 1, 2, 3]},
                              null_rate=0.15)
    if key_g:
        R = Relation(R.schema, [(i,) + t[1:] for i, t in enumerate(R.sorted_rows())])
    S = dbrel.random_relation(rng, ["k", "v"], rng.randint(0, 7), domain={"k": [1, 2, 3], "v": [0, 1, 2, 5]},
                              null_rate=0.15)
    return R, S


class TestEagerAggregation(unittest.TestCase):
    def test_eager_equals_lazy(self):
        rng = random.Random(1)
        for _ in range(150):
            R, S = random_tables(rng)
            for group in (["g"], []):
                self.assertEqual(eager(R, S, group, ALL), lazy(R, S, group, ALL), (R, S, group))
                aggs = rng.sample(ALL, rng.randint(1, 3))
                self.assertEqual(eager(R, S, group, aggs), lazy(R, S, group, aggs), (R, S, group, aggs))

    def test_worked_example(self):
        aggs = [("count_star", None, "n"), ("sum", "v", "sv"), ("sum", "x", "sx"), ("count", "x", "cx"),
                ("avg", "v", "av")]
        want = Relation(("g", "n", "sv", "sx", "cx", "av"),
                        [("a", 5, 17, 80, 5, Fraction(17, 4)), ("b", 3, 14, None, 0, Fraction(14, 3))])
        self.assertEqual(lazy(R0, S0, ["g"], aggs), want)
        self.assertEqual(eager(R0, S0, ["g"], aggs), want)
        P = dbrel.aggregate(S0, ["k"], [("count_star", None, "c"), ("sum", "v", "s"), ("count", "v", "m")])
        self.assertEqual(P, Relation(("k", "c", "s", "m"), [(None, 1, 7, 1), (1, 2, 3, 1), (2, 3, 14, 3)]))
        self.assertEqual(join_sizes(R0, S0), (8, 3))

    def test_naive_finals_are_wrong(self):
        P = dbrel.aggregate(S0, ["k"], [("count_star", None, "c"), ("avg", "v", "a")])
        J = dbrel.natural_join(R0, P)
        count_rows = dbrel.aggregate(J, ["g"], [("count_star", None, "n")])
        self.assertEqual(count_rows, Relation(("g", "n"), [("a", 2), ("b", 1)]))
        unweighted = dbrel.aggregate(J, ["g"], [("sum", "x", "sx")])
        self.assertEqual(unweighted, Relation(("g", "sx"), [("a", 30), ("b", None)]))
        avg_of_avgs = dbrel.aggregate(J, ["g"], [("avg", "a", "av")])
        self.assertEqual(avg_of_avgs, Relation(("g", "av"), [("a", Fraction(23, 6)), ("b", Fraction(14, 3))]))
        self.assertNotEqual(avg_of_avgs, lazy(R0, S0, ["g"], [("avg", "v", "av")]))

    def test_dropping_the_final_grouping(self):
        rng = random.Random(2)
        for _ in range(150):
            R, S = random_tables(rng, key_g=True)
            self.assertEqual(eager_without_final(R, S, ALL), lazy(R, S, ["g"], ALL), (R, S))
        aggs = [("count_star", None, "n"), ("sum", "v", "sv")]
        self.assertEqual(eager_without_final(R0, S0, aggs), Relation(("g", "n", "sv"), [("a", 2, 3), ("a", 3, 14),
                                                                                        ("b", 3, 14)]))
        self.assertNotEqual(eager_without_final(R0, S0, aggs), lazy(R0, S0, ["g"], aggs))

    def test_no_grouping_and_an_empty_join(self):
        R = Relation(("g", "k", "x"), [("a", None, 1), ("b", 9, 2)])
        want = Relation(("n", "count_v", "sum_v", "avg_x"), [(0, 0, None, None)])
        aggs = [("count_star", None, "n"), ("count", "v", "count_v"), ("sum", "v", "sum_v"), ("avg", "x", "avg_x")]
        self.assertEqual(lazy(R, S0, [], aggs), want)
        self.assertEqual(eager(R, S0, [], aggs), want)
        self.assertEqual(eager(R, S0, ["g"], aggs), Relation(("g", "n", "count_v", "sum_v", "avg_x"), []))

    def test_the_join_reads_fewer_rows(self):
        rng = random.Random(3)
        for _ in range(100):
            R, S = random_tables(rng)
            before, after = join_sizes(R, S)
            self.assertLessEqual(after, min(before, len(R)))

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            eager(R0, S0, ["k"], ALL)
        with self.assertRaises(ValueError):
            eager(R0, S0, ["g"], [("median", "v", "m")])
        with self.assertRaises(ValueError):
            eager(R0, S0, ["g"], [("sum", "k", "s")])
        with self.assertRaises(ValueError):
            eager(R0, S0, ["g"], [("count_star", "v", "n")])
        with self.assertRaises(ValueError):
            eager(R0, S0, ["g"], [("sum", "v", "c")])
        with self.assertRaises(ValueError):
            lazy(Relation(("g", "k"), []), S0, ["g"], ALL)
        with self.assertRaises(ValueError):
            eager(R0, S0.with_mode(dbrel.SET), ["g"], ALL)


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

Exercises

  1. Give the partial and final aggregates for the population variance of S.vS.v.
  2. Apply eager count to the example: group RR by (g,k)(g, k) with a count, join with SS, and compute SUM(vv) for each gg.
  3. Show that COUNT(DISTINCT S.vS.v) cannot be computed from PP as defined, and give a lower grouping of SS from which it can be computed.
  4. The join is RR left outer join SS. Change lines L2 to L5 so that COUNT(*) and SUM(vv) are right for the rows of RR with no match.

References

  1. Eager aggregation and lazy aggregation, the transformations eager and lazy group-by, eager and lazy count, double eager and double lazy, and eager and lazy split, with their conditions as functional dependencies in the join result
  2. Including group-by in query optimization, general locator: the cost-based choice of the place of a grouping in a join plan, in an optimizer of the System R style

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises