Algorithmadvanced
Conjunctive query minimization
Also called tableau minimization, query core computation.
Find the smallest equivalent conjunctive query by deleting atoms while the query still maps homomorphically into the smaller one.
- Time
- O(a k^(k+1)) worst
- Space
- O(a k^2) extra
- Where
- a = the largest arity of a relation; k = the number of atoms of the query
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
Conjunctive query minimization takes a conjunctive query and returns an equivalent conjunctive query with the smallest number of atoms. It tries each atom once: if the query has a homomorphism into the query without that atom, the atom is redundant, and it goes. Chandra and Merlin (1977) showed that the result is the core of the query, which is unique up to a renaming of the variables, and that no equivalent conjunctive query has fewer atoms. A query with fewer atoms needs fewer joins, so this is the classic step of semantic query optimization. Each test is an NP-complete homomorphism problem, and the whole task is NP-hard.
In plain words
A query asks for rows that match a pattern of conditions. Sometimes one condition says nothing new: every row that matches the other conditions also matches it, after you rename some helper variables. You can then delete that condition and the answers stay the same.
The algorithm goes through the conditions one at a time. For each one, it asks: can I send the whole query into the query without this condition, so that each condition lands on a condition that is still there and the output columns stay fixed? If yes, the condition goes. At the end, no condition can go, and no smaller query gives the same answers.
The problem
We use set semantics: a relation is a set of tuples, and a query returns a set of tuples. A conjunctive query is a rule
where each is a tuple of variables and constants and each variable of the head occurs in the body. Two queries are equivalent, , if for every database . A homomorphism from to is a map from the variables of to the terms of , the identity on constants, with and an atom of the body of for each . By the Chandra-Merlin theorem, if and only if there is a homomorphism from to .
Input. A conjunctive query with atoms. Output. A conjunctive query with the smallest number of atoms among all conjunctive queries equivalent to .
For a set of atoms of , write for the query with the head of and the body .
The algorithm
MINIMIZE tries each atom once, in the order of the body. HOM is a backtracking search for a homomorphism, one source atom at a time.
MINIMIZE(Q)- 1
S ← the body of Q - 2
for each atom α of the body of Q, in order - 3
if HOM(Q_S, Q_{S − {α}}) succeeds then - 4
S ← S − {α} ▷ α is redundant - 5
return Q_S HOM(P, P')- 6
h ← the map that sends the head of P to the head of P' (fail on a clash) SEARCH(1, h), with α_1, ..., α_n the atoms of P:- 7
if i > n then return h - 8
for each atom β of P' with the relation name of α_i - 9
g ← h extended so that h(α_i) = β (skip β on a clash) - 10
if SEARCH(i + 1, g) succeeds then return its map - 11
fail
Line L4 is safe for any α found at line L3. The identity map is a homomorphism from to , so , and the map found at line L3 gives the other direction. A head variable is mapped to itself, so it still occurs in , and the query stays safe. If the body has two equal atoms, line L4 deletes one copy.
The code sorts the atoms of so that atoms with fewer candidates in come first, which cuts the search but does not change the answer.
Example
Take . It asks for pairs joined by a path of length two, twice, and for an edge out of .
| atom tried | homomorphism into the rest | result | body after the step |
|---|---|---|---|
| , | removed | ||
| removed | |||
| must go to , then is missing | kept | the same | |
| no atom left of the form | kept | the same | |
| removed |
The result is . It has two atoms, and no conjunctive query with one atom is equivalent, because none of the three atoms can go. Here a different order of the body would keep instead, which is the same query up to the renaming .
The head matters. For nothing can go, since and are fixed. The Boolean query folds onto and keeps one atom.
Correctness
The proofs are in the correctness proof. There are three steps.
- Each step keeps equivalence. This is the argument under the pseudocode. So at each point.
- At the end, no single atom can be deleted. Let be kept when the set was , and let be the final set, so . Suppose is a homomorphism from to . Since , there is a homomorphism from to . Then maps into , whose atoms are all in . So the test at line L3 would have succeeded for , a contradiction. One pass is enough.
- If no single atom can be deleted, the query has the fewest atoms. Let have fewer atoms than . Homomorphisms from to and from to give the map from to itself, whose image has at most as many atoms as . So some atom is not in the image, and is a homomorphism from to .
Chandra and Merlin also showed that two minimal equivalent queries are the same up to a renaming of the variables. This minimal query is the core of .
Proof: MINIMIZE returns an equivalent conjunctive query with the fewest atomsfull
We use set semantics and the pseudocode of the page. has the head and the body , a list of atoms. For a sublist of , is the query with the head and the body . A homomorphism from to maps the variables of to the terms of , is the identity on constants, sends the head of to the head of , and sends each atom of to an atom of . We use the Chandra-Merlin theorem: if and only if there is a homomorphism from to . Homomorphisms compose, and a composition of homomorphisms is a homomorphism.
Termination. Line L2 runs times. HOM is a depth-first search of depth at most , with at most choices at each level, so it stops.
Lemma 1 (HOM is correct). HOM succeeds if and only if there is a homomorphism from to , and then it returns one.
Proof. Line L6 fixes the image of the head variables, as each homomorphism must, and fails if one variable must go to two different terms or a constant of the head of is not equal to the term at that place in the head of . By induction on , SEARCH succeeds if and only if extends to a map that sends to atoms of and agrees with : line L8 tries every atom that can go to, and line L9 keeps exactly the extensions that send to . For there is nothing left, and line L7 returns .
Lemma 2 (each step keeps equivalence and safety). At each point, , and each head variable occurs in .
Proof. At the start . Suppose it holds for , and line L4 sets after line L3 found a homomorphism from to . The identity is a homomorphism from to , since each atom of is in and the heads are equal. So , and gives . For safety, let be a head variable. It occurs in some atom , and because sends the head to the head. So occurs in , an atom of .
Lemma 3 (one pass is enough). Let be the final body. For no atom is there a homomorphism from to .
Proof. Each atom of was tried at line L3 and kept. Let be the body at the time of that test, so (as lists, with obtained from by deletions) and . Suppose is a homomorphism from to . By Lemma 2, , so and there is a homomorphism from to . Then is a homomorphism from to . Each atom of is an atom of , so is also a homomorphism from to . By Lemma 1, the test at line L3 then succeeds for , and is not kept, a contradiction.
Lemma 4 (no deletable atom means fewest atoms). Let be a conjunctive query with body such that for no there is a homomorphism from to . Then every conjunctive query has at least atoms.
Proof. Let have the body . By the Chandra-Merlin theorem there are homomorphisms from to and from to . The map is a homomorphism from to . Each atom of goes under to an atom of , and then under to one atom of , so the set of image atoms has at most distinct atoms. If , some atom of is not in , and is a homomorphism from to . This is not possible, so . If has two equal atoms, the identity sends to with one copy deleted, so the hypothesis already excludes equal atoms, and counts distinct atoms.
Theorem. MINIMIZE returns a conjunctive query , whose body is a sublist of the body of and whose head variables occur in the body, such that no conjunctive query equivalent to has fewer atoms.
Proof. By Lemma 2, and is safe. By Lemma 3, meets the hypothesis of Lemma 4. Each query equivalent to is equivalent to , so by Lemma 4 it has at least atoms.
Uniqueness up to renaming. Let and be two results, for example from two orders of the body. Both are minimum, so . Take homomorphisms from to and from to . The map sends to itself, and by the proof of Lemma 4 its image has all atoms, so it is a permutation of the atoms of . Some power of , with , fixes each atom of . Each variable of is at some place of some atom, and fixes that atom, so fixes the variable too. So is the identity, and is injective on the variables of . The image is a set of atoms of , and it has atoms because is a bijection on the atoms of , so , and maps the variables of onto the variables of . So is a bijection between the variables that maps the body of onto the body of and fixes the head and the constants. The two results differ only in the names of the existential variables.
Complexity
Let be the number of atoms of and the largest arity. The bounds are in the word RAM model and are combined complexity: the query is the input, and there is no database.
- One test (theorem). HOM visits at most levels and tries at most target atoms per level, so its search tree has nodes. Each extension costs time with a dictionary. That is time per test.
- The whole algorithm (theorem). tests, so time in the worst case. The search keeps one map of at most variables per level, which is extra space.
- Hardness (theorem). For a graph , let be the Boolean query with the atoms and for each edge . Take the Boolean query on disjoint variables, where has no loops. If is 3-colorable, the part maps into the triangle and the core has 6 atoms. If the core has 6 atoms, it is the image of the triangle, so maps into a triangle and is 3-colorable. So computing the size of the core is NP-hard, and no polynomial algorithm is expected.
- Polynomial cases (theorem). For acyclic queries and for queries of bounded query width, containment and minimization take polynomial time (Chekuri and Rajaraman 2000). The homomorphism test is then a constraint satisfaction problem with an acyclic or bounded treewidth structure.
Real queries have few atoms, so the exponential bound is rarely a problem in practice. This is a common observation, not a theorem.
Properties
- The result is unique up to renaming. Every order of the atoms gives a query with the same number of atoms, and all of them are isomorphic. The atoms that stay can differ.
- The result is a subquery. Its body is a subset of the body of . No new variables or atoms come in.
- The result is minimum, not only minimal. No conjunctive query equivalent to has fewer atoms, even one with atoms that are not in .
- Constants and head variables are fixed. A homomorphism can rename only the existential variables.
Variants and improvements
- Tableau minimization. Aho, Sagiv and Ullman (1979) write a select-project-join expression as a tableau, one row per atom, and minimize the tableau by deleting rows. This is the same algorithm. For their class of simple tableaux, they gave a polynomial-time method.
- Minimization under dependencies. With functional or tuple-generating dependencies, first apply the chase to the query, then minimize. Atoms that the dependencies make redundant then also go.
- Unions of conjunctive queries. Delete each member that is contained in another member, then minimize each member. The Sagiv-Yannakakis theorem shows that this gives a smallest equivalent union.
- Cores in data exchange. The same retraction step computes the core of a universal solution, an instance with labeled nulls instead of variables. See data exchange core computation.
- Acyclic queries. Chekuri and Rajaraman replace the backtracking search by a polynomial test when the query is acyclic or has bounded query width.
When to use it
Use it in an optimizer for queries with set semantics, such as SQL queries with SELECT DISTINCT, Datalog rule bodies, and queries over views that a user or a tool has built by combining smaller queries. Generated queries often have redundant joins, and each atom that goes saves one join. Use it also before a containment or equivalence test that you run many times, since the core is a small canonical form.
Pitfalls
- Bag semantics. Under bag semantics, which plain SQL uses, the number of copies of each answer counts. Chaudhuri and Vardi (1993) showed that two conjunctive queries are then equivalent if and only if they are isomorphic, so no atom is redundant, and containment is much harder, with cases that are still open. Do not minimize a query without
DISTINCTthis way. - Deleting by a subset test. An atom is not redundant because its variables occur in other atoms. In both atoms share all variables, but neither can go. Only a homomorphism into the smaller query is a correct test.
- Renaming a head variable. The map must send the head to itself. A search that lets for a head variable deletes atoms that are needed.
- Built-in predicates. With or in the body the homomorphism test is no longer correct. Containment of such queries needs other methods.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conjunctive-query-minimization/. The authors are listed in prov/PG64E9.jsonl.
"""Minimization of conjunctive queries under set semantics (Chandra and Merlin 1977).
A term is a variable (a str) or a constant (an int). An atom is (relation name, tuple of
terms). A conjunctive query is (head, body): head is a tuple of terms and body is a list of
atoms, and every variable of the head occurs in the body. The query Q(x) :- R(x, y), S(y, 3)
is (("x",), [("R", ("x", "y")), ("S", ("y", 3))]).
"""
def is_var(t) -> bool:
return isinstance(t, str)
def variables(atoms) -> list:
out = []
for _, terms in atoms:
for t in terms:
if is_var(t) and t not in out:
out.append(t)
return out
def _extend(h: dict, terms, target_terms):
"""Extend the map h so that it sends terms to target_terms, or return None."""
if len(terms) != len(target_terms):
return None
g = dict(h)
for s, t in zip(terms, target_terms):
if is_var(s):
if s in g and g[s] != t:
return None
g[s] = t
elif s != t:
return None
return g
def homomorphism(source, target):
"""Find a homomorphism from the query source to the query target.
It is a map h from the variables of source to the terms of target, the identity on
constants, with h(head of source) = head of target and h(atom) in the body of target for
each atom of the body of source. Return the map as a dict, or None. Backtracking search,
one source atom at a time."""
head_s, body_s = source
head_t, body_t = target
start = _extend({}, head_s, head_t) # @line L6
if start is None:
return None
by_name = {}
for name, terms in body_t:
by_name.setdefault(name, []).append(terms)
order = sorted(range(len(body_s)), key=lambda i: len(by_name.get(body_s[i][0], ())))
def search(k: int, h: dict):
if k == len(order): # @line L7
return h
name, terms = body_s[order[k]]
for target_terms in by_name.get(name, ()): # @line L8
g = _extend(h, terms, target_terms) # @line L9
if g is not None:
found = search(k + 1, g) # @line L10
if found is not None:
return found
return None # @line L11
return search(0, start)
def is_contained(q1, q2) -> bool:
"""Q1 is contained in Q2 under set semantics iff there is a homomorphism from Q2 to Q1."""
return homomorphism(q2, q1) is not None
def is_equivalent(q1, q2) -> bool:
return is_contained(q1, q2) and is_contained(q2, q1)
def minimize(query, trace=None):
"""Return a minimal conjunctive query equivalent to query whose body is a subset of the
body of query. The atoms are tried once each, in the order of the body. If trace is a list,
append (atom, removed) for each atom tried."""
head, body = query
keep = list(body) # @line L1
for atom in body: # @line L2
rest = list(keep)
rest.remove(atom)
removed = homomorphism((head, keep), (head, rest)) is not None # @line L3
if removed:
keep = rest # @line L4
if trace is not None:
trace.append((atom, removed))
return head, keep # @line L5
def evaluate(query, db) -> set:
"""Evaluate a conjunctive query on a database under set semantics.
db maps a relation name to a set of tuples of constants. Backtracking over the atoms."""
head, body = query
def search(k: int, h: dict, out: set) -> None:
if k == len(body):
out.add(tuple(h[t] if is_var(t) else t for t in head))
return
name, terms = body[k]
for row in db.get(name, ()):
g = _extend(h, terms, row)
if g is not None:
search(k + 1, g, out)
out = set()
search(0, {}, out)
return out
test_conjunctive_query_minimization.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conjunctive-query-minimization/. The authors are listed in prov/PG64E9.jsonl.
import itertools
import random
from conjunctive_query_minimization import (
evaluate,
homomorphism,
is_equivalent,
is_var,
minimize,
variables,
)
def brute_homomorphism(source, target) -> bool:
"""The definition: try every map from the variables of source to the terms of target."""
head_s, body_s = source
head_t, body_t = target
vs = variables(body_s)
terms = sorted({t for _, ts in body_t for t in ts} | set(head_t), key=repr)
facts = set(body_t)
for values in itertools.product(terms, repeat=len(vs)):
h = dict(zip(vs, values))
def image(ts):
return tuple(h[t] if is_var(t) else t for t in ts)
if image(head_s) != tuple(head_t):
continue
if all((name, image(ts)) in facts for name, ts in body_s):
return True
return False
def safe(head, body) -> bool:
return all(not is_var(t) or t in variables(body) for t in head)
def brute_force_minimum(query) -> int:
"""The smallest number of atoms of an equivalent subquery, by trying all subsets."""
head, body = query
for size in range(len(body) + 1):
for sub in itertools.combinations(body, size):
sub = list(sub)
if not safe(head, sub):
continue
q = (head, sub)
if brute_homomorphism(query, q) and brute_homomorphism(q, query):
return size
return len(body)
def random_query(rng, names=("x", "y", "z", "u", "v")):
names = list(names)
k = rng.randint(1, 5)
body = []
for _ in range(k):
if rng.random() < 0.7:
terms = (rng.choice(names), rng.choice(names))
body.append(("E", terms))
else:
terms = (rng.choice(names), rng.choice(names + [1]))
body.append(("R", terms))
vs = variables(body)
head = tuple(rng.sample(vs, rng.randint(0, min(2, len(vs)))))
return head, body
def random_db(rng):
dom = [1, 2, 3]
return {
"E": {(rng.choice(dom), rng.choice(dom)) for _ in range(rng.randint(0, 6))},
"R": {(rng.choice(dom), rng.choice(dom)) for _ in range(rng.randint(0, 4))},
}
def edge_atoms(edges, prefix):
body = []
for a, b in edges:
body.append(("E", (f"{prefix}{a}", f"{prefix}{b}")))
body.append(("E", (f"{prefix}{b}", f"{prefix}{a}")))
return body
def test_page_example():
q = (("x", "z"), [
("E", ("x", "y")), ("E", ("y", "z")), ("E", ("x", "w")), ("E", ("w", "z")), ("E", ("x", "u")),
])
trace = []
head, body = minimize(q, trace)
assert body == [("E", ("x", "w")), ("E", ("w", "z"))]
assert [removed for _, removed in trace] == [True, True, False, False, True]
assert is_equivalent(q, (head, body))
def test_constants_and_head():
# The constant 1 blocks the map y -> 2.
q = (("x",), [("R", ("x", "y")), ("R", ("x", 1))])
assert minimize(q)[1] == [("R", ("x", 1))]
q = (("x",), [("R", ("x", 2)), ("R", ("x", 1))])
assert minimize(q)[1] == q[1]
# A head variable can not be renamed, so nothing goes.
q = (("x", "y"), [("E", ("x", "z")), ("E", ("y", "z"))])
assert minimize(q)[1] == q[1]
# The Boolean version folds y onto x.
q = ((), [("E", ("x", "z")), ("E", ("y", "z"))])
assert len(minimize(q)[1]) == 1
# Duplicate atoms.
q = (("x",), [("E", ("x", "y")), ("E", ("x", "y"))])
assert minimize(q)[1] == [("E", ("x", "y"))]
def test_homomorphism_against_brute_force():
rng = random.Random(11)
for _ in range(300):
q1, q2 = random_query(rng), random_query(rng)
if len(q1[0]) != len(q2[0]):
continue
found = homomorphism(q1, q2)
assert (found is not None) == brute_homomorphism(q1, q2)
if found is not None:
image = lambda ts: tuple(found[t] if is_var(t) else t for t in ts)
assert image(q1[0]) == q2[0]
assert all((n, image(ts)) in set(q2[1]) for n, ts in q1[1])
def test_minimize_against_brute_force():
rng = random.Random(20261118)
for _ in range(200):
q = random_query(rng, ("x", "y", "z", "u"))
head, body = minimize(q)
rest = list(q[1])
for atom in body:
rest.remove(atom)
assert safe(head, body)
assert brute_homomorphism(q, (head, body)) and brute_homomorphism((head, body), q)
assert len(body) == brute_force_minimum(q), q
# No single atom of the result can go: it is minimal.
for atom in body:
smaller = list(body)
smaller.remove(atom)
assert not (safe(head, smaller) and brute_homomorphism((head, body), (head, smaller)))
def test_same_answers_on_random_databases():
rng = random.Random(5)
for _ in range(150):
q = random_query(rng)
m = minimize(q)
for _ in range(4):
db = random_db(rng)
assert evaluate(q, db) == evaluate(m, db)
def test_core_size_decides_three_coloring():
# The core of Q_G and Q_K3 together has 6 atoms iff G is 3-colorable.
triangle = [(0, 1), (1, 2), (2, 0)]
c5 = [(i, (i + 1) % 5) for i in range(5)]
k4 = [(a, b) for a in range(4) for b in range(a + 1, 4)]
for edges, colorable in ((c5, True), (k4, False), ([(0, 1), (1, 2)], True)):
q = ((), edge_atoms(triangle, "t") + edge_atoms(edges, "g"))
size = len(minimize(q)[1])
assert (size == 6) == colorable
q = ((), edge_atoms(k4, "g") + edge_atoms(triangle, "t"))
assert len(minimize(q)[1]) == 12
def test_order_changes_the_atoms_not_the_size():
rng = random.Random(9)
for _ in range(100):
head, body = random_query(rng)
sizes = set()
for _ in range(3):
shuffled = list(body)
rng.shuffle(shuffled)
sizes.add(len(minimize((head, shuffled))[1]))
assert len(sizes) == 1
History
Chandra and Merlin (1977) defined conjunctive queries, proved the homomorphism criterion for containment, and showed that every conjunctive query has a unique minimal equivalent query, found by deleting atoms. Aho, Sagiv and Ullman (1979) stated the method for tableaux of select-project-join expressions, proved NP-completeness for the general case, and gave polynomial methods for simple tableaux. Chaudhuri and Vardi (1993) showed that the picture changes under bag semantics. Chekuri and Rajaraman (1997, journal version 2000) gave polynomial containment and minimization for acyclic queries and for bounded query width.
References
- Ashok K. Chandra and Philip M. Merlin, Optimal implementation of conjunctive queries in relational data bases, Proceedings of the 9th Annual ACM Symposium on Theory of Computing (STOC), 77 to 90 (1977), the minimization of conjunctive queries by homomorphisms and the uniqueness of the minimal query up to renaming
- Alfred V. Aho, Yehoshua Sagiv and Jeffrey D. Ullman, Efficient optimization of a class of relational expressions, ACM Transactions on Database Systems 4(4), 435 to 454 (1979), tableau minimization, and the polynomial-time method for simple tableaux
- Alfred V. Aho, Yehoshua Sagiv and Jeffrey D. Ullman, Equivalences among relational expressions, SIAM Journal on Computing 8(2), 218 to 246 (1979), tableaux for select-project-join expressions and the NP-completeness of their equivalence
- Chandra Chekuri and Anand Rajaraman, Conjunctive query containment revisited, Theoretical Computer Science 239(2), 211 to 229 (2000), polynomial-time containment and minimization for acyclic queries and for queries of bounded query width
- Surajit Chaudhuri and Moshe Y. Vardi, Optimization of real conjunctive queries, Proceedings of the 12th ACM Symposium on Principles of Database Systems (PODS), 59 to 70 (1993), containment and equivalence of conjunctive queries under bag semantics
- Serge Abiteboul, Richard Hull and Victor Vianu, Foundations of Databases, Addison-Wesley (1995), Chapter 6 (static analysis and optimization), the section on query minimization and tableaux
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PG64E9 Edit this page History Report an error Markdown