Algorithm Search⌘K

Techniquecore

Subquery unnesting

Also called subquery decorrelation, query unnesting.

Rewrite a correlated nested subquery as a join or an outer join with grouping, so that it is evaluated once instead of once per row.

Subquery unnesting is the technique that rewrites a query with a subquery in its WHERE clause into a query of joins, semijoins, antijoins and groupings. A subquery is correlated when it reads a column of the outer row, as in S.k = R.k. Evaluated as written, it runs once for each row of RR. After the rewrite, the optimizer can choose the join order and the join algorithms, and the subquery work is done once for the whole table. The rewrite must give the same bag of rows as the original query under the SQL rules for NULL, and that is the hard part: the COUNT bug and the NOT IN case are both errors of rewrites that ignore empty groups or nulls.

In plain words

A query asks, for each order, whether the customer has any complaint, or whether the number of complaints equals a stored value. Done literally, the database looks through all complaints once for each order. That is slow.

It is better to count the complaints of all customers in one pass, and then match each order with its customer's count. A question about "any complaint" becomes a check that the customer appears in the complaints.

Two details make this harder than it looks. A customer with no complaints has no line in the counts, but the real count is zero, so the rewrite must keep the orders that find no match and give them a zero. A missing value in the data also changes the answer of a "not in this list" question, so the rewrite must treat missing values exactly as the original does.

When it applies

  • The query is SQL, so tables and results are bags. Each row of RR that passes the WHERE condition appears in the result as many times as it appears in RR, whatever the subquery returns.
  • The condition has a subquery that is a function of the outer row. The code of this page uses the outer table R(k,x)R(k, x) and the inner table S(k,v)S(k, v) with these conditions: EXISTS (SELECT * FROM S WHERE S.k = R.k), its negation, R.k IN (SELECT S.k FROM S), R.k NOT IN (SELECT S.k FROM S), and R.x op (SELECT agg(S.v) FROM S WHERE S.k = R.k) with op one of =, <>, <, <=, >, >= and agg one of COUNT(*), COUNT, SUM, MIN and MAX.
  • The correlation is an equality on columns. Then the inner rows can be grouped once by the correlated column. Other correlations, such as S.k < R.k, need the general method with the set of distinct outer values in the Variations section.
  • A scalar subquery without an aggregate must return at most one row, or SQL raises an error at run time. A rewrite with a join silently returns several rows instead, so it applies only when a key of SS proves that the subquery returns at most one row.
  • The WHERE test keeps a row only if the condition is TRUE. FALSE and UNKNOWN both drop the row, and the rewrite uses this fact at line L6.

The template

Write γk; agg(v)→a(S)\gamma_{k;\,\mathrm{agg}(v) \to a}(S) for the grouping of SS by kk, agg(∅)\mathrm{agg}(\emptyset) for the value of the aggregate on no rows (0 for COUNT(*) and COUNT, NULL for SUM, MIN and MAX), and R⋉SR \ltimes S for the semijoin. A join test with NULL on either side is UNKNOWN, so no row with a NULL join value has a match.

  1. UNNEST(R, S, condition) ▷ the rows of R whose condition is TRUE, as a bag
  2. 1if condition is EXISTS with S.k = R.k, or R.k IN S.k then return R ⋉ π_k(S)
  3. 2if condition is NOT EXISTS with S.k = R.k then return ANTIJOIN(R, π_k(S))
  4. 3if condition is R.k NOT IN S.k then return NULL-AWARE-ANTIJOIN(R, π_k(S))
  5. 4G ← γ_{k; agg(v) → a}(S) ▷ condition is R.x op (agg(S.v) where S.k = R.k)
  6. 5if agg(∅) is not NULL then T ← LEFT-OUTER-JOIN(R, G, R.k = G.k), with a ← agg(∅) in each row of R with no match
  7. 6else T ← R ⋈_{R.k = G.k} G ▷ a row with no group compares with NULL and fails
  8. 7return π_{k, x}(σ_{x op a}(T))

NULL-AWARE-ANTIJOIN(R,K)(R, K) returns RR if KK is empty. If KK holds a NULL, it returns the empty bag. Otherwise it returns the antijoin of the rows of RR whose kk is not NULL with KK.

