Algorithms for Optimizing Acyclic Queries
Abstract
Most research on query optimization has centered on binary join algorithms like hash join and sort-merge join. However, recent years have seen growing interest in theoretically optimal algorithms, notably Yannakakis’ algorithm. These algorithms rely on join trees, which differ from the operator trees for binary joins and require new optimization techniques. We propose three approaches to constructing join trees for acyclic queries. First, we give an algorithm to enumerate all join trees of an -acyclic query by edits in linear time with amortized constant delay, which forms the basis of a cost-based optimizer for acyclic joins. Second, we show the Maximum Cardinality Search algorithm by Tarjan and Yannakakis constructs the unique shallowest join tree for any Berge-acyclic query, thus enabling parallel execution of large join queries. Finally, we prove that a simple algorithm by Hu et al. converts any connected left-deep linear plan of a -acyclic query into a join tree, allowing reuse of optimizers developed for binary joins.
Keywords and phrases:
Query Optimization, Join Trees, EnumerationFunding:
Wim Van den Broeck: Wim Van den Broeck acknowledges support from the L. Meltzers Høyskolefond and the Research Council of Norway, grant number 326537.Copyright and License:
2012 ACM Subject Classification:
Information systems Query optimization ; Theory of computation Database theory ; Mathematics of computing Graph theoryEditors:
Balder ten Cate and Maurice FunkSeries and Publisher:
Leibniz International Proceedings in Informatics, Schloss Dagstuhl – Leibniz-Zentrum für Informatik
1 Introduction
The query optimizer sits at the heart of a database system. It takes a query as input and generates a plan for efficient execution, allowing users to program declaratively without worrying about performance. Among the many relational algebra operators, join has received significant attention in optimization research. Its compositional nature allows for combining information from multiple relations, constructing complex queries from simple ones, and producing an output asymptotically larger than the inputs. The primary challenge is the join ordering problem to find the best arrangement of many join operations. Most existing research has focused on binary join algorithms such as hash join and sort-merge join, but these can produce unnecessarily large intermediates. Recent work has revived interest in optimal join algorithms, notably Yannakakis’ instance-optimal algorithm [42] for acyclic queries, which runs in linear time in the input and output size, . Its execution is guided by join trees whose nodes are relations, different from traditional binary join plans with relations at the leaves and join operators at the internal nodes. Although the algorithm is optimal regardless of the join tree, the choice of plan can affect practical performance. In this paper, we study the optimization problem in the context of Yannakakis-style algorithms.
A query optimizer typically has two parts: a plan generator and a cost model to assess each plan. This paper focuses on plan generation and presents three approaches:
-
1.
Given the line graph (Definition 6) of an -acyclic query , Algorithm 2 enumerates all join trees by edits111To avoid redundant work, enumeration by edits [22] outputs the difference between consecutive elements. with amortized constant delay, i.e., in where is the number of trees generated (Theorem 27). If the query is -acyclic, Algorithm 4 further reduces the total time complexity to (Theorem 28).
-
2.
Given a Berge-acyclic query, we prove that the classic Maximum Cardinality Search algorithm by Tarjan and Yannakakis [38] yields a unique shallowest join tree (Theorem 35), enabling parallel execution of very large queries.
-
3.
Given a connected left-deep linear join plan for any -acyclic query, we prove that a simple algorithm by Hu et al. [20] always converts the plan into a valid join tree (Corollary 39), allowing reuse of existing optimizers.
The rest of the paper is organized as follows: Section 2 discusses related work; Section 3 introduces relevant concepts and notations; Section 4 presents the join tree enumeration algorithms; Section 5 introduces the unique shallowest join tree, namely the canonical join tree and its construction; Section 6 discusses the conversion from binary plans to join trees; Section 7 concludes the paper by pointing to avenues for future work. For easy reference, the key notations are summarized in Table 1. Additional technical details and proofs are provided in the extended report [27].
2 Related Work
Join order optimization is well studied, with algorithms based on dynamic programming (DP) from the bottom up [29, 33, 31], cost-based rewriting from the top down [11, 15], greedy heuristics [5, 14, 37], and randomized search [35]. Since the plan space is exponential, most methods prune it: some restrict to left-deep plans [21, 23], while others avoid Cartesian products [29, 30]. Our algorithms restrict the query plans to those running in linear time for acyclic queries. In particular, while avoiding Cartesian products requires each subplan to form a spanning tree of the corresponding subquery’s join graph,222The join graph of a query has a vertex for each relation and an edge for each pair of relations that join with each other. We later define this as the line graph of the query hypergraph in Definition 6. our algorithms find maximum spanning trees of the weighted join graph. Several algorithms for ordering binary joins are based on dynamic programming and tabulate shared structures among different plans [29, 30]. This is desirable because subplans are grouped into equivalence classes, and the optimal plan can be constructed in a bottom-up manner. Future work may explore constructing compact representations of join trees, suitable for dynamic programming.
Several recent papers have proposed practical implementations of Yannakakis’ algorithm for acyclic queries [2, 20, 40, 45]. For example, Zhao et al. [45] find that different query plans perform similarly, thanks to the optimality of Yannakakis’ algorithm. They adopt a simple heuristic to construct the join tree by picking the largest input relation as the root, and then greedily attaching the remaining relations into the tree. Inspired by this algorithm, we prove in Section 5 that for Berge-acyclic queries there is a unique shallowest join tree for any given root where the depth of each node is minimized. Furthermore, this tree can be constructed in linear time by Tarjan and Yannakakis’ Maximum Cardinality Search algorithm [38]. Shallow trees are desirable for parallel execution, where the depth of the tree determines the number of sequential steps. Other practical implementations of Yannakakis’ algorithm leverage existing optimizers for binary joins and convert a binary plan into a join tree [2, 20]. In particular, Hu et al. [20] find that every left-deep linear plan encountered in practice can be converted into a join tree by a simple algorithm. This is not surprising, as we will prove in Section 6 that every connected left-deep linear plan of a -acyclic query must traverse some join tree from root to leaves.
On the theoretical side, attention has been focused on finding (hyper-)tree decompositions to improve the asymptotic complexity of query processing [36, 19, 16]. The general goal is to find a decomposition with small width which can be used to guide the execution of join algorithms. Most algorithms find a single decomposition with minimum width to achieve the optimal asymptotic complexity [36, 19, 16]. Nevertheless, different decompositions with the same width may still lead to different performance in practice, and cost-based optimization remains crucial. For this, Carmeli et al. [6] propose an algorithm to enumerate tree decompositions with polynomial delay. In this paper, we focus on acyclic queries and their join trees, which are precisely the decompositions with width 1. Our enumeration algorithm can generate all join trees by edits with amortized constant delay.
3 Preliminaries
| Variable | Definition |
|---|---|
| == | Hypergraph, its vertex set and hyperedge set |
| Incidence function mapping each hyperedge to its vertices | |
| Size of hypergraph: | |
| Neighborhood of in : set of hyperedges containing | |
| Equivalent hypergraph, its vertices, and incidence function | |
| == | (Multi-)graph, its nodes (corresponding to hyperedges) and edges |
| Incidence function mapping each edge to its endpoints, weight function | |
| Equivalent graph (Def. 15) and its incident function | |
| can be slid into (Def. 16) | |
| = | Line graph of , edge label , weight |
| Size of line graph: | |
| Subgraph of induced by | |
| A join tree (JT) and a monotonic weight JT (Def. 20) rooted at | |
| = | Set of (unrooted) join trees of and also of |
| Depth of node in the rooted tree | |
| Parent, children and siblings of a node or an edge in a rooted tree | |
| Lowest common ancestor of , and level ancestor of at depth | |
| LCA edges of a non-tree edge |
We focus on full conjunctive queries [1] in this paper and identify each query with its hypergraph, where each vertex represents a variable and each hyperedge represents a relation. Table 1 summarizes key notations introduced throughout the paper.
Definition 1 (Hypergraph).
A hypergraph consists of a set of vertices , a set of hyperedges and an incidence function .
We only consider hypergraphs without isolated vertices, empty hyperedges or duplicated hyperedges over the same set of vertices. We assume each hyperedge contains a bounded number () of vertices exclusive to . When there is no ambiguity, we will use interchangeably with , with , and with . We will also apply common set operations directly to hyperedges, e.g., for .
In fact, the reader can often ignore and identify a hyperedge with its set of vertices; the purpose of is to relate hyperedges over different vertex sets across hypergraphs in the correctness proofs of our algorithms.
We write and to refer to the vertices and edges of respectively. The size of a hypergraph is the total size of all hyperedges . We let denote the neighborhood of , consisting of all hyperedges containing .
Definition 2 (Multigraph).
A multigraph consists of a set of vertices , a set of edges , and the incidence function such that for any . An edge is a self-loop if . Edges are parallel if .
We denote the set of vertices in with , because we will soon define the line graph of a hypergraph where each vertex in represents a hyperedge. We write and to refer to the vertices and edges of respectively.
Definition 3 (Simple Graph).
A simple graph is a multigraph with no parallel edges or self-loops, i.e., the incidence function is injective and always returns two distinct vertices.
Because each edge in a simple graph can be identified with its two endpoints , we will omit and write for when there is no ambiguity.
Definition 4 (Cycle, Clique and Diamond).
In a simple graph , a sequence of distinct vertices where is
-
a cycle if there is an edge between and for all ;
-
an n-clique if the induced graph has an edge between each pair of vertices;
-
a diamond if and has one fewer edge than a .
A weighted graph is a (multi-)graph where each edge is assigned a weight:
Definition 5 (Weighted Graph).
A weighted graph consists of a multigraph and weight function assigning a natural number to each edge in .
The line graph of a hypergraph is the “intersection graph” of its hyperedges:
Definition 6 (Line Graph).
For a hypergraph , the line graph consists of a simple graph and an edge labeling function . The vertices of are the hyperedges of , and there is an edge when . The edge labeling function maps each edge to the intersection of the hyperedges represented by the endpoints of : .
In addition, we define a weight function mapping each edge to the size of its label:
Definition 7 (Line Graph Edge Weight).
For each edge , the weight function is defined as .
When there is no ambiguity from the context, we simply write as , and we may treat the line graph as a weighted graph . The size of a line graph is the sum of all edge weights . For any subgraph of , we let denote the subgraph of induced by .
Example 8.
Figure 1(a) shows an example hypergraph of size 14. The line graph is shown in Figure 1(b). For instance, hyperedges and share two vertices and , so they are connected by an edge in the line graph. The edge weight is given by . Each unannotated edge in connects two hyperedges sharing only the vertex . Otherwise, the common vertices shared by a pair of hyperedges are annotated next to the corresponding edge. The size of the line graph is .
Definition 9 (Join Tree).
A join tree of hypergraph is a spanning tree of such that is a connected subtree for each . If a certain vertex is specified as the root, becomes a rooted join tree.
We use to denote the set of nodes and to denote the set of edges of tree . The requirement that be a connected subtree is also known as the running intersection property [13]. We write or to denote the set of unrooted join trees of . We use to denote a join tree rooted at . When there is no ambiguity, we simply write . The depth of a node in the rooted tree , denoted , is defined as its distance from the root.
Four common notions of hypergraph acyclicity are defined in increasing order of strictness [13], namely -acyclic -acyclic -acyclic Berge-acyclic.
Definition 10 (Hypergraph Acyclicity).
A hypergraph is:
-
-acyclic if it admits a join tree as in Definition 9;
-
-acyclic if every subgraph of is -acyclic;
-
-acyclic if it does not contain any cycle. A cycle is a sequence of length of distinct hyperedges and distinct vertices such that every belongs to and no other while belongs to and possibly other hyperedges;
-
Berge-acyclic if it does not contain any Berge cycle. A Berge cycle is a sequence of length of distinct vertices and distinct hyperedges such that .
The following classic result relates join trees of to maximum spanning trees of :
Theorem 11 (Maier [28]).
Given an -acyclic hypergraph , a tree with nodes in is a join tree of if and only if it is a maximum spanning tree (MST) of .
Join trees for acyclic hypergraphs can be constructed by GYO reduction:
Definition 12.
A GYO reduction order is a sequence of hyperedges such that for each , there is some , called the parent of , such that .
The GYO reduction algorithm [43] finds such an order iteratively, and attaches each hyperedge to its parent to form a join tree. It generates the join tree as shown in Figure 1(c), where, for example, the node is the parent of , denoted as and the root has no parent.
Another way to construct join trees is via the Maximum Cardinality Search (MCS) algorithm [38], and we present a simplified version in Algorithm 1. The join tree produced by the algorithm is called an MCS tree. Given an input hypergraph and a hyperedge chosen as the root, Algorithm 1 constructs a rooted MCS tree by iteratively expanding toward hyperedges connected with those already processed. The algorithm maintains a set of unprocessed hyperedges and a set of unvisited vertices. Initially, the MCS tree contains no edges, and the first hyperedge to be processed is the root . In each iteration, the algorithm processes the current hyperedge by examining all of its unvisited vertices in . Whenever such a vertex is encountered, every remaining hyperedge that contains records as its tentative parent . Once all vertices of are marked as visited, they are removed from . The hyperedge is marked as processed and removed from . After processing each , the edge between and its recorded parent is added to the MCS tree as . The algorithm selects as the next hyperedge an element of that maximizes the number of already visited vertices, namely a hyperedge that maximizes , breaking ties arbitrarily. This process continues until all hyperedges have been processed, when the recorded edges form an MCS tree rooted at .
Example 13.
On in Figure 1(a) with , Algorithm 1 examines all vertices of . also becomes the tentative parent of five hyperedges, . It proceeds to check the next hyperedge with the most visited vertices as in Line 9. At this point, each of the five has one visited vertex, Algorithm 1 breaks the tie arbitrarily, say proceeding with , and examining all its vertices. Its parent is finalized as . Each of the remaining four again has one visited vertex, so Algorithm 1 proceeds to check . Its parent is finalized as . While checking , Algorithm 1 examines the vertex that is also in , their parents are updated to . It continues until all hyperedges are processed. By connecting each hyperedge with its parent, Algorithm 1 constructs the MCS tree in Figure 1(d).
Algorithm 1 can generate different join trees by varying the choice of root and tie-breaking strategy. However, it does not guarantee to generate all possible trees. For example, it never generates the join tree shown in Figure 1(c).
We extend the notions of parent, children and siblings to edges of a rooted tree. Let be an edge of tree rooted at (and not incident to ). Its parent is the unique tree edge incident to and closer to the root . We let denote the set of children of in . The siblings of are the set of edges incident to the parent of , namely . Edges incident to the root do not have a parent and are all siblings.
Lemma 14 shows that an MCS tree is “somewhat monotonic” in that every edge must contain some variable not in its parent. If two edges share any variable not in their parents, they must be siblings.
Lemma 14.
Let be an MCS tree. For an edge that has a parent, then
-
1.
-
2.
For another edge
Computation model.
Throughout the paper we assume the Random Access Machine model of computation, where one can allocate an array of size in time. Constant-time operations include accessing and updating an array element, adding or deleting an element in a linked list, and the common arithmetic operations on integers.
4 Enumerating Join Trees
Our strategy for enumerating the join trees of a hypergraph starts from Theorem 11 which allows us to reduce the problem to the enumeration of maximum spanning trees (MSTs) of the line graph . The best known algorithm for MST enumeration333Eppstein focuses on minimum spanning trees, but the same algorithm applies to maximum spanning trees with flipped comparisons. is due to Eppstein [12] by deriving from the input graph a so-called equivalent graph . Every spanning tree of corresponds to an MST of and vice versa. Eppstein gives an algorithm (and proves a matching lower bound) in time to construct the equivalent graph from an arbitrary weighted graph with edges and vertices. Then to enumerate all MSTs of , he applies existing algorithms to enumerate the spanning trees of . Since there are optimal spanning tree enumeration algorithms that run in time [22, 34], the overall time complexity to enumerate MSTs is . The main result of this section is an algorithm for enumerating join trees leveraging the structure of acyclic hypergraphs and their line graphs. In particular:
-
Given the line graph of an -acyclic hypergraph, we can construct an equivalent graph of in , thus enumerating the join trees in time (Theorem 27).
-
Given any -acyclic hypergraph , we can construct an equivalent graph of in , lowering the overall time complexity of enumeration to (Theorem 28).
Note that can be quadratic in while , so the second item above yields a better bound.
In the rest of this section, we first define the equivalent graph. Then, we present the algorithm for enumerating join trees of -acyclic hypergraphs. Finally, we adapt the algorithm to enumerate join trees of -acyclic hypergraphs more efficiently.
4.1 Equivalent Graph
The key idea of Eppstein’s algorithm [12] is to construct an equivalent graph whose spanning trees one-to-one correspond to the MSTs of the input graph , thereby reducing MST enumeration to spanning tree enumeration.
Definition 15 (Equivalent Graph [12]).
Given a weighted graph , a multigraph is an equivalent graph of if the spanning trees of one-to-one correspond to the maximum spanning trees of : a set of edges induces a spanning tree of if and only if induces an MST of .
In what follows, we may use the notation or to refer to an equivalent graph of the line graph of hypergraph . Note that shares the same vertices and edges of , and they only differ in the incidence function mapping each edge to its endpoints. Such an equivalent graph can be constructed from by applying a series of sliding transformations: for two incident edges with and , we can slide along by updating , if . Note that the edge retains its identity after sliding, which explains the need for the incidence function . Furthermore, we will use a given rooted MST as a guide, and only slide edges towards the root. More formally:
Definition 16 (Sliding Transformation [12]).
Let be a MST of rooted at . Let be an edge such that with closer to the root than in . If another edge shares with , i.e., , and , then sliding along results in a graph that is identical to , except that the incidence function maps to .
The key result by Eppstein shows that applying sliding transformations on along a rooted MST to a fixpoint results in an equivalent graph of . To state this formally, we first define an ordering on graphs based on sliding transformations. It is easy to verify the following is a partial order:
Definition 17 (Sliding Partial Order).
We write if can be obtained from by applying a sequence of sliding transformations along a rooted MST of .
Applying sliding transformations to a fixpoint therefore yields a maximal element under the sliding partial order.
Theorem 18 (Sliding produces at fixpoint [12]).
Given a weighted graph and a rooted MST , and let be a maximal element under . Then is an equivalent graph of .
The choice of the initial rooted MST can affect the structure of the equivalent graph, but the order of sliding transformations performed has no impact [12].
Example 19.
Given the 6-clique line graph in Figure 1(b), we find a rooted MST as shown in Figure 2(a). Among all the tree edges shown as black solid lines, we can only apply the sliding transformation to the edge whose weight is lighter than its parent tree edge with . We slide along the tree edge to the root so that the edge becomes as shown by the solid curve in Figure 2(b). Non-tree edges can slide similarly. We consider two examples, illustrated with a dashed line and with a dotted line in Figure 2(a). All other non-tree edges are shown in light gray. We can slide along tree edge to become as shown by the dashed curve in Figure 2(b). Both ends of can slide along the tree edges to the root so that the edge becomes a self-loop as shown by the dotted loop in Figure 2(b). This edge will not appear in any spanning tree of , and therefore not a part of any MST of . We refer to such an edge as a non-MST edge, as opposed to an MST edge. Denoting the graph after sliding as , ordering holds. By applying sliding transformations to a fixpoint, we obtain an equivalent graph , where there are two sets of parallel edges highlighted by thick lines in Figure 2(c) (self-loops are omitted). For example, the tree edge in and non-tree edges become parallel in between and . Therefore holds under the sliding partial order. We can easily verify that each spanning tree of corresponds to an MST of , such as in Figure 2(d).
4.2 Enumerating Join Trees of -Acyclic Hypergraphs
The bottleneck of Eppstein’s algorithm for constructing equivalent graphs of arbitrary weighted graphs lies in a subroutine that identifies where each edge will eventually slide to. Because each edge can only slide along a heavier edge, it will eventually be “blocked” by a lighter or equally weighted edge along its path to the root. The subroutine essentially performs binary search to find the blocking edge, leading to the factor in the overall complexity. The key to our improvement is to show that for every acyclic hypergraph , we can construct an equivalent hypergraph whose join trees one-to-one correspond to those of , but one special join tree of has monotonically increasing weight from root to leaf, which enables constant-time identification of the blocking edge.
Definition 20.
A monotonic weight join tree is a rooted join tree of such that for any that has a parent edge , .
We can always construct such a given any -acyclic hypergraph :
Theorem 21.
Given an -acyclic hypergraph , there exists an equivalent hypergraph over the same hyperedge set that
-
admits a monotonic weight join tree , and
-
.
Example 22.
in Figure 3(a) is a hypergraph with similar structure to in Figure 1(a). differs from by one vertex and admits the same set of join trees. Therefore, finding an equivalent graph is sufficient for enumerating the join trees of . also admits a monotonic weight join tree in Figure 3(b).
A monotonic weight join tree can accelerate the construction of the equivalent graph in several ways. First, all tree edges are already “in place”, because they cannot slide along their lighter parent edges. We therefore need only consider non-tree edges. For each non-tree edge , there are two possible cases. First, if one endpoint, say , is an ancestor of the other, say , then can only slide to become parallel to the edge right below on the path connecting and in . This is because all edges on that path must be no lighter than due to the running intersection property of join trees, but since has monotonically increasing weight, at most one edge (the one right below ) can have equal weight to . If this edge has weight equal to , it becomes the blocking edge, and slides to become parallel to it; otherwise, slides to a self-loop at . In the second case, if neither endpoint is an ancestor of the other, there are at most two blocking edges, namely those below the lowest common ancestor of and on the path between them. We therefore only need to compare the weight of with these two potentially blocking edges to determine the destination of .
Example 23.
Consider again in Figure 3(c). First note that every tree edge is heavier than its parent edge, and each non-tree edge is no heavier than any edge on the path connecting its endpoints in the tree. There is one edge, , where one endpoint () is an ancestor of the other (). The only potentially blocking edge is right below . But because is heavier, slides to become a self-loop at . For the edge , all edges on the tree path connecting the endpoints are heavier, so also slides to a self-loop at their LCA . Finally, is blocked by the two edges and below their LCA , as all three edges have a weight of 1. Therefore slides to .
Our algorithm for constructing the equivalent graph leverages the insight above to slide each edge in constant time. In the following, we first define a few helpful notations and describe a preprocessing step to build helper data structures, before presenting the algorithm.
Given a rooted MCS tree of a line graph , a non-tree edge is . There is a path in between and via their lowest common ancestor . We define the LCA edges as a set of at most two tree edges on the path and incident to . If , are ancestor and child, then , otherwise, .
During pre-processing, we first conduct a breadth-first search on to obtain the depth table of each tree node in . Then we build two data structures in to facilitate the constant-time query of the lowest common ancestor (LCA) [3] given two nodes, and the level ancestor (LA) [4] of a node , which is the ancestor of at a given depth. Algorithm 2 assumes these data structures are prebuilt and available, which allows finding of any non-tree edge in constant time as follows:
We are now ready to present Algorithm 2 which constructs by sliding each non-tree edge with weight . There are two cases. First, if returns a single edge, then one endpoint is an ancestor of the other. By the definition above always returns the ancestor node first, while the other node is denoted as . The weight of is then compared with : if is lighter, slides to a self-loop at ; otherwise the weights must be equal, and slides to be parallel to . Second, if returns two edges, then neither endpoint is an ancestor of the other. In this case we compare with the two edges in . If is lighter than both, slides to a self-loop at ; if equals one of them, slides to be parallel to that edge; otherwise, equals both, and slides to be incident to each of the highest depth endpoints of both edges. The four cases are exhaustive, as the non-tree edge never outweighs any of its LCA edges by the running intersection property.
Theorem 24.
Given a hypergraph with a monotonic weight join tree , Algorithm 2 produces an Equivalent Graph .
The notation highlights later applications to equivalent hypergraphs, although Theorem 24 applies to any hypergraph admitting a monotonic weight join tree.
Although Algorithm 2 constructs an equivalent graph of in constant time per edge, such an may be asymptotically larger than . Perhaps surprisingly, running Algorithm 2 directly on produces the same equivalent graph! This is because is constructed in a way that preserves the structure of , keeping the relative weights of an edge and its LCA edges invariant. Intuitively, we construct by making “local copies” of the vertices in : this perturbs the weights to be monotonic along , while ensuring the weights are adjusted consistently. In particular, when making a new copy of a vertex , we add to all hyperedges that contain , namely . This way, in if and only if in . As a result, all comparisons in Algorithm 2 return the same result when running on or . We illustrate this with the following example.
Example 25.
In Figure 3(a), we made a copy of and added it to all hyperedges containing in . This maintains the relative weights between the tree edge and the non-tree edges highlighted in Figure 3(c): all three non-tree edges remain lighter than . Were we to make a copy of to add to (which contains every hyperedge in ), the weights of the non-tree edges relative to their respective LCA edges would also remain unchanged.
Finally, because and share the same join trees, there must be that is the same as . Together with Theorem 24, this means running Algorithm 2 directly on produces an equivalent graph of :
Theorem 26.
Given the line graph and an MCS tree of an -acyclic hypergraph , Algorithm 2 returns an equivalent graph in time .
Figure 4 shows an example of applying Algorithm 2 to in Figure 1(a). Once we compute the equivalent graph , we can apply existing algorithms [22, 34] to enumerate all its spanning trees by edits with amortized constant delay. And because the MCS tree can be constructed in linear time from which in turn can be recovered from in linear time, the overall time complexity of enumerating all join trees of is linear in the size of plus the number of join trees:
Theorem 27.
Given the line graph of an -acyclic hypergraph , the join trees of can be enumerated in time .
4.3 -Acyclic Queries
The run time of Algorithm 2 depends on the size of the line graph which can be quadratically larger than the input hypergraph. If is -acyclic, we can bring the total time complexity of enumeration down to . Using an algorithm by Leitert [25], we can construct from in time when is -acyclic; furthermore, because every edge in of a -acyclic is an MST edge [25], we have , and so , hiding the term in the overall complexity. However, the constructed by Leitert is unweighted, so we need to modify Algorithm 2 slightly to slide each non-tree edge based on the weights of its LCA edges alone. We first modify MCS (Algorithm 1) to track the weight of each tree edge as in Algorithm 3. Then, we update the cases of Algorithm 2 to those in Algorithm 4. First, if returns a single edge, we directly slide to be parallel to it, because we know is an MST edge and therefore will not become a self-loop. Otherwise, if returns two edges, we compare the weights of those two edges, instead of comparing them with . This is again because we know is an MST edge, so it must have weight equal to at least one of its LCA edges. If one of the LCA edges is lighter, must have equal weight to that edge, and we slide to be parallel to it. Otherwise, if both LCA edges have the same weight, must also have the same weight, and we slide to be under both edges to form a triangle. In all cases we only use the weights of the tree edges and do not need to know .
Theorem 28.
The join trees of a -acyclic can be enumerated in time .
5 The Canonical Join Tree of a Berge-Acyclic Query
An acyclic query can have exponentially many join trees with respect to its size. For example, the line graph of a clique query with relations is an -clique with join trees by Cayley’s formula [7]. Enumerating all join trees can be prohibitive for large queries. The query optimizer does not need to consider all possible join trees to achieve good performance. For example, the implementation of Yannakakis’ algorithm by Zhao et al. [45] achieves similar performance on any join tree rooted at the largest relation. An alternative to enumeration is therefore to simply construct one join tree for a given root. This can be done in linear time by the Maximum Cardinality Search (MCS) algorithm from a chosen relation as shown in Algorithm 1. In this section, we prove that for a Berge-acyclic query the MCS algorithm produces a shallowest tree, where the depth of each tree node is minimized. We prove that this shallowest tree is unique, and therefore call it the canonical join tree.
Definition 29.
A join tree rooted at is canonical if for any other join tree rooted at and any .
A shallow join tree has practical benefits. For example, the depth of the join tree determines the number of sequential steps required in a parallel join algorithm. A shallow join tree also tends to be wide and have more leaves, allowing better utilization of indices.
Although Berge-acyclicity was thought to be too restrictive when it was first introduced to database theory [13], we found it to be general enough to cover almost all acyclic queries encountered in the wild. As shown in Table 2, among queries from five popular benchmarks, are -acyclic, and only 8 of these are not Berge-acyclic. In retrospect, this should not be surprising, as most joins in relational databases are over primary/foreign keys. Emerging workloads in graph databases usually involve simple graphs and seldom require composite key joins. A query without composite key joins admits a linear hypergraph, where each pair of hyperedges shares at most one vertex. The following result establishes an equivalence between -acyclicity with linearity and Berge-acyclicity.
| Name | # Queries | # -Acyclic | # Composite-Key Joins | # Berge-Acyclic |
|---|---|---|---|---|
| TPC-H[39] | 22 | 21 | 2 | 19 |
| JOB[24] | 113 | 113 | 0 | 113 |
| STATS-CEB[17] | 2603 | 2603 | 0 | 2603 |
| CE[8] | 3004 | 1839 | 0 | 1839 |
| Spider-NLP[44] | 4712 | 4709 | 6 | 4703 |
Proposition 30.
An -acyclic hypergraph is Berge-acyclic if and only if it is linear.
By Proposition 30, every edge in the line graph of a Berge-acyclic hypergraph has a weight of 1. Every spanning tree is a maximum spanning tree, therefore a join tree.
Corollary 31.
For a Berge-acyclic hypergraph , any spanning tree of is a join tree.
In the rest of this section, we prove the existence and uniqueness of the canonical join tree rooted at any relation of a Berge-acyclic hypergraph, and show that it can be constructed by MCS as in Algorithm 1.
The key insight leading to the existence and uniqueness of the canonical join tree is that the line graph of a Berge-acyclic hypergraph is geodetic [32], meaning that there is a unique shortest path between any pair of vertices. The canonical join tree can then be constructed by taking the union of all shortest paths from the root to each other vertex, as this will guarantee minimal depth for each vertex. The key step to establish the geodetic property is to show that is a special class of chordal graphs called block graphs. Chordal graphs are intimately related to acyclic hypergraphs [9], and a block graph is a special chordal graph defined as follows:
Definition 32 (Chordal and Block).
A simple graph is
-
chordal [10] if every cycle of length at least 4 has a chord, i.e., an edge that is not part of the cycle but connects two vertices of the cycle;
-
a block graph [18] if it is chordal and diamond-free, i.e., no subgraph induced by any is a diamond (Definition 4).
Lemma 33.
The line graph of a Berge-acyclic hypergraph is a block graph.
Together with the fact that every block graph is geodetic (with a unique shortest path between any two vertices) [32], Lemma 33 implies the following corollary.
Corollary 34.
Let be the line graph of a Berge-acyclic hypergraph . There is a unique shortest path between any two vertices in .
We are now ready to prove the existence and uniqueness of the canonical join tree.
Theorem 35.
A Berge-acyclic hypergraph has a unique canonical tree.
Proof.
Let be the line graph of , and be the shortest path in between , we prove that is the unique canonical join tree for rooted at .
By Corollary 31 any spanning tree of is a join tree. is connected and spans all vertices in , because it contains the shortest path from to every . It remains to show that is acyclic, which we prove by induction on the distance between and . Let . contains only the root. The subgraph is trivially acyclic. Assuming that is acyclic, we consider a vertex . Corollary 34 guarantees a unique shortest path between each pair of vertices . Each is connected to a unique neighbor that is at distance from . Otherwise, there are at least two distinct shortest paths from to . Therefore is acyclic, and is a spanning tree thus a join tree of .
The join tree is canonical, because the path from to each is the shortest and therefore minimizing the depth . The canonical tree is unique by Corollary 34.
The canonical join tree can be constructed by the MCS algorithm as shown in Algorithm 1:
Theorem 36.
Given a Berge-acyclic hypergraph , running Algorithm 1 from constructs the canonical tree .
6 Converting a Binary Join Plan to a Join Tree
Recent approaches [20, 2] that convert a binary join plan into a join tree have gained popularity as they allow system builders to leverage existing query optimizers designed for binary join plans. In this section, we focus on an algorithm by Hu et al. [20] to convert left-deep linear join plans into join trees as shown in Figure 5. We prove that the algorithm converts any connected left-deep linear join plan into a join tree if and only if the query is -acyclic. This can be seen as a new characterization of -acyclic queries. We formally define binary join plans and describe the algorithm by Hu et al. in Algorithm 5.
Definition 37.
A left-deep linear plan is a sequence of hyperedges . It is connected if for each , .
Query optimizers strive to produce connected plans, to avoid expensive Cartesian products. Many optimizers produce exclusively left-deep linear plans. Plans that are not left-deep are called bushy, and such plans may still be decomposed into left-deep fragments [41].
Given a left-deep linear plan, Hu et al. [20] generate a join tree with Algorithm 5. The algorithm chooses the first relation as the root and iterates through the rest of the plan. For each relation , it finds the first relation that contains all attributes shared by with all previous relations, , and assigns as the parent of . The algorithm constructs a join tree if it finds a parent for each .
Hu et al. [20] proved that the algorithm succeeds whenever the input plan is the reverse of a GYO-reduction order. They also observed that every left-deep linear plan produced for queries in standard benchmarks is indeed the reverse of a GYO-reduction order. This is not a coincidence, as we show that every connected left-deep linear join plan must be the reverse of a GYO-reduction order if and only if the query is -acyclic.
Theorem 38.
A query is -acyclic if and only if every connected left-deep linear join plan for the query is the reverse of a GYO-reduction order.
Immediately following Theorem 38, we can conclude the following.
Corollary 39.
For any -acyclic query, Algorithm 5 converts a given connected left-deep linear join plan to a join tree.
7 Conclusion and Future Work
We proposed three approaches for constructing join trees. Our enumeration algorithm in Section 4 generates join trees by edits with amortized constant delay; in Section 5, we showed that the Maximum Cardinality Search algorithm constructs the unique shallowest join tree for any Berge-acyclic query; in Section 6, we characterize the class of binary join plans that can be converted to join trees. Practitioners can choose from the three approaches to integrate instance-optimal algorithms into their system: a cost-based optimizer can use our enumeration algorithm to generate candidate query plans; a system aiming to support very large queries can implement the MCS algorithm to generate shallow join trees to improve parallelism; and a more conservative extension can derive join trees using existing optimization infrastructure, while our final result guarantees the validity of the output.
Future work includes compact representations of join trees for dynamic programming, as in binary plan optimizers, and the challenging cost estimation for Yannakakis-style algorithms: the random-walk approach [26] models joint probabilities for binary joins, whereas an efficient and accurate solution for semijoins remains to be found.
Our work also raises further theoretical questions. Can join tree enumeration achieve worst-case constant delay? We proved Berge-acyclicity sufficient for the existence and uniqueness of the canonical join tree, but it is not necessary, and -acyclicity is insufficient as shown in Figure 6. What is the precise characterization of hypergraphs that admit a unique canonical join tree for any root, or for some root? How can our algorithms be extended to enumerate tree decompositions à la Carmeli et al. [6]? One possible direction is to further develop connections between MSTs of the line graph and tree decompositions of the hypergraph. For example, we are considering using the determinants of the line graph Laplacian as heuristics to guide the search for good tree decompositions.
References
- [1] Serge Abiteboul, Richard Hull, and Victor Vianu. Foundations of Databases. Addison-Wesley, 1995. URL: http://webdam.inria.fr/Alice/.
- [2] Liese Bekkers, Frank Neven, Stijn Vansummeren, and Yisu Remy Wang. Instance-optimal acyclic join processing without regret: Engineering the yannakakis algorithm in column stores. Proc. VLDB Endow., 18(8):2413–2426, 2025. URL: https://www.vldb.org/pvldb/vol18/p2413-vansummeren.pdf.
- [3] Michael A. Bender and Martin Farach-Colton. The lca problem revisited. In LATIN 2000, volume 1776 of Lecture Notes in Computer Science, pages 88–94. Springer, 2000. doi:10.1007/10719839_9.
- [4] Michael A. Bender and Martin Farach-Colton. The level ancestor problem simplified. Theoretical Computer Science, 321(1):5–12, 2004. doi:10.1016/J.TCS.2003.05.002.
- [5] Nicolas Bruno, César A. Galindo-Legaria, and Milind Joshi. Polynomial heuristics for query optimization. In Proceedings of ICDE 2010, pages 589–600. IEEE, 2010. doi:10.1109/ICDE.2010.5447916.
- [6] Nofar Carmeli, Batya Kenig, and Benny Kimelfeld. Efficiently enumerating minimal triangulations. In Proceedings of the 36th ACM Symposium on Principles of Database Systems (PODS 2017), pages 273–287. ACM, 2017. doi:10.1145/3034786.3056109.
- [7] Arthur Cayley. A theorem on trees. Quarterly Journal of Pure and Applied Mathematics, 23:376–378, 1889.
- [8] Jeremy Chen, Yuqing Huang, Mushi Wang, Semih Salihoglu, and Ken Salem. Accurate summary-based cardinality estimation through the lens of cardinality estimation graphs. Proc. VLDB Endow., 15(8):1533–1545, 2022. doi:10.14778/3529337.3529339.
- [9] Alessandro D’atri and Marina Moscarini. On hypergraph acyclicity and graph chordality. Information Processing Letters, 29(5):271–274, 1988. doi:10.1016/0020-0190(88)90121-4.
- [10] Pablo De Caria and Marisa Gutierrez. On basic chordal graphs and some of its subclasses. Discrete Applied Mathematics, 210:261–276, 2016. doi:10.1016/j.dam.2015.05.002.
- [11] David DeHaan and Frank Wm. Tompa. Optimal top-down join enumeration. In Proceedings of SIGMOD 2007, pages 785–796, 2007. doi:10.1145/1247480.1247567.
- [12] David Eppstein. Representing all minimum spanning trees with applications to counting and generation. UC Irvine, 1995.
- [13] Ronald Fagin. Degrees of acyclicity for hypergraphs and relational database schemes. J. ACM, 30(3):514–550, 1983. doi:10.1145/2402.322390.
- [14] Leonidas Fegaras. A new heuristic for optimizing large queries. In Proceedings of DEXA 1998, volume 1460 of Lecture Notes in Computer Science, pages 726–735. Springer, 1998. doi:10.1007/BFB0054528.
- [15] Pit Fender and Guido Moerkotte. Counter strike: Generic top-down join enumeration for hypergraphs. Proc. VLDB Endow., 6(14):1822–1833, 2013. doi:10.14778/2556549.2556565.
- [16] Georg Gottlob, Matthias Lanzinger, Cem Okulmus, and Reinhard Pichler. Fast parallel hypertree decompositions in logarithmic recursion depth. ACM Trans. Database Syst., 49(1):1:1–1:43, 2024. doi:10.1145/3638758.
- [17] Yuxing Han, Ziniu Wu, Peizhi Wu, Rong Zhu, Jingyi Yang, Liang Wei Tan, Kai Zeng, Gao Cong, Yanzhao Qin, Andreas Pfadler, Zhengping Qian, Jingren Zhou, Jiangneng Li, and Bin Cui. Cardinality estimation in dbms: A comprehensive benchmark evaluation. Proc. VLDB Endow., 15(4):752–765, 2021. doi:10.14778/3503585.3503586.
- [18] Frank Harary. A characterization of block-graphs. Canadian Mathematical Bulletin, 6(1):1–6, 1963.
- [19] Zongyan He and Jeffrey Xu Yu. A branch-&-bound algorithm for fractional hypertree decomposition. Proc. VLDB Endow., 17(13):4655–4667, 2024. URL: https://www.vldb.org/pvldb/vol17/p4655-he.pdf.
- [20] Zeyuan Hu, Yisu Remy Wang, and Daniel P. Miranker. Treetracker join: Simple, optimal, fast. ACM Trans. Database Syst., October 2025. Just Accepted. doi:10.1145/3774325.
- [21] Toshihide Ibaraki and Tiko Kameda. On the optimal nesting order for computing n-relational joins. ACM Trans. Database Syst., 9(3):482–502, 1984. doi:10.1145/1270.1498.
- [22] Sanjiv Kapoor and H. Ramesh. Algorithms for enumerating all spanning trees of undirected and weighted graphs. SIAM Journal on Computing, 24(2):247–265, 1995. doi:10.1137/S009753979225030X.
- [23] Ravi Krishnamurthy, Haran Boral, and Carlo Zaniolo. Optimization of nonrecursive queries. In Proceedings of the 12th International Conference on Very Large Data Bases (VLDB 1986), pages 128–137. Morgan Kaufmann, 1986. URL: http://www.vldb.org/conf/1986/P128.PDF.
- [24] Viktor Leis, Andrey Gubichev, Atanas Mirchev, Peter Boncz, Alfons Kemper, and Thomas Neumann. How good are query optimizers, really? Proc. VLDB Endow., 9(3):204–215, 2015. doi:10.14778/2850583.2850594.
- [25] Arne Leitert. Computing the union join and subset graph of acyclic hypergraphs in subquadratic time. In WADS 2021, volume 12808 of Lecture Notes in Computer Science, pages 571–584. Springer, 2021. doi:10.1007/978-3-030-83508-8_41.
- [26] Feifei Li, Bin Wu, Ke Yi, and Zhuoyue Zhao. Wander join: Online aggregation via random walks. In Proceedings of the 2016 International Conference on Management of Data (SIGMOD 2016), pages 615–629. ACM, 2016. doi:10.1145/2882903.2915235.
- [27] Zheng Luo, Wim Van den Broeck, Guy Van den Broeck, and Yisu Remy Wang. Algorithms for optimizing acyclic queries, 2026. doi:10.48550/arXiv.2509.14144.
- [28] David Maier. The Theory of Relational Databases. Computer Science Press, 1983.
- [29] Guido Moerkotte and Thomas Neumann. Analysis of two existing and one new dynamic programming algorithm for the generation of optimal bushy join trees without cross products. In Proceedings of VLDB 2006, pages 930–941, 2006. URL: http://dl.acm.org/citation.cfm?id=1164207.
- [30] Guido Moerkotte and Thomas Neumann. Dynamic programming strikes back. In Proceedings of the ACM SIGMOD International Conference on Management of Data (SIGMOD 2008), pages 539–552. ACM, 2008. doi:10.1145/1376616.1376672.
- [31] Thomas Neumann. Query simplification: Graceful degradation for join-order optimization. In Proceedings of SIGMOD 2009, pages 403–414, 2009. doi:10.1145/1559845.1559889.
- [32] Øystein Ore. Theory of Graphs, volume 38 of American Mathematical Society Colloquium Publications. American Mathematical Society, 1962. doi:10.1090/coll/038.
- [33] Patricia G. Selinger, Morton M. Astrahan, Donald D. Chamberlin, Raymond A. Lorie, and Thomas G. Price. Access path selection in a relational database management system. In Proceedings of SIGMOD 1979, pages 23–34, 1979. doi:10.1145/582095.582099.
- [34] Akiyoshi Shioura, Akihisa Tamura, and Takeaki Uno. An optimal algorithm for scanning all spanning trees of undirected graphs. SIAM J. Comput., 26(3):678–692, 1997. doi:10.1137/S0097539794270881.
- [35] Michael Steinbrunn, Guido Moerkotte, and Alfons Kemper. Heuristic and randomized optimization for the join ordering problem. VLDB Journal, 6(3):191–208, 1997. doi:10.1007/S007780050040.
- [36] Vaishali Surianarayanan, Anikait Mundhra, Ajaykrishnan E. S, and Daniel Lokshtanov. Fast hypertree decompositions via linear programming: Fractional and generalized. Proc. ACM Manag. Data, 3(3):159:1–159:27, 2025. doi:10.1145/3725296.
- [37] Arun N. Swami. Optimization of large join queries: Combining heuristic and combinatorial techniques. In Proceedings of SIGMOD 1989, pages 367–376, 1989. doi:10.1145/67544.66961.
- [38] Robert E. Tarjan and Mihalis Yannakakis. Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs. SIAM Journal on Computing, 13(3):566–579, 1984. doi:10.1137/0213035.
- [39] Transaction Processing Performance Council. TPC Benchmark H (Decision Support). https://tpc.org/tpc_documents_current_versions/pdf/tpc-h_v3.0.1.pdf, 2023. Standard Specification, Revision 3.0.1.
- [40] Qichen Wang, Bingnan Chen, Binyang Dai, Ke Yi, Feifei Li, and Liang Lin. Yannakakis+: Practical acyclic query evaluation with theoretical guarantees. Proc. ACM Manag. Data, 3(3):235:1–235:28, 2025. doi:10.1145/3725423.
- [41] Yisu Remy Wang, Max Willsey, and Dan Suciu. Free join: Unifying worst-case optimal and traditional joins. Proc. ACM Manag. Data, 1(2), 2023. doi:10.1145/3589295.
- [42] Mihalis Yannakakis. Algorithms for acyclic database schemes. In Proceedings of VLDB 1981, pages 82–94, 1981.
- [43] C. T. Yu and M. Z. Ozsoyoglu. An algorithm for tree-query membership of a distributed query. In COMPSAC 1979, pages 306–312. IEEE, 1979. doi:10.1109/CMPSAC.1979.762509.
- [44] Tao Yu, Rui Zhang, Kai Yang, Michihiro Yasunaga, Dongxu Wang, Zifan Li, James Ma, Irene Li, Qingning Yao, Shanelle Roman, Zilin Zhang, and Dragomir R. Radev. Spider: A large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-sql task. In Proceedings of EMNLP 2018, pages 3911–3921. Association for Computational Linguistics, 2018. doi:10.18653/v1/d18-1425.
- [45] Junyi Zhao, Kai Su, Yifei Yang, Xiangyao Yu, Paraschos Koutris, and Huanchen Zhang. Debunking the myth of join ordering: Toward robust sql analytics. Proc. ACM Manag. Data, 3(3), 2025. doi:10.1145/3725283.