Why it works. For a row rr, the inner rows that the subquery sees are the rows ss of SS with s.k=r.ks.k = r.k TRUE, which is the empty bag when r.kr.k is NULL. Line L1: EXISTS is TRUE exactly when this bag is not empty, which is the definition of the semijoin with the SQL join test. IN with an uncorrelated list is TRUE exactly when some s.ks.k equals r.kr.k, and it is never TRUE when r.kr.k is NULL, so it is the same semijoin. The semijoin keeps each row of RR with its count and never repeats it. Line L2 is the complement of line L1 within RR, as NOT EXISTS is never UNKNOWN. Line L3: r.k NOT IN K is the negation of a disjunction of the tests r.k=s.kr.k = s.k. It is TRUE for every row when KK is empty. If KK holds a NULL, one term of the disjunction is UNKNOWN, so the negation is FALSE or UNKNOWN and never TRUE. If KK has no NULL, the negation is TRUE exactly when r.kr.k is not NULL and equals no value of KK. Lines L4 to L6: the bag that the subquery sees is the group of r.kr.k in GG if there is one, and the empty bag otherwise. GG has at most one row for each value of kk, so the join gives each row of RR at most one partner and keeps its count. When agg(∅)\mathrm{agg}(\emptyset) is NULL, the original comparison for a row with no group is UNKNOWN, so the row is dropped, as the inner join of line L6 drops it. When agg(∅)\mathrm{agg}(\emptyset) is 0, the outer join of line L5 keeps the row and gives it 0. The group of GG with key NULL never joins, which is correct, because no outer row sees it.

Cost. The nested query evaluates the subquery once for each row of RR, which costs O(∣R∣⋅∣S∣)O(|R| \cdot |S|) with scans. After the rewrite, a hash grouping and a hash join cost O(∣R∣+∣S∣)O(|R| + |S|) expected time, and the optimizer can also use a sort-based plan or an index. The code of this page builds the operators of the dbrel helper by their definitions, with nested loops, so it shows that the results are the same, not that the rewrite is faster.

Example. Take R={(1,0),(2,0),(3,2),(NULL,0)}R = \{(1, 0), (2, 0), (3, 2), (\mathrm{NULL}, 0)\} as (k,x)(k, x) and S={(1,5),(1,7),(3,NULL),(NULL,4)}S = \{(1, 5), (1, 7), (3, \mathrm{NULL}), (\mathrm{NULL}, 4)\} as (k,v)(k, v).

condition original query rewrite of this page naive rewrite
x = (SELECT COUNT(*) ... S.k = R.k) (2,0)(2, 0), (NULL,0)(\mathrm{NULL}, 0) lines L4, L5 and L7: the same inner join with GG: empty
k NOT IN (SELECT k FROM S) empty line L3: empty antijoin: (2,0)(2, 0), (NULL,0)(\mathrm{NULL}, 0)
EXISTS (... S.k = R.k) (1,0)(1, 0), (3,2)(3, 2) line L1: the same join, then projection: (1,0)(1, 0) twice, (3,2)(3, 2)

For the first row of the table, the counts that the subquery returns are 2 for k=1k = 1, 0 for k=2k = 2, 1 for k=3k = 3 and 0 for the row with a NULL key, which sees no inner row. The grouping GG is {(1,2),(3,1),(NULL,1)}\{(1, 2), (3, 1), (\mathrm{NULL}, 1)\}. It has no group for k=2k = 2, so the inner join loses (2,0)(2, 0), and it cannot match the NULL key, so it loses (NULL,0)(\mathrm{NULL}, 0) too. If the row (NULL,4)(\mathrm{NULL}, 4) is removed from SS, the original NOT IN query returns (2,0)(2, 0) only: the row with a NULL key gets UNKNOWN, as it is compared with a list that is not empty. With an empty SS, NOT IN returns all four rows of RR. The tests check these cases and random tables with NULL values against the original query, for every condition.

Classic examples

  • Kim's types. Kim classified a nested block by whether it is correlated (type J) or not, and whether it has an aggregate (type A). An uncorrelated aggregate is a constant and runs once. Types N and J become semijoins, as at line L1. Type JA becomes a grouping and a join, as at lines L4 and L6.
  • The COUNT bug. Ganski and Wong showed that Kim's transformation of type JA queries gives wrong answers for COUNT, because the inner join drops the outer rows with no inner rows. Their repair computes the aggregate for every outer value with an outer join, as at line L5.
  • NOT IN as a null-aware antijoin. An optimizer can use a special antijoin for NOT IN that checks for NULL in the inner input, as at line L3, because the plain antijoin is the rewrite of NOT EXISTS only. The NOT IN case is also an example of how SQL answers on tables with nulls can differ from the certain answers, as Libkin discusses.
  • Rewrites before the search. Optimizers often unnest in a rewrite phase, and then the Cascades or Selinger search orders the joins that the rewrite made.

Variations

  • General unnesting. For any correlation, first compute D=DISTINCT(πk(R))D = \mathrm{DISTINCT}(\pi_k(R)), the outer values. Then evaluate the subquery once for each value of DD with a left outer join of DD with SS and a grouping by DD, and join the result back to RR. Neumann and Kemper describe this with a dependent join that is pushed down until no correlation is left. The join back must treat two NULL values as equal (IS NOT DISTINCT FROM). The code has this variant as general_unnest. With a plain equality it loses (NULL,0)(\mathrm{NULL}, 0) in the example.
  • COUNT(*) after an outer join. In the general variant, the padded row of a value of DD with no inner row must not be counted. COUNT(*) over the outer join gives 1 for it. The code counts a column of SS that is never NULL in a real match, here S.kS.k, which gives 0.
  • Magic sets. Computing DD first and passing it into the subquery is the idea of the magic sets rewriting of Datalog: compute the bindings that the caller needs, then only the answers for those bindings.
  • Groupjoin. Lines L4 and L5 group SS and then join it with RR. An operator that does both in one hash table on kk saves one pass and one table.
  • Aggregation below or above the join. When the rewrite gives a join with a grouping on top, eager aggregation decides whether to group before the join.

Pitfalls

  • The COUNT bug. An inner join with the grouped subquery drops the outer rows with no inner row. This is wrong exactly when agg(∅)\mathrm{agg}(\emptyset) is not NULL. For COUNT(*) and COUNT, use an outer join and replace the padding with 0. For SUM, MIN and MAX, the inner join is right, as the tests check on random tables.
  • NOT IN as a plain antijoin. The antijoin keeps the rows of RR whose key matches nothing, and it keeps a row with a NULL key. NOT IN keeps neither when the list holds a NULL, and it drops a NULL key when the list is not empty. In the example, the antijoin returns two rows and NOT IN returns none.
  • EXISTS as a join. A join of RR with SS repeats each row of RR once for each match. In the example, (1,0)(1, 0) appears twice. Use a semijoin. A DISTINCT after the join does not repair it when RR itself has duplicate rows, as their copies are then lost.
  • The join back with plain equality. In general unnesting, the rows of RR whose correlated column is NULL do not match their own value of DD. Use a null-safe equality.
  • Scalar subqueries with more than one row. The join hides the run-time error of the original query and returns extra rows.
  • Other aggregates. AVG of no rows is NULL, so it follows the rule of SUM. A user aggregate with another value on no rows needs line L5 with that value.

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)
subquery_unnesting.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subquery-unnesting/. The authors are listed in prov/0C9G7B.jsonl.
"""Unnesting of subqueries in WHERE, with SQL nulls, on top of the dbrel helper.

The outer table is R(k, x) and the inner table is S(k, v), both bags. The
query keeps the rows of R that pass one of these WHERE conditions:

    ("exists",)            EXISTS (SELECT * FROM S WHERE S.k = R.k)
    ("not_exists",)        NOT EXISTS (SELECT * FROM S WHERE S.k = R.k)
    ("in",)                R.k IN (SELECT S.k FROM S)
    ("not_in",)            R.k NOT IN (SELECT S.k FROM S)
    ("scalar", op, agg)    R.x op (SELECT agg(S.v) FROM S WHERE S.k = R.k)

where op is one of =, <>, <, <=, >, >= and agg is count_star, count, sum,
min or max. nested() evaluates the query by its definition, once per row of
R. unnest() returns the rewritten query evaluated with joins, semijoins,
antijoins and one grouping. kim_unnest() is the rewrite with an inner join
that has the COUNT bug, and general_unnest() is the rewrite through the set of
distinct outer values, in the style of Neumann and Kemper.
"""

from collections import Counter
from typing import Tuple

import dbrel
from dbrel import Relation, cmp3, tv_not, tv_or

OPS = ("=", "<>", "<", "<=", ">", ">=")
AGGS = ("count_star", "count", "sum", "min", "max")


def _check(R: Relation, S: Relation, cond: Tuple) -> None:
    if sorted(R.schema) != ["k", "x"] or sorted(S.schema) != ["k", "v"]:
        raise ValueError("R must have the attributes 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 not cond or cond[0] not in ("exists", "not_exists", "in", "not_in", "scalar"):
        raise ValueError("unknown condition %r" % (cond,))
    if cond[0] == "scalar" and (len(cond) != 3 or cond[1] not in OPS or cond[2] not in AGGS):
        raise ValueError("a scalar condition is ('scalar', op, agg)")


def empty_value(agg: str):
    """The value of the aggregate on an empty input: 0 for the counts, NULL for the others."""
    return dbrel.agg_value(agg, [])


def nested(R: Relation, S: Relation, cond: Tuple) -> Relation:
    """The original query: for each row of R, evaluate the subquery and the condition."""
    _check(R, S, cond)
    out = {}
    for t, c in R.rows.items():
        r = R.as_dict(t)
        inner = dbrel.select(S, lambda s: cmp3("=", s["k"], r["k"]))
        if cond[0] == "exists":
            ok = len(inner) > 0
        elif cond[0] == "not_exists":
            ok = len(inner) == 0
        elif cond[0] in ("in", "not_in"):
            found = False
            for u in S.rows:
                found = tv_or(found, cmp3("=", r["k"], S.as_dict(u)["k"]))
            ok = found if cond[0] == "in" else tv_not(found)
        else:
            _, op, agg = cond
            (row,) = dbrel.aggregate(inner, [], [(agg, "v", "a")]).rows
            ok = cmp3(op, r["x"], row[0])
        if ok is True:
            out[t] = c
    return Relation(R.schema, out)


def left_outer_join_on_k(R: Relation, G: Relation) -> Relation:
    """R left outer join G on R.k = G.k; G has k and other attributes, and its k is renamed gk."""
    G2 = dbrel.rename(G, {"k": "gk"})
    matched = dbrel.theta_join(R, G2, lambda row: cmp3("=", row["k"], row["gk"]))
    pad = Relation(G2.schema, [tuple(None for _ in G2.schema)])
    unmatched = dbrel.product(dbrel.antijoin(R, G), pad)
    return dbrel.union(matched, unmatched)


def null_aware_antijoin(R: Relation, S: Relation) -> Relation:
    """R.k NOT IN (SELECT S.k FROM S) as an antijoin that keeps the SQL result with nulls."""
    if len(S) == 0:
        return R
    if any(S.as_dict(u)["k"] is None for u in S.rows):
        return Relation(R.schema, [])
    return dbrel.antijoin(dbrel.select(R, lambda r: r["k"] is not None), S)


def unnest(R: Relation, S: Relation, cond: Tuple) -> Relation:
    """The rewritten query, with no evaluation of the subquery per row."""
    _check(R, S, cond)
    kind = cond[0]
    if kind in ("exists", "in"):  # @line L1
        return dbrel.semijoin(R, dbrel.project(S, ["k"]))
    if kind == "not_exists":  # @line L2
        return dbrel.antijoin(R, dbrel.project(S, ["k"]))
    if kind == "not_in":  # @line L3
        return null_aware_antijoin(R, dbrel.project(S, ["k"]))
    _, op, agg = cond
    G = dbrel.aggregate(S, ["k"], [(agg, "v", "a")])  # @line L4
    if empty_value(agg) is not None:  # @line L5
        T = left_outer_join_on_k(R, G)
        gi, ai, rows = T.index("gk"), T.index("a"), Counter()
        for row, c in T.rows.items():
            row = list(row)
            if row[gi] is None:  # a padded row: the group of R.k is empty
                row[ai] = empty_value(agg)
            rows[tuple(row)] += c
        T = Relation(T.schema, rows)
    else:
        T = dbrel.theta_join(R, dbrel.rename(G, {"k": "gk"}), lambda row: cmp3("=", row["k"], row["gk"]))  # @line L6
    return dbrel.project(dbrel.select(T, lambda row: cmp3(op, row["x"], row["a"])), R.schema)  # @line L7


def kim_unnest(R: Relation, S: Relation, cond: Tuple) -> Relation:
    """Kim's rewrite of a scalar aggregate: group S by k and join with an inner join."""
    _check(R, S, cond)
    if cond[0] != "scalar":
        raise ValueError("Kim's rewrite here is for scalar aggregates")
    _, op, agg = cond
    G = dbrel.rename(dbrel.aggregate(S, ["k"], [(agg, "v", "a")]), {"k": "gk"})
    T = dbrel.theta_join(R, G, lambda row: cmp3("=", row["k"], row["gk"]))
    return dbrel.project(dbrel.select(T, lambda row: cmp3(op, row["x"], row["a"])), R.schema)


def general_unnest(R: Relation, S: Relation, cond: Tuple, null_safe: bool = True) -> Relation:
    """Unnesting through the distinct outer values D, then a join back to R.

    D = DISTINCT R.k. The subquery is computed once for each value of D by an
    outer join of D with S and a grouping by D.k, so every value of D gets a
    result, also the empty one. The join back to R must treat two nulls as
    equal (IS NOT DISTINCT FROM); with null_safe=False it uses =, which loses
    the rows of R whose k is NULL.
    """
    _check(R, S, cond)
    if cond[0] != "scalar":
        raise ValueError("general_unnest here is for scalar aggregates")
    _, op, agg = cond
    D = dbrel.rename(dbrel.distinct(dbrel.project(R, ["k"])), {"k": "d"})
    S2 = dbrel.rename(S, {"k": "sk"})
    DS = dbrel.union(dbrel.theta_join(D, S2, lambda row: cmp3("=", row["d"], row["sk"])),
                     dbrel.product(dbrel.select(D, lambda row: not any(cmp3("=", row["d"], S2.as_dict(u)["sk"])
                                                                         for u in S2.rows)),
                                   Relation(S2.schema, [(None, None)])))
    inner_agg = (agg, "v", "a") if agg != "count_star" else ("count", "sk", "a")
    T = dbrel.aggregate(DS, ["d"], [inner_agg])

    def same(row):
        if null_safe and row["k"] is None and row["d"] is None:
            return True
        return cmp3("=", row["k"], row["d"])

    J = dbrel.theta_join(R, T, same)
    return dbrel.project(dbrel.select(J, lambda row: cmp3(op, row["x"], row["a"])), R.schema)
test_subquery_unnesting.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subquery-unnesting/. The authors are listed in prov/0C9G7B.jsonl.

import random
import unittest

import dbrel
from dbrel import Relation
from subquery_unnesting import AGGS, OPS, general_unnest, kim_unnest, nested, null_aware_antijoin, unnest

CONDS = [("exists",), ("not_exists",), ("in",), ("not_in",)] + [("scalar", op, agg) for op in OPS for agg in AGGS]
R0 = Relation(("k", "x"), [(1, 0), (2, 0), (3, 2), (None, 0)])
S0 = Relation(("k", "v"), [(1, 5), (1, 7), (3, None), (None, 4)])


def random_tables(rng):
    R = dbrel.random_relation(rng, ["k", "x"], rng.randint(0, 5), domain={"k": [1, 2, 3], "x": [0, 1, 2]},
                              null_rate=0.2)
    S = dbrel.random_relation(rng, ["k", "v"], rng.randint(0, 5), domain={"k": [1, 2, 3], "v": [0, 1, 2]},
                              null_rate=0.2)
    return R, S


class TestUnnesting(unittest.TestCase):
    def test_rewrites_equal_the_nested_query(self):
        rng = random.Random(1)
        for _ in range(60):
            R, S = random_tables(rng)
            for cond in CONDS:
                want = nested(R, S, cond)
                self.assertEqual(unnest(R, S, cond), want, (R, S, cond))
                if cond[0] == "scalar":
                    self.assertEqual(general_unnest(R, S, cond), want, (R, S, cond))

    def test_count_bug(self):
        cond = ("scalar", "=", "count_star")
        self.assertEqual(nested(R0, S0, cond), Relation(("k", "x"), [(2, 0), (None, 0)]))
        self.assertEqual(kim_unnest(R0, S0, cond), Relation(("k", "x"), []))
        self.assertEqual(unnest(R0, S0, cond), nested(R0, S0, cond))
        self.assertEqual(nested(R0, S0, ("scalar", "=", "count")), Relation(("k", "x"), [(2, 0), (None, 0)]))

    def test_kim_is_right_when_the_empty_value_is_null(self):
        rng = random.Random(2)
        wrong = 0
        for _ in range(60):
            R, S = random_tables(rng)
            for op in OPS:
                for agg in ("sum", "min", "max"):
                    self.assertEqual(kim_unnest(R, S, ("scalar", op, agg)), nested(R, S, ("scalar", op, agg)))
                for agg in ("count_star", "count"):
                    wrong += kim_unnest(R, S, ("scalar", op, agg)) != nested(R, S, ("scalar", op, agg))
        self.assertGreater(wrong, 0)

    def test_not_in_with_nulls(self):
        naive = dbrel.antijoin(R0, dbrel.project(S0, ["k"]))
        self.assertEqual(naive, Relation(("k", "x"), [(2, 0), (None, 0)]))
        self.assertEqual(nested(R0, S0, ("not_in",)), Relation(("k", "x"), []))
        S1 = dbrel.select(S0, lambda s: s["k"] is not None)
        self.assertEqual(nested(R0, S1, ("not_in",)), Relation(("k", "x"), [(2, 0)]))
        self.assertEqual(null_aware_antijoin(R0, dbrel.project(S1, ["k"])), Relation(("k", "x"), [(2, 0)]))
        empty = Relation(("k", "v"), [])
        self.assertEqual(nested(R0, empty, ("not_in",)), R0)
        self.assertEqual(unnest(R0, empty, ("not_in",)), R0)
        self.assertEqual(nested(R0, S0, ("not_exists",)), naive)

    def test_exists_needs_a_semijoin(self):
        want = Relation(("k", "x"), [(1, 0), (3, 2)])
        self.assertEqual(nested(R0, S0, ("exists",)), want)
        self.assertEqual(unnest(R0, S0, ("exists",)), want)
        joined = dbrel.project(dbrel.natural_join(R0, S0), ["k", "x"])
        self.assertEqual(joined, Relation(("k", "x"), [(1, 0), (1, 0), (3, 2)]))

    def test_general_unnesting_needs_null_safe_join_back(self):
        cond = ("scalar", "=", "count_star")
        self.assertEqual(general_unnest(R0, S0, cond), nested(R0, S0, cond))
        self.assertEqual(general_unnest(R0, S0, cond, null_safe=False), Relation(("k", "x"), [(2, 0)]))

    def test_duplicates_in_the_outer_table(self):
        R = Relation(("k", "x"), [(1, 2), (1, 2), (2, 0), (2, 0), (2, 0)])
        for cond in CONDS:
            self.assertEqual(unnest(R, S0, cond), nested(R, S0, cond))
        self.assertEqual(len(unnest(R, S0, ("scalar", "=", "count_star"))), 5)

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            nested(R0, S0, ("scalar", "==", "count"))
        with self.assertRaises(ValueError):
            unnest(R0, S0, ("scalar", "=", "avg_of"))
        with self.assertRaises(ValueError):
            unnest(Relation(("k", "y"), []), S0, ("exists",))
        with self.assertRaises(ValueError):
            unnest(R0.with_mode(dbrel.SET), S0, ("exists",))
        with self.assertRaises(ValueError):
            kim_unnest(R0, S0, ("exists",))


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

Exercises

  1. Rewrite R.x > (SELECT MAX(S.v) FROM S WHERE S.k = R.k) and explain why the inner join gives the right answer when some groups are empty.
  2. Give tables for which R.k NOT IN (SELECT S.k FROM S) and NOT EXISTS (SELECT * FROM S WHERE S.k = R.k) differ, with no NULL in RR.
  3. Rewrite R.x = (SELECT COUNT(*) FROM S WHERE S.k = R.k) with general unnesting. What must be counted after the outer join of DD with SS, and why is COUNT(*) wrong there?
  4. Rewrite EXISTS (SELECT * FROM S WHERE S.k = R.k AND S.v > R.x). Why can SS not be grouped by kk alone, and what does the set DD hold?

References

  1. On optimizing an SQL-like nested query, the types of nesting (A, N, J, JA and D) and the algorithms that transform each type into a query without nesting
  2. Optimization of nested SQL queries revisited, the COUNT bug of the transformation of type JA queries, and the repair that computes the aggregate for every outer value with an outer join
  3. Of nests and trees: a unified approach to processing queries that contain nested subqueries, aggregates, and quantifiers, general locator: one method for nested subqueries, aggregates and quantifiers
  4. Unnesting arbitrary queries, general locator: the dependent join, the set of distinct outer values and the rules that push the dependent join down until no correlation is left
  5. Leonid Libkin, SQL's three-valued logic and certain answers, ACM Transactions on Database Systems 41(1), 2016, article 1, general locator: the difference between SQL answers on databases with nulls and certain answers

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