Query Compiler
Query Compiler
(Under Construction)
[expected time to completion: 5 years]
Guido Moerkotte
September 3, 2009
Contents
I Basics 3
1 Introduction 5
1.1 General Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 DBMS Architecture . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Interpretation versus Compilation . . . . . . . . . . . . . . . . . . 6
1.4 Requirements for a Query Compiler . . . . . . . . . . . . . . . . 9
1.5 Search Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.6 Generation versus Transformation . . . . . . . . . . . . . . . . . 12
1.7 Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8 Organization of the Book . . . . . . . . . . . . . . . . . . . . . . 13
3 Join Ordering 31
3.1 Queries Considered . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.1.1 Query Graph . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.1.2 Join Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.1.3 Simple Cost Functions . . . . . . . . . . . . . . . . . . . . 34
3.1.4 Classification of Join Ordering Problems . . . . . . . . . . 40
3.1.5 Search Space Sizes . . . . . . . . . . . . . . . . . . . . . . 41
3.1.6 Problem Complexity . . . . . . . . . . . . . . . . . . . . . 45
3.2 Deterministic Algorithms . . . . . . . . . . . . . . . . . . . . . . 47
3.2.1 Heuristics . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.2.2 Determining the Optimal Join Order in Polynomial Time 49
3.2.3 The Maximum-Value-Precedence Algorithm . . . . . . . . 56
3.2.4 Dynamic Programming . . . . . . . . . . . . . . . . . . . 61
3.2.5 Memoization . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.2.6 Join Ordering by Generating Permutations . . . . . . . . 79
3.2.7 A Dynamic Programming based Heuristics for Chain Queries 81
3.2.8 Transformation-Based Approaches . . . . . . . . . . . . . 94
i
ii CONTENTS
II Foundations 197
V Implementation 423
36 Outlook 505
Bibliography 518
Index 578
E ToDo 579
List of Figures
xi
xii LIST OF FIGURES
Goals
Primary Goals:
• book covers many query languages (at least SQL, OQL, XQuery (XPath))
Secondary Goals:
• book is thin
Acknowledgements
Introducer to query optimization: Günther von Bültzingsloewen
Peter Lockemann
First paper coauthor: Stefan Karl,
Coworkers: Alfons Kemper, Klaus Peithner, Michael Steinbrunn, Donald
Kossmann, Carsten Gerlhof, Jens Claussen,
Sophie Cluet, Vassilis Christophides, Georg Gottlob, V.S. Subramanian,
Sven Helmer, Birgitta König-Ries, Wolfgang Scheufele, Carl-Christian Kanne,
Thomas Neumann, Norman May, Matthias Brantner
Robin Aly
xv
LIST OF FIGURES 1
Discussions: Umesh Dayal, Dave Maier, Gail Mitchell, Stan Zdonik, Tamer
Özsu, Arne Rosenthal,
Don Chamberlin, Bruce Lindsay, Guy Lohman, Mike Carey, Bennet Vance,
Laura Haas, Mohan, CM Park,
Yannis Ioannidis, Götz Graefe, Serge Abiteboul, Claude Delobel Patrick
Valduriez, Dana Florescu, Jerome Simeon, Mary Fernandez, Christoph Koch,
Adam Bosworth, Joe Hellerstein, Paul Larson, Hennie Steenhagen, Harald
Schöning, Bernhard Seeger,
Encouragement: Anand Deshpande
Manuscript: Simone Seeger,
and many others to be inserted.
2 LIST OF FIGURES
Part I
Basics
3
Chapter 1
Introduction
5
6 CHAPTER 1. INTRODUCTION
CTS
execution plan
RTS
result
Rewrite
query interpretation
calculus result
tion, add/drop a view, update database items (e.g. tuples, relations, objects),
change authorizations, and state a query. Within the book, we will only be
concerned with the tiny last item.
interprete(SQLBlock x) {
eval(s, f , w, t, R) {
if(f .empty())
if(w(t))
R += s(t);
else
foreach(t0 ∈ first(f ))
eval(s, tail(f ), w, t ◦ t0 , R);
}
marized in Figure 1.4. First, the query is rewritten. Again, unnesting nested
queries is a main technique for performance gains. Other rewrites will be dis-
cussed in Part ??. After the rewrite, the plan generation takes place. Here,
an optimal plan is constructed. Whereas typically rewrite takes place on a
calculus-based representation of the query, plan generation constructs an alge-
braic expression containing well-known operators like selection and join. Some-
times, after plan generation, the generated plan is refined: some polishing takes
place. Then, code is generated, that can be interpreted by the runtime system.
More specifically, the query execution engine—a part of the runtime system—
interpretes the query execution plan. Let us illustrate this. The following query
8 CHAPTER 1. INTRODUCTION
query
parsing CTS
abstract syntax tree
nfst
internal representation
rewrite I query
internal representationoptimizer
plan generation
internal representation
rewrite II
internal representation
code generation
execution plan
The CTS translates this query into a query execution plan. Part of the plan
is shown in Fig. 1.6. One rarely sees a query execution plan. This is the reason
why I included one. But note that the form of query execution plans differs
from DBMS to DBMS since it is (unfortunately) not standardized the way SQL
is. Most DBMSs can give the user abstract representations of query plans. It
is worth the time to look at the plans generated by some commercial DBMSs.
I do not expect the reader to understand the plan in all details. Some of
these details will become clear later. Anyway, this plan is given to the RTS
which then interprets it. Part of the result of the interpretation might look like
this:
RETURNFLAG LINESTATUS SUM QTY SUM EXTPR ...
A F 3773034 5319329289.68 ...
N F 100245 141459686.10 ...
N O 7464940 10518546073.98 ...
R F 3779140 5328886172.99 ...
This should look familar to you.
The above query plan is very simple. It contains only a few algebraic op-
erators. Usually, more algebraic operators are present and the plan is given in
a more abstract form that cannot be directly executed by the runtime system.
Fig. 2.10 gives an example of an abstracted more complex operator tree. We
will work with representations closer to this one.
A typical query compiler architecture is shown in Figure 1.5. The first com-
ponent is the parser. It produces an abstract syntax tree. This is not always the
case but this intermediate representation very much simplifies the task of fol-
lowing component. The NFST component performs several tasks. The first step
is normalization. This mainly deals with introducing new variables for subex-
pressions. Factorization and semantic analysis are performed during NFST.
Last, the abstract syntax tree is translated into the internal representation. All
these steps can typically be performed during a single path through the query
representation. Semantic analysis requires looking up schema definitions. This
can be expensive and, hence, the number of lookups should be minimized. Af-
ter NFST the core optimization steps rewrite I and plan generation take place.
Rewrite II does some polishing before code generation. These modules directly
correspond to the phases in Figure 1.4. They are typically further devided into
submodules handling subphases. The most prominent example is the prepara-
tion phase that takes place just before the actual plan generation takes place.
In our figures, we think of preparation as being part of the plan generation.
2. Completeness
(group
(tbscan
{segment ’lineitem.C4Kseg’ 0 4096}
{nalslottedpage 4096}
{ctuple ’lineitem.cschema’}
[ 20
LOAD_PTR 1
LOAD_SC1_C 8 1 2 // L_RETURNFLAG
LOAD_SC1_C 9 1 3 // L_LINESTATUS
LOAD_DAT_C 10 1 4 // L_SHIPDATE
LEQ_DAT_ZC_C 4 ’1998-02-09’ 1
] 2 1 // number of help-registers and selection-register
) 10 22 // hash table size, number of registers
[ // init
MV_UI4_C_C 1 0 // COUNT(*) = 0
LOAD_SF8_C 4 1 6 // L_QUANTITY
LOAD_SF8_C 5 1 7 // L_EXTENDEDPRICE
LOAD_SF8_C 6 1 8 // L_DISCOUNT
LOAD_SF8_C 7 1 9 // L_TAX
MV_SF8_Z_C 6 10 // SUM/AVG(L_QUANTITY)
MV_SF8_Z_C 7 11 // SUM/AVG(L_EXTENDEDPRICE)
MV_SF8_Z_C 8 12 // AVG(L_DISCOUNT)
SUB_SF8_CZ_C 1.0 8 13 // 1 - L_DISCOUNT
ADD_SF8_CZ_C 1.0 9 14 // 1 + L_TAX
MUL_SF8_ZZ_C 7 13 15 // SUM(L_EXTDPRICE * (1 - L_DISC))
MUL_SF8_ZZ_C 15 14 16 // SUM((...) * (1 + L_TAX))
] [ // advance
INC_UI4 0 // inc COUNT(*)
MV_PTR_Y 1 1
LOAD_SF8_C 4 1 6 // L_QUANTITY
LOAD_SF8_C 5 1 7 // L_EXTENDEDPRICE
LOAD_SF8_C 6 1 8 // L_DISCOUNT
LOAD_SF8_C 7 1 9 // L_TAX
MV_SF8_Z_A 6 10 // SUM/AVG(L_QUANTITY)
MV_SF8_Z_A 7 11 // SUM/AVG(L_EXTENDEDPRICE)
MV_SF8_Z_A 8 12 // AVG(L_DISCOUNT)
SUB_SF8_CZ_C 1.0 8 13 // 1 - L_DISCOUNT
ADD_SF8_CZ_C 1.0 9 14 // 1 + L_TAX
MUL_SF8_ZZ_B 7 13 17 15 // SUM(L_EXTDPRICE * (1 - L_DISC))
MUL_SF8_ZZ_A 17 14 16 // SUM((...) * (1 + L_TAX))
] [ // finalize
UIFC_C 0 18
DIV_SF8_ZZ_C 10 18 19 // AVG(L_QUANTITY)
DIV_SF8_ZZ_C 11 18 20 // AVG(L_EXTENDEDPRICE)
DIV_SF8_ZZ_C 12 18 21 // AVG(L_DISCOUNT)
] [ // hash program
HASH_SC1 2 HASH_SC1 3
] [ // compare program
CMPA_SC1_ZY_C 2 2 0
EXIT_NEQ 0
CMPA_SC1_ZY_C 3 3 0
])
Figure 1.6: Execution plan
5. Graceful degradation
1.5. SEARCH SPACE 11
6. Robustness
First of all, the query compiler must produce correct query evaluation plans.
That is, the result of the query evaluation plan must be the result of the query
as given by the specification of the query language. It must also cover the
complete query language. The next issue is that an optimal query plan must
(should) be generated. However, this is not always that easy. That is why some
database researchers say that one must avoid the worst plan. Talking about
the quality of a plan requires us to fix the optimization goal. Several goals are
reasonable: We can optimize throughput, minimize response time, minimize
resource consumption (both, memory and CPU), and so on. A good query
compiler supports two optimization goals: minimize resource consumption and
minimize the time to produce the first tuple. Obviously, both goals cannot be
achieved at the same time. Hence, the query compiler must be instructed about
the optimization goal.
Irrespective of the optimization goal, the query compiler should produce the
query evaluation plan fast. It does not make sense to take 10 seconds to optimize
a query whose execution time is below a second. This sounds reasonable but
is not trivial to achieve. As we will see, the number of query execution plans
that are equivalent to a given query, i.e. produce the same result as the query,
can be very large. Sometimes, very large even means that not all plans can
be considered. Taking the wrong approach to plan generation will result in no
plan at all. This is the contrary of graceful degradation. Expressed positively,
graceful degradation means that in case of limited resources, a plan is generated
that may not be the optimal plan, but also not that far away from the optimal
plan.
Last, typical software quality criteria should be met. We only mentioned
robustness in our list, but others like maintainability must be met also.
equivalent
plans
actual
search space
potential
search space
1.7 Focus
In this book, we consider only the compilation of queries. We leave out many
special aspects like query optimization for multi-media database systems or
1.8. ORGANIZATION OF THE BOOK 13
multidatabase systems. These are just two omissions. We further do not con-
sider the translation of update statements which — especially in the presence
of triggers — can become quite complex. Furthermore, we assume the reader to
be familiar with the fundamentals of database systems [225, 413, 550, 604, 707]
and their implementation [347, 270]. Especially, knowledge on query execution
engines is required [294].
Last, the book presents a very personal view on query optimization. To
see other views on the same topic, I strongly recommend to read the literature
cited in this book and the references found therein. A good start are overview
articles, PhD theses, and books, e.g. [782, 275, 381, 382, 398, 465] [522, 526,
562, 719, 739, 766, 767].
this problem allows to discuss some issues like search space sizes and problem
complexities. The third reason is that we do not have to delve into details.
We can stick to very simple (you might call them unrealistic) cost functions,
do not have to concern ourselves with details of the runtime system and the
like. Expressed positively, we can concentrate on some algorithmic aspects
of the problem. In Chapter 4 we do the opposite. The reader will not find
any advanced algorithms in this chapter but plenty of details on disks and cost
functions. The goal of the rest of the book is then to bring these issues together,
broaden the scope of the chapters, and treat problems not even touched by
them. The main issue not touched is query rewrite.
Chapter 2
Those attributes belonging to the key of the relations have been underlined.
With the following query we ask for all students attending a lecture by a
Professor called “Larson”.
15
16 CHAPTER 2. TEXTBOOK QUERY OPTIMIZATION
2.2 Algebra
Let us briefly recall the standard definition of the most important algebra-
ic operators. Their inputs are relations, that is sets of tuples. Sets do not
contain duplicates. The attributes of the tuples are assumed to be simple (non-
decomposable) values. The most common algebraic operators are defined in
Fig. 2.1. Although the common set operations union (∪), intersection (∩), and
setdifference (\) belong to the relational algebra, we did not list them. Re-
member that ∪ and ∩ are both commutative and associative. \ is neither of
them. Further, for ∪ and ∩, two distributivity laws hold. However, since these
operations are not used in this section, we refer to Figure 7.1 in Section 7.1.1.
Before we can understand Figure 2.1, we must clarify some terms and no-
tations. For us, a tuple is a mapping from a set of attribute names (or at-
tributes for short) to their corresponding values. These values are taken from
certain domains. An actual tuple is denoted embraced by brackets. They
include a comma-separated list of the form attribute name, column and at-
tribute value as in [name: ‘‘Anton’’, age: 2]. If we have two tuples
with different attribute names, they can be concatenated, i.e. we can take the
union of their attributes. Tuple concatentation is denoted by ‘◦’. For exam-
ple [name: ‘‘Anton’’, age: 2] ◦ [toy: ‘‘digger’’] results in [name:
‘‘Anton’’, age: 2, toy: ‘‘digger’’]. Let A and A0 be two sets of at-
tributes where A0 ⊆ A holds. Further let t a tuple with schema A. Then, we can
project t on the attributes in A (written as t.A). The resulting tuple contains on-
ly the attributes in A0 ; others are discarded. For example, if t is the tuple [name:
‘‘Anton’’, age: 2, toy: ‘‘digger’’] and A = {name, age}, then t.A is
the tuple [name: ‘‘Anton’’, age: 2].
A relation is a set of tuples with the same attributes. The schema of a
relation is the set of attributes. For a relation R this is sometimes denoted by
sch(R), the schema of R. We denote it by A(R) and extend it to any algebraic
expression producing a set of tuples. That is, A(e) for any algebraic expression
is the set of attributes the resulting relation defines. Consider the predicate
age = 2 where age is an attribute name. Then, age behaves like a free variable
that must be bound to some value before the predicate can be evaluated. This
motivates us to often use the terms attribute and variable synonymously. In the
above predicate, we would call age a free variable. The set of free variables of
an expression e is denoted by F(e).
Sometimes it is useful to work with sequences of attributes in compari-
son predicates. Let A = ha1 , . . . , ak i and B = hb1 , . . . , bk i be two attribute
sequences. Then for any comparison operator θ ∈ {=, ≤, <, ≥, >, 6=}, the ex-
pression AθB abbreviates a1 θb1 ∧ a2 θb2 ∧ . . . ∧ ak θbk .
Often, a natural join is defined. Consider two relations R1 and R2 . Define
Ai := A(Ri ) for i ∈ {1, 2}, and A := A1 ∩ A2 . Assume that A is non-empty
and A = ha1 , . . . , an i. If A is non-empty, the natural join is defined as
R1 1 R2 := ΠA1 ∪A2 (R1 1p ρA:A0 (R2 ))
where ρA:A0 renames the attributes ai in A to a0i in A0 and the predicate p has
the form A = A0 , i.e. a1 = a01 ∧ . . . ∧ an = a0n .
2.3. CANONICAL TRANSLATION 17
For our algebraic operators, several equivalences hold. They are given in
Figure 2.2. For them to hold, we typically require that the relations involved
have disjoint attribute sets. That is, we assume—even for the rest of the book—
that attribute names are unique. This is often achieved by using the notation
R.a for a relation R or v.a for a variable ranging over tuples with an attribute
a. Another possibility is to use the renaming operator ρ.
Some equivalences are not always valid. Their validity depends on whether
some condition(s) are satisfied or not. For example, Eqv. 2.4 requires F(p) ⊆ A.
That is, all attribute names occurring in p must be contained in the attribute set
A the projection retains: otherwise, we could not evaluate p after the projection
has been applied. Although all conditions in Fig. 2.2 are of this flavor, we will
see throughout the course of the book that more complex conditions exist.
select distinct a1 , a2 , . . . , am
from R1 c1 , R2 c2 , . . . , Rn cn
where p
Here, the Ri are relation names and the ci are correlation names. The ai in
the select clause are attribute names (or expressions of the form ci .ai ) taken
from the relations in the from clause. The predicate p is assumed to be a
conjunction of comparisions between attributes or attributes and constants.
The translation process then follows the procedure described in Figure 2.3.
First, we construct an expression that produces the cross product of the entries
18 CHAPTER 2. TEXTBOOK QUERY OPTIMIZATION
((. . . ((R1 × R2 ) × R3 ) . . .) × Rn ).
σp ((. . . ((R1 × R2 ) × R3 ) . . .) × Rn ).
3. Let s be the content of the select distinct clause. For the canonical
translation it must be of either ’*’ or a list a1 , . . . , an of attribute names.
Construct the expression
W if s = ’*’
S :=
Πa1 ,...,an (W ) if s = a1 , . . . , an
4. Return S.
where p equals
s.SNo = a.ASNo and a.ALNo = l.LNo and l.LPNo = p.PNo and p.PName =
‘Larson’.
Note that we used the notation R[r] to say that a relation named R has the
correlation name r. During the course of the book we will be more precise
about the semantics of this notation and it will deviate from the one suggested
here. We will take r as a variable successively bound to the elements (tuples)
in R. However, for the purpose of this chapter it is sufficient to think of it
as associating a correlation name with a relation. The query is represented
graphically in Figure 2.7 (top).
20 CHAPTER 2. TEXTBOOK QUERY OPTIMIZATION
3. introduce joins
(Eqv. 2.15: →)
Πs.SN ame (
σs.SN o=a.ASN o (
σa.ALN o=l.LN o (
σl.LP N o=p.P N o (
σp.P N ame=‘Larson0 (
((Student[s] × Attend[a]) × Lecture[l]) × Prof essor[p])))))
Πs.SN ame (
σl.LP N o=p.P N o (
σa.ALN o=l.LN o (
σs.SN o=a.ASN o (Student[s] × Attend[a])
×Lecture[l])
×(σp.P N ame=‘Larson0 (Prof essor[p]))))
After translation and Steps 1 and 2 the algebraic expression looks like
Πs.SN ame (
σs.SN o=a.ASN o (
σa.ALN o=l.LN o (
(Student[s] × σl.LT itle=‘Databases I 0 (Lecture[l])) × Attend[a]))).
Neither of σs.SN o=a.ASN o and σa.ALN o=l.LN o can be pushed down further. Only
after reordering the cross products such as in
Πs.SN ame (
σs.SN o=a.ASN o (
σa.ALN o=l.LN o (
(Student[s] × Attend[a]) × σl.LT itle=‘Databases I 0 (Lecture[l]))))
Πs.SN ame (
σa.ALN o=l.LN o (
σs.SN o=a.ASN o (Student[s] × Attend[a])
×σl.LT itle=‘Databases I 0 (Lecture[l])))
This is the reason why in some textbooks reorder cross products before selec-
tions are pushed down [225]. In this appoach, reordering of cross products takes
into account the selection predicates that can possibly be pushed down to the
leaves and down to just prior a cross product. In any case, the Steps 2 and 4
are highly interdependent and there is no simple solution. 2
After this small excursion let us resume rewriting our main example query.
The next step to be applied is converting cross products to join operations (Step
3). The motivation behind this step is that the evaluation of cross products
2.4. LOGICAL QUERY OPTIMIZATION 23
is very expensive and results in huge intermediate results. For every tuple in
the left input an output tuple must be produced for every tuple in the right
input. A join operation can be implemented much more efficiently. Applying
Equivalence 2.15 from left to right to our example query results in
Πs.SN ame (
((Student[s] 1s.SN o=a.ASN o Attend[a])
1a.ALN o=l.LN o Lecture[l])
1l.LP N o=p.P N o (σp.P N ame=‘Larson0 (Prof essor[p])))
All students and their attendances to some lecture are considered. The result
and hence the input to the next join will be very big. On the other hand, if there
is only one professor named Larson, the output of σp.P N ame=‘Larson0 (Prof essor[p])
is a single tuple. Joining this single tuple with the relation Lecture results in
an output containing one tuple for every lecture taught by Larson. For a large
university, this will be a small subset of all lectures. Continuing this line, we
get the following algebraic expression:
Πs.SN ame (
((σp.P N ame=‘Larson0 (Prof essor[p])
1p.P N o=l.LP N o Lecture[l])
1l.LN o=a.ALN o Attend[a])
1a.ASno=s.SN o Student[s])
Πs.SN ame (
Πa.ASN o (
Πl.LN O (
Πp.P N o (σp.P N ame=‘Larson0 (Prof essor[p]))
1p.P N o=l.LP N o
Πl.LP no,l.LN o (Lecture[l]))
1l.LN o=a.ALN o
Πa.ALN o,a.ASN o (Attend[a]))
1a.ASno=s.SN o
Πs.SN o,s.SN ame (Student[s]))
is thus an enforcer since it makes sure that the required property holds. As we
will see, properties and enforcers play a crucial role during plan generation.
If common subexpressions are detected at the algebraic level, it might be
beneficial to compute them only once and store the result. To do so, a tmp
operator must be introduced. Later on, we will see more of these operators
that materialize (partial) intermediate results in order to avoid the same com-
putation to be performed more than once. An alternative is to allow QEPs
which are DAGs and not merely trees (see Section ??).
Physical query optimization is concerned with all the issues mentioned
above. The outline of it is given in Figure 2.9. Let us demonstrate this for
our small example query. Let us assume that there exists an index on the name
of the professors. Then, instead of scanning the whole professor relation, it
is beneficial to use the index to retrieve only those professors named Larson.
Further, since a sort merge join is very robust and not the slowest alternative,
we choose it as an implementation for all our join operations. This requires that
we sort the inputs to the join operator on the join attributes. Since sorting is
a pipeline breaker, we introduce it between the projections and the joins. The
resulting plan is
Πs.SN ame (
Sorta.ASN o (Πa.ASN o (
Sortl.LN o (Πl.LN O (
Sortp.P N o (Πp.P N o (IdxScanp.P N ame=‘Larson0 (Prof essor[p])))
1smj
p.P N o=l.LP N o
Sortl.LP N o (Πl.LP no,l.LN o (Lecture[l])))
1smj
l.LN o=a.ALN o
Sorta.ALN o (Πa.ALN o,a.ASN o (Attend[a]))))
1smj
a.ASno=s.SN o
Sorts.SN o (Πs.SN o,s.SN ame (Student[s])))
where we annotated the joins with smj to indicate that they are sort merge
joins. The sort operator has the attributes on which to sort as a subscript. We
cheated a little bit with the notation of the index scan. The index is a physical
entity stored in the database. An index scan typically allows to retrieve the
TIDs of the tuples qualifying the predicate. If this is the case, another access
to the relation itself is necessary to fetch the relevant attributes (p.PNo in
our case) from the qualifying tuples of the relation. This issue is rectified in
Chapter 4. The plan is shown as an operator graph in Figure 2.10.
2.6 Discussion
This chapter left open many interesting issues. We took it for granted that the
presentation of a query is an algebraic expression or operator tree. Is this really
true? We have been very vague about ordering joins and cross products. We
only considered queries of the form select distinct. How can we assure correct
duplicate treatment for select all? We separated query optimization into two
distinct phases: logical and physical query optimization. Any separation into
26 CHAPTER 2. TEXTBOOK QUERY OPTIMIZATION
different phases results in the danger of not producing an optimal plan. Logical
query optimization turned out to be a little difficult: pushing selections down
and reordering joins are mutually interdependent. How can we integrate these
steps into a single one and thereby avoid the problem mentioned? Further, our
logical query optimization was not cost based and cannot be: too much infor-
mation is still missing from the plan to associate precise costs with a logical
algebraic expression. How can we integrate the phases? How can we determine
the costs of a plan? We covered only a small fraction of SQL. We did not discuss
disjunction, negation, union, intersection, except, aggregate functions, group-
by, order-by, quantifiers, outer joins, and nested queries. Furthermore, how
about other query languages like OQL, XPath, XQuery? Further, enhance-
ments like materialized views exist nowadays in many commercial systems.
How can we exploit them beneficially? Can we exploit semantic information?
Is our exploitation of index structures complete? What happens if we encounter
NULL-values? Many questions and open issues remain. The rest of the book
is about filling these gaps.
2.6. DISCUSSION 27
p c p c p a
l l l
p l s a
s a c s a c s a
c
c
p p p
c c a
l l l p l a s
a s a a s a s
a c
p p p
c c
s s s
l p a s
a l a a l a a l c
c s s s
c c c
p p p
l p s a
a l c a l c a l
s c s c s
p p p
c a s p l
l a a l a l a c
p c p c p
s s s a s l p
l a a l a l a c
s c s c s a
a a a s a l p
l p c l p cl p
c
s c s c s a
a a a s a p l
p l p l p l
Πs.SN ame
Πs.SN ame
σs.SN o = a.ASN o
σa.ALN o = l.LN o
σl.LP N o = p.P N o
Πs.SN ame
σl.P N o = p.P N o
Professor[p]
Student[s] Attend[a]
Πs.SN ame
l.P N o = p.P N o
Student[s] Attend[a]
Πs.SN ame
a.ASN o = s.SN o
Professor[p]
Πs.SN ame
a.ASN o = s.SN o
l.LN o Student[s]
Professor[p]
Πs.SN ame
smj
a.ASno = s.SN o
Sorta.ASN o Sorts.SN o
smj
l.LN o=a.ALN o Student[s]
Sortl.LN o Sorta.ALN o
smj
p.P N o=l.LP N o Attend[a]
Sortp.P N o Sortl.LP N o
Professor[p]
Figure 2.10: Plan for example query after physical query optimization
Chapter 3
Join Ordering
The problem of join ordering is a very restricted and — at the same time —
a very complex one. We have touched this issue while discussing logical query
optimization in Chapter 2. Join ordering is performed in Step 4 of Figure 2.5.
In this chapter, we simplify the problem of join ordering by not considering du-
plicates, disjunctions, quantifiers, grouping, aggregation, or nested queries. Ex-
pressed positively, we concentrate on conjunctive queries with simple and cheap
join predicates. What this exactly means will become clear in the next section.
Subsequent sections discuss different algorithms for solving the join ordering
problem. Finally, we take a look at the structure of the search space. This is
important if different join ordering algorithms are compared via benchmarks.
If the wrong parameters are chosen, benchmark results can be misleading.
The algorithms of this chapter form the core of every plan generator.
31
32 CHAPTER 3. JOIN ORDERING
s.SNo = a.ASNo
Student Attend
a.ALNo = l.LNo
Professor Lecture
l.LPNo = p.PNo
p.PName = ’Larson’
select distinct *
from R1 ,. . . ,Rn
where p
select *
from R1, R2, R3, R4
where f(R1.a, R2.a,R3.a) = g(R2.b,R3.b,R4.b)
((((R2 1 R3 ) 1 R1 ) 1 R4 ) 1 R5 )
|Ri 1pi,j Rj |
fi,j =
|Ri | ∗ |Rj |
This is the number of tuples in the join’s result divided by the number of tuples
in the Cartesian Product between Ri and Rj . If fi,j is 0.1, then only 10% of
all tuples in the Cartesian Product survive the predicate pi,j . Note that the
selectivity is always a number between 0 and 1 and that fi,j = fj,i . We use an
f and not an s, since the selectivity of a predicate is often called filter factor .
Besides the relation’s cardinalities, the selectivities of the join predicates
pi,j are assumed to be given as input to the join ordering algorithm. Therefore,
we can compute the output cardinality of a join Ri 1pi,j Rj , as
From this it becomes clear that if there is no join predicate for two relations
Ri and Rj , we can assume a join predicate true and associate a selectivity of
1 with it. The output cardinality is then the cardinality of the cross product
3.1. QUERIES CONSIDERED 35
Note that this formula assumes that the selectivities are independent of each
other. Assuming independence is common but may be very misleading. More
on this issue can be found in Chapter ??. Nevertheless, we assume independence
and stick to the above formula.
For sequences of joins we can give a simple cardinality definition. Let s =
R1 , . . . , Rn be a sequence of relations. Then
n Y
Y k
|s| = ( fi,k |Rk |).
k=1 i=1
Given the above, a query graph alone is not really sufficient for the speci-
fication of a join ordering problem: cardinalities and selectivities are missing.
On the other hand, from a complete list of cardinalities and selectivities we can
derive the query graph. Obviously, the following defines a chain query with
query graph R1 − − − R2 − − − R3 :
|R1 | = 10
|R2 | = 100
|R3 | = 1000
f1,2 = 0.1
f2,3 = 0.2
In all examples, we assume for all i and j for which fi,j is not given that there
is no join predicate and hence fi,j = 1.
We now come to cost functions. The first cost function we consider is called
Cout . For a join tree T , Cout (T ) is the sum of all output cardinalities of all joins
in T . Recursively, we can define Cout as
0 if T is a single relation
Cout (T ) =
|T | + Cout (T1 ) + Cout (T2 ) if T = T1 1 T2
are too complex for this section, we stick to simple cost functions proposed by
Krishnamurthy, Boral, and Zaniolo [443]. They argue that these cost functions
are appropriate for main memory database systems. For the three different
join implementations nested loop join (nlj), hash join (hj), and sort merge join
(smj), they give the following cost functions:
where ei are join trees and h is the average length of the collision chain in the
hash table. We will assume h = 1.2. All these cost functions are defined for a
single join operator. The cost of a join tree is defined as the sum of the costs of
all joins it contains. We use the symbols Cx to also denote the costs of not only
a single join but the costs of the whole tree. Hence, for sequences s of relations,
we have
n
X
Cnlj (s) = |s1 , . . . , si−1 | ∗ |si |
i=2
Xn
Chj (s) = 1.2|s1 , . . . , si−1 |
i=2
Xn n
X
Csmj (s) = |s1 , . . . , si−1 | log(|s1 , . . . , si−1 |) + |si | log(|si |)
i=2 i=1
Some notes on the cost functions are in order. First, note that these cost
functions are even for main memory a little incomplete. For example, constant
factors are missing. Second, the cost functions are mainly devised for left-deep
trees. This becomes apparent when looking at the costs of hash joins. It is
assumed that the right input is already stored in an appropriate hash table.
Obviously, this can only hold for base relations, giving rise to left-deep trees.
Third, Chj and Csmj do not work for cross products. However, we can extend
these cost functions by defining the cost of a cross product to be equal to
its output cardinality, which happens to be the cost of Cnlj . Fourth, in reality,
more complex cost functions are used and other parameters like the width of the
tuples—i.e. the number of bytes needed to store them—also play an important
role. Fifth, the above cost functions assume that the same join algorithm is
chosen throughout the whole plan. In practice, this will not be true.
For the above chain query, we compute the costs of different join trees. The
last join tree contains a cross product.
Cout Cnlj Chj Csmj
R1 1 R2 100 1000 12 697.61
R2 1 R3 20000 100000 120 10630.26
R1 × R3 10000 10000 10000 10000.00
(R1 1 R2 ) 1 R3 20100 101000 132 11327.86
(R2 1 R3 ) 1 R1 40000 300000 24120 32595.00
(R1 × R3 ) 1 R2 30000 1010000 22000 143542.00
3.1. QUERIES CONSIDERED 37
For the calculation of Cout note that |R1 1 R2 1 R3 | = 20000 is included in all
of the last three lines of its column. For the nested loop cost function, the costs
are calculated as follows:
• The costs of the same join tree differ under the different cost functions.
• The cheapest join tree is (R1 1 R2 ) 1 R3 under all four cost functions.
• The join order matters even for join trees without cross products.
We would like to emphasize that the join order is also relevant under other cost
functions.
Avoiding cross products is not always beneficial, as the following query
specifiation shows:
|R1 | = 1000
|R2 | = 2
|R3 | = 2
f1,2 = 0.1
f1,3 = 0.1
Note that although the absolute numbers are quite small, the ratio of the best
and the second best join tree is quite large. The reader is advised to find more
examples and to apply other cost functions.
The following example illustrates that a bushy tree can be superior to any
linear tree. Let us use the following query specification:
|R1 | = 10
|R2 | = 20
|R3 | = 20
|R4 | = 10
f1,2 = 0.01
f2,3 = 0.5
f3,4 = 0.01
If we do not consider cross products, we have for the symmetric (see below)
cost function Cout the following join trees and costs:
Join Tree Cout
R1 1 R2 2
R2 1 R3 200
R3 1 R4 2
((R1 1 R2 ) 1 R3 ) 1 R4 24
((R2 1 R3 ) 1 R1 ) 1 R4 222
(R1 1 R2 ) 1 (R3 1 R4 ) 6
Note that all other linear join trees fall into one of these classes, due to the
symmetry of the cost function and the join ordering problem. Again, the reader
is advised to find more examples and to apply other cost functions.
If we want to annotate a join operator by its implementation—which is
necessary for the correct computation of costs—we write 1impl for an imple-
mentation impl. For example, 1smj is a sort-merge join, and the according cost
function Csmj is used to compute its costs.
Two properties of cost functions have some impact on the join ordering
problem. The first is symmetry. A cost function Cimpl is called symmetric if
Cimpl (R1 1impl R2 ) = Cimpl (R2 1impl R1 ) for all relations R1 and R2 . For
symmetric cost functions, it does not make sense to consider commutativity.
Hence, it suffices to consider left-deep trees only if we want to restrict ourselves
to linear join trees. Note that Cout , Cnlj , Csmj are symmetric while Chj is not.
The other property is the adjacent sequence interchange (ASI) property.
Informally, the ASI property states that there exists a rank function such that
the order of two subsequences is optimal if they are ordered according to the
rank function. The ASI property is formally defined in Section 3.2.2. Only for
tree queries and cost functions with the ASI property, a polynomial algorithm
to find an optimal join order is known. Our cost functions Cout and Chj have the
ASI property, Csmj does not. Summarizing the properties of our cost functions,
we see that the classification is orthogonal:
3.1. QUERIES CONSIDERED 39
ASI ¬ ASI
symmetric Cout , Cnlj Csmj
¬ symmetric Chj (see text)
For the missing case of a non-symmetric cost function not having the ASI
property, we can use the cost function of the hybrid hash join [204, 576].
We turn to another not really well-researched topic. The goal is to cut
down the number of cost functions which have to be considered for optimization
and to possibly allow for simpler cost functions, which saves time during plan
generation. Unfortunately, we have to restrict ourselves to left-deep join trees.
Let s denote a sequence or permutation of a given set of joins. We define an
equivalence relation on cost functions.
That is, ΣIR is the set of all cost functions that are equivalent to Cout .
Let us consider a very simple example. The last element of the sum in Cout
is the size of the final join (all relations are joined). This is not the case for the
following cost function:
n−1
X
0
Cout (s) := |s1 , . . . , si |
i=2
0
Obviously, we have Cout is ΣIR. The next observation shows that we can
construct quite complex ΣIR cost functions:
Observation 3.1.3 Let C1 and C2 be two ΣIR cost functions. For non-
decreasing functions f1 : R → R and f2 : R × R → R and constants c ∈ R
and d ∈ R+ , we have that EX
C1 + c
C1 ∗ d
f1 ◦ C1
f2 ◦ (C1 , C2 )
are ΣIR. Here, ◦ denotes function composition and (·, ·) function pairing.
There are of course many more possibilites of constructing ΣIR functions. For
the cost functions Chj , Csmj , and Cnlj , we now investigate which of them have
the ΣIR property.
40 CHAPTER 3. JOIN ORDERING
and observation 3.1.3, we conclude that Chj is ΣIR for a fixed relation to be
joined first. If we can optimize Cout in polynomial time, then we can optimize
Cout for a fixed starting relation. Indeed, by trying each relation as a starting
EX relation, we can find the optimal join tree in polynomial time. An algorithm
that computes the optimal solution for an arbitrary relation to be joined first
can be found in Section 3.2.2.
Now, consider Csmj . Since
n
X
|s1 , . . . , si−1 |log(|s1 , . . . , si−1 |)
i=2
|R1 R2 | = 90
|R1 R3 | = 100
|R2 R3 | = 100
and
We see that R1 R2 R3 has the smallest sum of intermediate result sizes but
produces the highest cost. Hence, Cnlj is not ΣIR.
The query graph classes considered are chain, star , tree, and cyclic. For the join
tree classes we distinguish between the different join tree shapes, i.e. whether
they are left-deep, zig-zag, or bushy trees. We left out the right-deep trees, since
they do not differ in their behavior from left-deep trees. We also have to take
into account whether cross products are considered or not. For cost functions,
we use a simple classification: we only distinguish between those that have the
ASI property and those that do not. This leaves us with 4∗3∗2∗2 = 48 different
join ordering problems. For these, we will first review search space sizes and
complexity. Then, we discuss several algorithms for join ordering. Last, we give
some insight into cost distributions over the search space and how this might
influence the benchmarking of different join ordering algorithms.
Join Trees with Cross Products We consider the number of join trees for
a query graph with n relations. When cross products are allowed, the number
of left-deep and right-deep join trees is n!. By allowing cross products, the
query graph does not restrict the search space in any way. Hence, any of the n!
permutations of the n relations corresponds to a valid left-deep join tree. This
is true independent of the query graph.
Similarly, the number of zig-zag trees can be estimated independently of
the query graph. First note that for joining n relations, we need n − 1 join
operators. From any left-deep tree, we derive zig-zag trees by using the join’s
commutativity and exchange the left and right inputs. Hence, from any left-
deep tree for n relations, we can derive 2n−2 zig-zag trees. We have to subtract
another one, since the bottommost joins’ arguments are exchanged in different
left-deep trees. Thus, there exists a total of 2n−2 n! zig-zag trees. Again, this
number is independent of the query graph.
The number of bushy trees can be estimated as follows. First, we need the
number of binary trees. For n leaf nodes, the number of binary trees is given
by C(n − 1), where C(n) is defined by the recurrence
n−1
X
C(n) = C(k)C(n − k − 1)
k=0
with C(0) = 1. The numbers C(n) are called the Catalan Numbers (see [179]).
They can also be computed by the following formula:
1 2n
C(n) = .
n+1 n
42 CHAPTER 3. JOIN ORDERING
After we know the number of binary trees with n leaves, we now have to
attach the n relations to the leaves in all possible ways. For a given binary
tree, this can be done in n! ways. Hence, the total number of bushy trees is
n!C(n − 1). This can be simplified as follows (see also [262, 454, 753]):
1 2(n − 1)
n!C(n − 1) = n!
n n−1
1 (2n − 2)!
= n!
n (n − 1)!((2n − 2) − (n − 1))!
(2n − 2)!
=
(n − 1)!
The induction step for n > 1 provided by Thomas Neumann goes as follows:
n−1
X
f (n) = n + f (k − 1) ∗ (n − k)
k=2
n−3
X
= n+ f (k + 1) ∗ (n − k − 2)
k=0
n−3
X
= n+ 2k ∗ (n − k − 2)
k=0
n−2
X
= n+ k2n−k−2
k=1
n−2
X n−2
X
n−k−2
= n+ 2 + (k − 1)2n−k−2
k=1 k=2
n−2
X n−2
X
= n+ 2n−j−2
i=1 j=i
n−2
X n−i−2
X
= n+ 2j
i=1 j=0
n−2
X
= n+ (2n−i−1 − 1)
i=1
n−2
X
= n+ 2i − (n − 2)
i=1
= n + (2n−1 − 2) − (n − 2)
= 2n−1
as the left or right argument of the join. Hence, we can compute f(n) as
n−1
X
2 f(k) f(n − k)
k=1
This is equal to
2n−1 C(n − 1)
Star Queries, No Cartesian Product The first join has to connect the
center relation R0 with any of the other relations. The other relations can
follow in any order. Since R0 can be the left or the right input of the first
join, there are 2 ∗ (n − 1)! possible left-deep join trees for Star Queries with no
Cartesian Product.
The number of zig-zag join trees is derived by exchanging the arguments
of all but the first join in any left-deep join tree. We cannot consider the first
join since we did so in counting left-deep join trees. Hence, the total number of
zig-zag join trees is 2 ∗ (n − 1)! ∗ 2n−2 = 2n−1 ∗ (n − 1)!.
Constructing bushy join trees with no Cartesian Product from a Star Query
other than zig-zag join trees is not possible.
Remarks The numbers for star queries are also upper bounds for tree queries.
For clique queries, no join tree containing a cross product is possible. Hence,
all join trees are valid join trees and the search space size is the same as the
corresponding search space for join trees with cross products.
To give the reader a feeling for the numbers, the following tables contain
the potential search space sizes for some n.
Note that in Figure 2.6 only 32 join trees are listed, whereas the number of
bushy trees for chain queries with four relations is 40. The missing eight cases
are those zig-zag trees which are symmetric (i.e. derived by applying commu-
tativity to all occurring joins) to the ones contained in the second column.
From these numbers, it becomes immediately clear why historically the
search space of query optimizers was restricted to left-deep trees and cross
products for connected query graphs were not considered.
clique problem was used for the reduction [273]. Cout was also used in the other
proofs of NP-hardness results. The next line goes back to the same paper.
Ibaraki and Kameda also described an algorithm to solve the join ordering
problem for tree queries producing optimal left-deep trees for a special cost
function for a nested-loop n-way join algorithm. Their algorithm was based on
the observation that their cost function has the ASI property. For this case,
they could derive an algorithm from an algorithm for a sequencing problem for
job scheduling designed by Monma and Sidney [533]. They, in turn, used an
earlier result by Lawler [459]. The algorithm of Ibaraki and Kameda was slightly
generalized by Krishnamurthy, Boral, and Zaniolo, who were also able to sketch
a more efficient algorithm. It improves the time bounds from O(n2 log n) to
O(n2 ). The disadvantage of both approaches is that with every relation, a fixed
(i.e. join-tree independent) join implementation must be associated before the
optimization starts. Hence, it only produces optimal trees if there is only one
join implementation available or one is able to guess the optimal join method
before hand. This might not be the case. The polynomial algorithm which we
term IKKBZ is described in Section 3.2.2.
For star queries, Ganguly investigated the problem of generating optimal
left-deep trees if no cross products but two different cost functions (one for
nested loop join, the other for sort merge join) are allowed. It turned out that
this problem is NP-hard [267].
The next line is due to Cluet and Moerkotte [165]. They showed by reduc-
tion from 3DM that taking into account cross products results in an NP-hard
problem even for star queries. Remember that star queries are tree queries and
general graphs.
The problem for general bushy trees follows from a result by Scheufele and
Moerkotte [657]. They showed that building optimal bushy trees for cross
products only (i.e. all selectivities equal one) is already NP-hard. This result
also explains the last two lines.
By noting that for star queries, all bushy trees that do not contain a cross
product are left-deep trees, the problem can be solved by the IKKBZ algorithm
for left-deep trees. Ono and Lohman showed that for chain queries dynamic
programming considers only a polynomial number of bushy trees if no cross
products are considered [553]. This is discussed in Section 3.2.4.
The table is rather incomplete. Many open problems exist. For example,
if we have chain queries and consider cross products: is the problem NP-hard
or in P? Some results for this problem have been presented [657], but it is
still an open problem (see Section 3.2.7). Open is also the case where we
produce optimal bushy trees with no cross products for tree queries. Yet another
example of an open problem is whether we could drop the ASI property and are
still able to derive a polynomial algorithm for a tree query. This is especially
important, since the cost function for a sort-merge algorithm does not have the
ASI property.
Good summaries of complexity results for different join ordering problems
can be found in the theses of Scheufele [655] and Hamalainen [338].
Given that join ordering is an inherently complex problem with no polyno-
mial algorithm in sight, one might wonder whether there exists good polynomial
3.2. DETERMINISTIC ALGORITHMS 47
approximation algorithms. Chances are that even this is not the case. Chatter-
ji, Evani, Ganguly, and Yemmanuru showed that three different optimization
problems — all asking for linear join trees — are not approximable [119].
GreedyJoinOrdering-1({R1 , . . . , Rn }, (*weight)(Relation))
Input: a set of relations to be joined and a weight function
Output: a join order
S = ; // initialize S to the empty sequence
R = {R1 , . . . , Rn }; // let R be the set of all relations
while(!empty(R)) {
Let k be such that: weight(Rk ) = minRi ∈R (weight(Ri ));
R\ = Rk ; // eliminate Rk from R
S◦ = Rk ; // append Rk to S
}
return S
This algorithm takes cross products into account. If we are only interested
in left-deep join trees with no cross products, we have to require that Rk is
connected to some of the relations contained in S in case S 6= . Note that a
more efficient implementation would sort the relations according to their weight.
Not all heuristics can be implemented with a greedy algorithm as simple as
above. An often-used heuristics is to take the relation next that produces the
smallest (next) intermediate result. This cannot be determined by the relation
alone. One must take into account the sequence S already processed, since on-
ly then the selectivities of all predicates connecting relations in S and the new
relation are deducible. And we must take the product of these selectivities and
the cardinality of the new relation in order to get an estimate of the intermedi-
ate result’s cardinality. As a consequence, the weights become relative to S. In
other words, the weight function now has two parameters: a sequence of rela-
tions already joined and the relation whose relative weight is to be computed.
Here is the next algorithm:
48 CHAPTER 3. JOIN ORDERING
GreedyJoinOrdering-2({R1 , . . . , Rn },
(*weight)(Sequence of Relations, Relation))
Input: a set of relations to be joined and a weight function
Output: a join order
S = ; // initialize S to the empty sequence
R = {R1 , . . . , Rn }; // let R be the set of all relations
while(!empty(R)) {
Let k be such that: weight(S, Rk ) = minRi ∈R (weight(S, Ri ));
R\ = Rk ; // eliminate Rk from R
S◦ = Rk ; // append Rk to S
}
return S
GOO({R1 , . . . , Rn })
Input: a set of relations to be joined
Output: join tree
Trees := {R1 , . . . , Rn }
while (|Trees| != 1) {
find Ti , Tj ∈ Trees such that i 6= j, |Ti 1 Tj | is minimal
among all pairs of trees in Trees
Trees − = Ti ;
Trees − = Tj ;
Trees + = Ti 1 Tj ;
}
return the tree contained in Trees;
Our GOO variant differs slightly from the one proposed by Fegaras. He uses
arrays, explicitly handles the forming of the join predicates, and materializes
intermediate result sizes. Hence, his algorithm is a little more elaborated, but
we assume that the reader is able to fill in the gaps.
None of our algorithms so far considers different join implementations. An
explicit consideration of commutativity for non-symmetric cost functions could
also help to produce better join trees. The reader is asked to work out the details
of these extensions. In general, the heuristics do not produce the optimal plan. EX
The reader is advised to find examples where the heuristics are far off the best
possible plan. EX
The IKKBZ-Algorithm considers only join operations that have a cost func-
tion of the form:
cost(Ri 1 Rj ) = |Ri | ∗ hj (|Rj |)
where each Rj can have its own cost function hj . We denote the set of hj by
H and parameterize cost functions with it. Example instanciations are
• hj ≡ 1.2 for main memory hash-based joins
• hj ≡ id for nested-loop joins
where id is the identity function. Let us denote by ni the cardinality of the
relation Ri (ni := |Ri |). Then, the hi (ni ) represent the costs per input tuple to
be joined with Ri .
The algorithm works as follows. For every relation Rk it computes the
optimal join order under the assumption that Rk is the first relation in the join
sequence. The resulting subproblems then resemble a job-scheduling problem
that can be solved by the Monma-Sidney-Algorithm [533].
In order to present this algorithm, we need the notion of a precedence graph.
A precedence graph is formed by taking a node in the (undirected) query graph
and making this node a root node of a (directed) tree where the edges point
away from the selected root node. Hence, for acyclic, connected query graphs—
those we consider in this section—a precedence graph is a tree. We construct
the precedence graph of a query graph G = (V, E) as follows:
• Make some relation Rk ∈ V the root node of the precedence graph.
• As long as not all relations are included in the precedence graph: Choose
a relation Ri ∈ V , such that (Rj , Ri ) ∈ E is an edge in the query graph
and Rj is already contained in the (partial) precedence graph constructed
so far and Ri is not. Add Rj and the edge Rj → Ri to the precedence
graph.
A sequence S = v1 , . . . , vk of nodes conforms to a precedence graph G = (V, E)
if the following conditions are satisfied:
1. for all i (2 ≤ i ≤ k) there exists a j (1 ≤ j < i) with (vj , vi ) ∈ E and
2. there is no edge (vi , vj ) ∈ E for i > j.
For non-empty sequences U and V in a precedence graph, we write U → V if,
according to the precedence graph, U must occur before V . This requires U
and V to be disjoint. More precisely, there can only be paths from nodes in U
to nodes in V and at least one such path exists.
Consider the following query graph:
R1 R5
R3 R4
R2 R6
3.2. DETERMINISTIC ALGORITHMS 51
For this query graph, we can derive the following precedence graphs:
R1 R2 R3
R3 R3 R1 R2 R4
R2 R4 R1 R4 R5 R6
R5 R6 R5 R6
R4 R5 R6
R3 R5 R6 R4 R4
R3 R5 R6 R3 R5 R3
R1 R2 R1 R2
R2 1 R6
R3 1 R5
R4 1 R4
R5 1 R3
R6 R1 R2
Define
R1,2,...,k := R1 1 R2 1 · · · 1 Rk
n1,2,...,k := |R1,2,...,k |
For a given precedence graph, let Ri be a relation and Ri be the set of relations
from which there exists a path to Ri . Then, in any join tree adhering to the
Q in Ri and only those will be joined before Ri .
precedence graph, all relations
Hence, we can define si = Rj ∈Ri fi,j for i > 1. Note that for any i only one j
52 CHAPTER 3. JOIN ORDERING
with fi,j 6= 1 exists in the product. If the precedence graph is a chain, then the
following holds:
and, in general,
k
Y
n1,2,...,k = (si ∗ ni ).
i=1
CH () = 0
CH (Rj ) = 0 if Rj is the root
CH (Rj ) = hj (nj ) else
CH (S1 S2 ) = CH (S1 ) + T (S1 ) ∗ CH (S2 )
where
T () = 1
Y
T (S) = (si ∗ ni )
Ri ∈S
Definition 3.2.2 Let A and B be two sequences and V and U two non-empty
sequences. We say that a cost function C has the adjacent sequence interchange
property (ASI property) if and only if there exists a function T and a rank
function defined for sequences S as
T (S) − 1
rank(S) =
C(S)
Lemma 3.2.3 The cost function CH defined in Definition 3.2.1 has the ASI
property.
CH (AU V B) = CH (A)
+T (A)CH (U )
+T (A)T (U )CH (V )
+T (A)T (U )T (V )CH (B)
and, hence,
• B → Ai , ∀ 1 ≤ i ≤ n
• Ai → B, ∀ 1 ≤ i ≤ n
• B 6→ Ai and Ai 6→ B, ∀ 1 ≤ i ≤ n
Lemma 3.2.5 Let C be any cost function with the ASI property and {A, B}
a module. If A → B and additionally rank(B) ≤ rank(A), then we find an
optimal sequence among those in which B directly follows A.
54 CHAPTER 3. JOIN ORDERING
Proof Every optimal permutation must have the form (U, A, V, B, W ), since
A → B. Assumption: V 6= . If rank(V ) ≤ rank(A), then we can ex-
change V and A without increasing the costs. If rank(A) ≤ rank(V ), we
have rank(B) ≤ rank(V ) due to the transitivity of ≤. Hence, we can exchange
B and V without increasing the costs. Both exchanges produce legal sequences
obeying the precedence graph, since {A, B} is a module. 2
If the precedence graph demands A → B but rank(B) ≤ rank(A), we speak
of contradictory sequences A and B. Since the lemma shows that no non-empty
subsequence can occur between A and B, we will combine A and B into a new
single node replacing A and B. This node represents a compound relation
comprising all relations in A and B. Its cardinality is computed by multiplying
the cardinalities of all relations occurring in A and B, and its selectivity s is
the product of all the selectivities si of the relations Ri contained in A and B.
The continued process of this step until no more contradictory sequence exists
is called normalization. The opposite step, replacing a compound node by the
sequence of relations it was derived from, is called denormalization.
We can now present the algorithm IKKBZ.
IKKBZ(G)
Input: an acyclic query graph G for relations R1 , . . . , Rn
Output: the best left-deep tree
R = ∅;
for (i = 1; i ≤ n; + + i) {
Let Gi be the precedence graph derived from G and rooted at Ri ;
T = IKKBZ-Sub(Gi );
R+ = T ;
}
return best of R;
IKKBZ-Sub(Gi )
Input: a precedence graph Gi for relations R1 , . . . , Rn rooted at some Ri
Output: the optimal left-deep tree under Gi
while (Gi is not a chain) {
let r be the root of a subtree in Gi whose subtrees are chains;
IKKBZ-Normalize(r);
merge the chains under r according to the rank function
in ascending order;
}
IKKBZ-Denormalize(Gi );
return Gi ;
IKKBZ-Normalize(r)
Input: the root r of a subtree T of a precedence graph G = (V, E)
Output: a normalized subchain
while (∃ r0 , c ∈ V , r →∗ r0 , (r0 , c) ∈ E: rank(r0 ) > rank(c)) {
replace r0 by a compound relation r00 that represents r0 c;
3.2. DETERMINISTIC ALGORITHMS 55
};
R1
100 18
R2 1 1 R5 19
2 3 R2 R3 R4 20
10 100 49 24
50 25
R1 1
R4
3
5
1 R6,7 5
1
4 2
R3 R6 1
R7
100 A) 10 10 20 D)
5
R5 6
R1
R1
19
R2 R3 R4 20
49 24
50 25
R2 R3 R4,6,7 199
320
4 49 24
R5 R6 5 50 25
5
6 5
E) R5 6
B)
1
R7 2
R1
19
R2 R3 R4 20
49 24
50 25
R5 R6,7 3 F)
C) 5
5
6
R1 R2 R3 R4 p2,3
I II
p1,2 p3,4
R4
p2,3
R3
p1,2 R1 R2
IV a) p2,3 IV b)
p3,4
R1 R2 R3 R4
p1,2
V a) p2,3 V b)
p1,2 p3,4
R1 R2 R3 R4
Figure 3.4: A query graph, its directed join graph, some spanning trees and
join trees
I R1 R2 R3 R4 R5
p3,4
Figure 3.5: A query graph, its directed join tree, a spanning tree and its problem
| 1u |
wu,v = .
|u u v|
(Lee, Shih, and Chen actually attach two weights to each edge: one additional
weight for the size of the tuples (in bytes) [460].)
3.2. DETERMINISTIC ALGORITHMS 59
The weights of physical edges are equal to the si of the dependency graph
used in the IKKBZ-Algorithm (Section 3.2.2). To see this, assume R(u) =
{R1 , R2 }, R(v) = {R2 , R3 }. Then
| 1u |
wu,v =
|u u v|
|R1 1u R2 |
=
|R2 |
f1,2 |R1 | |R2 |
=
|R2 |
= f1,2 |R1 |
MVP(G)
Input: a weighted directed join graph G = (V, Ep , Ev )
Output: an effective spanning tree
Q1 .insert(V ); /* priority queue with smallest node weights w(·) first */
Q2 = ∅; /* priority queue with largest node weights w(·) first */
G0 = (V 0 , E 0 ) with V 0 = V and E 0 = Ep ; /* working graph */
S = (VS , ES ) with VS = V and ES = ∅; /* resulting effective spanning tree */
while (!Q1 .empty() && |ES | < |V | − 1) { /* Phase I */
60 CHAPTER 3. JOIN ORDERING
v = Q1 .head();
among all (u, v) ∈ E 0 , wu,v < 1 such that
S 0 = (V, ES0 ) with ES0 = ES ∪ {(u, v)} is acyclic and effective
select one that maximizes cost(1v , S) - cost(1v , S 0 );
if (no such edge exists) {
Q1 .remove(v);
Q2 .insert(v);
continue;
}
MvpUpdate((u, v));
recompute w(·) for v and its ancestors; /* rearranges Q1 */
}
while (!Q2 .empty() && |ES | < |V | − 1) { /* Phase II */
v = Q2 .head();
among all (u, v), (v, u) ∈ E 0 denoted by (x, y) henceforth
such that
S 0 = (V, ES0 ) with ES0 = ES ∪ {(x, y)} is acyclic and effective
select the one that minimizes cost(1v , S 0 ) - cost(1v , S);
MvpUpdate((x, y));
recompute w(·) for y and its ancestors; /* rearranges Q2 */
}
return S;
MvpUpdate((u, v))
Input: an edge to be added to S
Output: side-effects on S, G0 ,
ES ∪ = {(u, v)};
E 0 \ = {(u, v), (v, u)};
E 0 \ = {(u, w)|(u, w) ∈ E 0 }; /* (1) */
E 0 ∪ = {(v, w)|(u, w) ∈ Ep , (v, w) ∈ Ev }; /* (3) */
if (v has two inflowing edges in S) { /* (2) */
E 0 \ = {(w, v)|(w, v) ∈ E 0 };
}
if (v has one outflowing edge in S) { /* (1) in paper but not needed */
E 0 \ = {(v, w)|(v, w) ∈ E 0 };
}
Note that in order to test for the effectiveness of a spanning tree in the
algorithm, we just have to check the conditions for the node the selected edge
leads to.
MvpUpdate first adds the selected edge to the spanning tree. It then elim-
inates edges that need not to be considered for building an effective spanning
tree. Since (u, v) has been added, both (u, v) and (v, u) do not have to be
considered any longer. Also, since effective spanning trees are binary trees, (1)
every node must have only one parent node and (2) at most two child nodes.
The edges leading to a violation are eliminated by MvpUpdate in the lines com-
3.2. DETERMINISTIC ALGORITHMS 61
mented with the corresponding numbers. For the line commented (3) we have
the situation that u → v 99K w and u → w in G. This means that u and w have
common relations, but v and w do not. Hence, the result of performing v on
the result of u will have a common relation with w. Thus, we add a (physical)
edge v → w.
(((R1 1 R2 ) 1 R3 ) 1 R4 ) 1 R5
and
(((R3 1 R1 ) 1 R2 ) 1 R4 ) 1 R5 .
If we know that ((R1 1 R2 ) 1 R3 ) is cheaper than ((R3 1 R1 ) 1 R2 ), we
know that the first join tree is cheaper than the second. Hence, we could avoid
generating the second alternative and still won’t miss the optimal join tree. The
general principle behind this is the optimality principle (see [178]). For the join
ordering problem, it can be stated as follows.1
To see why this holds, assume that the optimal join tree T for relations R1 , . . . , Rn
contains a subtree S which is not optimal. That is, there exists another join
tree S 0 for the relations contained in S with strictly lower costs. Denote by
T 0 the join tree derived by replacing S in T by S 0 . Since S 0 contains the same
relations as S, T 0 is a join tree for the relations R1 , . . . , Rn . The costs of the join
operators in T and T 0 that are not contained in S and S 0 are the same. Then,
since the total cost of a join tree is the sum of the costs of the join operators
and S 0 has lower costs than S, T 0 has lower costs than T . This contradicts the
optimality of T .
The idea of dynamic programming applied to the generation of optimal join
trees now is to generate optimal join trees for subsets of R1 , . . . , Rn in a bottom-
up fashion. First, optimal join trees for subsets of size one, i.e. single relations,
are generated. From these, optimal join trees of size two, three and so on until
n are generated.
Let us first consider generating optimal left-deep trees. There, join trees for
subsets of size k are generated from subsets of size k − 1 by adding a new join
operator whose left argument is a join tree for k − 1 relations and whose right
argument is a single relation. Exchanging left and right gives us the procedure
for generating right-deep trees. If we want to generate zig-zag trees since our
cost function is asymmetric, we have to consider both alternatives and take
the cheapest one. We capture this in a procedure CreateJoinTree that takes
1
The optimality principle does not hold in the presence of properties.
62 CHAPTER 3. JOIN ORDERING
CreateJoinTree(T1 , T2 )
Input: two (optimal) join trees T1 and T2 .
for linear trees, we assume that T2 is a single relation
Output: an (optimal) join tree for joining T1 and T2 .
BestTree = NULL;
for all implementations impl do {
if(!RightDeepOnly) {
Tree = T1 1impl T2
if (BestTree == NULL || cost(BestTree) > cost(Tree)) {
BestTree = Tree;
}
}
if(!LeftDeepOnly) {
Tree = T2 1impl T1
if (BestTree == NULL || cost(BestTree) > cost(Tree)) {
BestTree = Tree;
}
}
}
return BestTree;
DP-Linear-1({R1 , . . . , Rn })
Input: a set of relations to be joined
Output: an optimal left-deep (right-deep, zig-zag) join tree
for (i = 1; i <= n; ++i) {
BestTree({Ri }) = Ri ;
3.2. DETERMINISTIC ALGORITHMS 63
{R1 R2 R3 R4}
{R1 R4}
{R1 R3} {R2 R4}
{R1 R2} {R3 R4}
{R2 R3}
R1 R2 R3 R4
}
for (i = 1; i < n; ++i) {
for all S ⊆ {R1 , . . . , Rn }, |S| = i do {
for all Rj ∈ {R1 , . . . , Rn }, Rj 6∈ S do {
if (NoCrossProducts && !connected({Rj }, S)) {
continue;
}
CurrTree = CreateJoinTree(BestTree(S),Rj );
S 0 = S ∪ {Rj };
if (BestTree(S 0 ) == NULL || cost(BestTree(S 0 )) > cost(CurrTree)) {
BestTree(S 0 ) = CurrTree;
}
}
}
}
return BestTree({R1 , . . . , Rn });
a join predicate between one of the relations in its first argument and one of
the relations in its second. The variable BestTree keeps track of the best join
trees generated for every subset of the relations {R1 , . . . , Rn }. How this is done
may depend on several parameters. The approaches are to use a hash table or
XC search an array of size 2n (−1). Another issue is how to represent the sets of relations.
space size Typically, bitvector representations are used. Then, testing for membership,
difference computing a set’s complement, adding elements and unioning is cheap. Yet
problem another issue is the order in which join trees are generated. The procedure
DP-Linear-1 takes the approach to generate the join trees for subsets of size
1, 2, . . . , n. To do so, it must be able to access the subsets of {R1 , . . . , Rn } or
their respective join trees by their size. One possibility is to chain all the join
trees for subsets of a given size k (1 ≤ k ≤ n) and to use an array of size n to
keep pointers to the start of the lists. In this case, to every join tree the set of
relations it contains is attached, in order to be able to perform the test Ri 6∈ S.
One way to do this is to embed a bitvector into each join tree node.
Figure 3.6 illustrates how the procedure DP-Linear-1 works. In its first
loop, it initializes the bottom row of join trees of size one. Then it computes
the join trees joining exactly two relations. This is indicated by the next group
of join trees. Since the figure leaves out commutativity, only one alternative
join tree for every subset of size two is generated. This changes for subsets of
size three. There, three alternative join trees are generated. Only the best join
tree is retained. This is indicated by the ovals that encircle three join trees.
Only this best join tree of size three is used to generate the final best join tree.
The short clarification after the algorithm already adumbrated that the
order in which join trees are generated is not compulsory. The only necessary
condition is the following.
Let S be a subset of {R1 , . . . , Rn }. Then, before a join tree for S
can be generated, the join trees for all relevant subsets of S must
already be available.
Note that this formulation is general enough to also capture the generation of
bushy trees. It is, however, a little vague due to its reference to “relevance”.
EX For the different join tree classes, this term can be given a precise semantics.
Let us take a look at an alternative order to join tree generation. Assume
that sets of relations are represented as bitvectors. A bitvector is nothing more
than a base two integer. Successive increments of an integer/bitvector lead to
different subsets. Further, the above condition is satisfied. We illustrate this by
a small example. Assume that we have three relations R1 , R2 , R3 . The i-th bit
from the right in a three-bit integer indicates the presence of Ri for 1 ≤ i ≤ 3.
000 {}
001 {R1 }
010 {R2 }
011 {R1 , R2 }
100 {R3 }
101 {R1 , R3 }
110 {R2 , R3 }
111 {R1 , R2 , R3 }
3.2. DETERMINISTIC ALGORITHMS 65
DP-Linear-2({R1 , . . . , Rn })
Input: a set of relations to be joined
Output: an optimal left-deep (right-deep, zig-zag) join tree
for (i = 1; i <= n; ++i) {
BestTree(1 << i) = Ri ;
}
for (S = 1; S < 2n ; ++S) {
if (BestTree(S) != NULL) continue;
for all i ∈ S do {
S 0 = S \ {i};
CurrTree = CreateJoinTree(BestTree(S 0 ),Ri );
if (BestTree(S) == NULL || cost(BestTree(S)) > cost(CurrTree)) {
BestTree(S) = CurrTree;
}
}
}
return BestTree(2n − 1);
DP-Linear-2 differs from DP-Linear-1 not only in the order in which join trees
are generated. Another difference is that it takes cross products into account.
From DP-Linear-2, it is easy to derive an algorithm that explores the space
of bushy trees.
DP-Bushy({R1 , . . . , Rn })
Input: a set of relations to be joined
Output: an optimal bushy join tree
for (i = 1; i <= n; ++i) {
BestTree(1 << i) = Ri ;
}
for (S = 1; S < 2n ; ++S) {
if (BestTree(S) != NULL) continue;
for all S1 ⊂ S do {
S2 = S \ S1 ;
CurrTree = CreateJoinTree(BestTree(S1 ), BestTree(S2 ));
if (BestTree(S) == NULL || cost(BestTree(S)) > cost(CurrTree)) {
BestTree(S) = CurrTree;
}
}
}
return BestTree(2n − 1);
66 CHAPTER 3. JOIN ORDERING
This algorithm also takes cross products into account. The critical part is the
generation of all subsets of S. Fortunately, Vance and Maier [778] provide a
code fragment with which subset bitvector representations can be generated
very efficiently. In C, this fragment looks as follows:
S1 = S & - S;
do {
/* do something with subset S1 */
S1 = S & (S1 - S);
} while (S1 != S);
S represents the input set. S1 iterates through all subsets of S where S itself and
the empty set are not considered. Analogously, all supersets an be generated
as follows:
S1 = ~S & - ~S;
/* do something with first superset S1 */
while (S1 ) {
S1 = ~S & (S1 - ~S)
/* do something with superset S1
}
S represents the input set. S1 iterates through all supersets of S including S
itself.
These equations can be derived from the following by summing over k > 1
where k gives the size of the connected subset:
#csgchain (n, k) = (n − k + 1)
cycle 1 n=k
#csg (n, k) =
n else
n k=1
#csgstar (n, k) = n−1
k>1
k−1
n
#csgclique (n, k) =
k
Join Trees With Cartesian Product For the analysis of dynamic pro-
gramming variants that do consider cross products, the notion of join-pair is
helpful. Let S1 and S2 be subsets of the nodes (relations) of the query graph.
We say (S1 , S2 ) is a join-pair, if and only if
1. S1 and S2 are disjoint
If (S1 , S2 ) is a join-pair, then (S2 , S1 ) is a join pair. Further, if T1 is a join tree
for the relations in S1 and T2 is one for those in S2 , then we can construct two
valid join trees T1 1 T2 and T2 1 T1 where the joins may be cross products.
Hence, the number of join-pairs coincides with the search space a dynamic pro-
gramming algorithm explores. In fact, the number of join-pairs is the minimum
number of join trees any dynamic programming algorithm that considers cross
products has to investigate.
If CreateJoinTree considers commutativity of joins, the number of calls
to it is precisely expressed by the count of non-symmetric join-pairs. In other
68 CHAPTER 3. JOIN ORDERING
Join Trees without Cross Products In this paragraph, we assume that the
query graph is connected. For the analysis of dynamic programming variants
that do not consider cross products, it is helpful to have the notion of a csg-
cmp-pair. Let S1 and S2 be subsets of the nodes (relations) of the query graph.
We say (S1 , S2 ) is a csg-cmp-pair , if and only if
1. S1 induces a connected subgraph of the query graph,
(n − 1)2
The following table presents some results for the above formulas.
Compare this table with the actual sizes of the search spaces in Section 3.1.5.
The dynamic programming algorithms can be implemented very efficiently
and often form the core of commercial plan generators. However, they have
the disadvantage that no plan is generated if they run out of time or space
since the search space they have to explore is too big. One possible remedy
goes as follows. Assume that a dynamic programming algorithm is stopped
in the middle of its way through its actual search space. Further assume that
the largest plans generated so far involve k relations. Then the cheapest of the
plans with k relations is completed by applying any heuristics (e.g. MinSel). The
completed plan is then returned. In Section 3.4.5, we will see two alternative
solutions. Another solution is presented in [417].
DPsize
Input: a connected query graph with relations R = {R0 , . . . , Rn−1 }
Output: an optimal bushy join tree without cross products
for all Ri ∈ R {
BestPlan({Ri }) = Ri ;
}
for all 1 < s ≤ n ascending // size of plan
for all 1 ≤ s1 < s { // size of left subplan
s2 = s − s1 ; // size of right subplan
for all S1 ⊂ R : |S1 | = s1
S2 ⊂ R : |S2 | = s2 {
++InnerCounter;
6 S1 ∩ S2 ) continue;
if (∅ =
if not (S1 connected to S2 ) continue;
++CsgCmpPairCounter;
p1 =BestPlan(S1 );
p2 =BestPlan(S2 );
CurrPlan = CreateJoinTree(p1 , p2 );
if (cost(BestPlan(S1 ∪ S2 )) > cost(CurrPlan)) {
BestPlan(S1 ∪ S2 ) = CurrPlan;
}
}
}
OnoLohmanCounter = CsgCmpPairCounter / 2;
return BestPlan({R0 , . . . , Rn−1 });
BestPlan does not contain a plan for the relations in S or the one it contains
is more expensive than CurrPlan, we register CurrPlan with BestPlan.
The algorithm DPsize can be made more efficient in case of s1 = s2 . The
algorithm as stated cycles through all plans p1 joining s1 relations. For each
such plan, all plans p2 of size s2 are tested. Assume that plans of equal size are
represented as a linked list. If s1 = s2 , then it is possible to iterate through the
list for retrieving all plans p1 . For p2 we consider the plans succeeding p1 in the
list. Thus, the complexity can be decreased from s1 ∗s2 to s1 ∗s2 /2 The following
formulas are valid only for the variant of DPsize where this optimization has
been incorporated (see [529] for details).
If the counter InnerCounter is initialized with zero at the beginning of the
algorithm DPsize, then we are able to derive analytically its value after DPsize
terminates. Since this value of the inner counter depends on the query graph,
we have to distinguish several cases. For chain, cycle, star, and clique queries,
chain , I cycle , I star , and I clique the value of InnerCounter
we denote by IDPsize DPsize DPsize DPsize
after termination of algorithm DPsize.
chain (n) =
For chain queries, we then have: IDPsize
with q(n) = n2n−1 − 5 ∗ 2n−3 + 1/2(n2 − 5n + 4). For clique queries, we have:
clique
IDPsize (n) =
(
22n−2 − 5 ∗ 2n−2 + 1/4 2n n
n − 1/4 n/2 + 1 n even
22n−2 − 5 ∗ 2n−2 + 1/4 2n
n +1 n odd
Note that 2n n √
n is in the order of Θ(4 / n).
Proofs of the above formulas as well as implementation details for the algo-
rithm DPsize can be found in [529].
DPsub
Input: a connected query graph with relations R = {R0 , . . . , Rn−1 }
Output: an optimal bushy join tree
for all Ri ∈ R {
BestPlan({Ri }) = Ri ;
}
for 1 ≤ i < 2n − 1 ascending {
S = {Rj ∈ R|(bi/2j c mod 2) = 1}
if not (connected S) continue; // ∗
for all S1 ⊂ S, S1 6= ∅ do {
++InnerCounter;
S2 = S \ S1 ;
if (S2 = ∅) continue;
if not (connected S1 ) continue;
if not (connected S2 ) continue;
if not (S1 connected to S2 ) continue;
++CsgCmpPairCounter;
p1 = BestPlan(S1 );
p2 = BestPlan(S2 );
CurrPlan = CreateJoinTree(p1 , p2 );
if (cost(BestPlan(S)) > cost(CurrPlan)) {
BestPlan(S) = CurrPlan;
}
}
}
OnoLohmanCounter = CsgCmpPairCounter / 2;
return BestPlan({R0 , . . . , Rn−1 });
its binary representation. Taken as bitvectors, the integers in the range from 1
to 2n − 1 exactly represent the set of all non-empty subsets of {R0 , . . . , Rn−1 },
including the set itself. Further, by starting with 1 and incrementing by 1, the
enumeration order is valid for dynamic programming: for every subset, all its
subsets are generated before the subset itself.
This enumeration is very fast, since increment by one is a very fast operation.
However, the relations contained in S may not induce a connected subgraph of
the query graph. Therefore, we must test for connectedness. The goal of the
next loop over all subsets of S is to find the best plan joining all the relations
in S. Therefore, S1 ranges over all non-empty, strict subsets of S. This can be
done very efficiently by applying the code snippet of Vance and Maier [777, 778].
Then, the subset of relations contained in S but not in S1 is assigned to S2 .
Clearly, S1 and S2 are disjoint. Hence, only connectedness tests have to be
performed. Since we want to avoid cross products, S1 and S2 both must induce
connected subgraphs of the query graph, and there must be a join predicate
between a relation in S1 and one in S2 . If these conditions are fulfilled, we can
construct a plan CurrPlan by joining the plans associated with S1 and S2 . If
3.2. DETERMINISTIC ALGORITHMS 73
BestPlan does not contain a plan for the relations in S or the one it contains
is more expensive than CurrPlan, we register CurrPlan with BestPlan.
chain , I cycle ,
For chain, cycle, star, and clique queries, we denote by IDPsub DPsub
star , and I clique
IDPsub DPsub the value of InnerCounter after termination of algorithm
DPsub.
For chains, we have
chain
IDPsub (n) = 2n+2 − nn − 3n − 4 (3.6)
The number of failures for the additional check can easily be calculated as
2n − #csg(n) − 1.
Sample numbers Fig. 3.9 contains tables with values produced by our for-
mulas for input query graph sizes between 2 and 20. For different kinds of query
graphs, it shows the number of csg-cmp-pairs (#ccp). and the values for the
inner counter after termination of DPsize and DPsub applied to the different
query graphs.
Looking at these numbers, we observe the following:
• For chain and cycle queries, the DPsize soon becomes much faster than
DPsub.
• For star and clique queries, the DPsub soon becomes much faster than
DPsize.
From the latter observation we can conclude that in almost all cases the tests
performed by both algorithms in their innermost loop fail. Both algorithms
are far away from the theoretical lower bound given by #ccp. This conclusion
motivates us to derive a new algorithm whose InnerCounter value is equal to
the number of csg-cmp-pairs.
Chain Cycle
n #ccp DPsub DPsize #ccp DPsub DPsize
2 1 2 1 1 2 1
5 20 84 73 40 140 120
10 165 3962 1135 405 11062 2225
15 560 130798 5628 1470 523836 11760
20 1330 4193840 17545 3610 22019294 37900
Star Clique
n #ccp DPsub DPsize #ccp DPsub DPsize
2 1 2 1 1 2 1
5 32 130 110 90 180 280
10 2304 38342 57888 28501 57002 306991
15 114688 9533170 57305929 7141686 14283372 307173877
20 4980736 2323474358 59892991338 1742343625 3484687250 309338182241
Figure 3.9: Size of the search space for different graph structures
chain queries, the DPsub algorithm considers many subproblems which are not
connected and, therefore, are not relevant for the solution, i.e. the tests in the
innermost loop fail for the majority of cases. The main idea of our algorithm
DPccp is that it only considers pairs of connected subproblems. More precisely,
the algorithm considers exactly the csg-cmp-pairs of a graph.
Thus, our goal is to efficiently enumerate all csg-cmp-pairs (S1 , S2 ). Clearly,
we want to enumerate every pair once and only once. Further, the enumera-
tion must be performed in an order valid for dynamic programming. That is,
whenever a pair (S1 , S2 ) is generated, all non-empty subsets of S1 and S2 must
have been generated before as a component of a pair. The last requirement is
that the overhead for generating a single csg-cmp-pair must be constant or at
most linear. This condition is necessary in order to beat DPsize and DPsub.
If we meet all these requirements, the algorithm DPccp is easily specified:
iterate over all csg-cmp-pairs (S1 , S2 ) and consider joining the best plans as-
sociated with them. Figure 3.10 shows the pseudocode. The first steps of an
example enumeration are shown in Figure 3.11. Thick lines mark the connect-
ed subsets while thin lines mark possible join edges. Note that the algorithm
explicitly exploits join commutativity. This is due to our enumeration algo-
rithm developed below. If (S1 , S2 ) is a csg-cmp-pair, then either (S1 , S2 ) or
(S2 , S1 ) will be generated, but never both of them. An alternative is to modify
CreateJoinTree to take care of commutativity.
We proceed as follows. Next we discuss an algorithm enumerating non-
empty connected subsets S1 of {R0 , . . . , Rn−1 }. Then, we show how to enumer-
ate the complements S2 such that (S1 , S2 ) is a csg-cmp-pair.
Let us start the exposition by fixing some notations. Let G = (V, E) be
an undirected graph. For a node v ∈ V define the neighborhood IN(v) of v as
IN(v) := {v 0 |(v, v 0 ) ∈ E}. For a subset S ⊆ V of V we define the neighborhood of
S as IN(S) := ∪v∈S IN(v) \ S. The neighborhood of a set of nodes thus consists
3.2. DETERMINISTIC ALGORITHMS 75
DPccp
Input: a connected query graph with relations R = {R0 , . . . , Rn−1 }
Output: an optimal bushy join tree
for all Ri ∈ R) {
BestPlan({Ri }) = Ri ;
}
for all csg-cmp-pairs (S1 , S2 ), S = S1 ∪ S2 {
++InnerCounter;
++OnoLohmanCounter;
p1 = BestPlan(S1 );
p2 = BestPlan(S2 );
CurrPlan = CreateJoinTree(p1 , p2 );
if (cost(BestPlan(S)) > cost(CurrPlan)) {
BestPlan(S) = CurrPlan;
}
CurrPlan = CreateJoinTree(p2 , p1 );
if (cost(BestPlan(S)) > cost(CurrPlan)) {
BestPlan(S) = CurrPlan;
}
}
CsgCmpPairCounter = 2 * OnoLohmanCounter;
return BestPlan({R0 , . . . , Rn−1 });
0 1 1 1 1 0 0 0 1
...
2 3 2 3 3 2 3 2 3 2 2 3
Graph 1. 2. 3. 4. 5. 6. 7. ...
of all nodes reachable by a single edge. Note that for all S, S 0 ⊂ V we have
IN(S ∪ S 0 ) = (IN(S) ∪ IN(S 0 )) \ (S ∪ S 0 ). This allows for an efficient bottom-up
calculation of neighborhoods.
The following statement gives a hint on how to construct an enumeration
procedure for connected subsets. Let S be a connected subset of an undirected
graph G and S 0 be any subset of IN(S). Then S ∪ S 0 is connected. As a
consequence, a connected subset can be enlarged by adding any subset of its
neighborhood.
We could generate all connected subsets as follows. For every node vi ∈ V
we perform the following enumeration steps: First, we emit {vi } as a connected
subset. Then, we expand {vi } by calling a routine that extends a given connect-
ed set to bigger connected sets. Let the routine be called with some connected
set S. It then calculates the neighborhood IN(S). For every non-empty subset
76 CHAPTER 3. JOIN ORDERING
R0
R1 R2 R3
R4
EnumerateCsgRec(G, S, X)
N = IN(S) \ X;
for all S 0 ⊆ N , S 0 6= ∅, enumerate subsets first {
emit (S ∪ S 0 );
}
for all S 0 ⊆ N , S 0 6= ∅, enumerate subsets first {
EnumerateCsgRec(G, (S ∪ S 0 ), (X ∪ N ));
}
EnumerateCsgRec
S X N emit/S
{4} {0, 1, 2, 3, 4} ∅
{3} {0, 1, 2, 3} {4}
{3, 4}
{2} {0, 1, 2} {3, 4}
{2, 3}
{2, 4}
{2, 3, 4}
{1} {0, 1} {4}
{1, 4}
→ {1, 4} {0, 1, 4} {2, 3}
{1, 2, 4}
{1, 3, 4}
{1, 2, 3, 4}
{0} {0} {1, 2, 3}
{0, 1}
{0, 2}
{0, 3}
{0, 1, 2}
{0, 1, 3}
{0, 2, 3}
{0, 1, 2, 3}
→ {0, 1} {0, 1, 2, 3} {4}
{0, 1, 4}
→ {0, 2} {0, 1, 2, 3} {4}
{0, 2, 4}
of every csg-cmp-pair. Then, for each such S1 , we generate all its complement
components S2 . This can be done by calling EnumerateCsgRec with the correct
parameters. Remember that we have to generate every csg-cmp-pair once and
only once.
To achieve this, we use a similar technique as for connected subsets, using
the breadth-first numbering to define an enumeration order: we consider only
sets S2 in the complement of S1 (with (S1 , S2 ) being a csg-cmp-pair) such that
S2 contains only vj with j larger than any i with vi ∈ S1 . This avoids the
generation of duplicates.
We need some definitions to state the actual algorithm. Let S1 ⊆ V be
a non-empty subset of V . Then, we define min(S1 ) := min({i|vi ∈ S1 }).
This is used to extract the starting node from which S1 was constructed (see
Lemma ??). Let W ⊂ V be a non-empty subset of V . Then, we define
Bi (W ) := {vj |vj ∈ W, j ≤ i}. Using this notation, the algorithm to construct
all S2 for a given S1 such that (S1 , S2 ) is a csg-cmp-pair looks as follows:
78 CHAPTER 3. JOIN ORDERING
EnumerateCmp
Input: a connected query graph G = (V, E), a connected subset S1
Precondition: nodes in V are numbered according to a breadth-first search
Output: emits all complements S2 for S1 such that (S1 , S2 ) is a csg-cmp-pair
X = Bmin(S1 ) ∪ S1 ;
N = IN(S1 ) \ X;
for all (vi ∈ N by descending i) {
emit {vi };
EnumerateCsgRec(G, {vi }, X ∪ (Bi ∩ N ));
}
Hence, {R4 } is emitted and together with {R1 }, it forms the csg-cmp-pair
({R1 }, {R4 }). Then, the recursive call to EnumerateCsgRec follows with ar-
guments G, {R4 }, and {R0 , R1 , R4 }. Subsequent EnumerateCsgRec generates
the connected sets {R2 , R4 }, {R3 , R4 }, and {R2 , R3 , R4 }, giving three more
csg-cmp-pairs.
3.2.5 Memoization
Whereas dynamic programming constructs the join trees iteratively from small
trees to larger trees, i.e. works bottom up, memoization works recursively. For a
given set of relations S, it produces the best join tree for S by recursively calling
itself for every subset S1 of S and considering all join trees between S1 and its
complement S2 . The best alternative is memoized (hence the name). The rea-
son is that two (even different) (sub-) sets of all relations may very well have the
common subsets. For example, {R1 , R2 , R3 , R4 , R5 } and {R2 , R3 , R4 , R5 , R6 }
have the common subset {R2 , R3 , R4 , R5 }. In order to avoid duplicate work,
memoization is essential.
In the following variant of memoization, we explore the search space of all
EX bushy trees and consider cross products. We split the functionality across two
functions. The first one initializes the BestTree data structure with single
relation join trees for Ri and then calls the second one. The second one is the
core memoization procedure which calls itself recursively.
3.2. DETERMINISTIC ALGORITHMS 79
MemoizationJoinOrdering(R)
Input: a set of relations R
Output: an optimal join tree for R
for (i = 1; i <= n; ++i) {
BestTree({Ri }) = Ri ;
}
return MemoizationJoinOrderingSub(R);
MemoizationJoinOrderingSub(S)
Input: a (sub-) set of relations S
Output: an optimal join tree for S
if(NULL == BestTree(S)) {
for all S1 ⊂ S do {
S2 = S \ S1 ;
CurrTree = CreateJoinTree(MemoizationJoinOrderingSub(S1 ), MemoizationJoinOrderingSub(
if (BestTree(S) == NULL || cost(BestTree(S)) > cost(CurrTree)) {
BestTree(S) = CurrTree;
}
}
}
return BestTree(S);
Again, pruning techniques can help to speed up plan generation [688]. ToDo?
ConstructPermutations(Query Specification)
Input: query specification for relations {R1 , . . . , Rn }
Output: optimal left-deep tree
BestPermutation = NULL;
Prefix = ;
Rest = {R1 , . . . , Rn };
ConstructPermutationsSub(Prefix, Rest);
return BestPermutation
80 CHAPTER 3. JOIN ORDERING
ConstructPermutationsSub(Prefix, Rest)
Input: a prefix of a permutation and the relations to be added (Rest)
Ouput: none, side-effect on BestPermutation
if (Rest == ∅) {
if (BestPermutation == NULL || cost(Prefix) < cost(BestPermutation)) {
BestPermutation = Prefix;
}
return
}
foreach (Ri , Rj ∈ Rest) {
if (cost(Prefix ◦ hRi , Rj i) ≤ cost(Prefix ◦ hRj , Ri i)) {
ConstructPermutationsSub(Prefix ◦ hRi i, Rest \ {Ri });
}
if (cost(Prefix ◦ hRj , Ri i) ≤ cost(Prefix ◦ hRi , Rj i)) {
ConstructPermutationsSub(Prefix ◦ hRj i, Rest \ {Rj });
}
}
return
The algorithm can be made more efficient, if the foreach loop considers only
a single relation and performs the swap test with this relation and the last
relation occurring in Prefix.
The algorithm has two main advantages over dynamic programming and
memoization. The first advantage is that it needs only linear space opposed
to exponential space for the two mentioned alternatives. The other main
advantage over dynamic programming is that it generates join trees early,
whereas with dynamic programming we only generate a plan after the whole
search space has been explored. Thus, if the query contains too many joins—
that is, the search space cannot be fully explored in reasonable time and
space—dynamic programming will not generate any plan at all. If stopped,
ConstructPermutations will not necessarily compute the best plan, but still
some plans have been investigated. This allows us to stop it after some time
limit has exceeded. The time limit itself can be fixed, like 100 ms, or variable,
like 5% of the execution time of the best plan found so far.
The predicates in the if statement can be made more efficient if a (local)
ranking function is available. Further speed-up of the algorithm can be achieved
if additionally the idea of memoization is applied (of course, this jeopardizes
the small memory footprint).
The following variant might be interesting if one is willing to go from linear
space consumption to quadratic space consumption. The original algorithm
is then started n times, once for each relation as a starting relation. The n
different instantiations then have to run interleaved. This variant reduces the
dependency on the starting relation.
ToDo/EX Worst Case Analysis
ToDo/EX Pruning/memoization/propagation
3.2. DETERMINISTIC ALGORITHMS 81
Let us introduce some notions used for the algorithms. We have to gener-
alize the rank used in the IKKBZ algorithm to relativized ranks. We start by
relativizing the cost function. The costs of a sequence s relative to a sequence
u are defined as
Cu () := 0
Cu (Ri ) := 0 if u =
Y
Cu (Ri ) := ( fj,i )ni if u 6=
Rj <uRi Ri
with
Tu () := 1
Y Y
Tu (s) := ( fj,i ) ∗ ni
Ri ∈s Rj <us Ri
There are 6 possible orderings of the relations with the following costs:
C(R1 R2 R3 ) = 1 ∗ 100 ∗ 0.9 + 1 ∗ 100 ∗ 10 ∗ 0.9 ∗ 0.9 = 900
C(R1 R3 R2 ) = 1 ∗ 10 + 1 ∗ 10 ∗ 100 ∗ 0.9 ∗ 0.9 = 820
C(R2 R3 R1 ) = 100 ∗ 10 ∗ 0.9 + 100 ∗ 10 ∗ 1 ∗ 0.9 ∗ 0.9 = 1710
C(R2 R1 R3 ) = C(R1 R2 R3 )
C(R3 R1 R2 ) = C(R1 R3 R2 )
C(R3 R2 R1 ) = C(R2 R3 R1 )
Note that the cost function is invariant with respect to the order of the first two
relations. The minimum over all costs is 820, and the corresponding optimal
join ordering is R1 R3 R2 .
2
Using the relativized cost function, we can define the relativized rank.
Definition 3.2.8 (rank) The rank of a sequence s relative to a non-empty
sequence u is given by
Tu (s) − 1
ranku (s) :=
Cu (s)
In the special case that s consists of a single relation Ri , the intuition behind
the rank function becomes transparent. Let fi be the product of the selectivities
between relations in u and Ri . Then ranku (Ri ) = fif|R i |−1
i |Ri |
. Hence, the rank
becomes a function of the form f (x) = x−1 x . This function is monotonously
increasing in x for x > 0. The argument to the function f (x) is (for the
computation of the size of a single relation Ri ) fi |Ri |. But this is the factor by
which the next intermediate result will increase (or decrease). Since we sum up
intermediate results, this is an essential number. Furthermore, it follows from
the monotonicity of f (x) that ranku (Ri ) ≤ ranku (Rj ) if and only if fi |Ri | ≤
fj |Rj | where fj is the product of all selectivities between Rj and relations in u.
Hence, within the optimal sequence, the relation with the smallest rank (here
R3 , since rankR1 (R3 ) < rankR1 (R2 )) is preferred. As the next lemma will
show, this is no accident.
2
Using the rank function, the following lemma can be proved.
Lemma 3.2.9 For sequences
Lemma 3.2.10 Let u, x and y be three subchains where x and y are not inter-
connected. Then we have:
A special case occurs when x and y are single relations. Then the above condi-
tion simplifies to
rankux (y) < ranku (x) ≤ ranku (y)
To explain the intuition behind the definition of contradictory subchains, we
need another example.
and
C(R1 R2 R3 ) = 15
C(R1 R3 R2 ) = 20
3.2. DETERMINISTIC ALGORITHMS 85
Hence,
and (R2 , R3 ) is a contradictory pair within R1 R2 R3 . Now the use of the term
contradictory becomes clear: the costs do not behave as could be expected from
the ranks. 2
The next (obvious) lemma states that contradictory chains are necessarily
connected.
Now we present the fact that between a contradictory pair of relations, there
cannot be any other relation not connected to them without increasing cost.
C(R1 R2 R3 R5 R4 ) = 4 + 8 + 16 + 8 = 36
C(R1 R2 R5 R3 R4 ) = 4 + 8 + 16 + 8 = 36
C(R1 R5 R2 R3 R4 ) = 2 + 8 + 16 + 8 = 34
2
The next lemma shows that, if there exist two sequences of single rank-
sorted relations, then their costs as well as their ranks are necessarily equal.
and the subsequences xi and yj are all optimal (with respect to the fixed prefixes
x1 . . . xi−1 and y1 . . . yj−1 ), then S and S 0 have equal costs.
Consider the problem of merging two optimal unconnected chains. If we
knew that the ranks of relations in an optimal chain are always sorted in as-
cending order, we could use the classical merge procedure to combine the two
chains. The resulting chain would also be rank-sorted in ascending order and,
according to Lemma 3.2.14, it would be optimal. Unfortunately, this does not
work, since there are optimal chains whose ranks are not sorted in ascending
order: those containing sequences with contradictory ranks.
Now, as shown in Lemma 3.2.13, between contradictory pairs of relations
there cannot be any other relation not connected to them. Hence, in the merging
process, we have to take care that we do not merge a contradictory pair of
relations with a relation not connected to the pair. In order to achieve this,
we apply the same trick as in the IKKBZ algorithm: we tie the relations of a
contradictory subchain together by building a compound relation. Assume that
we tie together the relations r1 , . . . , rn to a new relation r1,...,n . Then we define
the size of r1,...,n as |r1,...,n | = |r1 1 . . . 1 rn | Further, if some ri (1 ≤ i ≤ n)
does have a connection to some rk 6∈ {r1 , . . . , rn } then we define the selectivity
factor fr1,...,n ,rk between rk and r1,...,n as fr1,...,n ,rk = fi,k .
If we tie together contradictory pairs, the resulting chain of compound re-
lations still does not have to be rank-sorted with respect to the compound
relations. To overcome this, we iterate the process of tying contradictory pairs
of compound relations together until the sequence of compound relations is
rank-sorted, which will eventually be the case. That is, we apply the normal-
ization as used in the IKKBZ algorithm. However, we have to reformulate it
for relativized costs and ranks:
Normalize(p,s)
while (there exist subsequences u, v (u 6= ) and
compound relations x, y such that s = uxyv
and Cpu (xy) ≤ Cpu (yx)
and rankpu (x) > rankpux (y)) {
replace xy by a compound relation (x, y);
}
return (p, s);
3.2. DETERMINISTIC ALGORITHMS 87
The compound relations in the result of the procedure Normalize are called
contradictory chains. A maximal contradictory subchain is a contradictory sub-
chain that cannot be made longer by further tying steps. Resolving the tyings
introduced in the procedure normalize is called de-normalization. It works the
same way as in the IKKBZ algorithm. The cost, size and rank functions can
now be extended to sequences containing compound relations in a straightfor-
ward way. We define the cost of a sequence containing compound relations to
be identical with the cost of the corresponding de-normalized sequence. The
size and rank functions are defined analogously.
The following simple observation is central to the algorithms: every chain
can be decomposed into a sequence of adjacent maximal contradictory sub-
chains. For convenience, we often speak of chains instead of subchains and of
contradictory chains instead of maximal contradictory subchains. The mean-
ing should be clear from the context. Further, we note that the decomposi-
tion into adjacent maximal contradictory subchains is not unique. For exam-
ple, consider an optimal subchain r1 r2 r3 and a sequence u of preceding rela-
tions. If ranku (r1 ) > rankur1 (r2 ) > rankur1 r2 (r3 ) one can easily show that
both (r1 , (r2 , r3 )) and ((r1 , r2 ), r3 ) are contradictory subchains. Nevertheless,
this ambiguity is not important since in the following we are only interest-
ed in contradictory subchains which are optimal . In this case, the condition
Cu (xy) ≤ Cu (yx) is certainly true and can therefore be neglected. One can
show that for the case of optimal subchains the indeterministically defined nor-
malization process is well-defined, that is, if S is optimal, normalize(P,S) will
always terminate with a unique “flat” decomposition of S into maximal contra-
dictory subchains (flat means that we remove all but the outermost parenthesis,
e.g. (R1 R2 )(((R5 R4 )R3 )R6 ) becomes (R1 R2 )(R5 R4 R3 R6 )).
The next two lemmata and the conjecture show a possible way to overcome
the problem that if we consider cross products, we have an unconstrained or-
dering problem and the idea of Monma and Sidney as exploited in the IKKBZ
algorithm is no longer applicable. The next lemma is a direct consequence of
the normalization procedure.
The next result shows how to build an optimal sequence from two optimal
non-interconnected sequences.
Lemma 3.2.16 Let x and y be two optimal sequences of relations where x and
y are not interconnected. Then the sequence obtained by merging the maximal
contradictory subchains in x and y (as obtained by normalize) according to
their ascending rank is optimal.
88 CHAPTER 3. JOIN ORDERING
Conjecture 3.2.2 Consider two sequences S and T containing exactly the re-
lations R1 ,. . . ,Rn . Let S = s1 . . . sk and T = t1 . . . tl be such that each of the
maximal contradictory subchains si , i = 1, . . . , k and tj , j = 1, . . . , l are optimal
recursively decomposable. Then S and T have equal costs.
This cost function can be treated in a more elegant way than C. The new rank
function is now defined as ranku (s) := (Tu (s) − 1)/Cu0 (s). Note that the rank
function is now defined even if u = and s is a single relation. The size function
remains unchanged. At the end of this subsection, we describe how our results
can be adapted to the original cost function C.
The rank of a contradictory chain depends on the relative position of the
relations that are directly connected to it. For example, the rank of the con-
tradictory subchain (R5 R3 R4 R2 ) depends on the position of the neighbouring
relations R1 and R6 relative to (R5 R3 R4 R2 ). That is, whether they appear be-
fore or after the sequence (R5 R3 R4 R2 ). Therefore, we introduce the following
fundamental definitions:
Definition 3.2.17 (neighbourhood) We call the set of relations that are di-
rectly connected to a subchain (with respect to the query graph G) the complete
neighbourhood of that subchain. A neighbourhood is a subset of the complete
neighbourhood. The complement of a neighbourhood u of a subchain s is defined
as v \ u, where v denotes the complete neighbourhood of s.
s = R2 R4 R3 R6 R5 R1 .
Note that any contradictory subchain occurring in the optimal sequence (except
at the first and last positions) necessarily has matching contradictory subchains
preceding and succeeding it in the list. In fact, every contradictory subchain X
occurring in the optimal join sequence must satisfy the following two conditions.
the list (with respect to the given prefix). With the use of this information, all
branches that do not lead to a complete join sequence can be pruned.
Let us analyze the worst case time complexity of the algorithm. The two
dynamic programming steps both iterate over O(n2 ) different extents, and each
extent gives rise to O(n) splittings. Moreover, for each extent one normalization
is necessary, which requires linear time (cost, size and rank can be computed in
constant time using recurrences). Therefore, the complexity of the two dynamic
programming steps is O(n4 ). Sorting O(n2 ) contradictory chains can be done
in time O(n2 log n). The step where all “useless” contradictory subchains are
eliminated, consists of two stages of a reachability algorithm which has com-
plexity O(n4 ). If conjecture 3.2.2 is true, the backtracking step requires linear
time, and the total complexity of the algorithm is O(n4 ). Otherwise, if con-
jecture 3.2.2 is false, the algorithm might exhibit exponential worst case time
complexity.
We now describe how to reduce the problem for our original cost function
C to the problem for the modified cost function C 0 . One difficulty with the
original cost function is that the ranks are defined only for subsequences of at
least two relations. Hence, for determining the first relation in our solution
we do not have sufficient information. An obvious solution to this problem
is to try every relation as starting relation, process each of the two resulting
chain queries separately and choose the chain with minimum costs. The new
complexity will increase by about a factor of n. This first approach is not
very efficient, since the dynamic programming computations overlap consider-
ably, e.g. if we perform dynamic programming on the two overlapping chains
R1 R2 R3 R4 R5 R6 and R2 R3 R4 R5 R6 R7 , for the intersecting chain R2 R3 R4 R5 R6
everything is computed twice. The cue is that we can perform the dynamic pro-
gramming calculations before we consider a particular starting relation. Hence,
the final algorithm can be sketched as follows:
Algorithm CHAIN-I:
Suppose that conjecture 3.2.2 is true, and we can replace the backtracking part
by a search for the first solution. Then the complexity of the step 1 is O(n4 ),
3.2. DETERMINISTIC ALGORITHMS 93
whereas the complexity of step 2 amounts to ni=1 (O(i2 ) + O(n − i)2 + O(n)) =
P
O(n3 ). Hence, the total complexity would be O(n4 ) in the worst case. Of
course, if our conjecture is false, the necessary backtracking step might lead to
an exponential worst case complexity.
(a) Let L1 be the result of applying the steps 2 and 3 of Algorithm II’ to
all optimal recursive decomposable subchains whose extent (N, M )
satisfies Ri ∈ N and M ⊆ {R1 , . . . , Ri }.
(b) Let L2 be the result of applying the steps 2 and 3 of Algorithm II’ to
all optimal recursive decomposable subchains whose extent (N, M )
satisfies Ri N and M ⊆ {Ri , . . . , Rn }.
(c) Let L be the result of merging L1 and L2 according to their ranks.
94 CHAPTER 3. JOIN ORDERING
(d) De-normalize L.
(e) Use Ri L to update the current-best join ordering.
R1 1 R2 ; R2 1 R1 Commutativity
(R1 1 R2 ) 1 R3 ; R1 1 (R2 1 R3 ) Right Associativity
R1 1 (R2 1 R3 ) ; (R1 1 R2 ) 1 R3 Left Associativity
(R1 1 R2 ) 1 R3 ; (R1 1 R3 ) 1 R2 Left Join Exchange
R1 1 (R2 1 R3 ) ; R2 1 (R1 1 R3 ) Right Join Exchange
Two more rules are often used to transform left-deep trees. The first opera-
tion (swap) exchanges two arbitrary relations in a left-deep tree. The second
operation (3Cycle) performs a cyclic rotation of three arbitrary relations in a
left-deep tree. To account for different join methods, a rule called join method
exchange is introduced.
The first rule set (RS-0) we are using contains the commutativity rule and
both associativity rules. Applying associativity can lead to cross products. RS-0
If we do not want to consider cross products, we only apply any of the two
associativity rules if the resulting expression does not contain a cross product.
It is easy to extend ApplyTransformations to cover this by extending the if
conditions with
and (ConsiderCrossProducts || connected(·))
where the argument of connected is the result of applying a transformation.
ExhaustiveTransformation({R1 , . . . , Rn })
Input: a set of relations
Output: an optimal join tree
Let T be an arbitrary join tree for all relations
Done = ∅; // contains all trees processed
ToDo = {T }; // contains all trees to be processed
while (!empty(ToDo)) {
Let T be an arbitrary tree in ToDo
ToDo \ = T ;
Done ∪ = T ;
Trees = ApplyTransformations(T );
for all T ∈ Trees do {
if (T 6∈ ToDo ∪ Done) {
ToDo + = T ;
}
}
}
96 CHAPTER 3. JOIN ORDERING
ApplyTransformations(T )
Input: join tree
Output: all trees derivable by associativity and commutativity
Trees = ∅;
Subtrees = all subtrees of T rooted at inner nodes
for all S ∈ Subtrees do {
if (S is of the form S1 1 S2 ) {
Trees + = S2 1 S1 ;
}
if (S is of the form (S1 1 S2 ) 1 S3 ) {
Trees + = S1 1 (S2 1 S3 );
}
if (S is of the form S1 1 (S2 1 S3 )) {
Trees + = (S1 1 S2 ) 1 S3 ;
}
}
return Trees;
Besides the problems mentioned above, this algorithm also has the problem
that the sharing of subtrees is a non-trivial task. In fact, we assume that
ApplyTransformations produces modified copies of T . To see how ExhaustiveTransformation
works, consider again Figure 2.6. Assume that the top-left join tree is the initial
join tree. Then, from this join tree ApplyTransformations produces all trees
reachable by some edge. All of these are then added to ToDo. The next call
to ApplyTransformations with any to the produced join trees will have the
initial join tree contained in Trees. The complete set of visited join trees after
this step is determined from the initial join tree by following at most two edges.
Let us reformulate the algorithm such that it uses a data structure similar
to dynamic programming or memoization in order to avoid duplicate work. For
any subset of relations, dynamic programming remembers the best join tree.
This does not quite suffice for the transformation-based approach. Instead, we
have to keep all join trees generated so far including those differing in the order
of the arguments or a join operator. However, subtrees can be shared. This
is done by keeping pointers into the data structure (see below). So, the dif-
ference between dynamic programming and the transformation-based approach
becomes smaller. The main remaining difference is that dynamic programming
only considers these join trees while with the transformation-based approach
we have to keep the considered join trees since other join trees (more beneficial)
might be generatable from them.
The data structure used for remembering trees is often called the MEMO
structure. For every subset of relations to be joined (except the empty set), a
class exists in the MEMO structure. Each class contains all the join trees that
join exactly the relations describing the class. Here is an example for join trees
containing three relations.
3.2. DETERMINISTIC ALGORITHMS 97
ExhaustiveTransformation2(Query Graph G)
Input: a query specification for relations {R1 , . . . , Rn }.
Output: an optimal join tree
initialize MEMO structure
ExploreClass({R1 , . . . , Rn })
return best of class {R1 , . . . , Rn }
ExploreClass(C)
Input: a class C ⊆ {R1 , . . . , Rn }
Output: none, but has side-effect on MEMO-structure
while (not all join trees in C have been explored) {
choose an unexplored join tree T in C
ApplyTransformation2(T )
mark T as explored
}
return
ApplyTransformations2(T )
Input: a join tree of a class C
Output: none, but has side-effect on MEMO-structure
ExploreClass(left-child(T ));
ExploreClass(right-child(T ));
foreach transformation T and class member of child classes {
98 CHAPTER 3. JOIN ORDERING
T1 : Commutativity C1 10 C2 ; C2 11 C1
Disable all transformations T1 , T2 , and T3 for 11 .
The second column shows the initialization with an arbitrarily chosen join
tree. The third column is the one filled by the Apply Transformation2 proce-
dure. We apply the rule set RS-1, which consists of three transformations. Each
join is annotated with three bits, where the i-th bit indicates whether Ti is appli-
cable (1) or not (0). After initializing the MEMO structure, ExhaustiveTransformation2
calls ExploreClass for {R1 , R2 , R3 , R4 }. The only (unexplored) join tree is
{R1 , R2 } 1111 {R3 , R4 }, which will become the argument of ApplyTransformations2.
Next, ExploreClass is called on {R1 , R2 } and {R3 , R4 }. In both cases, T1 is
the only applicable rule, and the result is shown in the third column under steps
1 and 2. Now we have to apply all transformations on {R1 , R2 } 1111 {R3 , R4 }.
Commutativity T1 gives us {R3 , R4 } 1000 {R1 , R2 } (Step 3). For right associa-
tivity, we have two elements in class {R1 , R2 }. Substituting them and applying
T2 gives
1. (R1 1 R2 ) 1 {R3 , R4 } ; R1 1100 (R2 1111 {R3 , R4 })
The latter contains a cross product. This leaves us with the former as the result
of Step 5. We also add {R1 , R2 } 1111 R3 . Now that {R1 , R2 } 1111 {R3 , R4 } is
completely explored, we turn to {R3 , R4 } 1000 {R1 , R2 }, but all transformations
are disabled here.
R1 1100 {R2 , R3 , R4 } is next. First, {R2 , R3 , R4 } has to be explored. The
only entry is R2 1111 {R3 , R4 }. Remember that {R3 , R4 } is already explored.
T2 is not applicable. The other two transformations give us
T1 {R3 , R4 } 1000 R2
Those join trees not exhibiting a cross product are added to the MEMO struc-
ture under 6. Applying commutativity to {R2 , R4 } 1100 R3 gives 7. Commuta-
tivity is the only rule enabled for R1 1100 {R2 , R3 , R4 }. Its application results
in 8.
{R1 , R2 , R3 } 1100 R4 is next. It is simple to explore the class {R1 , R2 , R3 }
with its only entry {R1 , R2 } 1111 R3 :
T1 R3 1000 {R1 , R2 }
Commutativity can still be applied to R1 1100 (R2 1111 R3 ). All the new entries
are numbered 9. Commutativity is the only rule enabled for {R1 , R2 , R3 } 1100
R4 Its application results in 10.
2
The next two sets of transformations were originally intended for generating
all bushy/left-deep trees for a clique query [582]. They can, however, also be
used to generate all bushy trees when cross products are considered. The rule
set RS-2 for bushy trees is
T1 : Commutativity C1 10 C2 ; C2 11 C1
Disable all transformations T1 , T2 , T3 , and T4 for 11 .
If we initialize the MEMO structure with left-deep trees, we can strip down
the above rule set to Commutativity and Left Associativity. The reason is an
observation made by Shapiro et al.: from a left-deep join tree we can generate
all bushy trees with only these two rules [688].
If we want to consider only left-deep trees, the following rule set RS-3 is
appropriate:
T1 Commutativity R1 10 R2 ; R2 11 R1
Here, the Ri are restricted to classes with exactly one relation. T1 is
disabled for 11 .
T2 Right Join Exchange (C1 10 C2 ) 11 C3 ; (C1 12 C3 ) 13 C2
Disable T2 for 13 .
the ranking/unranking algorithms into two phases. For ranking, first the in-
version vector of the permutation is established. Then, ranking takes place for
the inversion vector. Unranking works in the opposite direction. The inver-
sion vector of a permutation π = π0 , . . . , πn−1 is defined to be the sequence
v = v0 , . . . , vn−1 , where vi is equal to the number of entries πj with πj > πi
and j < i. Inversion vectors uniquely determine a permutation [759]. However,
naive algorithms of this approach again require O(n2 ) time. Better algorithms
require O(n log n). Using an elaborated data structure, Dietz’ algorithm re-
quires O((n log n)/(log log n)) [208]. Other orders like the Steinhaus-Johnson-
Trotter order have been exploited for ranking/unranking but do not yield any
run-time advantage over the above mentioned algorithms (see [442, 617]).
Since it is not important for our problem that any order constraints are sat-
isfied for the ranking/unranking functions, we use the fastest possible algorithm
established by Myrvold and Ruskey [541]. It runs in O(n) which is also easily
seen to be a lower bound.
The algorithm is based on the standard algorithm to generate random per-
mutations [192, 214, 535]. An array π is initialized such that π[i] = i for
0 ≤ i ≤ n − 1. Then, the loop
Unrank(n, r) {
Input: the number n of elements to be permuted
and the rank r of the permutation to be constructed
Output: a permutation π
for (i = 0; i < n; + + i) π[i] = i;
Unrank-Sub(n, r, π);
return π;
}
}
Unrank-Sub(n, r, π) {
for (i = n; i > 0; − − i) {
3.3. PROBABILISTIC ALGORITHMS 103
5. Attach the relations in order p from left to right as leaf nodes to the binary
tree obtained in Step 2.
The only step that we still have to discuss is Step 2. It is a little involved and we
can only try to bring across the general idea. For details, the reader is referred
to the literature [479, 480, 481].
Consider Figure 3.15. It contains all 14 possible trees with four inner nodes.
The trees are ordered according to the rank we will consider. The bottom-most
number below any tree is its rank in [0, 14[. While unranking, we do not generate
the trees directly, but an encoding of the tree instead. This encoding works as
follows. Any binary tree corresponds to a word in a Dyck language with one
pair of parenthesis. The alphabet hence consists of Σ = {0 (0 , 0 )0 }. For join trees
with n inner nodes, we use Dyck words of length 2n whose parenthesization is
correct. That is, for every 0 (0 , we have a subsequent 0 )0 . From a given join tree,
we obtain the Dyck word by a preorder traversal. Whenever we encounter an
inner node, we encode this with a 0 (0 . All but the last leaf nodes are encoded
by a 0 )0 . Appending all these 2n encodings gives us a Dyck word of length 2n.
Figure 3.15 shows directly below each tree its corresponding Dyck word. In the
line below, we simply changed the representation by substituting every 0 (0 by a
0 10 and every 0 )0 by a 0 00 . The encoding that will be generated by the unranking
algorithm is shown in the third line below each tree: we remember the places
(index in the bit-string) where we find a 0 10 .
In order to do the unranking, we need to do some counting. Therefor, we
map Dyck words to paths in a triangular grid. For n = 4 this grid is shown in
Figure 3.16. We always start at (0, 0) which means that we have not opened a
parenthesis. When we are at (i, j), opening a parenthesis corresponds to going
to (i + 1, j + 1) and closing a parenthesis to going to (i + 1, j − 1). We have
thus established a bijective mapping between Dyck words and paths in the grid.
Thus counting Dyck words corresponds to counting paths.
104 CHAPTER 3. JOIN ORDERING
4 1
[0,0]
3 4 1
[1,4[
2 9 3 1
[4,9[
1 14 5 2
[9,14[
1 2 3 4 5 6 7 8
Note the special case q(0, 0) = p(2n, 0) = C(n). In Figure 3.16, we annotated
nodes (i, j) by p(i, j). These numbers can be used to assign (sub-) intervals to
paths (Dyck words, trees). For example, if we are at (4, 4), there exists only
a single path to (2n, 0). Hence, the path that travels the edge (4, 4) → (5, 3)
has rank 0. From (3, 3) there are four paths to (2n, 0), one of which we already
considered. This leaves us with three paths that travel the edge (3, 3) → (4, 2).
The paths in this part as assigned ranks in the interval [1, 4[. Figure 3.16 shows
the intervals near the edges. For unranking, we can now proceed as follows.
Assume we have a rank r. We consider opening a parenthesis (go from (i, j) to
(i + 1, j + 1)) as long as the number of paths from that point does no longer
exceed our rank r. If it does, we close a parenthesis instead (go from (i, j) to
(i − 1, j + 1)). Assume, that we went upwards to (i, j) and then had to go down
to (i − 1, j + 1). We subtract the number of paths from (i + 1, j + 1) from our
rank r and proceed iteratively from (i − 1, j + 1) by going up as long as possible
and going down again. Remembering the number of parenthesis opened and
closed along our way results in the required encoding. The following algorithm
finalizes these ideas.
UnrankTree(n, r)
Input: a number of inner nodes n and a rank r ∈ [0, C(n − 1)]
Output: encoding of the inner leaves of a tree
lNoParOpen = 0;
lNoParClose = 0;
i = 1; // current encoding
j = 0; // current position in encoding array
while (j < n) {
k = q(lNoParOpen + lNoParClose + 1, lNoParOpen - lNoParClose + 1);
if (k ≤ r) {
r -= k;
106 CHAPTER 3. JOIN ORDERING
++lNoParClose;
} else {
aTreeEncoding[j++] = i;
++lNoParOpen;
}
++i;
}
Given an array with the encoding of a tree, it is easy to construct the tree
from it. The following procedure does that.
TreeEncoding2Tree(n, aEncoding) {
Input: the number of internal nodes of the tree n
Output: root node of the result tree
root = new Node; /* root of the result tree */
curr = root; /* curr: current internal node whose subtrees are to be created */
i = 1; /* pointer to entry in encoding */
child = 0; /* 0 = left , 1 = right: next child whose subtree is to be created */
while (i < n) {
lDiff = aEncoding[i] - aEncoding[i − 1];
for (k = 1; k < lDif f ; + + k) {
if (child == 0) {
curr->addLeftLeaf();
child = 1;
} else {
curr->addRightLeaf();
while (curr->right() != 0) {
curr = curr->parent();
}
child = 1;
}
}
if (child == 0) {
curr->left(new Node(curr)); // curr becomes parent of new node
curr = curr->left();
++i;
child = 0;
} else {
curr->right(new Node(curr));
curr = curr->right();
++i;
child = 0;
}
}
while (curr != 0) {
3.3. PROBABILISTIC ALGORITHMS 107
R1 S1 R1 R1 S1
R2 S2 S1 R2 R1
R2 S1 R2
v v
S2 S2 S2
R S
v v v
(R, S, [1, 1, 0]) (R, S, [2, 0, 0]) (R, S, [0, 2, 0])
within Sk .
Accordingly, we partition the set of all possible merges into subsets. Each
subset is determined by α0 . For example, the set of possible merges of two
lists L1 and L2 with length l1 = l2 = 4 is partitioned into subsets with α0 = j
for 0 ≤ j ≤ 4. In each partition, we have M (j, l2 − 1) elements. To unrank
a number P r ∈ [1, M (l1 , l2 )], we first determine the partition by computing k =
j 0
minj r ≤ i=0 M (j, l2 − 1). Then, α0 = l1 − k. With the new rank r =
Pk
r − i=0 M (j, l2 − 1), we start iterating all over. The following table gives
the numbers for our example and can be used to understand the unranking
algorithm. The algorithm itself can be found in Figure 3.18.
Definition 3.3.1 Let T be a join tree and v be a leaf of T . The anchored list
representation L of T is constructed as follows:
UnrankDecomposition(r, l1 , l2 )
Input: a rank r, two list sizes l1 and l2
Output: a merge specification α.
for (i = 0; i ≤ l2 ; + + i) {
alpha[i] = 0;
}
i = k = 0;
while (l1 > 0 && l2 > 0) {
m = M (k, l2 − 1);
if (r ≤ m) {
alpha[i + +] = l1 − k;
l1 = k;
k = 0;
− − l2 ;
} else {
r− = m;
+ + k;
}
}
alpha[i] = l1 ;
return alpha;
T1 v T1 T1
T1 v T2
T2 T2
v
w T2 w w w
e +e [0, 5, 5, 5, 3]
e c ∗c [0, 0, 2, 3]
a b c d
b d [0, 1, 1] +c [0, 1]
+c
a
[0, 1] +b d [1]
[1] a
Figure 3.20: A query graph, its tree, and its standard decomposition graph
• Ti = (Li , w).
Let α be the integer composition such that L is the result of merging L1 and L2
on α. Then we call (T1 , T2 , α) a merge triplet. We say that T is decomposed
into (constructed from) (T1 , T2 , α) on V1 and V2 .
3. call QG2SDG(G0 , r)
with
QG2SDG(G0 , r)
Input: a query tree G0 = (V, E) and its root r
Output: a standard query decomposition tree of G0
Let {w1 , . . . , wn } be the children of v;
switch (n) {
case 0: label v with "v";
case 1:
label v as "+v ";
QG2SDG(G0 , w1 );
otherwise:
label v as "∗v ";
create new nodes l, r with label +v ;
E \ = {(v, wi )|1 ≤ i ≤ n};
E ∪ = {(v, l), (v, r), (l, w1 )} ∪ {(r, wi )|2 ≤ i ≤ n};
QG2SDG(G0 , l);
QG2SDG(G0 , r);
}
return G0 ;
Note that QG2SDG transforms the original graph G0 into its SDG by side-effects.
Thereby, the n-ary tree is transformed into a binary tree similar to the procedure
described by Knuth [433, Chap 2.3.2]. Figure 3.20 shows a query graph G, its
tree G0 rooted at e, and its standard decomposition tree.
v(k)
For an efficient access to the number of join trees in some partition TG
in the unranking algorithm, we materialize these numbers. This is done in the
count array. The semantics of a count array [c0 , c1 , . . . , cn ] of a node u with
label ◦v (◦ ∈ {+, ∗}) of the SDG is that u can construct ci different trees in
which leaf v is at level i. Then, the total number of trees for a query can be
computed by summing up all the ci in the count array of the root node of the
decomposition tree.
To compute the count and an additional summand adornment of a node
labeled +v , we use the following lemma.
Lemma 3.3.4 Let G = (V, E) be a query graph with n nodes, v ∈ V such that
G0 = G|V \v is connected, (v, w) ∈ E, and 1 ≤ k < n. Then
v(k) w(i)
X
|TG |= |TG0 |
i≥k−1
3.3. PROBABILISTIC ALGORITHMS 113
This lemma follows from the observation made after the definition of the leaf-
insertion operation.
w(i)
The sets TG0 used in the summands of Lemma 3.3.4 directly correspond
v(k),i v(k),i
to subsets TG (k − 1 ≤ i ≤ n − 2) defined such that T ∈ TG if
v(k)
1. T ∈ TG ,
v(k)
X k v(i) v(k−i)
|TG | = |TG1 | |TG2 |
i
i
This lemma follows from the observation made after the definition of the tree-
merge operation.
w(i)
The sets TG0 used in the summands of Lemma 3.3.5 directly correspond
v(k),i v(k),i
to subsets TG (0 ≤ i ≤ k) defined such that T ∈ TG if
v(k)
1. T ∈ TG ,
Adorn(v)
Input: a node v of the SDG
Output: v and nodes below are adorned by count and summands
Let {w1 , . . . , wn } be the children of v;
switch (n) {
case 0: count(v) := [1]; // no summands for v
case 1:
Adorn(w1 );
assume count(w1 ) = [c10 , . . . , c1m1 ];
count(v) = [0, c1 , . . . , cm1 +1 ] where ck = m 1
P 1
i=k−1 ci ;
summands(v) 0
= [s , . . . , s m 1 +1 ] where s = [s0 , . . . , skm1 +1 ] and
k k
1
ci if 0 < k and k − 1 ≤ i
ski =
0 else
case 2:
Adorn(w1 );
Adorn(w2 );
assume count(w1 ) = [c10 , . . . , c1m1 ];
assume count(w2 ) = [c20 , . . . , c2m2 ];
count(v) = [c0 , . . . , cm1 +m2 ] where
ck = m
P 1 k 1 2 2
i=0 i ci ck−i ; // ci = 0 for i 6∈ {0, . . . , m2 }
0 m +m ] where sk = [sk0 , . . . , skm1 ] and
k 1 2= [s , . . . , s
summands(v) 1 2
ski = i ci ck−i if 0 ≤ k − i ≤ m2
0 else
}
UnrankTreeNoCross(r,v)
Input: a rank r and the root v of the SDG
Output: adorned SDG
let count(v) = [x0 , . . . , xm ];
k := minj r ≤ ji=0 xi ; // efficiency: binary search on materialized sums.
P
r0 := r − k−1
P
i=0 xi ;
UnrankLocalTreeNoCross(v, r0 , k);
e(k)
The following table shows the intervals associated with the partitions TG for
the standard decomposition graph in Figure 3.20:
Partition Interval
e(1)
TG [1, 5]
e(2)
TG [6, 10]
e(3)
TG [11, 15]
e(4)
TG [16, 18]
3.3. PROBABILISTIC ALGORITHMS 115
UnrankingTreeNoCrossLocal(v, r, k)
Input: an SDG node v, a rank r, a number k identifying a partition
Output: adornments of the SDG as a side-effect
Let {w1 , . . . , wn } be the children of v
switch (n) {
case 0:
assert(r = 1 && k = 0);
// no additional adornment for v
case 1:
let count(v) = [c0 , . . . , cn ];
let summands(v) = [s0 , . . . , sn ];
assert(k ≤ n && r ≤ ck );
k1 = minj r ≤ ji=0 ski ;
P
P 1 −1 k
r1 = r − ki=0 si ;
insert-at(v) = k;
UnrankingTreeNoCrossLocal(w1 , r1 , k1 );
case 2:
let count(v) = [c0 , . . . , cn ];
let summands(v) = [s0 , . . . , sn ];
let count(w1 ) = [c10 , . . . , c1n1 ];
let count(w2 ) = [c20 , . . . , c2n2 ];
assert(k ≤ n && r ≤ ck );
k1 = minj r ≤ ji=0 ski ;
P
P 1 −1 k
q = r − ki=0 si ;
k2 = k − k1 ;
(r1 , r2 , a) = UnrankTriplet(q, c1k1 , c2k2 , ki );
α = UnrankDecomposition(a);
merge-using(v) = α;
UnrankingTreeNoCrossLocal(w1 , r1 , k1 );
UnrankingTreeNoCrossLocal(w2 , r2 , k2 );
}
116 CHAPTER 3. JOIN ORDERING
QuickPick(Query Graph G)
Input: a query graph G = ({R1 , . . . , Rn }, E)
Output: a bushy join tree
BestTreeFound = any join tree
while stopping criterion not fulfilled {
E 0 = E;
Trees = {R1 , . . . , Rn };
while (|Trees| > 1) {
choose e ∈ E 0 ;
E 0 − = e;
if (e connects two relations in different subtrees T1 , T2 ∈ Trees) {
Trees -= T1 ;
Trees -= T2 ;
Trees += CreateJoinTree(T1 , T2 );
}
}
Tree = single tree contained in Trees;
if (cost(Tree) < cost(BestTreeFound)) {
BestTreeFound = Tree;
}
}
return BestTreeFound
IterativeImprovementBase(Query Graph G)
Input: a query graph G = ({R1 , . . . , Rn }, E)
Output: a join tree
do {
JoinTree = random tree
JoinTree = IterativeImprovement(JoinTree)
3.3. PROBABILISTIC ALGORITHMS 117
IterativeImprovement(JoinTree)
Input: a join tree
Output: improved join tree
do {
JoinTree’ = randomly apply a transformation to JoinTree;
if (cost(JoinTree’) < cost(JoinTree)) {
JoinTree = JoinTree’;
}
} while (local minimum not reached)
return JoinTree
SimulatedAnnealing(Query Graph G)
Input: a query graph G = ({R1 , . . . , Rn }, E)
Output: a join tree
BestTreeSoFar = random tree;
Tree = BestTreeSoFar;
118 CHAPTER 3. JOIN ORDERING
do {
do {
Tree’ = apply random transformation to Tree;
if (cost(Tree’) < cost(Tree)) {
Tree = Tree’;
} else {
0
with probability e−(cost(T ree )−cost(T ree))/temperature
Tree = Tree’;
}
if (cost(Tree) < cost(BestTreeSoFar)) {
BestTreeSoFar = Tree’;
}
} while (equilibrium not reached)
reduce temperature;
} while (not frozen)
return BestTreeSoFar
Besides the rule set used, the initial temperature, the temperature reduc-
tion, and the definitions of equilibrium and frozen determine the algorithm’s
behavior. For each of them several alternatives have been proposed in the lit-
erature. The starting temperature can be calculated as follows: determine the
standard deviation σ of costs by sampling and multiply it with a constant val-
ue ([747] use 20). An alternative is to set the starting temperature twice the
cost of the first randomly selected join tree [385] or to determine the starting
temperature such that at least 40% of all possible transformations are accepted
[723].
For temperature reduction, we can apply the formula temp∗ = 0.975 [385]
λt
or max(0.5, e− σ ) [747].
The equilibrium is defined to be reached if for example the cost distribution
of the generated solutions is sufficiently stable [747], the number of iterations is
sixteen times the number of relations in the query [385], or number of iterations
is the same as the number of relations in the query [723].
We can establish frozenness if the difference between the maximum and
minimum costs among all accepted join trees at the current temperature equals
the maximum change in cost in any accepted move at the current temperature
[747], the current solution could not be improved in four outer loop iterations
and the temperature has been fallen below one [385], or the current solution
could not be improved in five outer loop iterations and less than two percent of
the generated moves were accepted [723].
Considering databases are used in mission critical applitions. Would you
bet your business on these numbers?
the cheapest is considered even if its cost are higher than the costs of the current
join tree. In order to avoid running into cycles, a tabu set is maintained. It
contains the last join trees generated, and the algorithm is not allowed to visit
them again. This way, it can escape local minima, since eventually all nodes in
the valley of a local minimum will be in the tabu set. The stopping conditions
could be that there ws no improvement over the current best solution found
during the last given number of iterations or if the set neighbors minus the tabu
set is empty (in line (*)).
Tabu Search looks as follows:
TabuSearch(Query Graph)
Input: a query graph G = ({R1 , . . . , Rn }, E)
Output: a join tree
Tree = random join tree;
BestTreeSoFar = Tree;
TabuSet = ∅;
do {
Neighbors = all trees generated by applying a transformation to Tree;
Tree = cheapest in Neighbors \ TabuSet; (*)
if (cost(Tree) < cost(BestTreeSoFar)) {
BestTreeSoFar = Tree;
}
if(|TabuSet| > limit) remove oldest tree from TabuSet;
TabuSet += Tree;
} while (not stopping condition satisfied);
return BestTreeSoFar;
• Chromosome ←→ string
• Gene ←→ character
R2 1
1
R1 2
1 1 1243
R3
3
1 R3 R4 R5
4
R5 R4
R1 R2
The subsequence exchange for the ordered list encoding works as follows.
Assume two individuals with chromosomes u1 v1 w1 and u2 v2 w2 . From these we
generate u1 v10 w1 and u2 v20 w2 , where vi0 is a permutation of the relations in vi
such that the order of their appearence is the same as in u3−i v3−i w3−i . In order
to adapt the subsequence exchange operator to the ordinal number encoding,
we have to require that the vi are of equal length (|v1 | = |v2 |) and occur at the
same offset (|u1 | = |u2 |). We then simply swap the vi . That is, we generate
u1 v2 w1 and u2 v1 w2 .
The subset exchange is defined only for the ordered list encoding. Within
the two chromosomes, we find two subsequences of equal length comprising the
same set of relations. These sequences are then simply exchanged.
3.4.2 AB-Algorithm
The AB-Algorithm was developed by Swami and Iyer [748, 749]. It builds on
the IKKBZ-Algorithm by resolving its limitations. First, if the query graph
is cyclic, a spanning tree is selected. Second, two different cost functions for
joins (join methods) are supported by the AB-Algorithm: nested loop join and
sort merge join. In order to make the sort merge join’s cost model fit the ASI
property, it is simplified. Third, join methods are assigned randomly before
IKKBZ is called. Afterwards, an iterative improvement phase follows. The
algorithm can be formulated as follows:
AB(Query Graph G)
Input: a query graph G = ({R1 , . . . , Rn }, E)
Output: a left-deep join tree
while (number of iterations ≤ n2 ) {
if G is cyclic take spanning tree of G
randomly attach a join method to each relation
JoinTree = result of IKKBZ
while (number of iterations ≤ n2 ) {
apply Iterative Improvement to JoinTree
}
}
return best tree found
larger than in centralized systems [454]. The basic idea is that simulated an-
nealing is called n times with different initial join trees, if n is the number of
relations to be joined. Each join sequence in the set Solutions produced by
GreedyJoinOrdering-3 is used to start an independent run of simulated an-
nealing. As a result, the starting temperature can be decreased to 0.1 times
the cost of the initial plan.
3.4.4 GOO-II
GOO-II appends an Iterative Improvement step to the GOO-Algorithm.
IDP-1({R1 , . . . , Rn }, k)
Input: a set of relations to be joined, maximum block size k
Output: a join tree
for (i = 1; i <= n; ++i) {
BestTree({Ri }) = Ri ;
}
ToDo = {R1 , . . . , Rn };
while (|ToDo| > 1) {
k = min(k, |ToDo|);
for (i = 2; i < k; ++i) {
for all S ⊆ ToDo, |S| = i do {
for all O ⊂ S do {
BestTree(S) = CreateJoinTree(BestTree(S \ O), BestTree(O));
}
}
}
find V ⊂ ToDo, |V | = k
with cost(BestTree(V )) = min{cost(BestTree(W )) | W ⊂ ToDo, |W | = k};
generate new symbol T ;
BestTree({T }) = BestTree(V );
ToDo = (ToDo \ V ) ∪ {T };
for all O ⊂ V do delete(BestTree(O));
}
return BestTree({R1 , . . . , Rn });
IDP-2({R1 , . . . , Rn }, k)
Input: a set of relations to be joined, maximum block size k
Output: a join tree
for (i = 1; i <= n; ++i) {
BestTree({Ri }) = Ri ;
}
ToDo = {R1 , . . . , Rn };
while (|ToDo| > 1) {
// apply greedy algorithm to select a good building block
B = ∅;
for all v ∈ ToDo, do {
B += BestTree({v});
}
do {
find L, R ∈ B
with cost(CreateJoinTree(L,R))
= min{cost(CreateJoinTree(L0 ,R0 )) | L0 , R0 ∈ B};
P = CreateJoinTree(L,R));
B = (B \ {L, R}) ∪ {P };
} while (P involves no more than k relations and |B| > 1);
// reoptimize the bigger of L and R,
// selected in the last iteration of the greedy loop
if (L involves more tables than R) {
ReOpRels = relations involved in L;
} else {
ReOpRels = relations involved in R;
}
P = DP-Bushy(ReOpRels);
generate new symbol T ;
BestTree({T }) = P ;
ToDo = (ToDo \ ReOpRels) ∪ {T };
for all O ⊂ V do delete(BestTree(O));
}
return BestTree({R1 , . . . , Rn });
α(e) to denote the first element of a sequence. We identify single element se-
quences with elements. The function τ retrieves the tail of a sequence, and ⊕
concatenates two sequences. We denote the empty sequence by .
We define the algebraic operators recursively on their input sequences. The
order-preserving join operator is defined as the concatenation of an order-
preserving selection and an order-preserving cross product. For unary oper-
ators, if the input sequence is empty, the output sequence is also empty. For
126 CHAPTER 3. JOIN ORDERING
binary operators, the output sequence is empty whenever the left operand rep-
resents an empty sequence.
The order-preserving join operator is based on the definition of an order-
preserving cross product operator defined as
ˆ ) ⊕ (τ (e )×e
ˆ 2 := (α(e1 )×e
e1 ×e 2 1 ˆ 2)
where
ˆ := if e2 =
e1 ×e2 ˆ
(e1 ◦ α(e2 )) ⊕ (e1 ×τ (e2 )) else
We are now prepared to define the join operation on ordered sequences:
Before introducing the algorithm, let us have a look at the size of the search
space. Since the order-preserving join is associative but not commutative, the
input to the algorithm must be a sequence of join operators or, likewise, a
sequence of relations to be joined. The output is then a fully parenthesized
expression. Given a sequence of n binary associative but not commutative
operators, the number of fully parenthesized expressions is (see [178])
1 if n = 1
P (n) = Pn−1
k=1 P (k)P (n − k) if n>1
applicable-predicates(R, P)
01 B=∅
02 foreach p ∈ P
03 IF (F(p) ⊆ A(R))
04 B+ = p
05 return B
construct-bushy-tree(R, P)
01 n = |R|
02 for i = 1 to n
03 B =applicable-predicates(Ri , P)
04 P =P \B
05 p[i, i] = B
06 s[i, i] = S0 (Ri , B)
07 c[i, i] = C0 (Ri , B)
08 for l = 2 to n
09 for i = 1 to n − l + 1
10 j =i+l−1
11 B = applicable-predicates(Ri...j , P)
12 P =P \B
13 p[i, j] = B
14 s[i, j] = S1 (s[i, j − 1], s[j, j], B)
15 c[i, j] = ∞
16 for k = i to j − 1
17 q = c[i, k] + c[k + 1, j] + C1 (s[i, k], s[k + 1, j], B)
18 IF (q < c[i,j])
19 c[i, j] = q
20 t[i, j] = k
extract-plan(R, t, p)
extract-subplan(R, t, p, i, j)
01 IF (j > i)
02 X = extract-subplan(R, t, p, i, t[i, j])
03 Y = extract-subplan(R, t, p, t[i, j] + 1, j)
04 return X 1̂p[i,j] Y
05 else
06 return σ̂p[i,i] (Ri )
statistics of the result of applying the predicates to the base relation and the
costs for computing these intermediate results, i.e. for retrieving the relevant
part of the base relation and applying the predicates (lines 02-07). Note that
this is not really trivial if there are several index structures that can be applied.
Then computing C0 involves considering different access paths. Since this is an
issue orthogonal to join ordering, we do not detail on it.
After we have the costs and statistics for sequences of length one, we com-
pute the same information for sequences of length two, three, and so on until
n (loop starting at line 08). For every length, we iterate over all subsequences
of that length (loop starting at line 09). We compute the applicable predicates
and the statistics. In order to determine the minimal costs, we have to consider
every possible split point. This is done by iterating the split point k from i to
j − 1 (line 16). For every k, we compute the cost and remember the k that
resulted in the lowest costs (lines 17-20).
The last subroutine takes the relations, the split points (t), and the applica-
ble predicates (p) as its input and extracts the plan. The whole plan is extracted
by calling extract-plan. This is done by instructing extract-subplan to re-
trieve the plan for all relations. This subroutine first determines whether the
plan for a base relation or that of an intermediate result is to be constructed.
In both cases, we did a little cheating here to keep things simple. The plan we
construct for base relations does not take the above-mentioned index structures
into account but simply applies a selection to a base relation instead. Obvi-
ously, this can easily be corrected. We also give the join operator the whole
set of predicates that can be applied. That is, we do not distinguish between
join predicates and other predicates that are better suited for a selection sub-
sequently applied to a join. Again, this can easily be corrected.
Let us have a quick look at the complexity of the algorithm. Given n rela-
tions with m attributes in total and p predicates, we can implement applicable-predicates
in O(pm) by using a bit vector representation for attributes and free variables
and computing the attributes for each sequence Ri , . . . , Rj once upfront. The
latter takes O(n2 m).
The complexity of the routine construct-bushy-tree is determined by the
three nested loops. We assume that S1 and C1 can be computed in O(p), which
is quite reasonable. Then, we have O(n3 p) for the innermost loop, O(n2 ) calls to
applicable-predicates, which amounts to O(n2 pm), and O(n2 p) for calls of
S1 . Extracting the plan is linear in n. Hence, the total runtime of the algorithm
is O(n2 (n + m)p)
In order to illustrate the algorithm, we need to fix the functions S0 , S1 , C0
and C1 . We use the simple cost function Cout . As a consequence, the array s
simply stores cardinalities, and S0 has to extract the cardinality of a given base
relation and multiply it by the selectivities of the applicable predicates. S1 mul-
tiplies the input cardinalities with the selectivities of the applicable predicates.
We set C0 to zero and C1 to S1 . The former is justified by the fact that every
relation must be accessed exactly once and hence, the access costs are equal in
130 CHAPTER 3. JOIN ORDERING
s
200
1
1
20
After initilization, the array c has 0 everywhere in its diagonal and the array p
empty sets.
For l = 2, the algorithm produces the following values:
Collecting all the above t[i, j] values leaves us with the following array as
input for extract-plan:
i\j 1 2 3 4
1 1 1 1
2 2 3
3 3
4
The function extract-plan merely calls extract-subplan. For the latter,
we give the call hierarchy and the result produced:
000 extract-plan(. . ., 1, 4)
100 extract-plan(. . ., 1, 1)
200 extract-plan(. . ., 2, 4)
210 extract-plan(. . ., 2, 3)
211 extract-plan(. . ., 2, 2)
212 extract-plan(. . ., 3, 3)
210 return (R2 1̂true R3 )
220 extract-plan(. . ., 4, 4)
200 return ((R2 1̂true R3 )1̂p3,4 R4 )
000 return (R1 1̂p1,2 ∧p1,4 ((R2 1̂true R3 )1̂p3,4 R4 ))
The total cost of this plan is c[1, 4] = 43.
How can we judge the complexity of a single instance of a join ordering prob-
lem? Using standard complexity theory, for single problem instances we easily
derive an algorithm that works in Θ(1). Hence, we must define other complexity
measures. Consider our introductory join ordering problem. A simple greedy
algorithm that orders relations according to their cardinality produces an op-
timal solution for it. Hence, one possibility to define the problem complexity
would be how far a solution produced by typical heuristics for join ordering
differ from the optimal solution. Another possibility is to use randomized al-
gorithms like iterative improvement of simulated annealing and see how far the
plans generated by them deviate from the optimal plan. These approaches have
the problem that the results may depend on the chosen algorithm. This can
be avoided by using the following approach. For each join ordering problem
instance, we compute the fraction of good plans compared to all plans. There-
for, we need a measure of “good”. Typical examples thereof would be to say a
plan is “good” if it does not deviate more than 10% or a factor of two from the
optimal plan.
If these investigations were readily available, there are certain obvious ben-
efits [438]:
1. The designer of an optimizer can classify queries such that heuristics are
applied where they guarantee success; cases where they are bound to fail
can be avoided. Furthermore, taking into account the vastly different run
time of the different join ordering heuristics and probabilistic optimization
procedures, the designer of an optimizer can choose the method that
achieves a satisfactory result with the least effort.
2. The developer of search procedures and heuristics can use this knowl-
edge to design methods solving hard problems (as exemplified for graph
coloring problems [370]).
The kind of investigation presented in this section first started in the context
of artificial intelligence where a paper by Cheeseman, Kanefsky, and Taylor
[138] spurred a whole new branch of research where the measures to judge
the complexity of problem instances was investigated for many different NP-
complete problems like satisfiability [138, 181, 277, 521], graph coloring [138],
Hamiltonian circuits [138], traveling salesman [138], and constraint satisfaction
[805].
We only present a small fraction of all possible investigations. The restric-
tions are that we do not consider all parameters that possibly influence the
problem complexity, we only consider left-deep trees, and we restrict ourselves
to the cost function Chj . The join graphs are randomly generated. Starting
with a circle, we randomly added edges until a clique is reached. The read-
er is advised to carry out his or her own experiments. Therefor, the following
pointer into the literature might be useful. Lanzelotte and Valduriez provide an
3.6. CHARACTERIZING SEARCH SPACES 133
object-oriented design for search strategies [452]. This allows easy modification
and even the exchange of the plan generator’s search strategy.
first few joins is small regardless of the connectivity, there is a lower limit to the
number of joined relations required to arrive at the critical intermediate result
size. If the connectivity is larger, this point is reached earlier, but there exists
a lower limit on the connectivity where this point is reached. The reason for
this lower limit is that the number of selectivities involved in the joins remains
small for the first couple of relations, independent of their connectivity. These
lines of argument explain subsequent findings, too.
The reader should be aware of the fact that the number of relations joined is
quite small (10) in our experiments. Further, as observed by several researchers,
if the number of joins increases, the number of “good” plans decreases [257, 745].
That is, increasing the number of relations makes the join ordering problem
more difficult.
Heuristics
For analyzing the influence of the parameters on the performance of heuristics,
we give the figures for four different heuristics. The first two are very simple.
The minSel heuristic selects those relations first of which incident join edges
exhibit the minimal selectivity. The recMinRel heuristic chooses those relations
first which result in the smallest intermediate relation.
We also analyzed the two advanced heuristics IKKBZ and RDC . The IKKBZ
heuristic [443] is based on an optimal join ordering procedure [377, 443] which
is applied to the minimal spanning tree of the join graph where the edges are
labeled by the selectivities. The family of RDC heuristics is based on the rela-
tional difference calculus as developed in [358]. Since our goal is not to bench-
mark different heuristics in order to determine the best one, we have chosen
the simplest variant of the family of RDC based heuristics. Here, the relations
are ordered according to a certain weight whose actual computation is—for
the purpose of this section—of no interest. The results of the experiments are
presented in Figure 3.30.
On a first glance, these figures look less regular than those presented so far.
This might be due to the non-stable behavior of the heuristics. Nevertheless,
we can extract the following observations. Many curves exhibit a peak at a
certain connectivity. Here, the heuristics perform worst. The peak connectivity
is dependent on the selectivity size but not as regular as in the previous curves.
Further, higher selectivities flatten the curves, that is, heuristics perform better
at higher selectivities.
Of course, if all local minima are of about the same cost, we do not have to
worry, otherwise we do. It would be very interesting to know the percentage of
local minima that are close to the global minima.
Concerning the second property, we first have to define the connection cost.
Let a and b be two nodes and P be the set of all paths from a to b. The
connection cost of a and b is then defined as minp∈P maxs∈p {cost(s)|s 6= a, s 6=
b}. Now, if the connection costs are high, we know that if we have to travel
from one local minima to another, there is at least one node we have to pass
which has high costs. Obviously, this is bad for our probabilistic procedures.
Ioannidis and Kang [386] call a search graph that is favorable with respect to
the two properties a well . Unfortunately, investigating these two properties
of real search spaces is rather difficult. However, Ioannidis and Kang, later
supported by Zhang, succeeded in characterizing cost wells in random graphs
[386, 387]. They also conclude that the search space comprising bushy trees is
better w.r.t. our two properties than the one for left-deep trees.
3.7 Discussion
Choose one of dynamic programming, memoization, permutations as the core
of your plan generation algorithm and extend it with the rest of book. ToDo
136 CHAPTER 3. JOIN ORDERING
3.8 Bibliography
ToDo: Oezsu, Meechan [563, 564]
Chapter 4
In this chapter we go down to the storage layer and discuss leaf nodes of query
execution plans and plan fragments. We briefly recap some notions, but reading
a book on database implementation might be helpful [347, 270]. Although
alternative storage technologies exist and are being developed [653], databases
are mostly stored on disks. Thus, we start out by introducing a simple disk
model to capture I/O costs. Then, we say some words about database buffers,
physical data organization, slotted pages and tuple identifiers (TIDs), physical
record layout, physical algebra, and the iterator concept. These are the basic
notions in order to start with the main purpose of this section: giving an
overview over the possibilities available to structure the low level parts of a
physical query evaluation plan. In order to calculate the I/O costs of these plan
fragments, a more sophisticated cost model for several kinds of disk accesses is
introduced.
137
138CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
arm spindle
arm head
assembly sector track
platter
head
arm
arm
pivot
cylinder
inner sectors. The highest density (e.g. in bits per centimeter) at which bits
can be separated is fixed for a given disk. For storing 512 B, this results in a
minimum sector length which is used for the tracks of the innermost cylinder.
Thus, since sectors on outer tracks are longer, storage capacity is wasted there.
To overcome this problem, disks have a varying number of sectors per track.
(This is where the picture lies.) Therefore, the cylinders are organized into
zones. Every zone contains a fixed number of consecutive cylinders, each having
a fixed number of sectors per track. Between zones, the number of sectors per
track varies. Outer zones have more sectors per track than inner zones. Since
the platters rotate with a fixed angular speed, sectors of outer cylinders can be
read faster than sectors of inner cylinders. As a consequence, the throughput
for reading and writing outer cylinders is higher than for inner cylinders.
Assume that we sequentially read all the sectors of all tracks of some con-
secutive cylinders. After reading all sectors of some track, we must proceed to
the next track. If it is contained in the same cylinder, then we must (simply)
use another head: a head switch occurs. Due to calibration, this takes some
time. Thus, if all sectors start at the same angular position, we come too late
to read the first sector of the next track and have to wait. To avoid this, the
angular start positions of the sectors of tracks in the same cylinder are skewed
such that this track skew compensates for the head switch time. If the next
track is contained in another cylinder, the heads have to switch to the next
cylinder. Again, this takes time and we miss the first sector if all sectors of a
surface start at the same angular positions. Cylinder skew is used such that
the time needed for this switch does not make us miss to start reading the next
sector. In general, skewing works in only one direction.
A sector can be addressed by a triple containing its cylinder, head (surface),
and sector number. This triple is called the physical address of a sector. How-
ever, disks are accessed using logical addresses. These are called logical block
numbers (LBN) and are consecutive numbers starting with zero. The disk in-
ternally maps LBNs to physical addresses. This mapping is captured in the
following table:
4.1. DISK DRIVE 139
SCSI bus
Disk 1
Disk 2
Seek Rotational
Disk 3 latency
Data transfer off mechanism Time
Read service time for disk 1
Read service time for disk 2
2. The disk controller decodes the command and calculates the physical
address.
3. During the seek the disk drive’s arm is positioned such that the accord-
140CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
ing head is correctly placed over the cylinder where the requested block
resides. This step consists of several phases.
4. The disk has to wait until the sector where the requested block resides
comes under the head (rotation latency).
5. The disk reads the sector and transfers data to the host.
Note that the transfers for different read requests are interleaved. This is pos-
sible since the capacity of the SCSI bus is higher than the read throughput of
the disk. Also note that we did not mention the operating system delay and
congestions on the SCSI bus.
Disk drives apply several strategies to accelerate the above-mentioned round-
trip time and access patterns like sequential read. Among them are caching,
ToDo read-ahead, and command queuing. (discuss interleaving?)
The seek and rotation latency times highly depend on the head’s position
on the platter surface. Let us consider seek time. A good approximation of the
seek time where d cylinders have to be travelled is given by
√
c1 + c2 d d <= c0
seektime(d) =
c3 + c4 d d > c0
where the constants ci are disk-specific. The constant c0 indicates the maximum
number of cylinders where no coast takes place: seeking over a distance of more
than c0 cylinders results in a phase where the disk arm moves with maximum
velocity.
For disk accesses, the database system must be able to estimate the time
they take to be executed. First of all, we need the parameters of the disk. It
is not too easy to get hold of them, but we can make use of several tools to
extract them from a given disk [209, 266, 752, 660, 815, 816]. However, then we
have a big problem: when calculating I/O costs, the query compiler has no idea
where the head will be when the query evaluation plan emits a certain read (or
write) command. Thus, we have to find another solution. In the following, we
will discuss a rather simplistic cost model that will serve us to get a feeling for
disk behavior. Later, we develop a more realistic model (Section 4.17).
The solution is rather trivial: we sum up all command sending and inter-
preting times as well the times for positioning (seek and rotation latency) which
4.1. DISK DRIVE 141
form by far the major part. Let us call the result latency time. Then, we assume
an average latency time. This, of course, may result in large errors for a single
request. However, on average, the error can be as “low” as 35% [640]. The next
parameter is the sustained read rate. The disk is assumed to be able to deliver
a certain amount of bytes per second while reading data stored consecutively.
Of course, considering multi-zone disks, we know that this is oversimplified,
but we are still in our simplistic model. Analogously, we have a sustained write
rate. For simplicity, we will assume that this is the same as the sustained read
rate. Last, the capacity is of some interest. A hypothetical disk (inspired by
disks available in 2004) then has the following parameters:
Model 2004
Parameter Value Abbreviated Name
capacity 180 GB Dcap
average latency time 5 ms Dlat
sustained read rate 100 MB/s Dsrr
sustained write rate 100 MB/s Dswr
The time a disk needs to read and transfer n bytes is then approximated by
Dlat + n/Dsrr . Again, this is overly simplistic: (1) due to head switches and
cylinder switches, long reads have lower throughput than short reads and (2)
multiple zones are not modelled correctly. However, let us use this very sim-
plistic model to get some feeling for disk costs.
Database management system developers distinguish between sequential
I/O and random I/O. For sequential I/O, there is only one positioning at the
beginning and then, we can assume that data is read with the sustained read
rate. For random I/O, one positioning for every unit of transfer—typically a
page of say 8 KB—is assumed. Let us illustrate the effect of positioning by a
small example. Assume that we want to read 100 MB of data stored consecu-
tively on a disk. Sequential read takes 5 ms plus 1 s. If we read in blocks of
8 KB where each block requires positioning then reading 100 MB takes 65 s.
Assume that we have a relation of about 100 MB in size, stored on a disk,
and we want to read it. Does it take 1 s or 65 s? If the blocks on which it is
stored are randomly scattered on disk and we access them in a random order,
65 s is a good approximation. So let us assume that it is stored on consecutive
blocks. Assume that we read in chunks of 8 KB. Then,
• other applications,
could move the head away from our reading position. (Congestion on the SCSI
bus may also be problem.) Again, we could be left with 65 s. Reading the
whole relation with one read request is a possibility but may pose problems
to the buffer manager. Fortunately, we can read in chunks much smaller than
100 MB. Consider Figure 4.3. If we read in chunks of 100 8 KB blocks we are
already pretty close to one second (within a factor of two).
142CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
64
32
16
1
1 4 16 64
Figure 4.3: Time to read 100 MB from disk (depending on the number of 8 KB
blocks read at once)
4.1. DISK DRIVE 143
Note that the interleaving of actions does not necessarily mean a negative
impact. This depends on the point of view, i.e. what we want to optimize. If we
want to optimize response time for a single query, then obviously the impact of
concurrent actions is negative. If, however, we want to optimize resource (here:
disk) usage, concurrent actions might help. ToDo?
There are two important things to learn here. First, sequential read is much
faster than random read. Second, the runtime system should secure sequential
read. The latter point can be generalized: the runtime system of a database
management system has, as far as query execution is concerned, two equally
important tasks:
• (asynchronous) prefetching,
• piggy-back scans,
Let us take yet another look at it. 100 MB can be stored on 12800 8 KB
pages. Figure 4.4 shows the time to read n random pages. In our simplistic cost
model, reading 200 pages randomly costs about the same as reading 100 MB
sequentially. That is, reading 1/64th of 100 MB randomly takes as long as
reading the 100 MB sequentially. Let us denote by a the positioning time, s
the sustained read rate, p the page size, and d some amount of consecutively
stored bytes. Let us calculate the break-even point
n ∗ (a + p/s) = a + d/s
n = (a + d/s)/(a + p/s)
= (as + d)/(as + p)
a and s are disk parameters and, hence, fixed. For a fixed d, the break-even
point depends on the page size. This is illustrated in Figure 4.5. The x-axis is
the page size p in multiples of 1 K and the y-axis is (d/p)/n for d = 100 MB.
For sequential reads, the page size does not matter. (Be aware that our
simplistic model heavily underestimates sequential reads.) For random reads,
144CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
2.5
1.5
0.5
0
0 100 200 30
512
256
128
64
32
16
8
1 2 4 8
Figure 4.5: Break-even point in fraction of total pages depending on page size
146CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
Theorem 4.1.1 (Qyang) If the disk arm has to travel over a region of C
cylinders, it is positioned on the first of the C cylinders and has to stop at s − 1
of them, then sDseek (C/s) is an upper bound for the seek time.
Given the page identifier, the buffer frame is found by a hashtable lookup.
Accesses to the hash table and the buffer frame need to be synchronized. Before
accessing a page in the buffer, it must be fixed. These points account for the
fact that the costs of accessing a page in the buffer are, therefore, greater than
zero.
Partition Relation
1 1
contains fragmented
N N
Segment N mapped M Fragment
1
N
consists of contains
N
Page
1
stores
N M
N represented 1 Tuple
Record
This query is valid only if the database item (relation) Student exists. It could
4.3. PHYSICAL DATABASE ORGANIZATION 149
2
This might not be true. Alternatively, the pages of a partition can be consecutively
numbered.
3
Extents are not shown in Fig. 4.6. They can be included between Partitions and Segments.
150CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
273 2
273 827
827 1
273 2
273 827
827 1
be cheaper than the first solution, there is still a non-negligible cost associated
with an attribute access.
The third physical record layout can be used to represent compressed at-
tribute values and even compressed length information for parts of varying size.
Note that if fixed size fields are compressed, their length becomes varying. Ac-
cess to an attribute now means decompressing length/offset information and
decompressing the value itself. The former is quite cheap: it boils down to an
indirect memory access with some offset taken from a matrix [799]. The cost
of the latter depends on the compression scheme used. It should be clear that
accessing an attribute value now is even more expensive. To make the costs of
an attribute access explicit was the sole purpose of this small section.
Remark Westmann et al. discuss an efficient implementation of compres-
sion and evaluate its performance [799]. Yiannis and Zobel report on experi-
ments with several compression techniques used to speed up the sort operator.
For some of them, the CPU usage is twice as large [?].
from Student
where ◦ denotes tuple concatenation and the ai must not be in A(e). (Remem-
ber that A(e) is the set of attributes produced by e.) Every input tuple t is
extended by new attributes ai , whose values are computed by evaluating the
expression ei , in which free variables (attributes) are bound to the attributes
(variables) provided by t.
The above problem can now be solved by
select name
from Student
where age > 30
The plan
Πn (χn:s.name (σa>30 (χa:s.age (Student[s]))))
does not. In the first plan the name attribute is only accessed for those students
with age over 30. Hence, it should be cheaper to evaluate. If the database
management system does not support this selective access mechanism, we often
find the scan enhanced by a list of attributes that is projected and included in
the resulting tuple stream.
In order to avoid copying attributes from their storage representation to
some main memory representation, some database management systems apply
another mechanism. They support the evaluation of some predicates directly
on the storage representation. These are boolean expressions consisting of sim-
ple predicates of the form Aθc for attributes A, comparison operators θ, and
constants c. Instead of a constant, c could also be the value of some attribute
or expression thereof given that it can be evaluated before the access to A.
Predicates evaluable on the disk representation are called SARGable where
SARG is an acronym for search argument. Note that SARGable predicates
may also be good for index lookups. Then they are called index SARGable.
In case they can not be evaluated by an index, they are called data SARGable
[672, 750, 275].
Since relation or segment scans can evaluate predicates, we have to extend
our notation for scans. Let I be a database item like a relation or segment.
Then, I[v; p] scans I, binds each item in I successively to v and returns only
those items for which p holds. I[v; p] is equivalent to σp (I[v]), but cheaper to
evaluate. If p is a conjunction of predicates, the conjuncts should be ordered
such that the attribute access cost reductions described above are reflected
(for details see Chapter ??). Syntactically, we express this by separating the
predicates by a comma as in Student[s; age > 30, name like ‘%m%0 ]. If we want
to make a distinction between SARGable and non-SARGable predicates, we
write I[v; ps ; pr ], with ps being the SARGable predicate and pr a non-SARGable
predicate. Additional extensions like a projection list are also possible.
4
The page on which the physical record resides must be fixed until all attributes are loaded.
Hence, an earlier point in time might be preferable.
4.9. TEMPORAL RELATIONS 155
It can be evaluated by
Dept[d] 1nl
e.dno=d.dno σe.age>30∧e.age<40 (Emp[d]).
Since the inner (right) argument of the nested-loop join is evaluated several
times (once for each department), materialization may pay off. The plan then
looks like
Dept[d] 1nl
e.dno=d.dno Tmp(σe.age>30∧e.age<40 (Emp[d])).
2. Dept[d] 1nl
e.dno=d.dno Rtmp [e]
The disk costs of writing and reading temporary relations can be calculated
using the considerations of Section 4.1.
select *
from TABLE(Primes(1,100)) as p
returns all primes between 1 and 100. The attribute names of the resulting
relation are specified in the declaration of the table function. Let us assume
that for Primes a single attribute prime is specified. Note that table func-
tions may take parameters. This does not pose any problems, as long as we
156CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
know that Primes is a table function and we translate the above query into
Primes(1, 100)[p]. Although this looks exactly like a table scan, the implemen-
tation and cost calculations are different.
Consider the following query where we extract the years in which we expect
a special celebration of Anton’s birthday.
select *
from Friends f,
TABLE(Primes(
CURRENT YEAR, EXTRACT(YEAR FROM f.birthday) + 100)) as p
where f.name = ‘Anton’
The result of the table function depends on our friend Anton. Hence, a join
is no solution. Instead, we have to introduce a new kind of join, the d-join
where the d stands for dependent. It is defined as
χb:EXT RACT Y EAR(f.birthday)+100 (σf.name=‘Anton0 (Friends[f ])) < Primes(c, b)[p] >
where we assume that some global entity c holds the value of CURRENT YEAR.
Let us do the above query for all friends. We just have to drop the where
clause. Obviously, this results in many redundant computations of primes. At
the SQL level, using the birthday of the youngest friend is beneficial:
select *
from Friends f,
TABLE(Primes(
CURRENT YEAR, (select max(birthday) from Friends) + 100)) as p
where p.prime ≥ f.birthday
At the algebraic level, this kind of optimizations will be considered in Section ??.
Things can get even more involved if table functions can consume and pro-
ToDo? duce relations, i.e. arguments and results can be relations.
Little can be said about the disk costs of table functions. They can be zero
if the function is implemented such that it does not access any disks (files stored
there), but it can also be very expensive if large files are scanned each time it is
called. One possibility is to let the database administrator specify the numbers
the query optimizer needs. However, since parameters are involved, this is
not really an easy task. Another possibility is to measure the table function’s
behavior whenever it is executed, and learn about its resource consumption.
4.11 Indexes
There exists a plethora of different index structures. In the context of relational
database management systems, the most versatile and robust index is the B-
tree or variants/improvements thereof (e.g. []). It is implemented in almost
4.11. INDEXES 157
If there exists a unique index on the key attribute eno, we can first access the
index to retrieve the TID of the employee tuple satisfying eno = 1077. Another
page access yields the tuple itself which constitutes the result of the query. Let
Empeno be the index on eno, then we can descend the B-tree, using 1077 as the
search key. A predicate that can be used to descend the B-tree or, in general,
governing search within an index structure, is called an index sargable predicate.
For the example query, the index scan, denoted as Empeno [x; eno = 1077],
retrieves a single leaf node entry with attributes eno and TID. Similar to the
regular scan, we assume x to be a variable holding a pointer to this index
entry. We use the notations x.eno and x.TID to access these attributes. To
dereference the TID, we use the map (χ) operator and a dereference function
deref (or ∗ for short). It turns a TID into a pointer in the buffer area. This of
course requires the page to be loaded, if it is not in the buffer yet. The complete
plan for the query is
Πname (χe:∗(x.TID),name:e.name (Empeno [x; eno = 1077]))
where we computed several new attributes with one χ operator. Note that
they are dependent on previously computed attributes and, hence, the order of
evaluation does matter.
We can make the dependency of the map operator more explicit by applying
a d-join. Denote by 2 an operator that returns a single empty tuple. Then
Πname (Empeno [x; eno = 1077] < χe:∗(x.TID),name:e.name (2) >)
is equivalent to the former plan. Joins and indexes will be discussed in Sec-
tion 4.14.
A range query like
select name
from Emp
where age ≥ 25 and age ≤ 35
5
Of course, any degree of clusteredness may occur and has to be taken into account in cost
calculations.
4.12. SINGLE INDEX ACCESS PATH 159
This alternative might turn out to be more efficient since sorting on an attribute
with a dense domain can be implemented efficiently. (We admit that in the
above example this is not worth considering.) There is another important
application of this technique: XQuery often demands output in document order.
If this order is destroyed during processing, it must at the latest be restored
when the output it produced [507]. Depending on the implementation (i.e. the
representation of document nodes or their identifiers), this might turn out to
be a very expensive operation.
The fact that index scans on B-trees return their result ordered on the
indexed attributes is also very useful if a merge-join on the same attributes (or
a prefix thereof, see Chapter 23 for further details) occurs. An example follows
later on.
Some predicates are not index SARGable, but can still be evaluated with
the index as in the following query
select name
from Emp
where age ≥ 25 and age ≤ 35 and age 6= 30
Some index scan implementations allow exclusive bounds for start and stop
conditions. With them, the query
select name
from Emp
where age > 25 and age < 35
Πname (χt:x.TID,e:∗t,name:e.name (Empage [x; 25 ≤ age; age ≤ 35; age 6= 25, age 6= 35]))
select name
from Emp
where age ≤ 20
we descend the B-tree to the “leftmost” page, i.e. the page containing the
smallest key value, and then proceed scanning leaf pages until we encounter the
key 20.
Having neither a start nor stop condition is also quite useful. The query
select count(*)
from Emp
can be evaluated by counting the entries in the leaf pages of a B-tree. Since
a B-tree typically occupies far fewer pages than the original relation, we have
a viable alternative to a relation scan. The same applies to the aggregate
functions sum and avg. The other aggregate functions min and max can be
evaluated much more efficiently by descending to the leftmost or rightmost leaf
page of a B-tree. This can be used to answer queries like
select min/max(salary)
from Emp
select name
from Emp
where salary = (select max(salary)
from Emp)
It can be evaluated by first computing the maximum salary and then retrieving
the employees earning this salary. This requires two descendants into the B-
tree, while obviously one is sufficient. Depending on the implementation of the
index (scan), we might be able to perform this optimization.
Further, the result of an index scan, whether it uses start and/or stop con-
ditions or not, is always sorted on the key. This property can be useful for
queries with no predicates. If we have neither a start nor a stop condition, the
resulting scan is called full index scan. As an example consider the query
select salary
from Emp
order by salary
Empsalary
5. a projection list.
A projection list has entries of the form a : x.b for attribute names a and b and
x being the name of the variable for the index entry. a : x.a is also allowed and
often abbreviated as a. We also often summarize start and stop conditions into
a single expression like in 25 ≤ age ≤ 35.
For a full index specification, we list all items in the subscript of the index
name separated by a semicolon. Still, we need some extensions to express the
queries with aggregation. Let a and b be attribute names, then we allow entries
of the form b : aggr(a) in the projection list and start/stop conditions of the
form min/max(a). The latter tells us to minimize/maximize the value of the
indexed attribute a. Only a complete enumeration gives us the full details. On
the other hand, extracting start and stop conditions and residual predicates
from a given boolean expression is rather simple. Hence, we often summarize
these three under a single predicate. This is especially useful when talking
about index scans in general. If we have a full index scan, we leave out the
predicate. We use a star ‘*’ as an abbreviated projection list that projects all
attributes of the index. (So far, these are the key attribute and the TID.) If
the projection list is empty, we assume that only the variable/attribute holding
the pointer to the index entry is projected.
Using this notation, we can express some plan fragments. These fragments
are complete plans for the above queries, except that the final projection is not
present. As an example, consider the following fragment:
All the plan fragments seen so far are examples of access paths. An access
path is a plan fragment with building blocks concerning a single database item.
4.12. SINGLE INDEX ACCESS PATH 163
Hence, every building block is an access path. The above plans touch two
database items: a relation and an index on some attribute of that relation.
If we say that an index concerns the relation it indexes, such a fragment is an
access path. For relational systems, the most general case of an access path uses
several indexes to retrieve the tuples of a single relation. We will see examples
of these more complex access paths in the following section. An access to the
original relation is not always necessary. A query that can be answered solely
by accessing indexes is called an index only query.
A query with in like
select name
from Emp
where age in {28, 29, 31, 32}
can be evaluated by taking the minimum and the maximum found in the left-
hand side of in as the start and stop conditions. We further need to construct
a residual predicate. The residual predicate can be represented either as age =
28 ∨ age = 29 ∨ age = 31 ∨ age = 32 or as age 6= 30.
An alternative is to use a d-join. Consider the example query
select name
from Emp
where salary in {1111, 11111, 111111}
Here, the numbers are far apart and separate index accesses might make sense.
Therefore, let us create a temporary relation Sal equal to {[s : 1111], [s :
11111], [s : 111111]}. When using it, the access path becomes
Some B-tree implementations allow efficient searches for multiple ranges and
implement gap skipping [31, 32, 144, 275, 276, 407, 467]. Gap skipping, some-
times also called zig-zag skipping, continues the search for keys in a new key
range from the latest position visited. The implementation details vary but
the main idea of it is that after one range has been completely scanned, the
current (leaf) page is checked for its highest key. If it is not smaller than the
lower bound of the next range, the search continues in the current page. If it
is smaller than the lower bound of the next range, alternative implementations
are described in the literature. The simplest is to start a new search from the
root for the lower bound. Another alternative uses parent pointers to go up a
page as long as the highest key of the current page is smaller than the lower
bound of the next range. If this is no longer the case, the search continues
downwards again.
Gap skipping gives even more opportunities for index scans and allows effi-
cient implementations of various index nested loop join strategies.
index scan on such an index. Having more attributes in the index makes it
more probable that queries are index-only.
Besides a full index scan, the index can be descended to directly search for
the desired tuple(s). Let us take a closer look at this possibility.
If the search predicate is of the form
k1 = c1 ∧ k2 = c2 ∧ . . . ∧ kj = cj
for some constants ci and some j <= n, we can generate the start and stop
condition
k1 = c1 ∧ . . . ∧ kj = cj .
This simple approach is only possible if the search predicates define values for
all search key attributes, starting from the first search key and then for all
keys up to the j-th search key with no key attribute unspecified in between.
Predicates concerning the other key attributes after the first non-specified key
attribute and the additional data attributes only allow for residual predicates.
This condition is often not necessary for multi-dimensional index structures,
whose discussion is beyond the book.
With ranges things become more complex and highly dependent on the
implementation of the facilities of the B-tree. Consider a query predicate re-
stricting key values as follows
k1 = c1 ∧ k2 ≥ c2 ∧ k3 = c3
a1 ≤ k1 ≤ b1 ∧ . . . ∧ aj ≤ kj ≤ bj
a2 ≤ k2 ≤ b2 ∧ . . . ∧ aj ≤ kj ≤ bj
as the residual predicate. If for some search key attribute kj the lower bound aj
is not specified, the start condition cannot contain kj and any kj+i . If for some
search key attribute kj the upper bound bj is not specified, the stop condition
cannot contain kj and any kj+i .
Two further enhancements of the B-tree functionality possibly allow for
alternative start/stop conditions:
So far, we are only able to exploit query predicates which specify value
ranges for a prefix of all key attributes. Consider querying a person on his/her
height and his/her hair color: haircolor = ’blond’ and height between
180 and 190. If we have an index on sex, haircolor, height, this index
cannot be used by means of the techniques described so far. However, since
there are only the two values male and female available for sex, we can rewrite
the query predicate to (sex = ’m’ and haircolor = ’blond’ and height
between 180 and 190) or (sex = ’f’ and haircolor = ’blond’ and height
between 180 and 190) and use two accesses to the index. This approach works
fine for attributes with a small domain and is described by Antoshenkov [32].
(See also the previous section for gap skipping.) Since the possible values for
key attributes may not be known to the query optimizer, Antoshenkov goes
one step further and shifts the construction of search ranges to index scan time.
Therefore, the index can be provided with a complex boolean expression which
is then refined (rewritten) as soon as search key values become known. Search
ranges are then generated dynamically, and gap skipping is applied to skip the
intervals between the qualifying ranges during the index scan.
select *
from Camera
where megapixel > 5 and distortion < 0.05
and noise < 0.01
and zoomMin < 35 and zoomMax > 105
We assume that on every attribute used in the where clause there exists an
index. Since the predicates are conjunctively connected, we can use a technique
called index and-ing. Every index scan returns a set (list) of tuple identifiers.
These sets/lists are then intersected. This operation is also called And merge
[485]. Using index and-ing, a possible plan is
((((
Cameramegapixel [c; megapixel > 5; TID]
∩
Cameradistortion [c; distortion < 0.05; TID])
∩
Cameranoise [c; noise < 0.01; TID])
∩
CamerazoomMin [c; zoomMin < 35; TID])
∩
CamerazoomMax [c; zoomMax > 105; TID])
166CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
This query can be evaluated by scanning the index on age and then eliminating
all employees with yearsOfEmployment = 10:
Empage [c; age ≥ 65; TID]\ EmpyearsOfEmployment [c; yearsOfEmployment 6= 10; TID]
Let us call the application of set difference on index scan results index differ-
encing.
Some predicates might not be very restrictive in the sense that more than
half the index has to be scanned. By negating these predicates and using
index differencing, we can make sure that at most half of the index needs to be
scanned. As an example consider the query
select *
from Emp
where yearsOfEmployment ≤ 5
and age ≤ 65
EmpyearsOfEmployment [c; yearsOfEmployment ≤ 5; TID] \ Empage [c; age > 65; TID]
becomes
where 2 returns a single empty tuple. Assume that every tuple contains an
attribute TID containing its TID. This attribute does not have to be stored
explicitly but can be derived. Then, we have the following alternative access
path for the join (ignoring projections):
For the join operator, the pointer-based join implementation developed in the
context of object-oriented databases may be the most efficient way to evaluate
the access path [695]. Obviously, sorting the result of the index scan on the
tuple identifiers can speed up processing since it turns random into sequential
I/O. However, this destroys the order on the key which might itself be useful
later on during query processing or required by the query7 . Sorting the tuple
ToDo identifiers was proposed by, e.g., Yao [836], Makinouchi, Tezuka, Kitakami, and
Adachi in the context of RDB/V1 [496]. The different variants (whether or not
and where to sort, join order) can now be transparently determined by the plan
generator: no special treatment is necessary. Further, the join predicates can
not only be on the tuple identifiers but also on key attributes. This often allows
to join with other than the indexed relations (or their indexes) before accessing
the relation.
Rosenthal and Reiner proposed to use joins to represent access paths with
indexes [629]. This approach is very elegant since no special treatment for index
processing is required. However, if there are many relations and indexes, the
search space might become very large, as every index increases the number
of joins to be performed. This is why Mohan, Haderle, Wang, and Cheng
abondoned this approach and sketched a heuristics which determines an access
path in case multiple indexes on a single table exist [532].
The query
select name,age
from Person
where name like ’R%’ and age between 40 and 50
is an index only query (assuming indexes on name and age) and can be trans-
lated to
Πname,age (
Empage [a; 40 ≤ age ≤ 50; TIDa, age]
1TIDa=TIDn
Empname [n; name ≥0 R0 ; name ≤0 R0 ; TIDn, name])
Let us now discuss the former of the two issues mentioned in the section’s
introduction. The query
select *
from Emp e, Dept d
where e.name = ‘Maier’ and e.dno = d.dno
If there are indexes on Emp.name and Dept.dno, we can replace σe.name=0 Maier0 (Emp[e])
by an index scan as we have seen previously:
Here, A(Emp) : t.∗ abbreviates access to all Emp attributes. This especially
includes dno:t.dno. (Strictly speaking, we do not have to access the name
attribute, since its value is already known.)
As we have also seen, an alternative is to use a d-join instead:
Let us abbreviate Empname [x; name = ‘Maier0 ] by Ei and χt:∗(x.T ID),A(e)t.∗ (2) by
Ea .
Now, for any e.dno, we can use the index on Dept.dno to access the ac-
cording department tuple:
Note that the inner expression Deptdno [y; y.dno = dno] contains the free variable
dno, which is bound by Ea . Dereferencing the TID of the department results
in the following algebraic modelling which models a complete index nested loop
join:
Ei < Ea >< Deptdno [y; y.dno = dno; dTID : y.TID] >< χu:∗dTID,A(Dept)u.∗ (2) >
Let us abbreviate Deptdno [y; y.dno = dno; dTID : y.TID] by Di and χu:∗dTID,A(Dept)u.∗ (2)
by Da . Fully abbreviated, the expression then becomes
• we can sort the result of the expression Ei < Ea > on dno for two reasons:
– If there are duplicates for dno, i.e. there are many employees named
“Maier” in each department, then this guarantees that no index page
(of the index Dept.dno) has to be read more than once.
– If additionally Dept.dno is a clustered index or Dept is an index-only
table contained in Dept.dno, then large parts of the random I/O can
be turned into sequential I/O.
170CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
– If the result of the inner is materialized (see below), then only one
result needs to be stored. Note that sorting is not necessary, but
grouping would suffice to avoid duplicate work.
• We can sort the result of the expression Ei < Ea >< Di > on dTID for
the same reasons as mentioned above for sorting the result of Ei on TID.
EX The reader is advised to explicitly write down the alternatives. Another exercise
is to give plan alternatives for the different cases of DB2’s Hybrid Join [275]
which can now be decomposed into primitives like relation scan, index scan,
d-join, sorting, TID dereferencing, and access to a unique index (see below).
Let us take a closer look at materializating the result of the inner of the d-
join. IBM’s DB2 for MVS considers temping (i.e. creating a temporary relation)
the inner if it is an index access [275]. Graefe provides a general discussion
on the subject [298]. Let us start with the above example. Typically, many
employees will work in a single department and possibly several of them are
called “Maier”. For everyone of them, we can be sure that there exists at most
one department. Let us assume that referential integrity has been specified.
Then, there exists exactly one department for every employee. We have to find
a way to rewrite the expression
such that the mapping dno−−→dTID is explicitly materialized (or, as one could
also say, cached ). For this purpose, Hellerstein and Naughton introduced a
modified version of the map operator that materializes its result [355]. Let us
denote this operator by χmat . The advantage of using this operator is that it
is quite general and can be used for different purposes (see e.g. [88], Chap. ??,
Chap. ??). Since the map operator extends a given input tuple by some at-
tribute values, which must be computed by an expression, we need one to
express the access to a unique index. For our example, we write
IdxAccDept
dno [y; y.dno = dno]
If we further assume that the outer (Ei < Ea >) is sorted on dno, then
it suffices to remember only the TID for the latest dno. We define the map
operator χmat,1 to do exactly this. A more efficient plan could thus be
select *
from Emp e, Wine w
where e.yearOfBirth = w.year
If we have no indexes, we can answer this query by a simple join where we only
have to decide the join method and which of the relations becomes the outer and
which the inner. Assume we have only wines from a few years. (Alternatively,
some selection could have been applied.) Then it might make sense to consider
the following alternative:
However, the relation Emp is scanned once for each Wine tuple. Hence, it might
make sense to materialize the result of the inner for every year value of Wine
if we have only a few year values. In other words, if we have many duplicates
for the year attribute of Wine, materialization may pay off since then we have
to scan Emp only once for each year value of Wine. To achieve caching of the
inner, in case every binding of its free variables possibly results in many tuples,
requires a new operator. Let us call this operator memox and denote it by
M [298, 88]. For the free variables of its only argument, it remembers the set
of result tuples produced by its argument expression and does not evaluate it
again if it is already cached. Using memox, the above plan becomes
It should be clear that for more complex inners, the memox operator can be
applied at all branches, giving rise to numerous caching strategies. Analogously
to the materializing map operator, we are able to restrict the materialization
to the results for a single binding for the free variables if the outer is sorted (or
grouped) on the free variables:
Sortw.yearOfBirth (Wine[w])
< M1 (EmpyearOfBirth [x; x.yearOfBirth = w.year] < χe:∗(x.TID),A(Emp):∗e (2) >) >
merge
EmpyearOfBirth [x] 1x.yearOfBirth=y.year Wineyear [y]
This example makes clear that the order provided by an index scan can be used
to speed up join processing. After evaluating this plan fragment, we have to
access the actual Emp and Wine tuples. We can consider zero, one, or two sorts
EX on their respective tuple identifiers. If the join is sufficiently selective, one of
these alternatives may prove more sufficient than the ones we have considered
so far.
Let R be the relation for which we have to retrieve the tuples. Then we use the
following abbreviations
We assume that the tuples are uniformly distributed among the m pages. Then,
each page stores B = N/m tuples. B is called blocking factor .
Let us consider some borderline cases. If k > N − N/m or m = 1, then all
pages are accessed. If k = 1 then exactly one page is accessed. The answer to
the general question will be expressed in terms of buckets (pages in the above
case) and items contained therein (tuples in the above case). Later on, we will
also use extents, cylinders, or tracks as buckets and tracks or sectors/blocks as
items.
We assume that a bucket contains items. The total number of items will be
N and the number of requested items will be k. The above question can then
be reformulated to how many buckets contain at least one of the k requested
items, i.e. how many qualifying buckets exist. We start out by investigating
the case where the items are uniformly distributed among the buckets. Two
subcases will be distinguished:
We then discuss the case where the items are non-uniformly distributed.
In any case, the underlying access model is random access. For example,
given a tuple identifier, we can directly access the page storing the tuple. Other
access models are possible. The one we will subsequently investigate is sequen-
tial access where the buckets have to be scanned sequentially in order to find
the requested items. After that, we are prepared to develop a model for disk
access costs.
Throughout this section, we will further assume that the probability that
1 N
we request a set with k items is N for all of the k possibilities to select
(k)
8
a k-set. We often make use of established equalities for binomial coefficients.
For convenience, the most frequently used equalities are listed in Appendix D.
8
A k-set is a set with cardinality k.
174CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
The second expression (4.4) is due to Yao, the third (4.5) is due to Waters.
Palvia and March proved both formulas to be equal [568] (see also [35]). The
fraction m = N/n may not be an integer. For these cases, it is advisable to
have a Gamma-function based implementation of binomial coeffcients at hand
(see [597] for details).
Depending on k and n, either the expression of Yao or the one of Waters is
faster to compute. After the proof of the above formulas and the discussion of
some special cases, we will give several approximations for p.
Proof The total number of possibilities to pick the k items from all N items is
N
k . The number of possibilities to pick k items from all items not contained in
a fixed single bucket is N k−n . Hence, the probability p that a bucket does not
N −n
k
p = N
k
(N − n)! k!(N − k)!
=
k!((N − n) − k)! N !
k−1
Y N −n−i
=
N −i
i=0
4.16. COUNTING THE NUMBER OF ACCESSES 175
2
Let us list some special cases:
n=1 k/N
n=N 1
k=0 0
k=1 B/N = (N/m)N = 1/m
k=N 1
We examine a slight generalization of the first case in more detail. Let N items
be distributed over N buckets such that every bucket contains exactly one item.
Further let us be interested in a subset of m buckets (1 ≤ m ≤ N ). If we pick
k items, then the number of buckets within the subset of size m that qualify is
k
mY1N (k) = m (4.6)
N
In order to see that the two sides are equal, we perform the following calculation:
N −1
Y1N (k) = (1 − k
N
)
k
(N −1)!
k!((N −1)−k)!
= (1 − N!
)
k!(N −k)!
(N − 1)!k!(N − k)!
= (1 − )
N !k!((N − 1) − k)!
N −k
= (1 − )
N
N N −k
= ( − )
N N
N −N +k
=
N
k
=
N
176CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
Since the computation of YnN (k) can be quite expensive, several approxima-
tions have been developed. The first one was given by Waters [791, 792]:
p ≈ (1 − k/N )n
This approximation (also described elsewhere [271, 568]) turns out to be pretty
good. However, below we will see even better approximations.
N,m
For Y n (k) Whang, Wiederhold, and Sagalowicz gave the following ap-
proximation for faster calculation [802]:
m ∗ [ (1 − (1 − 1/m)k )+
(1/(m2 b) ∗ k(k − 1)/2 ∗ (1 − 1/m)k−1 )+
(1.5/(m3 p4 ) ∗ k(k − 1)(2k − 1)/6 ∗ (1 − 1/m)k−1 ) ]
k
plower = (1 − )n
N − n−1
2
k k
pupper = ((1 − ) ∗ (1 − ))n/2
N N −n+1
for n = N/m. Dihr and Saharia claim that the maximal difference resulting
from the use of the lower and the upper bound to compute the number of page
accesses is 0.224—far less than a single page access.
Lemma 4.16.2 Let S be a set with |S| = N elements. Then, the number of
multisets with cardinality k containing only elements from S is
N N +k−1
=
k k
For a proof we just note that there is a bijection between the k-multisets and
the k-subsets of a N + k − 1-set. We can go from a multiset to a set by f with
f ({x1 ≤ . . . ≤ xk }) = {x1 + 0 < x2 + 1 < . . . < xk + (k − 1)} and from a set to a
multiset via g with g({x1 < . . . < xk }) = {x1 − 0 < x2 − 1 < . . . < xk − (k − 1)}.
N,m
Cheungn (k) = m ∗ CheungN
n (k) (4.7)
where
CheungN
n (k) = [1 − p̃] (4.8)
N −n+k−1
k
p̃ = N +k−1
(4.9)
k
k−1
Y N −n+i
= (4.10)
N +i
i=0
n−1
Y N −1−i
= (4.11)
N −1+k−i
i=0
Eq. 4.9 follows from the observation that the probability that some bucket
(N −n+k−1
k )
does not contain any of the k possibly duplicate items is N +k−1 . Eq. 4.10
( k )
follows from
N −n+k−1
k
p̃ = N +k−1
k
(N − n + k − 1)! k!((N + k − 1) − k)!
=
k!((N − n + k − 1) − k)! (N + k − 1)!
(N − n − 1 + k)! (N − 1)!
=
(N − n − 1)! (N − 1 + k)!
k−1
Y N −n+i
=
N +i
i=0
178CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
2
Cardenas discovered a formula that can be used to approximate p̃ [102]:
(1 − n/N )k
As Cheung pointed out, we can use the theorem to derive the number of
distinct items accessed contained in a k-multiset.
Nk
D(N, k) = (4.12)
N +k−1
if the elements in T occur with the same probability in S.
We apply the theorem for the specialQ0 case where every bucket contains exactly
N −1−i −1
one item (n = 1). In this case, i=0 N −1+k−i = NN−1+k . And the number of
N −1 N −1+k−N +1
qualifying buckets is N (1 − N −1+k ) = N ( N −1+k ) = N N +k−1 k
. 2
N
Another way to achieve this formula is the following. There are l pos-
sibilities to pick l different elements out of the N elements in T . In order to
build a k-multiset with l different elements, we mustadditionally choose n − l
N
l
elements from the l elements. Thus, we have l possibilities to
n−l
N
build a k-multiset. The total number of multisets is . Thus we may
l
conclude that
N
l
min(N,k) l
X n−l
D(N, k) = l
l=1
N
l
which can be simplified to the above.
4.16. COUNTING THE NUMBER OF ACCESSES 179
even when computing Y with Eq. 4.5. Nonetheless, for n ≥ 5, the error is
less than two percent. One of the problems when calculating the result of the
left-hand side is that the number of distinct items is not necessarily an integer.
To solve this problem, we can implement all our formulas using the Gamma-
function. But even then a small difference remains.
The approximation given in Theorem 4.16.3 is not too accurate. A better
approximation can be calculated from the probability distribution. Denote by
p(D(N, k) = j) the probability that the number of distinct values if we randomly
select k items with replacement from N given items equals j. Then
X
N k j
p(D(N, k) = j) = j(−1) ((j − l)/N )k
j l
l=0
and thus
min(N,k) X
X N j
D(N, k) = j j(−1)k ((j − l)/N )k
j l
j=1 l=0
This formula is quite intense to calculate. We can derive a very good approx-
imation by the following reasoning. We draw k elements from the set T with
|T | = N elements. Every element from T can be drawn at most k times. We
produce N buckets, one for each element of T . In each bucket, we insert k
copies of the according element from t. Then, a sequence of draws from T
with duplicates can be represented by a sequence of draws without duplicate
by mapping them to different copies. Thus, the first occurrence is mapped to
the first element in the according bucket, the second one to the second copy
and so on. Then, we can apply formula by Waters and Yao to calculate the
number of buckets (and hence elements of T ) hit:
N k,k
D(N, k) = Y N (k)
Since the approximation is quite accurate and we already know how to efficiently
calculate this formula, this is our method of choice.
We now turn to relax the first assumption. Christodoulakis models the distri-
bution by m numbers ni (for 1 ≤ i ≤ m) if there are m buckets. Each ni equals
the number of records in some bucket i [151]. Luk proposes Zipfian record
distribution [492]. However, Ijbema and Blanken say that Water and Yao’s
formula is still better, as Luk’s formula results in too low values [379]. They all
come up with the same general formula presented below. Vander Zander, Tay-
lor, and Bitton [843] discuss the problem of correlated attributes which results
in some clusteredness. Zahorjan, Bell, and Sevcik discuss the problem where
every item is assigned its own access probability [842]. That is, they relax the
second assumption. We will come back to these issues in Section ??.
We still assume that every item is accessed with the same probability.
However, we relax the first assumption. The following formula derived by
Christodoulakis [151], Luk [492], and Ijbema and Blanken [379] is a simple
application of Waters’s and Yao’s formula to a more general case.
Note that the product formulation in Eq. 4.5 of Theorem 4.16.1 results in a
more efficient computation. We make a note of this in the following corollary.
with ( Q
nj −1 N −k−i
i=0 N −i k ≤ nj
pj = (4.16)
0 N − nj < k ≤ N
If we compute the pj after we have sorted the nj in ascending order, we can use
the fact that
nj+1 −1
Y N −k−i
pj+1 = pj ∗ .
N −i
i=nj
We can also use the theorem to calculate the number of qualifying buckets
in case the distribution is given by a histogram.
4.16. COUNTING THE NUMBER OF ACCESSES 181
L
N,m X
W nj (k) = li YnNj (k) (4.17)
i=1
Last in this section, let us calculate the probability distribution for the
number of qualifying items within a bucket. The probability that x ≤ nj items
in a bucket j qualify can be calculated as follows. The number of possibilities
nj
to select x items in bucket nj is x . The number of possibilites to draw the
−nj
remaining k − x items from the other buckets is Nk−x . The total number
of possibilities to distribute k items over the buckets is Nk . This shows the
following:
nj
N −nj
x
XnNj (k, x) = N
k−x (4.18)
k
min(k,nj )
N,m X
X nj (k) = xXnNj (k, x) (4.19)
x=0
In standard statistics books the probability distribution XnNj (k, x) is called hy-
pergeometric distribution.
Let us consider the case where all nj are equal to n. Then we can calculate
the average number of qualifying items in a bucket. With y := min(k, n) we
182CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
have
min(k,n)
N,m X
X nj (k) = xXnN (k, x)
x=0
min(k,n)
X
= xXnN (k, x)
x=1
y
1 X n N −n
= N
x
k−x
k x=1
x
y
1 X x n N −n
= N k−x
k x=1
1 x
y
1 X n n−1 N −n
= N x−1 k−x
k x=1
1
n X
y−1
1 n−1 N −n
= N 0 + x (k − 1) − x
k x=0
n
1 n−1+N −n
= N 0+k−1
k
n
1 N −1
= N k−1
k
k k
= n =
N m
Let us consider the even more special case where every bucket contains a
single item. That is, N = m and ni = 1. The probability that a bucket contains
a qualifying item reduces to
1
N −1
x k−1
X1N (k, x) = N
k
N −1
k−1
= N
k
k k
= (= )
N m
Since x can then only be zero or one, the average number of qualifying items a
bucket contains is also Nk .
The formulas presented in this section can be used to estimate the number
of block/page accesses in case of random direct accesses. As we will see next,
other kinds of accesses occur and need different estimates.
is given by
B−j−1
b−1
BbB (j) = B
(4.20)
b
A more general theorem (see Theorem 4.16.13) was first presented by Yao [834].
The above formulation is due to Christodoulakis [152].
To see why the formula holds, consider the total number of bitvectors having
a one in position i followed by j zeros followed by a one. This number is B−j−2
b−2 .
We can chose B − j − 1 positions for i. The total number of bitvectors is Bb
and each bitvector has b − 1 sequences of the form that a one is followed by a
sequence of zeros is followed by a one. Hence,
B−j−2
(B − j − 1)
BbB (j) = B
b−2
(b − 1) b
B−j−1
b−1
= B
b
Part 1. of the theorem follows. To prove part 2., we count the number of
bitvectors that start with j zeros before the first one. There are B − j − 1
positions left for the remaining b−1 ones. Hence, the number of these bitvectors
is B−j−1
b−1 and part 2 follows. Part 3 follows by symmetry.
184CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
We can derive a less expensive way to evaluate the formula for BbB (j) as
follows. For j = 0, we have BbB (0) = Bb . If j > 0, then
B−j−1
b−1
BbB (j) = B
b
(B−j−1)!
(b−1)!((B−j−1)−(b−1))!
= B!
b!(B−b)!
(B − j − 1)! b!(B − b)!
=
(b − 1)!((B − j − 1) − (b − 1))! B!
(B − j − 1)! (B − b)!
= b
((B − j − 1) − (b − 1))! B!
(B − j − 1)! (B − b)!
= b
(B − j − b)! B!
b (B − j)! (B − b)!
=
B − j (B − b − j)! B!
j−1
b Y b
= (1 − )
B−j B−i
i=0
This formula is useful when BbB (j) occurs in sums over j because we can compute
the product incrementally.
Corollary 4.16.10 Using the terminology of Theorem 4.16.9, the expected val-
ue for the number of zeros
is
B−b
B X B−b
Bb = jBbB (j) = (4.21)
b+1
j=0
4.16. COUNTING THE NUMBER OF ACCESSES 185
Let us calculate:
B−b B−b
X B−j−1 X B−j−1
j = (B − (B − j))
b−1 b−1
j=0 j=0
B−b
X B−b
B−j−1 X B−j−1
= B − (B − j)
b−1 b−1
j=0 j=0
B−b
X B−b
X
b−1+j B−j
= B −b
b−1 b
j=0 j=0
B−b
X B−b
X
b−1+j b+j
= B −b
j b
j=0 j=0
(b − 1) + (B − b) + 1 b + (B − b) + 1
= B −b
(b − 1) + 1 b+1
B B+1
= B −b
b b+1
B+1 B
= (B − b )
b+1 b
With
B+1 B(b + 1) − (Bb + b)
B−b =
b+1 b+1
B−b
=
b+1
Corollary 4.16.11 Using the terminology of Theorem 4.16.9, the expected to-
tal number of bits from the first bit to the last one, both included, is
Bb + b
B tot (B, b) = (4.22)
b+1
To see this, we subtract from B the average expected number of zeros between
the last one and the last bit:
B−b B(b + 1) B − b
B− = −
b+1 b+1 b+1
Bb + B − B + b
=
b+1
Bb + b
=
b+1
Bb − B + 2b
B 1-span (B, b) = (4.23)
b+1
We have two possibilities to argue here. The first subtracts from B the number
of zeros at the beginning and the end:
B−b
B 1-span (B, b) = B − 2
b+1
Bb + B − 2B + 2b
=
b+1
Bb − B + 2b
=
b+1
The other possibility is to add the number of zeros between the first and the
last one and the number of ones:
B
B 1-span (B, b) = (b − 1)B b + b
B − b b(b + 1
= (b − 1) +
b+1 b+1
Bb − b2 − B + b + b2 + b
=
b+1
Bb − B + 2b
=
b+1
The number of bits from the first bit to the last one including both . . . The
EX or Cor? distance between the first and the last one . . .
Let us have a look at some possible applications of these formulas. If we
look up one record in an array of B records and we search sequentially, how
many array entries do we have to examine on average if the search is successful?
In [502] we find these formulas used for the following scenario. Let a file
consist of B consecutive cylinders. We search for k different keys, all of which
occur in the file. These k keys are distributed over b different cylinders. Of
course, we can stop as soon as we have found the last key. What is the expected
total distance the disk head has to travel if it is placed on the first cylinder of
the file at the beginning of the search?
Another interpretation of these formulas can be found in [369, 503]. Assume
we have an array consisting of B different entries. We sequentially go through
all entries of the array until we have found all the records for b different keys.
We assume that the B entries in the array and the b keys are sorted. Further,
all b keys occur in the array. On the average, how many comparisons do we
need to find all keys?
Vector of Buckets
A more general scenario is as follows. Consider a sequence of m buckets con-
taining ni items each. Yao [834] developed the following theorem.
4.16. COUNTING THE NUMBER OF ACCESSES 187
Applications of this formula can be found in [151, 152, 502, 504, 763]. Manolopou-
los and Kollias describe the analogue for the replacement model [502].
Lang, Driscoll, and Jou discovered a general theorem which allows us to
estimate the expected number of block accesses for sequential search.
where Y is a random variable for the last item in the sequence that occurs among
the k items searched.
proof? ?
With the help of this theorem, it is quite easy to derive many average
sequential accesses for different models. Cor or EX?
non-replacement replacement
random [148, 151, 492, 585, 802, 833] [102, 151, 568, 585]
sequential [56, 151, 449, 504, 568, 567, 700, 834] [151, 449, 504, 700]
tree-structured [449, 448, 504, 567, 589] [449, 448, 504, 700]
This is a good approximation, as long as Qs (i) is not too small (e.g. > 4).
Ccmd = N Dcmd
seek ∆gap
... ...
...
Ξ Ξ Ξ
| {z } | {z } | {z }
Scpe Scpe Scpe
The upper path illustrates Cseekgap , the lower braces indicate those parts for
which Cseekext is responsible.
The average seek cost for reaching the first qualifying cylinder is Davgseek .
How far are we now within the first extent? We use Corollary 4.16.10 to derive
that the number of non-qualifying cylinders preceding the first qualifying one
in some extent i is
Scpe (i) Scpe (i) − Qc (i)
B Qc (i) = .
Qc (i) + 1
The same is found for the number of non-qualifying cylinders following the
last qualifying cylinder. Hence, for every gap between the last and the first
qualifying cylinder of two extents i and i + 1, the disk arm has to travel the
distance
Scpe (i) Scpe (i+1)
∆gap (i) := B Qc (i) + Sfirst (i + 1) − Slast (i) − 1 + B Qc (i+1)
Let us turn to Cseekext (i). We first need the number of cylinders between
the first and the last qualifying cylinder, both included, in extent i. It can be
calculated using Corollary 4.16.12:
Hence, Ξ(i) is the minimal span of an extent that contains all qualifying cylin-
ders.
Using Ξ(i) and Theorem 4.1.1, we can derive an upper bound for Cseekext (i):
Ξ(i)
Cseekext (i) ≤ (Qc (i) − 1)Dseek ( ) (4.32)
Qc (i) − 1
4.17. DISK DRIVE COSTS FOR N UNIFORM ACCESSES 191
There are many more estimates for seek times. Older ones rely on a linear
disk model but also consider different disk scan policies. A good entry point is
the work by Theorey and Pinkerton [756, 757].
Crot (i) = Qt (i) DZscan (Szone (i)) B tot (DZspt (Szone (i)), Qspt (i)) (4.36)
Ssec ,D (Szone (i))
where Qspt (i) = W 1 Zspt
(N ) = DZspt (Szone (i)) SNsec is the expected
number of qualifying sectors per track in extent i. In case Qspt (i) < 1, we set
Qspt (i) := 1.
A more precise model is derived as follows. We sum up for all j the product
of (1) the probability that j sectors in a track qualify and (2) the average number
of sectors that have to be read if j sectors qualify. This gives us the number of
192CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
sectors that have to pass the head in order to read all qualifying sectors. We
only need to multiply this number by the time to scan a single sector and the
number of qualifying tracks. We can estimate (1) using Theorem 4.16.8. For
(2) we again use Corollary 4.16.11.
Using again Theorem 4.16.8, the expected rotational delay for the unquali-
fying sectors then is
We have to sum up this number for all extents and then add the time needed
to scan the N sectors. Hence
Sext
X
Crot = Crotpass (i) + Crotread (i)
i=1
where the total transfer cost for the qualifying sectors of an extent can be
estimated as
Crotread (i) = Qs (i) DZscan (Szone (i))
4.17. DISK DRIVE COSTS FOR N UNIFORM ACCESSES 193
Sext
X
Cheadswitch = (Qt (i) − Qc (i)) Dhdswitch (4.40)
i=1
4.17.7 Discussion
The disk drive cost model derived depends on many parameters. The first bunch
of parameters concerns the disk drive itself. These parameters can (and must
be) extracted from disk drives by using (micro-) benchmarking techniques [266,
752, 517, 660]. The second bunch of parameters concerns the layout of a segment
on disk. The database system is responsible for providing these parameters.
The closer it is to the disk, the easier these parameters are extracted. Building
a runtime system atop the operating system’s file system is obviously a bad
idea from the cost model perspective. If instead the storage manager of the
runtime system implements cylinder aligned extents (or at least track aligned
extents) using a raw I/O interface, the cost model will be easier to develop and
much more precise. Again, providing reliable cost models is one of the most
important tasks of the runtime system.
We have neglected many problems in our disk access model: partially filled
cylinders, pages larger than a block, disk drive’s cache, remapping of bad blocks,
non-uniformly distributed accesses, clusteredness, and so on. Whereas the first
two items are easy to fix, the rest is not so easy. In general, database systems
ignore the disk drive cache. The justifying argument is that the database buffer
is much larger than the disk drive’s cache and, hence, it is very unlikely that we
read a page that is not in the database buffer but in the disk cache. However,
this argument falls short for non-random accesses. Nevertheless, we will ignore
the issue in this book. The interested reader is referred to Shriver’s thesis for
disk cache modeling [701].
Remapping of bad sectors to other sectors really prevents the development
of a precise cost model for disk accesses. Modelling disk drives becomes already
a nightmare since a nice partitioning of the disk into zones is no longer possible
since some sectors, tracks and even cylinders are reserved for the remapping. So
even if no remapping takes place (which is very unlikely), having homogeneous
zones of hundreds of cylinders is a dream that will never come true. The
result is that we do not have dozens of homogeneous zones but hundreds (if
not thousands) of zones of medium homogeneity. These should be reduced to
a model of dozens of homogeneous zones such that the error does not become
too large. The remaining issues will be discussed later in the book. EX
194CHAPTER 4. DATABASE ITEMS, BUILDING BLOCKS, AND ACCESS PATHS
There is even more to say about our cost model. A very practical issue
arises if the number of qualifying cylinders is small. Then for some extent i,
the expected number of qualifying cylinders could be Qc (i) = 0.38. For some
of our formulas this is a big problem. As a consequence, special cases for small
EX N , small Qc , small Qt have to be developed and implemented.
Another issue is the performance of the cost model itself. The query com-
piler might evaluate the cost model’s formulas thousands or millions of times.
Hence, they should be fast to evaluate.
So far, we can adequately model the costs of N disk accesses. Some questions
remain. For example, how do we derive the number N of pages we have to
access? Do we really need to fetch all N pages from disk or will we find some
of them in the buffer? If yes, how many? Further, CPU costs are also an
important issue. Deriving a cost model for CPU costs is even more tedious
than modelling disk drive costs. The only choice available is to benchmark all
parts of a system and then derive a cost model using the extracted parameters.
To give examples of parameters to be extracted: we need the CPU costs for
accessing a page present in the buffer, for accessing a page absent in the buffer,
for a next call of an algebraic operator, for executing an integer addition, and
so on. Again, this cannot be done without tools [42, 210, 353, 394, 584].
The bottom line is that a cost model does not have to be accurate, but must
lead to correct decisions. In that sense, it must be accurate at the break even
points between plan alternatives. Let us illustrate this point by means of our
motivating example. If we know that the index returns a single tuple, it is quite
likely that the sequential scan is much more expensive. The same might be true
for 2, 3, 4, and 5 tuples. Hence, an accurate model for small N is not really
necessary. However, as we come close to the costs of a sequential scan, both the
cost model for the sequential scan and the one for the index-based access must
be correct since the product of their errors is the factor a bad choice is off the
best choice. This is a crucial point, since it is easy to underestimate sequential
access costs by a factor of 2-3 and overestimate random access cost by a factor
of 2-5.
4.19 Bibliography
ToDo:
• CPU Costs for B-tree search within inner and leaf pages [446]
• K accesses to unique index: how many page faults if buffer has size b?
[642]
• set oriented disk access to large complex objects [796, 795], assembly
operator: [412],
Foundations
197
Chapter 5
199
200 CHAPTER 5. LOGIC, NULL, AND BOOLEAN EXPRESSIONS
¬true =⇒ false
¬false =⇒ true
p∨p =⇒ p p∧p =⇒ p
p ∨ ¬p =⇒ true p ∧ ¬p =⇒ false
p1 ∨ (p1 ∧ p2 ) =⇒ p1 p1 ∧ (p1 ∨ p2 ) =⇒ p1
p ∨ false =⇒ p p ∧ true =⇒ p
p ∨ true =⇒ true p ∨ false =⇒ false
5.5 Bibliography
NULL-values: [637, 469, 638, 470]
5.5. BIBLIOGRAPHY 201
Commutativity
p1 ∨ p2 ⇐⇒ p2 ∨ p1 p1 ∧ p2 ⇐⇒ p2 ∧ p1
∃e1 ∃e2 p ⇐⇒ ∃e2 ∃e1 p ∀e1 ∀e2 p ⇐⇒ ∀e2 ∀e1 p
Associativity
(p1 ∨ p2 ) ∨ p3 ⇐⇒ p1 ∨ (p2 ∨ p3 ) (p1 ∧ p2 ) ∧ p3 ⇐⇒ p1 ∧ (p2 ∧ p3 )
Distributivity
p1 ∨ (p2 ∧ p3 ) ⇐⇒ (p1 ∨ p2 ) ∧ (p1 ∨ p3 ) p1 ∧ (p2 ∨ p3 ) ⇐⇒ (p1 ∧ p2 ) ∨ (p1 ∧ p3 )
∃e (p1 ∨ p2 ) ⇐⇒ (∃e p1 ) ∨ (∃ p2 ) ∀e (p1 ∧ p2 ) ⇐⇒ (∀e p1 ) ∧ (∀e p2 )
Idempotency
p∨p ⇐⇒ p p∧p ⇐⇒ p
p ∨ ¬p ⇐⇒ true p ∧ ¬p ⇐⇒ false
p1 ∨ (p1 ∧ p2 ) ⇐⇒ p1 p1 ∧ (p1 ∨ p2 ) ⇐⇒ p1
p ∨ false ⇐⇒ p p ∧ true ⇐⇒ p
p ∨ true ⇐⇒ true p ∧ false ⇐⇒ false
De Morgan
¬(p1 ∨ p2 ) ⇐⇒ ¬(p1 ) ∧ ¬(p2 ) ¬(p1 ∧ p2 ) ⇐⇒ ¬(p1 ) ∨ ¬(p2 )
Negation of Quantifiers
Elimination of Negation
x dxeN U LL bxcN U LL
true true true
⊥ true false
false false false
Functional Dependencies
In many query results attribute values are not independent of each other but
have certain dependencies. Keeping track of these dependencies is very useful
for many optimizations, for example in the following query
the order by clause can be simplified to c.id without affecting the result:
c.id is the key of customers, and thus determines c.nid. c.nid is joined with
n.id, which is the key of nations and determines n.name, thus transitively c.id
determines n.name.
These functional dependencies between attributes have been studied primar-
ily in the context of database design, but many optimization steps like order
optimization (Chapter 23) and query unnesting (Chapter 14) profit greatly from
known functional dependencies. In the following we first study functional de-
pendencies when all attributes are not NULL, then extend this to attributes
with NULL values, and finally discuss how functional dependencies are effected
by relational operators.
f : A1 → A2
For base relations functional dependencies can be derived from the schema,
in particular key constraints and check conditions [?]. For intermediate results
203
204 CHAPTER 6. FUNCTIONAL DEPENDENCIES
1. A2 ⊆ A1 ⇒ A1 → A2
2. A1 → A2 ⇒ (A1 ∪ A3 ) → (A2 ∪ A3 )
3. A1 → A2 ∧ A2 → A3 ⇒ A1 → A3
The Armstrong axioms are sound and complete, i.e., it is possible to derive
all valid functional dependencies by applying these three axioms. For practical
purposes it is often convenient to include three additional rules which can be
derived from the original axioms:
4. A1 → A2 ∧ A1 → A3 ⇒ A1 → (A2 ∪ A3 )
5. A1 → (A2 ∪ A3 ) ⇒ A1 → A2 ∧ A1 → A3
6. A1 → A2 ∧ (A2 ∪ A4 ) → A3 ⇒ (A1 ∪ A4 ) → A3
Given a set of functional dependencies F, we denote with F + the closure
of F, i.e., the set of all functional dependencies that can be derived from F by
using the inference rules shown above.
Closely related to the concept of functional dependencies is the concept of
keys: Given a relation R and an attribute set A ⊆ A(R), A is a super key of
R if A → A(R) holds in R. Further A is a key of R if the following condition
holds:
∀A(A0 ⊂ A ⇒ ¬(A0 → A(R))).
6.4 Bibliography
Chapter 7
X ∪∅ = X
X ∪X = X
X ∪Y = Y ∪X (commutativity)
(X ∪ Y ) ∪ Z = X ∪ (Y ∪ Z) (associativity)
X ∩∅ = ∅
X ∩x = X
X ∩Y = y∩X (commutativity)
(X ∩ Y ) ∩ Z = X ∩ (Y ∩ z) (associativity)
X \∅ = X
∅\X = ∅
X \Y 6= Y \X (∗ ∗ ∗wrong ∗ ∗∗)
(X \ Y ) \ Z 6= X \ (Y \ Z) (∗ ∗ ∗wrong ∗ ∗∗)
X ∪ (Y ∩ Z) = (X ∩ Y ) ∪ (X ∩ Z) (distributivity)
X ∩ (Y ∪ Z) = (X ∪ Y ) ∩ (X ∪ Z) (distributivity)
(X ∪ Y ) \ Z = (X \ Z) ∪ (Y \ Z) (distributivity)
205
206 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
ence is neither of them. Expressions containing the empty set can simplified.
Further, some distributivity laws hold.
As we have seen in Chapter 2, algebraic equivalences that reorder algebraic
operators form the fundamental core for query optimization. One could discuss
the reorderability of each pair of operators resulting in n2 investigations if the
number of operators in the algebra is n. In order to simplify this, we introduce
a general argument covering most of the cases. The observation will be that
set-linearity of set operators implies their reorderability easily.
A unary function f from sets to sets is called set-linear (or homomorph), if
and only if the following two conditions hold for all sets X and Y :
f (∅) = ∅
f (X ∪ Y ) = f (X) ∪ f (Y )
An n-ary mapping from sets to a set is called set-linear in its i-th argument, if
and only if for all sets X1 , . . . , Xn and Xi0 the following conditions hold:
X∪ ¯¯∅ = X
X∪ ¯X = X
X∪ ¯Y = Y∪ ¯X (commutativity)
(X ∪¯ Y )∪¯Z = X∪ ¯ (Y ∪
¯ Z) (associativity)
X∩ ¯¯∅ = ¯
∅
X∩ ¯x = X
X∩ ¯Y = Y∩ ¯X (commutativity)
(X ∩¯ Y )∩
¯Z = X∩ ¯ (Y ∩
¯ Z) (associativity)
¯
X \∅ ¯ = X
¯
∅¯\X = ¯
∅
X¯ \Y 6= Y ¯\X (∗ ∗ ∗wrong ∗ ∗∗)
(X ¯\Y )¯\Z 6= X ¯\(Y ¯\Z) (∗ ∗ ∗wrong ∗ ∗∗)
¯ ¯
X ∪(Y ∩Z) = (X ∩¯ Y )∪
¯ (x∩
¯ Z) (distributivity)
X∩ ¯ (Y ∪
¯ Z) 6= (X ∪¯ Y )∩
¯ (X ∪
¯ Z) (∗ ∗ ∗wrong ∗ ∗∗)
(X ∪Y )¯
¯ \Z 6= ¯ ¯
(X \Z)∪(Y \Z)¯ (∗ ∗ ∗wrong ∗ ∗∗)
minimum of the number its occurrences in X and Y . In the bag difference X ¯\Y
the number of occurrences of some element is the difference (−̇) of its occur-
rences in X and Y where a−̇b is defined as max(0, a − b). Using characteristic
functions, we can define
The laws for sets do not necessarily hold for bags (see Figure 7.2). We will
have that bag union and bag intersection are both commutative and associative.
Bag difference is neither of them. The only distributivity law that holds for bags
is the one that distributes a union over an intersection.
Having every operation twice, once for bags and once for sets is quite in-
convenient. Fortunately, for some operations we only need the one for bags.
We can get rid of some set operations as follows. Every set can be seen as a
¯
bag whose the characteristic function never exceeds one. Let I(S) turn a set S
into a bag with identical characteristic function. The partial function I¯−1 (B)
return a bag into a set if the bag’s characteristic function does not exceed one.
Otherwise let I¯−1 be undefined. Let X and Y be two sets. For the intersection
function we then have
I¯−1 (I(X)
¯ ∪ ¯ )) = X ∪ Y
¯ I(Y
That is, for any two sets X and Y bag union and set union are the same. This
gives rise to the notion of set-faithfulness. We call a unary function on sets f
set-faithtul if and only if
I¯−1 (f (I(X)))
¯ = f (X)
208 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
holds for all sets X. Analogously, binary functions g are set-faithful if and only
if
I¯−1 (g(I(X),
¯ ¯ ))) = f (X, Y )
I(Y
holds for all sets X and Y .
¯
\ and ∩¯ are set-faithful. Hence, we can (and often will) simply use \ and ∩
to denote set or bag difference and intersection. However, ∪ ¯ is not. Hence, we
have to carefully distinguish between ∪ ¯ and ∪.
To go from a bag to a set, we have to eliminate duplicates. Let us denote
by ΠD the duplicate elimination operation. For a given bag B we then have
χΠD (B) (z) = min(1, χB (z)).
Instead of working with sets and bags, we can work with bags only by
¯
identifying every set S with the bag I(S). We can annotate all bags with a
property indicating whether it contains duplicates or not. If at some place a
set is required and we cannot infer that the bag in that place is duplicate free,
we can use ΠD as an enforcer of the set property. Note that for every set S we
have ΠD (S) = S. Hence, ΠD does not do any harm except for the resources
it takes. The reasoning whether a given expression produces duplicates or not
will be very important, especially in the context of XPath/XQuery.
A unary function f from bags to bags is called bag-linear (or homomorph),
if and only if the following two conditions hold for all bags X and Y :
f (¯∅) = ¯∅
¯ Y ) = f (X)∪
f (X ∪ ¯ f (Y )
An n-ary mapping from bags to a bag is called bag-linear in its i-th argument,
if and only if for all bags X1 , . . . , Xn and Xi0 the following conditions hold:
f (X1 , . . . , Xi−1 , ¯
∅, Xi+1 , . . . , Xn ) = ¯∅
f (X1 , . . . , Xi−1 , Xi ∪ Xi0 , Xi+1 , . . . , Xn ) = f (X1 , . . . , Xi−1 , Xi , Xi+1 , . . . , Xn )
¯ f (X1 , . . . , Xi−1 , Xi0 , Xi+1 , . . . , Xn )
∪
• A(()R) = A(()S)
(R1̄S) 6= (R∩
¯ S)
For any sequence S, the length of the sequence is denoted by |S|. The above
sequence has length five. The empty sequence () contains zero elements and
has length zero.
As we consider only finite sequences, a sequence of length n ≥ 0 has a
characteristic function χ from an interval [0, n[ to a domain D. Outside [0, n[,
χ is undefined (⊥). Let S be a sequence. Then α(S) gives us the first element of
the sequence, i.e. α(S) = χS (0). For our example sequence, α(ha, b, b, c, bi) = a.
The rest or tail of a sequence S of length n is denoted by τ (S) and contains
all but the first element in the sequence. That is χτ (S) (i) = χS (i + 1). For our
example sequence, τ (ha, b, b, c, bi) = hb, b, c, bi.
Concatenation of two sequences is denoted by ⊕. The characteristic function
χS (i) if i < |S|
of the concatenation of two sequences S and T is χS⊕T (i) =
χT (i − |S|) if i ≥ |S|
As an example, ha, b, b, c, bi ⊕ ha, b, ci = ha, b, b, c, b, a, b, ci.
We can easily go from a sequence to a bag by just forgetting the order. To
convert a bag into a sequence, we typically have to apply a Sort operator. In
reality however, bags are often represented as (ordered) streams, i.e. they are
sequences. This is due to fact that most physical algebras are implemented
using the iterator concept introduced in Section 4.6.
Analogously to set and bag linearity, we can introduce sequence linearity
of unary and n-ary functions on sequences. In the definition, we only have to
exchange the set (bag) union operator by concatentation:
A unary function f from sequences to sequences is called sequence-linear , if
and only if the following two conditions hold for all sequences X and Y :
f () =
f (X ⊕ Y ) = f (X) ⊕ f (Y )
7.2 Algebra
Grouping Mapping and Commutativity Comment on ΠA (R1 ∩ R2 ) 6≡ ΠA (R1 ) ∩ ToDo
ΠA (R2 ) ΠA (R1 \ R2 ) 6≡ ΠA (R1 ) \ ΠA (R2 ) ToDo
210 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
• All operators are polymorphic and can deal with (almost) any kind of
complex arguments.
• The algebra is redundant since some special cases of the operators can be
implemented much more efficiently. These cases are often introduced as
abbreviations.
second one is dependent on the first one. This operator can be used for unnest-
ing nested queries and is in many cases equivalent to a join between two sets
with a membership predicate [694]. In some cases (as we will see later on), it
corresponds to an unnest operation. We introduced the d-join in order to cope
with the values of types that do not have extensions (i.e. there exist no explicit
set on which a join could be applied). The d-join is also useful for introducing
index structures.
The map operator χ ([416]) is well-known from the functional programming
language context. A special case of it, where it adds derived information in
form of an added attribute with an according value (e.g. by object-base lookup
or by method calls) to each tuple of a set has been proposed in [415, 416]. Later,
this special case was given the name materialization operator [80].
The unnest operator is known from NF2 [654, 636]. It will come in two
different flavors allowing us to perform unnesting not only on nested relations
but also on attributes whose value is a bulk of elements which are not tuples.
The last operator—the grouping operator—generalizes the nest operator quite a
bit. That is why we renamed it. In fact, there exist two grouping operators, one
unary grouping operator and one binary grouping operator. The unary grouping
operator groups one set of tuples according to a grouping condition. Further,
it can apply an arbitrary expression to the newly formed group. This allows an
efficient implementation by saving on intermediate results. The binary grouping
operator adds a group to each element in the first argument set. This group is
formed from the second argument. The grouping operator will exploit the fact
that in the object-oriented context attributes can have set-valued attributes.
As we will see, this is useful for both, unnesting nested queries and producing
nested results. A variant of the binary grouping operator is also called nest-join
[720]. Implementations of it are discussed in [120]. There, the binary grouping
operator is called MD-Join.
7.2.2 Preliminaries
As already mentioned, our algebraic operators can deal not only with standard
relations but are polymorphic in the general sense. In order to fix the domain
of the operators we need some technical abbreviations and notations. Let us
introduce these first.
Since our operators are polymorphic, we need variables for types. We use τ
possibly with a subscript to denote types. To express that a certain expression
is of type e, we write e :: τ . Starting from concrete names for types and type
variables, we can build type expressions the standard way by using type con-
structors to build tuple tupes ([·]), set types {·}, bag types {{·}} and sequence
types < · >. Having two type expressions t1 and t2 , we denote by t1 ≤ t2 , that
t1 is a subtype of t2 . It is important to note that this subtype relationship is not
based on the sub-/superclass hierarchy found in most object-oriented models.
Instead, it simply denotes substitutability. That is the type t1 provides at least
all the attributes and member functions that t2 provides [101].
Most of our algebraic operators are tuned to work on bulks of tuples. The
most important information here is the attributes provided. For this we intro-
212 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
• For an expression e with only one free variable x, we define e(t) = e[x ← t].
The mechanism is very much like the standard binding for the relational algebra.
Consider for example a select operation σa=3 (R), then we assume that a, the
free variable of the subscript expression a = 3 is bound to the value of the
attribute a of the tuples of the relation R. To express this binding explicitly,
we would write for a tuple t ∈ R (a = 3)(t). Since a is an attribute of R and
hence of t, by our convention a is replaced by t.a, the value of attribute a of
tuple t. Since we want to avoid name conflicts right away, we assume that all
variable/attribute names used in a query are distinct. This can be achieved in
a renaming step.
Application of a function f to arguments ei is denoted by either regular
(e.g., f (e1 , . . . , en )) or dot (e.g., e1 .f (e2 , . . . , en )) notation. The dot notation is
used for type associated methods occurring in the object-oriented context.
Last, we introduce the heavily overloaded symbol ◦. It denotes function
concatenation and (as a special case) tuple concatenation as well as the con-
catenation of tuple types to yield a tuple type containing the union of the
attributes of the two argument tuple types.
Sometimes it is useful to be able to produce a set/bag/sequence containing
only a single tuple with no attributes. This is done by the singleton scan
operator denoted by 2.
Very often, we are given some database item which is a bulk of other items.
Binding these to variables or equivalently, embedding the items into a tuple, we
use the notation e[x] for an expression e and a variable/attribute name x. For
1
e[v1 ← e1 , . . . , vn ← en ] denotes a substitution of the variables vi by the expressions ei
within an expression e.
7.2. ALGEBRA 213
set valued expressions e, e[x] is defined as e[x] = {[x : y]|y ∈ e}. For bags the
definition is analogous. For sequence valued expressions e, we define e[a] = if
e is empty and e[a] = h[a : α(e)]i ⊕ τ (e)[a] otherwise.
We are now ready to define the signatures of the operators of our algebra.
Their semantics is defined in a subsequent step. Remember that we consider
all operators as being polymorphic. Hence, their signatures are polymorphic
and contain type variables, denoted by τ often with an index. We only give the
signatures for set operators. For bag operators, just replace the set sign by the
214 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
bag sign.
∪ : {τ }, {τ } → {τ }
∩ : {τ }, {τ } → {τ }
\ : {τ }, {τ } → {τ }
σp : {τ } → {τ }
if p : τ → B
1p : {τ1 }, {τ2 } → {τ1 ◦ τ2 }
if τi ≤ [], p : τ1 , τ2 → B, and
A(τ1 ) ∩ A(τ2 ) = ∅
<p : {τ1 }, {τ2 } → {τ1 }
if τi ≤ [], p : τ1 , τ2 → B
p : {τ1 }, {τ2 } → {τ1 }
if τi ≤ [], p : τ1 , τ2 → B
1 g=c
p : {τ1 }, {τ2 } → {τ1 ◦ τ2+ }
if τ1 < [], c :: τ , τ2 < [g : τ ],
+ just adds a null value to the domain of τ2 ,
if it does not already contain one,
p : τ1 , τ2 → B
< · > : {τ1 }||{τ2 } → {τ1 ◦ τ2 }
if τi ≤ [],
A(τ1 ) ∩ A(τ2 ) = ∅
χf : {τ1 } → {τ2 }
if f : τ1 → τ2
Γg;θA;f : {τ } → {τ ◦ [g : τ 0 ]}
if τ ≤ [], f : {τ } → τ 0 , A ⊆ A(τ )
Γg;A1 θA2 ;f : {τ1 }, {τ2 } → {τ1 ◦ [g : τ 0 ]}
if τ1 ≤ [], f : {τ2 } → τ 0 , Ai ⊆ A(τi ) for i = 1, 2
µg : {τ } → {τ 0 }
if τ = [a1 : τ1 , . . . , an : τn , g : {τ0 }],
τ0 ≤ [],
τ 0 = [a1 : τ1 , . . . , an : τn ] ◦ τ0 ,
µg;c : {τ } → {τ 0 }
if τ = [a1 : τ1 , . . . , an : τn , g : {τ0 }],
τ0 6≤ [],
τ 0 = [a1 : τ1 , . . . , an : τn ] ◦ [c : τ0 ],
f latten : {{τ }} → {τ }
maxg;m;aθ;f : {τ } → [m : τa , g : τf ]
if τ ≤ [a : τa ], f : {τ } → τf
7.2. ALGEBRA 215
7.2.4 Selection
Note that in the following definition there is no restriction on the selection
predicate. It may contain path expressions, method calls, nested algebraic
operators, etc.
7.2.5 Projection
7.2.6 Map
These operators are fundamental to the algebra. As the operators mainly work
on sets of tuples, sets of non-tuples (mostly sets of objects) must be transformed
into sets of tuples. This is one purpose of the map operator. Other purposes
are dereferenciation, method and function application. Our translation process
also pushes all nesting into map operators.
The first definition corresponds to the standard map as defined in, e.g.,
[416]. The second definition concerns the special case of a materialize operator
[415, 80]. The third definition handles the frequent case of constructing a set
of tuples with a single attribute out of a given set of (non-tuple) values.
Note that the oo map operator obviates the need of a relational projection.
Sometimes the map operator is equivalent to a simple projection (or renaming).
In these cases, we will use π (or ρ) instead of χ.
Remember that the function A used in the last definition returns the set of
attributes of a relation.
216 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
The last join operator is called d-join (< · >). It is a join between two sets,
where the evaluation of the second set may dependent on the first set. It is
used to translate from clauses into the algebra. Here, the range definition of
a variable may depend on the value of a formerly defined variable. Whenever
possible, d-joins are rewritten into standard joins.
e1 < e2 > = {y ◦ x|y ∈ e1 , x ∈ e2 (y)}
Unnest Operators The unnest operators come in two different flavor. The
first one is responsible for unnesting a set of tuples on an attribute being a set
of tuples itself. The second one unnests sets of tuples on an attribute not being
a set of tuples but a set of something else, e.g., integers.
Flatten Operator The flatten operator flattens a set of sets by unioning the
elements of the sets contained in the outer set.
f latten(e) = {y|x ∈ e, y ∈ x}
7.2. ALGEBRA 217
Max Operator The M ax operator has a very specific use that will be ex-
plained in the sequel. Note that an analogous M in operator can be defined.
Remarks Note that, apart from the χ and f latten operations, all these op-
erations are defined on sets of tuples. This guarantees some nice properties
among which is the associativity of the join operations. Note also that the
operators may take complex expressions in their subscript, therefore allowing
nested algebraic expressions. This is the most fundamental feature of the alge-
bra when it comes to express nested queries at the algebraic level. Unnesting
is then expressed by algebraic equivalences moving algebraic expression out of
the superscript.
The Γ, f latten and M ax operations are mainly needed for optimization
purposes, as we will see in the sequel, but do not add power to the algebra.
Note that a M in operation similar to the M ax operation can easily be defined.
The algebra is defined on sets whereas most OBMS also manipulate lists
and bags. We believe that our approach can easily be extended by considering
lists as set of tuples with an added positional attribute and bags as sets of tuples
with an added key attribute.
∩ . . ..
\ . . ..
π . . ..
π d . . ..
χf is linear.
χf (∅) = ∅
χf (e1 ∪ e2 ) = {f (x)|x ∈ e1 ∪ e2 }
= {f (x)|x ∈ e1 } ∪ {f (x)|x ∈ e2 }
= χf (e1 ) ∪ χf (e2 )
1p is linear (for a proof see [783]). Similarly, < is linear. is linear in its
first argument but obviously not in its second.
∅ 1 g=c
p e = ∅
(e1 ∪ e2 ) 1 g=c
p e = {y ◦ x|y ∈ e1 ∪ e2 , x ∈ e, p(y, x)} ∪
{y ◦ z|y ∈ e1 ∪ e2 , ¬∃x ∈ e p(y, x), A(z) = A(e),
∀a a 6= g z.a = N U LL, a.g = c}
= (e1 1 g=c
p e) ∪ (e2 1 g=c
p e)
e1 1 g=c
p ∅ = ∅ iff e1 = ∅
∅<e> = ∅
(e1 ∪ e2 ) < e > = {y ◦ x|y ∈ e1 ∪ e2 , x ∈ e(y)}
= {y ◦ x|y ∈ e1 , x ∈ e(y)} ∪ {y ◦ x|y ∈ e2 , x ∈ e(y)}
= (e1 < e >) ∪ (e2 < e >)
7.2. ALGEBRA 219
Note that the notion of linearity cannot be applied to the second (in-
ner) argument of the d-join, since, in general, it cannot be evaluated
independently of the first argument. Below, we summarize some basic
observations on the d-join.
Γg;A;f is not linear.
Consider the following counterexample:
µg is linear.
µg (∅) = ∅
µg (e1 ∪ e2 ) = {x.[g] ◦ y|x ∈ e1 ∪ e2 , y ∈ x.g}
= {x.[g] ◦ y|x ∈ e1 , y ∈ x.g} ∪ {x.[g] ◦ y|x ∈ e2 , y ∈ x.g}
= µg (e1 ) ∪ µg (e2 )
f latten(e1 ∪ e2 )
= {x|y ∈ e1 ∪ e2 , x ∈ y}
= {x|y ∈ e1 , x ∈ y} ∪ {x|y ∈ e2 , x ∈ y}
= f latten(e1 ) ∪ f latten(e2 )
Note that the notion of linearity does not apply to the max operator, since it
does not return a set.
The concatenation of linear mappings is again a linear mapping. Assume f
and g to be linear mappings. Then
f (g(∅)) = ∅
f (g(x ∪ y)) = f (g(x) ∪ g(y))
= f (g(x)) ∪ f (g(y))
Reorderability Laws
From the linearity considerations of the previous subsection, it is easy to derive
reorderability laws.
Let f : {τ1f } → {τ2f } and g : {τ1g } → {τ2g } be two linear mappings. If
f (g({x})) = g(f ({x})) for all singletons {x} then
For the linear algebraic operators working on sets of tuples, we can replace
the semantic condition f (g({x})) = g(f ({x})) by a set of syntactic criterions.
The main issue here is to formalize that two operations do not interfere in
their consumer/producer/modifier relationship on attributes. In the relational
algebra we have the same problem. Nevertheless, it is often neglected there.
Consider for example the algebraic equivalence
σp (R 1 S) = (σp (R)) 1 S
Then, this algebraic equivalence is true only if the predicate p accesses only those
attributes already present in R. Now, for our operators we can be sure that
f (g(e)) = g(f (e)) for singleton sets e, if g does not consume/produce/modify an
attribute that f is going to access and if f is not going to consume/produce/modify
an attribute that is accessed by g. In fact, most of the conditions attached to
the algebraic equivalences given later on concern this point.
We now consider binary mappings. Let f1 be a binary mapping being linear
in its first argument, f2 a binary mapping being linear in its second argument,
and g a unary linear mapping. If f1 (g({x}), e0 ) = g(f1 ({x}, e0 )) for all x and e0
then
for all e. Again, we can recast the condition f1 (g({x}), e0 ) = g(f1 ({x}), e0 ) into
a syntactical criterion concerning the consumer/producer/modifier relationship
of attributes.
Analogously, if f2 (e, g({x})) = g(f2 (e, {x})) for all x and e then
for all e0 .
Since the outerjoin is not linear in its second argument, we state at least
some reorderability results concerning the reordering of joins with outerjoins
since much performance can be gained by chosing a (near-) optimal evaluation
order. The results are not original but instead taken from [626] and repeated
here for convenience:
L R
A B C C D E
a1 b1 c1 c1 d1 e1
a2 b2 c2 c3 d2 e2
L 1 R L 1 R
A B C D E A B C D E
a1 b1 c1 d1 e1 a1 b1 c1 d1 e1
a2 b2 c2 – – – – c3 d2 e2
L 1 R
A B C D E
a1 b1 c1 d1 e1
a2 b2 c2 – –
– – c3 d2 e2
associatively. Further, not always are outerjoins and joins reorderable. In this
subsection we discuss the reorderability of outerjoins. For a full account on the
topic see [626, 254, 263]
The occurance of an outer join can have several reasons. First, outer joins
are part of the SQL 2 specification. Second, outer joins can be introduced during
query rewrite. For example, unnesting nested queries or hierarchical views
may result in outer joins. Sometimes, it is also possible to rewrite universal
quantifiers to outerjoins [766, 187].
The different outer joins can be defined using the outer union operator
introduced by Codd [170]. Let R1 and R2 be two relations and S1 and S2 their
corresponding attributes. The outerjoin is then defined by padding the union
of the relations with null values to the schema S1 ∪ S2 :
+
R1 ∪ R2 = (R1 × {nullS2 \S1 }) ∪ (R2 × {nullS1 \S2 }) (7.7)
Given this definition of the outer union operator, we can define the outer join
operations as follows:
+
R1 1 p R2 = R1 1p R2 ∪ (R1 \ πS1 (R1 1p R2 )) (7.8)
+ +
R1 1 p R2 = R1 1p R2 ∪ (R1 \ πS1 (R1 1p R2 )) ∪ (R2 \ πS2 (R1 1p R2(7.9)
))
R1 1 p R2 = R2 1 R1 (7.10)
Each outer join preserves the tuples on the according side. For example, the left-
outer join preserves the tuples of the relation on the left-hand side. Figure 7.3
gives example applications of the different outer join operations. A null value
is indicated by a “-”.
Obviously, the left-outer join and the right-outer join are not commutative.
To illustrate associativity problems consider the following three relations
222 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
R S T
A B C D
a b - d
R 1 A=B S S 1 C=D∨C=null T
A B C B C D
a – – b – c
The expression R1 1 p12 (R2 1p23 R3 ) cannot be reordered given the equiva-
lences so far. It is equal to neither (R1 1 p12 R2 ) 1p23 R3 not (R1 1 p12 R2 ) 1p23
R3 . In order to allow reorderability on this expression, the generalized outer join
was introduced by Rosenthal and Galindo-Legaria [626]. It preserves attributes
for a set A ⊆ A(R1 ) and is defined as
+
R1 1 A
p R2 = (R1 1p R2 ) ∪ (πA (R1 ) \ πA (R1 1p R2 )) (7.20)
7.2. ALGEBRA 223
The generalized outer join can be generalized to preserve disjoint sets of at-
tributes in order to derive more equivalences [263].
We only gave the basic equivalences for reordering algebraic expressions
containing outer joins. General frameworks for dealing with these expressions
in toto are presented in [75, 263].
e<e> = e (7.27)
e1 < e2 > = e1 × e2 (7.28)
if F(e2 ) ∩ A(e1 ) = ∅
e1 < e2 > = e1 1 (e1 < e2 >) (7.29)
e1 < e2 >< e3 > = e1 < e3 >< e2 > (7.30)
if (A(e2 ) \ F(e2 )) ∩ F(e3 ) = ∅
and (A(e3 ) \ F(e3 )) ∩ F(e2 ) 6= ∅
πA(e1 ) (e1 < e2 >) = σe2 !=∅ (e1 ) (7.31)
(7.32)
We call a function
f extending :≺ ∀x, y : f (x) ◦ y ↓=⇒ f (x ◦ y) = f (x) ◦ y
We call a function
f restricting :≺ ∀x, y : f (x) ↓, x ◦ y ↓=⇒ f (x ◦ y) = f (x)
224 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
This equivalence should, e.g., be used form left to right for selections, in order
to reduce the cardinality for the Γ operator. For the binary Γ we have
This sketched equivalence only holds under certain conditions. For details on
the conditions and the correctness proof see [825] and Section ??.
Equivalences 7.44 and 7.45 bear similarity to equivalence EJA of [783] (p. 107),
where the outer-aggregation is used instead of semi-join and binary grouping,
respectively. Note that for checking conditions of the form πA2 (e2 ) ⊆ πA2 :A1 (e1 )
subtyping implying subsetrelationships on type extensions plays a major role
in object bases.
The following shows how to turn an outerjoin into a join:
e1 1 g:c
p e2 = e1 1p e2 (7.46)
if ¬p(c)
σps (e1 1 g:c
pj e2 ) = σps (e1 1pj e2 ) (7.47)
if ¬ps (c)
σf1 θf2 (e1 1 g:c
pj e2 ) = σf1 θf2 (e1 1pj e2 ) (7.48)
if ¬(f1 θf2 )(c)
We can easily check these conditions if some predicate (f1 θf2 )(c) is—after in-
serting c for the free variable—, iθ0 with i constant, or f1 ∈ ∅, or a similar
simple form. An application of these equivalences can sometimes be followed
by a removal of the join.
Note, that the latter equivalence depends on the knowledge we have on the
selection predicate. Note also, that the special outerjoin is only introduced
by unnesting nested χ operations. Hence, we could combine the equivalences
introducing the outerjoin and replacing it by a join into one. In case we have
even more information on the selection predicate than above, more specifically,
if it depends on a max or min aggregate, we can do so in a very efficient way:
σa=m (e1 )[m : agg(χb (e2 ))] = Aggg;m;a (e1 ).g (7.49)
if πa (e1 ) = πb (e2 )
χg:σa=m (e2 ) (χm:agg(e1 ) (e)) = χAggg;m;a (e1 ) (e) (7.50)
if πa (e1 ) = πb (e2 )
226 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
R A B S A C
a 5 a 7
a 6 a 8
Joining these relations R and S results in
R1S A B C
a 5 7
a 5 8
a 6 7
a 6 8
Applying ΓA;count(∗) to R and R 1 S yields
where p denotes
Figure 20.1 (a) shows this plan graphically. Note that the grouping operator
is executed last in the plan.
Now consider the plan where we push the grouping operator down:
This plan (see also Figure 20.1 (b)) is equivalent to the former plan. More-
over, if the grouping operator strongly reduces the cardinality of
σs.date≥... (Sold[s])
because every employee sells many items, then the latter plan might become
cheaper since the join inputs are smaller than in the former plan. This moti-
vates the search for conditions under which join and grouping operators can be
reordered. Several papers discuss this reorderability [129, 823, 824, 825, 826].
We will summarize their results in subsequent subsections.
*
select[all | distinct] A, F (B)
from R, S
where pR ∧ pS ∧ pR,S
group by G
with
G = GR ∪ GS , GR ⊆ A(R), GS ⊆ A(S),
B ⊆ A(R) A = AR ∪ AS , AR ⊆ GR , AS ⊆ GS
project[e.eid, amount]
join[e.eid=s.eid]
Sold[s]
(a)
project[e.eid, amount]
join[e.eid = s.eid]
select[s.date ...]
Sold[s]
(b)
We are interested in the conditions under which the query can be rewritten
into
select[all | distinct] A, F B
from R0 , S 0
where pR,S
with R0 (αR , F B) ≡
*
select all αR , F (B) as F B
7.2. ALGEBRA 229
from R
where pR
group by αR
and S 0 (αS ) ≡
select all αR
from S
where pS
[d]
ΠA,F Γ * (σpR (R)) 1pR,S σpS (S)
αR ;F : F (B)
holds iff in σpR ∧pS ∧pR,S (R × S) the following functional dependencies hold:
F D1 : G → αR
F D2 : αR , GS → κS
Note that since GS ⊆ G, this implies G → κS .
F D2 implies that for any group there is at most one join partner in S.
Hence, each tuple in Γ * (σpR (R)) contributes at most one row to the
αR ;F : F (B)
overall result.
F D1 ensures that each group of the expression on the left-hand side corre-
sponds to at most one group of the group expression on the right-hand side.
We now consider queries with a having clause.
In addition to the assumptions above, we have that the tables in the from
clause can be partitioned into R and S such that R contains all aggregated
columns of both the select and the having clause. We further assume that
conjunctive terms in the having clause that do not contain aggregate functions
have been moved to the where clause.
Let the predicate of the having clause have the form HR ∧ H0 where HR ⊆
A(R) and H0 ⊆ R ∪ S where H0 only contains non-aggregated columns from S.
We now consider all queries of the form
*
select[all | distinct] A, F (B)
from R, S
where pR ∧ pS ∧ pR,S
group by G
* *
having H0 F0 (B) ∧ HR FR (B)
* *
where F0 and FR are vectors of aggregate functions on the aggregated columns
B.
An alternative way to express such a query is
230 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
select[all | distinct] G, F B
from R0 , S
where cS ∧ cR,S ∧ H0 (F0 B)
where R0 (αR , F B, F0 B) ≡
* *
select all αR , F (B) as F B, F0 (B) as F0 B
from R
where cR
group by αR
*
having HR FR (B)
The according
equivalence
is [825]:
ΠG,F σHR ∧H0 Γ * * * σpR ∧pS ∧pR,S (R × S)
G;F : F (B),FR :FR (B),F0 :F0 (B)
≡
ΠG,F σpR,S ∧pS ∧H0 (F0 ) ΠG,F,F0 σHR Γ * * * (R) ×S
G;F : F (B),FR :FR (B)F0 :F0 (B)
Coalescing Grouping
In this subsection we introduce coalescing grouping which slightly generalizes
simple coalescing grouping as introduced in [129].
We first illustrate the main idea by means of an example.
Given two relation schemes
the query
select region, sum (total price) as s
from Sales, Department
where did = deptid
group by region
is straightforwardly translated into the following algebraic expression:
Γregion;s:sum(total price) (Sales 1deptid=did Department)
Note that Equivalence ?? cannot be applied here. However, if there are many
sales performed by a department, it might be worth reducing the cardinality of
the left join input by introducing an additional group operator. The result is
Γregion;s=sum(s0 ) Γdeptid;s0 :sum(total price) (Sales) 1deptid=did Department
• Allowed are only sum, min, max. Not allowed are avg and count.
• For any allowed aggregate function we only allow for agg(all . . .).
Forbidden is agg(distinct . . .).
with
G1 = (F (p) ∪ G) ∩ A (R1 )
Further, the following condition must hold for all i(1 ≤ i ≤ n):
! !
[ [
aggi Sk = aggi2 {aggi1 (Si )}
k k
Proof :
First, note that
[
R1 1p R2 = R1 1p {t2 } (7.52)
t2 ∈R2
ΓG;A (R1 [t1 ]) 1p {t2 } = σp(t1 ◦t2 ) (ΓG;A (R1 [t1 ])) (7.53)
= ΓG;A σp(t1 ◦t2 ) (R1 [t1 ])
= ΓG;A (R1 [t1 ] 1p {t2 })
232 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
holds where we have been a little sloppy with t1 . Applying (20.2) and (20.3)
to ΓG1 ;A1 (R1 ) 1p R2 , the inner part of the right-hand side of the equivalence
yields:
[
ΓG1 ;A1 (R1 ) 1p R2 = ΓG1 ;A1 (R1 ) 1p {t2 } (7.54)
t2 ∈R2
[
= ΓG1 ;A1 (R1 1p {t2 })
t2 ∈R2
[
ΓG;A (R1 1p R2 ) = ΓG;A {t1 ◦ t2 |t1 ∈ R1 , p (t1 ◦ t2 )} (7.56)
t2 ∈R2
S
Abbreviate {t1 ◦ t2 |t1 ∈ R1 , p (t1 ◦ t2 )} by Y.
t2 ∈R2
Applying the definition of ΓG;A yields:
{t ◦ a | t ∈ ΠG (Y ), a = (A1 : e1 , . . . , An : en ) , (7.57)
ai = aggi ({ei (s)|s ∈ Y, S|G = t})}
Compare (20.5) and (20.7). Since ΠG (X) = ΠG (Y ), they can only differ in
their values of Ai .
7.3. LOGICAL ALGEBRA FOR SEQUENCES 233
7.2.13 ToDo
[611]
Γ Γ Γ
1 1 1
1 a e 1 Γc 1
1 b 1 a e 1 a
ec c b c b
will occur. In order to keep the paper readable, we only employ the order-
preserving operators and use the same notation for them that has been used in
[161, 162] and SAL [63].
Again, our algebra will allow nesting of algebraic expressions. For example,
within a selection predicate of a select operator we allow the occurrence of
further nested algebraic expressions. Hence, a join within a selection predicate is
possible. This simplifies the translation procedure of nested XQuery expressions
into the algebra. However, nested algebraic expressions force a nested loop
evaluation strategy. Thus, the goal of the paper will be to remove nested
algebraic expressions. As a result, we perform unnesting of nested queries not
at the source level but at the algebraic level. This approach is more versatile
and less error-prone.
R2
R1 χ̂a:σ̂A1 =A2 (R2 ) (R1 ) =
A2 B
A1 A1 a
1 2
1 1 h[1, 2], [1, 3]i
1 3
2 2 h[2, 4], [2, 5]i
2 4
3 3 hi
2 5
where
ˆ := if e2 =
e1 ×e2 ˆ
(e1 ◦ α(e2 )) ⊕ (e1 ×τ (e2 )) else
We are now prepared to define the join operation on ordered sequences:
e1 1̂p e2 := σp (e1 ×e
ˆ 2)
The left outer join, which will play an essential role in unnesting, is defined
g:e
as e1 1̂ p e2 :=
g:e
(α(e1 )1̂p e2 ) ⊕ (τ (e1 ) 1̂ p e2 )
if (α(e1 )1̂p e2 ) 6=
(α(e1 ) ◦ ⊥A(e2 )\{g} ◦ [g : e]) else
g:e
⊕(τ (e1 ) 1̂ p e2 )
where g ∈ A(e2 ). Our definition deviates slightly from the standard left outer
join operator, as we want to use it in conjunction with grouping and (aggregate)
functions. Consider the relations R1 and R2 in Figure ??. If we want to join
R1 (via left outer join) to R2count that is grouped by A2 with counted values for
B, we need to be able to handle empty groups (for A1 = 3). e defines the value
given to attribute g for values in e1 that do not find a join partner in e2 (in this
case 0).
We define the dependency join (d-join for short) as
if e1 =
ˆ ˆ
e1 <e2 > := ˆ ˆ ˆ
α(e1 )×e2 (e1 ) ⊕ τ (e1 )<e2 > else
Let θ ∈ {=, ≤, ≥, <, >, 6=} be a comparison operator on atomic values. The
grouping operator which produces a sequence-valued new attribute containing
“the group” is defined by using a binary grouping operator.
where the binary grouping operator (sometimes called nest-join [720]) is defined
as
if e1 =
e1 Γ̂g;A1 θA2 ;f e2 :=
α(e1 ) ◦ [g : G(α(e1 )] ⊕ (τ (e1 )Γ̂g;A1 θA2 ;f e2
Here, G(x) := f (σx|A1 θA2 (e2 )) and function f assigns a meaningful value to
empty groups. See also Figure ?? for an example. The unary grouping operator
processes a single relation and obviously groups only on those values that are
present. The binary grouping operator works on two relations and uses the
left hand one to determine the groups. This will become important for the
correctness of the unnesting procedure.
R2
R1 Γ̂g;=A2 ;count (R2 ) = Γ̂g;=A2 ;id (R2 ) =
A2 B R2count R2g
A1
1 2
1 A2 g A2 g
1 3
2 1 2 1 h[1, 2], [1, 3]i
2 4
3 2 2 2 h[2, 4], [2, 5]i
2 5
R1 Γ̂g;A1 =A2 ;id (R2 ) =
g
R1,2
A1 g
1 h[1, 2], [1, 3]i
2 h[2, 4], [2, 5]i
3 hi
where e.g retrieves the sequence of tuples of attribute g. In case that g is empty,
it returns the tuple ⊥A(e.g) . (In our example in Figure ??, µ̂g (R2g ) = R2 .)
We define the unnest map operator as follows:
This operator is mainly used for evaluating XPath expressions. Since this is
a very complex issue [285, 287, 357], we do not delve into optimizing XPath
evaluation but instead take an XPath expression occurring in a query as it is
and use it in the place of e2 . Optimized translation of XPath is orthogonal to
our unnesting approach and not covered in this paper. The interested reader is
referred to [357].
238 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
7.3.3 Equivalences
To acquaint the reader with ordered sequences, we state some familiar equiva-
lences that still hold.
Of course, in the above equivalences the usual restrictions hold. For ex-
ample, if we want to push a selection predicate into the left part of a join,
it may not reference attributes of the join’s right argument. In other words,
F(p1 ) ∩ A(e2 ) = ∅ is required. As another example, equivalence 7.70 only holds
if F(e1 ) ∩ A(e1 ) = ∅ In Eqv. 7.69 the function f may not alter the schema and
b must be an attribute name. Please note that cross product and join are still
associative in the ordered context. However, neither of them is commutative.
Further, pushing selections into the second argument of a left-outer join is (in
general) not possible. For strict predicates we can do better but this is beyond
the scope of the paper.
7.3.4 Bibliography
Zaniolo [458]
7.4 Literature
• NF2 : [4, 174, 371, 636, 637, 469, 638, 470, 666]
• HAS: [107]
• BAGs: [22]
• OO Algebra [147]
• OO Algebra [160]
• OO Algebra [325]
• OO Algebra [484]
• OO Algebra [650]
• OO Algebra [841]
• SAL [63]: works on lists. Intended for semistructured data. SAL can be
thought of as the order-preserving counterpart of the algebra presented
in [161, 162] extended to handle semistructured data. These extensions
are similar to those proposed in [5, 153]
• TAX [393]: The underlying algebra’s data model is based on sets of or-
dered labeled trees. Intended for XML.
• [316]
• Geo: [330]
240 CHAPTER 7. AN ALGEBRA FOR SETS, BAGS, AND SEQUENCES
Chapter 8
Declarative Query
Representation
8.2 Datalog
8.5 Expressiveness
transitivity: [588]. aggregates: [431]. complex object and nested relations: [3].
8.6 Bibliography
241
242 CHAPTER 8. DECLARATIVE QUERY REPRESENTATION
Chapter 9
9.5 Bibliography
243
244 CHAPTER 9. TRANSLATION AND LIFTING
Chapter 10
Query Equivalence,
Containment, Minimization,
and Factorization
q(X, Y ) : −p(X, Y ).
under set semantics. The latter query now contains fewer body literals. Query
minimization now asks for an equivalent query with the least possible number
of body literals. One possible approach is to successively delete a body literal
until no more body literal can be deleted without violating equivalence to the
original query.
The above example is also illustrative since it shows that query equiva-
lence (and thus query containment) differs under different semantics: whereas
the above two queries are equivalent under set semantics, they are not under
bag semantics. To see this, consider the extensional database {p(a, b), p(a, b)}.
The result of the first query contains p(a, b) four times whereas the last query
contains is only 2 times.
245
246CHAPTER 10. QUERY EQUIVALENCE, CONTAINMENT, MINIMIZATION, AND FACTORIZAT
q1 : r1 : − l1 , . . . , lk
q2 : r2 : − l10 , . . . , lm
0
Let V(qi ) be the set of variables occurring in qi , and C(qi ) be the set of constants
occurring in qi . Further, let h be a substitution h : V(q2 ) → (V(q1 ) ∪ C(q1 )).
We call h a containment mapping from q2 to q1 , if and only if the following
conditions are fulfilled:
The latter condition states that for each body literal li0 in q2 there is a body
literal lj in q1 such that h(li ) = li0 . Note that this does not imply that h is
injective or surjective.
The following theorem connects containment mappings with the contain-
ment problem:
2. ¬∃ R0 ⊂ R R0 ≡ Q
This corollary implies that we can minimize a query that is a union of con-
junctive queries by eliminating those conjunctive queries Qi from it that are
contained in some Qj .
For conjunctive queries the problems of containment, equivalence, and min-
imization are
The problems of containment, equivalence, and minimization of conjunctive
queries are most difficitult if all body literals have a common predicate p. This
is quite an unrealistic assumption as typical conjunctive queries will not only
self-join the same relation. A first question is thus whether there exist special
cases where there are polynomial algorithms for containment checking. Another
strain of work is devoted to more complex queries. As it turns out, the results
become less nice and more restricted.
Theorem 10.1.5 Assume the two conjunctive queries q1 and q2 are of the form
q1 : p1 : − l1 , . . . , lk , e1 , . . . , el
q2 : p2 : − l10 , . . . , lm
0 , e0 , . . . , e0
1 n
where pi are the head literals, li and li0 are ordinary subgoals and ei and e0i
are inequalities. Let h be a containment mapping from q2 to q1 where both are
restricted to their ordinary literals. If additionally for all i = 1, . . . , n we have
e1 , . . . , el =⇒ h(e0i )
then q1 ⊆ q2 .
This result is due to Klug [432] who used the following procedure to reason
about inequalities using comparison operators in {=, <, ≤}. Given a set of
inequalities L, an directed graph G is defined whose nodes are the variables
and constants in L. Whenever for all x < y or x ≤ y in L, the edge (x, y) is
added to G. For all constants c and c0 in L, if c < c0 then we add an edge
(c, c0 ). Edges are labeled with the according comparison operator. For equality
predicates, an edge in both direction is added. Given the graph G, we conclude
that x ≤ y if there is a path from x to y and x < y only if additionally at least
one edge is labelled by <. An alternative is to use the procedure presented in
Section 11.2.3 to solve the inequality inference problem. It also allows for the
comparison operator 6=.
To see why a dense domain is important consider the domain of integers.
From 1 < x < 3 we can easily conclude that x = 2, a fact we can derive
neither from the procedure above nor from the axioms and inference procedure
presented in Section 11.2.3.
10.2. BAG SEMANTICS 249
10.3 Sequences
10.3.1 Path Expressions
XPath constructs and their short-hands to denote XPath sublanguages.
• branching (’[]’)
Otherwise XPath only contains the child axis and node name tests. These
sublanguages are represented as tree patterns.
Query containment for certain subclasses:
• Por is in PTIME
• P[],or is coNP-complete
• P| is coNP-complete [518]
[545] showed that P[],∗,//,| is coNP-complete for infinite alphabets and in
PSPACE for finite alphabets.
10.4. MINIMIZATION 251
• P//,| is PSPACE-complete
• P[],∗,// with variable binding and equivality tests is Πp2 - hard [201]
10.4 Minimization
minimization: [445]
10.6 Bibliography
In a pair of papers Aho, Sagiv, and Ullmann [16, 17] study equivalence, con-
tainment, and minimization problems for tableaux. More specifically, they
introduce a restricted variant of relational expressions containing projection,
natural join, and selection with predicates that only compare attributes with
constants. They further assume the existence of a universal relation. That
is, every relation R is the projection of the universal relation on A(R). Now,
these restricted conjunctive queries can be expressed with tableaux. The au-
thors tableaux equivalence, containment, and minimization problems also in
the presence of functional dependences. The investigated problems are all NP-
complete. Since the practical usefulness is limited we do not give the concrete
results of this pair of papers.
[134, 137] contains (complexity) results for deciding query equivalence in
the case of recursive and nonrecursive datalog.
252CHAPTER 10. QUERY EQUIVALENCE, CONTAINMENT, MINIMIZATION, AND FACTORIZAT
Rewrite Techniques
253
Chapter 11
Simple Rewrites
Constant subexpressions are evaluated and the result replaces the subexpres-
sion. For example an expression 1/100 is replaced by 0.01. Other expressions
like a − 10 = 50 can be rewritten to a = 40. However, the latter kind of rewrite
is rarely performed by commercial systems.
Eliminate Between
Eliminate IN
Eliminating LIKE
255
256 CHAPTER 11. SIMPLE REWRITES
Eliminate - and /
(x − y) ; x + (−y) x/y ; x ∗ (1/y)
11.2.2 Equality
Equality is a reflexive, symmetric and transitive binary relationship (see Fig. 11.2).
Such a relation is called an equivalence relation Hence, a set of conjunctively
258 CHAPTER 11. SIMPLE REWRITES
N OT true → f alse
N OT f alse → true
p AN D true → p
p AN D f alse → f alse
p OR true → true
p OR f alse → p
x=x
x=y =⇒ y = x
x = y ∧ y = z =⇒ x = z
11.2.3 Inequality
Table 11.1 gives a set of axioms used to derive new predicates from a set of
conjunctively occurring inequalities S (see [767], see Fig. 11.4).
11.2. DERIVING NEW PREDICATES 259
Step 3 can be performed as follows. For any true IUs X and Y we find these
IUs Z with X ≤ Z ≤ Y .
Then we check whether any two such Z’s are related by 6=. Here, it is
sufficient to check the original 6= pairs in S and these derived in 1.
A1 : X ≤ X
A2 : X < Y ⇒ X ≤ Y
A3 : X < Y ⇒ X 6= Y
A4 : X ≤ Y ∧ X 6= Y ⇒ X < Y
A5 : X 6= Y ⇒ Y 6= X
A6 : X < Y ∧ Y < Z ⇒ X < Z
A7 : X ≤ Y ∧ Y ≤ Z ⇒ X ≤ Z
A8 : X ≤ Z ∧ Z ≤ Y ∧ X ≤ W ∧ W ≤ Y ∧ W 6= Z ⇒ X 6= Y
11.2.4 Aggregation
select A1 , . . . , Ak , a1 , . . . , al
from R1 , . . . , Rn
where pw
group by
A1 , . . . , A m
having ph
260 CHAPTER 11. SIMPLE REWRITES
Even if we know that max(salary) > 100.000, the above query block is not
equivalent to
select deptNo, max(salary), min(salary)
from Employee
where salary ¿ 100.000
group by
deptNo
Neither is
select deptNo, max(salary)
from Employee
group by
deptNo
having avg(salary) ¿ 50.000
11.3. PREDICATE PUSH-DOWN AND PULL-UP 261
equivalent to
11.2.5 ToDo
[497]
11.6.1 Introduction
The growing importance of object-relational database systems (ORDBMS) [730]
has kindled a renewed interest in the efficient processing of set-valued attributes.
One particular problem in this area is the joining of two relations on set-valued
attributes [269, 360, 608]. Recent studies have shown that finding optimal join
algorithms with set-containment predicates is very hard [98]. Nevertheless, a
certain level of efficiency for joins on set-valued attributes is indispensable in
practice.
Obviously, brute force evaluation via a nested-loop join is not going to be
very efficient. An alternative is the introduction of special operators on the
physical level of a DBMS [360, 608]. Integration of new algorithms and data
structures on the physical level is problematic, however. On one hand this
approach will surely result in tremendous speed-ups, but on the other hand
this efficiency is purchased dearly. It is very costly to implement and integrate
new algorithms robustly and reliably.
262 CHAPTER 11. SIMPLE REWRITES
11.6.2 Preliminaries
In this section we give an overview of the definition of the set type. Due to the
deferral of set types to SQL-4 [247], we use a syntax similar to that of Informix
1 . A possible example declaration of a table with a set-valued attribute is:
setID is the key of the relation, whereas content stores the actual set. The
components of a set can be any built-in or user-defined type. In our case we
used set<char(3)>, because we wanted to store 3-grams (see also Section ??).
We further assume that on set-valued attributes the standard set operations
and comparison operators are available.
Our rewriting method is based on unnesting the internal nested representa-
tion. The following view defining the unnested version of the above table keeps
our representation more concise:
where setID identifies the corresponding set, d takes on the different values in
content and card is the cardinality of the set. We also need unnest<char(3)>,
a table function that returns a set in the form of a relation. As unnest<char(3)>
returns an empty relation for an empty set, we have to consider this special case
in the second subquery of the union statement, inserting a tuple containing a
dummy value.
(The comparison with 0 is only needed for DB2, which does not understand the
type bool.)
This query can be rewritten as follows. The basic idea is to join the unnest-
ed version of the table based on the set elements, group the tuples by their
set identifiers, count the number of elements for every set identifier and com-
pare this number with the original counts. The filter predicate vn1.card <=
vn2.card discards some sets that cannot be in the result of the set-containment
join. We also consider the case of empty sets in the second part of the query.
Summarizing the rewritten query we get
The formulation of the unnested query is much simpler than the unnested
query in Section 11.6.3. Due to our view definition, not much rewriting is
necessary. We just have to take care of empty sets again, although this time in
a different, simpler way.
11.7 Bibliography
This section is based on the investigations by Helmer and Moerkotte [363].
There, we also find a performance evaluation indicating that that the rewrites
depending on the relation sizes result in speed-up factors between 5 and 50 even
for moderately sized relations. Nevertheless, it is argued their, that support for
set-valued attributes must be build into the DBMS. A viable alternative to the
rewrites presented here is the usage of special join algorithms for join predicates
involving set-valued attributes [269, 359, 360, 499, 514, 515, 608]. Nevertheless,
as has been shown by Cai, Chakaravarthy, Kaushik, and Naughton, dealing
with set-valued attributes in joins theoretically (and of course practical) difficult
issue [98]. Last, to efficiently support simple selection predicates on set-valued
attributes, special index structures should be incorporated into the DBMS [361,
362, 364].
11.7. BIBLIOGRAPHY 265
IU::addEqualityClassUnderThis(IU* lIU){
IU*lRepresentativeThis = this -> getEqualityRepresentativeIU;
IU*lRepresentativeArg = aIU -> getEqualityRepresentativeIU;
IU::addEqualityPredicate(Compositing* p){
IU*lLeft = p -> leftIU;
IU*lRight = p -> rightIU;
if (p -> isEqualityPredicateIU &&
lLeft -> getEqualityRepresentativeIU ==
lRight -> getEqualityRepresentativeIU){
if(lLeft - > isBoundToConstantIU) {
lLeft -> addEqualityClassUnderThis(lRight);
}else
if(lRight -> isBoundToConstantIU){
lRight -> addEqualityClassUnderThis(lLeft),
}else
if (lLeft -> _equalityClassRank > lRight ->
_equalityClassRank){
lLeft -> addEqualityClassUnderThis(lRight)
}else{
lright -> addEqualityClassUnderThis(lLeft)
}
}
}
Figure 11.3:
266 CHAPTER 11. SIMPLE REWRITES
A1 X≤X
A2 X <Y ⇒ X≤Y
A3 X <Y ⇒ X 6= Y
A4 X ≤Y ∧X 6= Y ⇒ X<Y
A5 X 6= Y ⇒ Y 6= X
A6 X <Y ∧Y <Z ⇒ X<Z
A7 X ≤Y ∧Y ≤Z ⇒ X≤Z
A8 X ≤ Z ∧ Z ≤ Y ∧ X ≤ W ∧ W ≤ Y ∧ W 6= Z ⇒ X 6= Y
View Merging
create view
However, there are a few pitfalls. This simple version of view merging can
only be applied to simple select-project-join queries not containing duplicate
elimination, set operations, grouping or aggregation. In these cases, complex
view merging must be applied.
267
268 CHAPTER 12. VIEW MERGING
but view resolution with a subsequent push-down of the predicate e.salary >
150.000 will result in
select e.eno, e.name
from ( select e1.eno, e1.name, e1.salary, e1.dno
from Emp1[e1]
where e1.salary > 150000)
union
( all select e2.eno, e2.name, e2.salary, e2.dno
from Emp2[e2]
where e2.salary > 150000)
the query
select *
from EmpStat[e]
where e.dno = 10
can be rewritten to
select e.dno, min(e.salary) minSal, max(e.salary) maxSal, avg(e.salary) avgSal
from Emp[e]
where e.dno = 10
group by e.dno
selectd.name, s.avgSalary)
from Dept[d], (select e.dno, avg(salary) as avgSalary
from Emp[e]
group by e.dno) [s]
where d.location = ‘Paris‘ and
d.dno = s.dno
This query can then be unnested using the techniques of Section ??.
Sometimes strange results occur. Consider for example the view
This is perfectly o.k. You just need to think twice about it. The resulting plan
will contain two group operations: XXX Plan
and a query asking for all those employees together with their salaries in Parisian
departments earning the minimum salary:
Note that the employee relation occurs twice. Avoiding to scan the employee
relation twice can be done as follows:
12.5 Bibliography
Chapter 13
Quantifier treatment
13.1 Pseudo-Quantifiers
Again, the clue to rewrite subqueries with a ANY or ALL predicate is to apply
aggregate functions [268]. A predicate of the form
In the above rewrite rules, the predicate < can be replaced by =, ≤, etc. If the
predicate is > or ≥ then the above rules are flipped. For example, a predicate
of the form >ANY becomes >select min and >ALL becomes >select max.
After the rewrites have been applied, the Type A or Type JA unnesting
techniques can be applied, depending on the details of the inner query block.
273
274 CHAPTER 13. QUANTIFIER TREATMENT
...
where exists (select ...
from ...
where ...)
It is equivalent to
...
where 0 > (select count(. . . )
from ...
where ...)
...
where not exists (select ...
from ...
where ...)
is equivalent to
...
where 0 = (select count(. . . )
from ...
where ...)
After these rewrites have been applied, the Type A or Type JA unnesting
techniques can be applied, depending on the details of the inner query block.
Case-No. 1 2 3 4 5 6 7 8
p() p() p() p() p(e1 ) p(e1 ) p(e1 ) p(e1 )
q() q(e1 ) q(e2 ) q(e1 , e2 ) q() q(e1 ) q(e2 ) q(e1 , e2 )
Case-No. 9 10 11 12 13 14 15 16
p(e2 ) p(e2 ) p(e2 ) p(e2 ) p(e1 , e2 ) p(e1 , e2 ) p(e1 , e2 ) p(e1 , e2 )
q() q(e1 ) q(e2 ) q(e1 , e2 ) q() q(e1 ) q(e2 ) q(e1 , e2 )
Q ≡ select e1
from e1 in E1
where for all e2 in select e2
from e2 in E2
where p:
q
where p (called the range predicate) and q (called the quantifier predicate) are
predicates in a subset of the variables {e1 , e2 }. This query pattern is denoted
by Q.
In order to emphasize the (non-)occurrence of variables in a predicate p, we
write p(e1 , . . . , en ) if p depends on the variables e1 , . . . , en . Using this conven-
tion, we can list all the possible cases of variable occurrence. Since both e1 and
e2 may or may not occur in p or q, we have to consider 16 cases (see Table 13.1).
All cases but 12, 15, and 16 are rather trivial. Class 12 queries can be unnested
by replacing the universal quantifier by a division, set difference, anti-semijoin,
or counting. Class 15 queries are treated by set difference, anti-semijoin or
grouping with count aggregation. For Class 16 queries, the alternatives are set
difference, anti-semijoin, and grouping with count aggregation. In all cases,
special care has to be taken regarding NULL values. For details see [156].
select al.name
from al in Airline
where for all ap in (select ap
from ap in Airport
where apctry = ’USA’):
ap in al.lounges
Define U ≡ πap (σapctry=0 U SA0 (Airport[ap, apctry])). Then the three alternative
algebraic expressions equivalent to this query are
then Airline[name]
else µap:lounges (Airline[name, lounges]) ÷ U
This plan is only valid, if the projected attributes of Airline form a su-
perkey.
ifσp(e (E2 [e2 ])6=∅ (((E1 [e1 ] 1q(e1 ,e2 ) E2 [e2 ]) ÷ σp(e2 ) (E2 [e2 ])), E1 [e1 ])
2)
In case the selection σp(e2 ) (E2 [e2 ]) yields at least a one tuple or object, we can
apply the prediate p to the divident, as in
ifσp(e (E2 [e2 ])6=∅ (((E1 [e1 ] 1q(e1 ,e2 ) σp(e2 ) (E2 [e2 ])) ÷ σp(e2 ) (E2 [e2 ])), E1 [e1 ]).
2)
ifσp(e (E2 [e2 ])6=∅ ((µe2 :SetAttribute (E1 [e1 , SetAttribute]) ÷ σp(e2 ) (E2 [e2 ])), E1 [e1 ])
2)
E1 [e1 ] \ πe1 ((E1 [e1 ] × σp(e2 ) (E2 [e2 ])) \ (E1 [e1 ] 1q(e1 ,e2 ) σp(e2 ) (E2 [e2 ])))
This plan is mentioned in [719], however using a regular join instead of a semi-
join.
The anti-semijoin can be employed to eliminate the set difference yielding
the following plan:
E1 [e1 ]>¬q(e1 ,e2 ) σp(e2 ) (E2 [e2 ])
This plan is in many cases the most efficient plan. However, the correctness of
this plan depends on the uniqueness of e1 , i.e., the attribute(s) e1 must be a
(super) key of E1 . This is especially fulfilled in the object-oriented context if
e1 consists of or contains the object identifier.
We do not present the plans based group and count operations (see [156]).
13.3. UNIVERSAL QUANTIFIER 277
E1 [e1 ] \ πe1 ((E1 [e1 ] 1p(e1 ,e2 ) E2 [e2 ]) \ (E1 [e1 ] 1p(e1 ,e2 ) σq(e2 ) (E2 [e2 ])))
E1 [e1 ] \ πe1 ((E1 [e1 ] 1p(e1 ,e2 ) E2 [e2 ]) \ (E1 [e1 ] 1p(e1 ,e2 )∧q(e1 ,e2 ) E2 [e2 ])).
This plan can first be refined by replacing the seet difference of the two join
expression by a semijoin resultint in
Again, the uniqueness constraing on E2 [e2 ] is required for this most efficient
plan to be valid.
For all discussed classes, problems with NULL values might occur. In that
case, the plans have to refined [156].
278 CHAPTER 13. QUANTIFIER TREATMENT
13.4 Bibliography
[397] [188] [156] [610, 603]
Chapter 14
The first step in unnesting a query is view merging. This is simply the re-
placement of a view name by the view definitionThe result will always be a
nested query. Unnesting a nested query that resulted from view merging is not
different from unnesting any other nested query. However, due to a lack of
orthogonality, the kinds of nesting arising from view merging can be different
from that of “regular” nested queries. Several problems add to the complexity
of query unnesting.
• Special cases like empty results lead easily to bugs like the famous count
bug [424, 431, 268, 539, 540].
• If the nested query contains a grouping, special rules are needed to pull
up grouping operators [133].
• Special care has to be taken for a correct duplicate treatment [468, 586,
681, 682].
The main reason for the problems was that SQL lacked expressiveness and
unnesting took place at the query language level. The most important construct
needed for correctly unnesting queries are outer-joins [188, 268, 421, 227, 539].
After their introduction into SQL and their usage for unnesting, reordering
of outer-joins became an important topic [75, 188, 263, 539, 626]. Lately, a
unifying framework for different unnesting strategies was proposed in [540].
279
280 CHAPTER 14. UNNESTING NESTED QUERIES
Type JA nested queries have an inner block that is dependent on the outer block
and return a single element.
Obviously, the need for extending the relational classification arises from the
richness of the oo model compared to the relational one and its impact on
the query language. The classification we propose has three dimensions: the
original one plus two that are required by the following oo characteristics. In
the oo context, as opposed to the relational, (i) nested blocks may be located in
any clause of a select-from-where query and (ii) a dependency (i.e., reference
to a variable of the outer block) may be expressed in any clause of a query’s
inner block. We restrict the presentation to queries of type A/N/J/JA with
nesting and dependency (J/JA only) in the where clauses.
As in the relational context, the optimization of nested queries is done by
unnesting, using different kinds of joins and group operators. There are two
good reasons for unnesting nested queries. The first is that the underlying
evaluation plan of a nested query relies on nested loops that, as shown in [424],
can be very inefficient. On the other hand, we know of good algorithms for joins
and group operations (using indexes, sorting, hashing). The second reason
is that algebraic operators have nice properties that can be used for further
rewriting whereas nested algebraic expressions don’t have them a priori.
The original query is on the left-hand side. The rewritten query after NFST is
shown on the right-hand side—a convention holding throughout the rest of this
section. Note that the first define entry is independent of the second block.
Hence, it is written before it. Within the implementation of the query compiler
it is convenient to have an artificial outer SFWD-block to which the outer define
clause then belongs.
Type A nested queries can be unnested by moving them one block up (like
in the example). Sometimes, more efficient ways to to unnest these queries are
14.3. QUERIES OF TYPE N 281
possible. In the example the extent of Student has to be scanned twice. This
can be avoided by introducing the new algebraic operator MAX defined as
M AXf (e) := {x|x ∈ e, f (x) = maxy∈e (f (y))}
The MAX operator can be computed in a single pass over e.
Using MAX the above query can be expressed in the algebra as
q ≡ M AXs.age (Student[s])
select e.name
from Employee e
where e.dno in (select d.dno
from Department d
where d.name like ’S%’)
and its internal representation in textual form:
select en
from Employee[e] (J)
where ed in dnos
define en = e.name
ed = d.dno
dnos = (select dd
from Department[d](J)
where dn like ’S%’
define dd = d.dno
dn = d.dname)
If there further exists a reference constraint, we can eliminate the join altogeth-
er. For example, if the create table statement for Account contains a references
Customer on custno constraint on custno, then the query is equivalent to
select *
from Account[a]
The set ExpItems will be evaluated first, independently of query q. The result
of its evaluation will be used by the selection σxsi⊇ExpItems in the outer block.
The selection itself can be evaluated using an algorithm similar to that of a
relational division.
Note that there is no need to consider the negation of set comparisons,
since it is possible to define for each set comparison an equivalent negated
counterpart. Consider for example ¬(e1 ⊆ e2 ) and the set comparison operator
6⊆ defined as (e1 6⊆ e2 ) := (e1 \ e2 6= ∅).
For other cases and different unnesting possibilities see [162, 719]. The alter-
native unnesting strategies apply outer-joins and unary and binary grouping
operations.
Now, let us consider again the case featuring a set comparison. The query
below returns the employees who have sold all the items with a high-tech degree
larger than the sales speciality of the employee.
select x select x
from x in Employee from x in Employee
where x.SoldItems ⊇ where xsi ⊇ SpecialItems
select i define xsi = x.SoldItems
from i in Item xs = x.speciality
where i.hTD > x.speciality SpecialItems = select i
from i in Item
where ihTD > xs
define ihTD = i.hTD
The problem here is that the nested query is not constant. In order to unnest the
query and avoid several costly scans over the set of items, we have to associate
with each employee its corresponding set of special items. For this, we rely on
the following equivalence:
[188, 268] (remember, from the previous sections, that type N/J SQL queries
required anti-joins and semi-joins). In the oo context, there is no difference
between type J and type JA queries. The reason is that, in order to deal
with set comparison, outer-joins and grouping operations have already been
introduced to treat Type J queries and the resulting equivalences apply to type
J and type JA queries [162, 719]. The grouping operators have been defined
to allow the application of functions to the sets of grouped elements. This
function might as well be an aggregate function. Thus, by applying Eqv. 14.5–
14.8 aggregated type JA queries are treated in exactly the same manner as type
J queries.
Note that, if the applied function of the unary Γ in Equivalence 14.6 is an
aggregate function (as implied by type JA queries), then its right-hand side is
equivalent to the generalized aggregation of [188].
duplicate removal is enforced on the inner query but not on the outer. If we
just unnest is the way we did before, then both possibilities, specifying distinct
for the outer block and not specifying it, possibly results in wrong duplicate
288 CHAPTER 14. UNNESTING NESTED QUERIES
The zero value in the superscript ce = 0 corresponds to the result of the count
function on an empty set. The transformed query can be evaluated efficiently
using, for instance, a sort or an index on Employee.dept.
There exists one type J case where another more powerful technique can
be applied: a flatten operation is performed on the outer block, and there is
no tuple constructor within the outer block’s select clause. As shown in [161],
these queries can be optimized by pushing the flatten operation inside until it
is applied on stored attributes; thus eliminating the nesting. For completeness,
we repeat the example. The example query is
14.7. DIFFERENT KINDS OF DEPENDENCY 289
flatten(select flatten(select g
select tuple(name:c.name,age:c.age) from e in employee
from c in e.children define ec = e.children
where c.age < 18) g = select tuple(name:n,age:a)
from e in employee) from c in ec
where a < 18
define n = c.name
a = c.age )
where redundant tuple constructions were eliminated in the last steps. Note
that the flatten operation is now applied on stored data.
rewritten as
nq ≡ χsc.name (σscc=“Karlsruhe00 (χsc:s.customer,scc:sc.city (σs∈xs (Sale[s]))))
Type based rewriting can be performed again using the extent of class Cus-
tomer. This allows us, for instance, to use indexes on Customer.city and
Sale.customer to evaluate the query. However, since our goal is unnesting and
not general optimization, we do not detail on this. Concerning unnesting, it is
important to note that the dependency no longer specifies the range (xs[s]) but
now represents a predicate (σs∈xs ). Herewith, the algebraic expression is of the
same form as one resulting from a predicate dependency. Hence, our unnesting
techniques apply.
Remark Nothing restricts variables of the outer block to occur only at one
place within the inner block. If there exist several dependencies, all the cor-
responding unnesting techniques can be applied alternatively. Hence, if for
example a range and a predicate dependency occur, the latter should be used
for unnesting if the range dependency cannot be resolved by type based rewrit-
ing.
14.8 Unnesting IN
requires that the nested query produces no duplicates. this can be enforced by
introducing a duplicat elimination operation.
14.10 History
With his seminal paper Kim opened the area of unnesting nested queries in the
relational context [424]. Very quickly it became clear that enormous perfor-
292 CHAPTER 14. UNNESTING NESTED QUERIES
• Special cases like empty results lead easily to bugs like the count bug [431].
These have been corrected by taking different approaches [188, 431, 421,
268, 539, 540].
• If the nested query contains a grouping, special rules are needed to pull
up grouping operators [133].
• Special care has to be taken for a correct duplicate treatment [352, 468,
586, 681, 682].
The main reason for the problems was that SQL lacked expressiveness and
unnesting took place at the query language level. The most important construct
needed for correctly unnesting queries are outer-joins [188, 268, 421, 227, 539].
After their introduction into SQL and their usage for unnesting, reordering
of outer-joins became an important topic [75, 188, 263, 539, 626]. Lately, a
unifying framework for different unnesting strategies was proposed in [540].
With the advent of object-oriented databases and their query languages,
unnesting once again drew some attention from the query optimization research
community [161, 162, 720, 721, 719, 722]. Different from the relational unnest-
ing strategies which mainly performed at the (extended) SQL source level, re-
searchers prefered to use algebras that allowed nesting. For example, a predicate
of a selection operator could again contain algebraic operators. Unnesting than
took place at the algebraic level. The advantage of this approach are (1) it
is mainly query language independent and (2) by using algebraic equivalences,
correctness proofs could be delivered.
With the arrival of XQuery [240], the field was reopened by Paparizos et al.
[572]. Within their approach, unnesting takes place at the algebraic level. The
underlying algebra’s data model is based on sets of ordered labeled trees [393].
However, instead of using a simple equivalence, a verbal description of more
than one page is used to describe detection of applicability and the according
unnested plan. Since this description is verbal, it is not rigorous and indeed
buggy.
14.11 Bibliography
[256] [574] [612] [41] [100]
14.12 ToDo
betrachte unnesting query:
14.12. TODO 293
select [a:a,b:b]
from a in A
b in A.b
ExtremumSpecialCases ToDo
Nested Relational Approach: [100]
294 CHAPTER 14. UNNESTING NESTED QUERIES
Chapter 15
15.4 Bibliography
materialized view with aggregates: [717],
materialized view with disjunction: [11],
SQL Server: [282]
other: [12, 125, 126, 139, 472, 732, 764, 827] [114, 118, 140, 128, 244, 411,
457, 575, 602, 673]
some more including maintenance etc: [10, 14, 47, 81, 125, 133, 175, 328, 342]
[373, 410, 471, 599, 639, 228, 717] [732, 741, 740, 849, 828] [6, 215, 216, 350]
Overview: [334]
[473]
performance eval: [79]
Stacked views: [193]
recursion: [218]
with patterns (integration): [602], [217, 219], [200]
295
296CHAPTER 15. OPTIMIZING QUERIES WITH MATERIALIZED VIEWS
Chapter 16
297
298 CHAPTER 16. SEMANTIC QUERY REWRITE
16.4 Bibliography
[73] [65] [820] Foreign functions semantic rules rewrite: [128] Conjunctive Queries,
Branch Minimization: [633]
Part IV
Plan Generation
299
Chapter 17
• For large join queries do not apply transitivity of equality to derive new
predicates and disable cross products and possibly bushy trees.
17.4 Bibliography
301
302 CHAPTER 17. CURRENT SEARCH SPACE AND ITS LIMITS
Chapter 18
18.1 Introduction
Simple rewrites as indicated in Section ?? for IN and OR predicates that boil
down to comparisons of a column with a set of constants can eliminate disjunc-
tion from the plan or push it into a multirange index access.
Another possibility that can be used for disjunctions on single columns is
to use DISJOINT UNION of plans. This is a special form of UNION where
conditions ensure that no phantom duplicates are produced. The DISJOINT
UNION operator merely concatenates the result tables without any further
overhead like duplicate elimination.
For example a predicate of the form x = c1 or y = c2 where x and y are
columns of the same table results in two predicates
1. x = c1
2. x <> c1 AND y = c2
Obviously, no row can satisfy both conditions. Hence, the query select *
from R where x = c1 or y = c2 can be safely rewritten to
In case there are indexes on x and y efficient plans do exist. If they don’t the
table R needs to be scanned twice. This problem is avoided by using bypass
plans.
DISJOIN UNIONs can also be used for join predicates. Consider the follow-
ing example query: select * from R, S where R.a = S.a OR R.b = S.a This
query can be rewritten to (select * from R, S where R.a = S.a) DISJOINT
UNION (select * from R, S where R.a <> S.a and R.b = S.b) The gen-
eral condition here is that all equality predicates have one side identical. Note
that both tables are scanned and joined twice. Bypass plans will eliminate this
problem.
303
304 CHAPTER 18. OPTIMIZING QUERIES WITH DISJUNCTIONS
b a b c b c
a c a a a
Ia Ib II
a b <
c
b <
c a
I II
CNF plans never produce duplicates. The evaluation of the boolean factors
can stop as soon as some predicate evaluates to true. Again, some (expensive)
predicates might be evaluted more than once in CNF plans. Figure 18.3 shows
some bypass plans. Note the different output streams. It should be obvious,
that a bypass plan can be more efficient than both a CNF or DNF plan. It
c b c a a
- + +
b c a a c a
c
-- + - + - +
a a b b b
I II III IV V
is possible to extend the idea of bypass plans to join operators. However, this
and the algorithm to generate bypass plans is beyond the scope of the current
paper (see [418, 724, 158]).
306 CHAPTER 18. OPTIMIZING QUERIES WITH DISJUNCTIONS
• logical information
• physical information
– costs
– cardinality information
For fast processing, the first three set-valued items in the logical information
block are represented as bit-vectors. However, the problem is that an upper
bound on the size of these bitvectors is not reasonable. Hence, they are of
variant size. It is recommendable, to have a plan node factory that generates
plan nodes of different length such that the bit-vectors are included in the plan
node. A special interpreter class then knows the offsets and lengths of the
different bitvectors and supplies the operations needed to deal with them. This
bit-vector interpreter can be attached to the plan generator’s control block as
indicated in Fig. 25.3.
18.6 Bibliography
Disjunctive queries: P. Ciaccia and M. Scalas: Optimization Strategy for Re-
lational Queries. IEEE Transaction on Software Engineering 15 (10), pp 1217-
1235, 1989.
Kristofer Vorwerk, G. N. Paulley: On Implicate Discovery and Query Op-
timization. International Database Engineering and Applications Symposium
(IDEAS’02)
Jack Minker, Rita G. Minker: Optimization of Boolean Expressions-Historical
Developments. IEEE Annals of the History of Computing 2 (3), pp 227-238,
1980.
Chaudhuri: SIGMOD 03: [123]
Conjunctive Queries, Branch Minimization: [633]
Also Boolean Difference Calculus (?): [715]
308 CHAPTER 18. OPTIMIZING QUERIES WITH DISJUNCTIONS
Chapter 19
19.1 Introduction
In general, join and grouping operations are not reorderable. Consider the fol-
lowing relations R and S
R A B S A C
a 5 a 7
a 6 a 8
Joining these relations R and S results in
R1S A B C
a 5 7
a 5 8
a 6 7
a 6 8
Applying ΓA;count(∗) to R and R 1 S yields
309
310 CHAPTER 19. GROUPING AND AGGREGATION
where p denotes
Figure 20.1 (a) shows this plan graphically. Note that the grouping operator
is executed last in the plan. This is the standard translation technique applied
to SQL. However, Yan and Larson discovered that under certain circumstances
grouping and join can be reordered [823]. In sequel work, Yan and Larson as
well as Chaudhuri and Shim extended the possibilities to group before or after
a join [129, 823, 824, 825, 826]. These extensions of the search space are the
topic of this chapter.
Before we delve into details, let us consider an alternative plan for the above
query. Here, we push down the grouping operator: The plan then becomes:
This plan (see also Figure 20.1 (b)) is equivalent to the former plan. Moreover,
if the grouping operator strongly reduces the cardinality of
σs.date≥... (Sold[s])
because every employee sells many items, then the latter plan might become
cheaper since the join inputs are smaller than in the former plan. This moti-
vates the search for conditions under which join and grouping operators can be
reordered. Several papers discuss this reorderability and other kinds of search
space extensions [129, 823, 824, 825, 826]. We will summarize their results in
subsequent sections. Before that, we will take a look at aggregation functions
and their properties.
The plan for the rest of the chapter is the following. First, we take a closer
todo look at aggregate functions and their properties.
project[e.eid, amount]
join[e.eid=s.eid]
Sold[s]
(a)
project[e.eid, amount]
join[e.eid = s.eid]
select[s.date ...]
Sold[s]
(b)
Let N denote either a numeral data type (e.g. integer or float) or a tuple
[a1 : τ1 , . . . , an : τn ] where each type τn is a numeral data type. Further, let N
contain a special value NULL denoted by N U LL.
A scalar aggregation function agg is a function with signature
agg : bulk(()τ ) → N
.
A scalar aggregation function agg : bulk(()τ ) → N is called decomposable if
there exist functions
aggI : bulk(()τ ) → N 0
aggO : bulk(()N 0 ) → N
with
agg(Z) = aggO (bulk(()aggI (X), aggI (Y )))
for all X and Y (not empty) with Z = X ∪Bulk Y . This condition assures that
agg(Z) can be computed on arbitrary subsets (-lists, -bags) of Z independently
and the (partial) results can be joined to yield the correct (total) result. If the
condition holds, we say that agg is decomposable with inner aggI and outer
aggO . Decomposability will also be applied to vectors of aggregate functions.
A decomposable scalar aggregation function agg : bulk(()τ ) → N is called
reversible if for aggO there exists a function (aggO )−1 : N 0 , N 0 → N 0 with
for all X, Y , and Z with Z = X ∪Bulk Y . This condition assures that we can
compute agg(X) for a subset (-list, -bag) X of Z by “subtracting” its aggregated
complement Y from the “total” aggO (aggI (Z)) by using (aggO )−1 .
The fact that scalar aggregation functions can be decomposable and re-
versible is the basic observation upon which the efficient evaluation of aggrega-
tion functions builds.
As an example consider the scalar aggregation avg : {{(}}[a : f loat]) →
f loat averaging the values of the attributes a of a bag of tuples with a single
attribute a. It is reversible with
where
sum(X.a) denotes the sum of all values of attribute a of the tuples in X, and aggregation
function!duplicated
|X| denotes the cardinality of X. Note that aggI (∅) = [sum : 0, count : 0], and duplicated
γ([sum : 0, count : 0]) is undefined as is avg(∅). aggregation
Not all aggregation functions are decomposable and reversible. For instance, function
min and max are decomposable but not reversible. If an aggregation function
is applied to a bag that has to be converted to a set, then decomposabili-
ty is jeopardized for sum and count. That is, in SQL sum(distinct) and
count(distinct) are not decomposable.
Let us look at the decomposition of our five aggregation functions. We can
decompose them as follows:
agg∗c
i (ei ) is defined as aggi (ei ) if aggi is a class D aggregate function. If aggi
is a Class C aggregate function, we define agg∗c i (ei ) as aggi (ei ) ∗ c where c is
a special attribute that contains the result of some count in a subquery block.
F ∗c is called duplicated aggregation function of F .
OQL, the conversion function distinct is used. For example, the OQL query
avg(distinct(bag(1,1,2,3,3))) return 2. Similarily for XQuery.
We now come to an essential difference between SQL and OQL/XQuery.
SQL allows expressions of the form sum(a) where a is a single-valued attribute.
Since aggregation functions take bulk types as arguments, this expression may
seem to contain a type error. Let us call this false aggregates. There are
two cases to consider depending on whether the block where the aggregation
function(s) occur exhibits a group by or not. . . .
*
select[all | distinct] A, F (B)
from R, S
where pR ∧ pS ∧ pR,S
group by G
with
G = GR ∪ GS , GR ⊆ A(R), GS ⊆ A(S),
B ⊆ A(R) A = AR ∪ AS , AR ⊆ GR , AS ⊆ GS
We are interested in the conditions under which the query can be rewritten
into
select[all | distinct] A, F B
from R0 , S 0
where pR,S
with R0 (aggIR , F B) ≡
*
select all aggIR , F (B) as F B
from R
where pR
group by aggIR
and S 0 (aggIS ) ≡
[d]
ΠA,F Γ * (σpR (R)) 1pR,S σpS (S)
aggIR ;F : F (B)
holds iff in σpR ∧pS ∧pR,S (R × S) the following functional dependencies hold:
F D1 : G → aggIR
F D2 : aggIR , GS → κS
Note that since GS ⊆ G, this implies G → κS .
F D2 implies that for any group there is at most one join partner in S.
Hence, each tuple in Γ I * (σpR (R)) contributes at most one row to the
aggR ;F : F (B)
overall result.
F D1 ensures that each group of the expression on the left-hand side corre-
sponds to at most one group of the group expression on the right-hand side.
We now consider queries with a having clause.
In addition to the assumptions above, we have that the tables in the from
clause can be partitioned into R and S such that R contains all aggregated
columns of both the select and the having clause. We further assume that
conjunctive terms in the having clause that do not contain aggregation func-
tions have been moved to the where clause.
Let the predicate of the having clause have the form HR ∧ H0 where HR ⊆
A(R) and H0 ⊆ R ∪ S where H0 only contains non-aggregated columns from S.
We now consider all queries of the form
316 CHAPTER 19. GROUPING AND AGGREGATION
*
select[all | distinct] A, F (B)
from R, S
where pR ∧ pS ∧ pR,S
group by G
* *
having H0 F0 (B) ∧ HR FR (B)
* *
where F0 and FR are vectors of aggregation functions on the aggregated columns
B.
An alternative way to express such a query is
select[all | distinct] G, F B
from R0 , S
where cS ∧ cR,S ∧ H0 (F0 B)
R0 aggIR , F B, F0 B ≡
where
* *
select all aggIR , F (B) as F B, F0 (B) as F0 B
from R
where cR
group by aggIR
*
having HR FR (B)
The according
equivalence
is [825]:
ΠG,F σHR ∧H0 Γ * * * σpR ∧pS ∧pR,S (R × S)
G;F : F (B),FR :FR (B),F0 :F0 (B)
≡
ΠG,F σpR,S ∧pS ∧H0 (F0 ) ΠG,F,F0 σHR Γ * * * (R) ×S
G;F : F (B),FR :FR (B)F0 :F0 (B)
the query
Note that Equivalence ?? cannot be applied here. However, if there are many
sales performed by a department, it might be worth reducing the cardinality of
the left join input by introducing an additional group operator. The result is
• Allowed are only sum, min, max. Not allowed are avg and count.
• For any allowed aggregation function we only allow for agg(all . . .).
Forbidden is agg(distinct . . .).
with
G1 = (F (p) ∪ G) ∩ A (R1 )
Further, the following condition must hold for all i(1 ≤ i ≤ n):
! !
[ [
aggi Sk = aggi2 {aggi1 (Si )}
k k
318 CHAPTER 19. GROUPING AND AGGREGATION
Proof :
First, note that
[
R1 1p R2 = R1 1p {t2 } (19.2)
t2 ∈R2
ΓG;A (R1 [t1 ]) 1p {t2 } = σp(t1 ◦t2 ) (ΓG;A (R1 [t1 ])) (19.3)
= ΓG;A σp(t1 ◦t2 ) (R1 [t1 ])
= ΓG;A (R1 [t1 ] 1p {t2 })
holds where we have been a little sloppy with t1 . Applying (20.2) and (20.3)
to ΓG1 ;A1 (R1 ) 1p R2 , the inner part of the right-hand side of the equivalence
yields:
[
ΓG1 ;A1 (R1 ) 1p R2 = ΓG1 ;A1 (R1 ) 1p {t2 } (19.4)
t2 ∈R2
[
= ΓG1 ;A1 (R1 1p {t2 })
t2 ∈R2
[
ΓG;A (R1 1p R2 ) = ΓG;A {t1 ◦ t2 |t1 ∈ R1 , p (t1 ◦ t2 )} (19.6)
t2 ∈R2
S
Abbreviate {t1 ◦ t2 |t1 ∈ R1 , p (t1 ◦ t2 )} by Y.
t2 ∈R2
Applying the definition of ΓG;A yields:
{t ◦ a | t ∈ ΠG (Y ), a = (A1 : e1 , . . . , An : en ) , (19.7)
ai = aggi ({ei (s)|s ∈ Y, S|G = t})}
Compare (20.5) and (20.7). Since ΠG (X) = ΠG (Y ), they can only differ in
their values of Ai .
19.6. MORE POSSIBILITIES 319
select [all|distinct] ~ 1, A
P1 , P2 , A ~2
from R1 , R2
where p1 and p1,2 and p2
group by G1 , G 2
The abbreviations used are explained below. Note that the order or grouping of
entries in the different clauses is of no relevance. It was just introduced by us for
convenience. An overview of all the different plans that can be produced from
an initial plan is given in Figure ??. Every of the subsequent equivalences has
the initial plan as its left-hand side and one of the other plans as its right-hand
320 CHAPTER 19. GROUPING AND AGGREGATION
Γ Γ Γ
1 1 1
1 a e 1 Γc 1
1 b 1 a e 1 a
ec c b c b
side. Before giving the equivalences together with their conditions, we define
some notation, some of them already used in the query above:
G+ +
i are the columns of Ri participating in join and grouping, i.e. Gi := (Gi ∪
F(p1,2 )) ∩ A(Ri )
The query can be translated into the algebra as follows:
(D)
ΠP,A (ΓG;A~ (σp1 ∧p1,2 ∧p2 (R1 × R2 )))
where the projection is duplicate eliminating if and only if the query specifies
select distinct. P is allowed to contain more columns than those in G if these
are functionally determined by G.
For the equivalences to follow, we assume that duplicates are preserved.
That is, the algebraic query representation is
AA = AAd ∪ AAu
AAd = AA ∩ A(R1 )
AAu = AA ∩ A(R2 )
F = A1 ∪ A2
F [AAd , AAu ]ΠA [GAd , GAu , AAd , AAu ]G[GAd , GAu ]σ[p1 ∧ p1,2 ∧ p2 ](R1 × R2 )
322 CHAPTER 19. GROUPING AND AGGREGATION
and E2 :=
with E3 :=
are equivalent if
1. A1 contains only decomposable aggregation functions and can be decom-
posed into Fd1 and Fd2
3. H1 −−→ G+
1 holds in σ[p1 ]R1
Note that the equivalence assumes that duplicates are preserved (no ΠD (default
in paper is ΠA which is not written) at the beginning of E1 ).
The main theorem requires that the final selection columns are the same as
the grouping columns, and that the final projection must not remove duplicates.
This can be relaxed. The final selection columns may be a subset of the grouping
columns and the final projection may remove duplicates [822].
Eager/Lazy Group-By We consider the special case where G1 contains
all the aggregation columns. In the following:
H1 denotes a set of columns in R1
and E2 :=
~ O [F AAd ]ΠA [GAd , GAu , F AAd ]G[GAd , GAu ]ΠA [GAd , GAu , F AAd ]σ[p1,2 ∧p2 ](E3 )
A
where E3 :=
~ I [AA]ΠA [H1 , GA+ , AA]G[H1 ]σ[p1 ]R1 ) × R2
(A d
are equivalent if
1. all aggregation functions in F[AA] are decomposable and can be decom-
posed into A~ I and A
~O
2. H1 −−→ G+
1 holds in σ[p1 ]R1
Proof:
19.6. MORE POSSIBILITIES 323
• Deleting all terms related to AAu in E2 of the main theorem gives the E2
here.
H1 denotes a set of grouping (!sic!in YaLa95 for the first time) columns in R1
CNT denotes the column produced by count(*) after grouping σ[p1 ]R1 on
H1
and E2 :=
where E3 :=
(COU N T []ΠA [H1 , GA+
d ]G[H1 ]σ[p1 ]R1 ) × R2
are equivalent if
2. H1 −−→ G+
1 holds in σ[p1 ]R1
COUNT[] means that we add CNT:COUNT(*) to the select list of the subquery
block.
If within the equivalence F only contains Class D aggregation functions, we
can simply use a distinct in the subquery block. We then call the transforma-
tion from E1 to E2 eager distinct and its reverse application lazy distinct. Note
that in this case Fa is the same as F .
Proof:
• Removing all terms related to AAd in E2 of the main theorem gives the
E2 here.
CNT denotes the column produced by count(*) after grouping σ[p2 ]R2 on
H2
and E2 :=
~ O [F AA], CN T ]ΠA [GAd , GAu , F AA, CN T ]G[GAd , GAu ]σ[p1,2 ](E3 × E4 )
Fa [A
where E3 :=
(COU N T []ΠA [H2 , GA+
u ]G[H2 ]σ[p2 ]R2 )
and E4 :=
~ I [AA]ΠA [H1 , GA+ , AA]G[H1 ]σ[p1 ]R1 )
(A d
are equivalent if
1. H2 −−→ G+
2 holds in σ[p1 ]R2
2. H1 −−→ G+
1 holds in σ[p1 ]R1
and E2 :=
where E3 :=
(COU N T []ΠA [H2 , GA+
u ]G[H2 ]σ[p2 ]R2 )
and E4 :=
(F [AA]ΠA [H1 , GA+
d , AA]G[H1 ]σ[p1 ]R1 )
are equivalent if
1. H2 −−→ G+
2 holds in σp1 (R2 )
19.6. MORE POSSIBILITIES 325
2. H1 −−→ G+
1 holds in σp1 (R1 )
5. G+
1 −−→ H1 holds in σ[p1 ]R1
6. G+
2 −−→ H2 holds in σ[p2 ]R2
Proof in [822].
Eager/Lazy Split In the following equivalence
A1 denotes the columns produced by A1 in the first aggregation of table σ[p1 ]R1
on H1
A2 denotes the columns produced by A2 in the first aggregation of table σ[p2 ]R2
on H2
F [AAd , AAu ]ΠA [GAd , GAu , AAd , AAu ]G[GAd , GAu ]σ[p1 ∧ p1,2 ∧ p2 ](R1 × R2 )
and E2 :=
where E3 :=
and E4 :=
4. H2 −−→ G+
2 holds in σ[p1 ]R2
5. H1 −−→ G+
1 holds in σ[p1 ]R1
Proof:
ΓG;A~ := ΠD (χ[g1 :g1 ,...,gk :gk ,a1 :g.a1 ,...,an :g.an ] (Γg;=G;[A]
~ (e)))
Translation Table:
Translation Table:
19.8. AGGREGATION OF NON-EQUI-JOIN RESULTS 327
GA+
d G+1 aGpa grouping columns plus join columns of R1
GA+
u G+2 aGpb grouping columns plus join columns of R2
H aNx set of attributes
NGAd H1 aNa
NGAu H2 aNb
CNT c c
19.9 Bibliography
The main source of information for this section are the papers by Yan and
Larson [823, 824, 825, 826]. These papers cover the material discussed in this
section although in a different notation. An informal description of some of the
ideas presented here can be found in a paper by Chaudhuri and Shim [129].
All of these papers somewhat discuss the the topic of introducing the optimal
placement of Grouping and Aggregation in a plan generator. Chaudhuri and
Shim devoted another paper to this important topic [131]. Duplicate removal
is a special case of grouping with no aggregation taking place. Already very
early on, Dayal, Goodman, and Katz observed that duplicate removal, can
be pushed down beneficially [189]. This finding was confirmed by Pirahesh,
328 CHAPTER 19. GROUPING AND AGGREGATION
Hellerstein, and Hasan [586]. Gupta, Harinarayan, and Quass [326] discusses
to push down duplicate elimination into a plan by counting the number of
occurring duplicates. That is, they change the representation of the bag. After
joins are performed, they reverse this represenatation change.
Pre-Aggregation: [365, 456] cardinality estimates for pre-aggregation: [366]
ToDo: [611], [634]
Aggregates: [15, 781, 130, 131, 133, 163, 164, 188] [226, 252, 313, 326, 327,
349, 421, 422] [431, 430, 527, 540, 542, 560, 690, 704, 717] [825, 847, 500]
Chapter 20
20.1 Introduction
In general, join and grouping operations are not reorderable. Consider the fol-
lowing relations R and S
R A B S A C
a 5 a 7
a 6 a 8
Joining these relations R and S results in
R1S A B C
a 5 7
a 5 8
a 6 7
a 6 8
Applying ΓA;count(∗) to R and R 1 S yields
329
330 CHAPTER 20. GROUPING AND AGGREGATION
where p denotes
Figure 20.1 (a) shows this plan graphically. Note that the grouping operator
is executed last in the plan.
Now consider the plan where we push the grouping operator down:
This plan (see also Figure 20.1 (b)) is equivalent to the former plan. More-
over, if the grouping operator strongly reduces the cardinality of
σs.date≥... (Sold[s])
because every employee sells many items, then the latter plan might become
cheaper since the join inputs are smaller than in the former plan. This moti-
vates the search for conditions under which join and grouping operators can be
reordered. Several papers discuss this reorderability [129, 823, 824, 825, 826].
We will summarize their results in subsequent sections.
*
select[all | distinct] A, F (B)
from R, S
where pR ∧ pS ∧ pR,S
group by G
20.2. LAZY AND EAGER GROUP BY 331
project[e.eid, amount]
join[e.eid=s.eid]
Sold[s]
(a)
project[e.eid, amount]
join[e.eid = s.eid]
select[s.date ...]
Sold[s]
(b)
with
G = GR ∪ GS , GR ⊆ A(R), GS ⊆ A(S),
B ⊆ A(R) A = AR ∪ AS , AR ⊆ GR , AS ⊆ GS
We are interested in the conditions under which the query can be rewritten
into
select[all | distinct] A, F B
from R0 , S 0
where pR,S
with R0 (αR , F B) ≡
*
select all αR , F (B) as F B
from R
where pR
group by αR
and S 0 (αS ) ≡
select all αR
from S
where pS
[d]
ΠA,F Γ * (σpR (R)) 1pR,S σpS (S)
αR ;F : F (B)
holds iff in σpR ∧pS ∧pR,S (R × S) the following functional dependencies hold:
F D1 : G → αR
F D2 : αR , GS → κS
Note that since GS ⊆ G, this implies G → κS .
F D2 implies that for any group there is at most one join partner in S.
Hence, each tuple in Γ * (σpR (R)) contributes at most one row to the
αR ;F : F (B)
overall result.
F D1 ensures that each group of the expression on the left-hand side corre-
sponds to at most one group of the group expression on the right-hand side.
We now consider queries with a having clause.
In addition to the assumptions above, we have that the tables in the from
clause can be partitioned into R and S such that R contains all aggregated
20.3. COALESCING GROUPING 333
columns of both the select and the having clause. We further assume that
conjunctive terms in the having clause that do not contain aggregate functions
have been moved to the where clause.
Let the predicate of the having clause have the form HR ∧ H0 where HR ⊆
A(R) and H0 ⊆ R ∪ S where H0 only contains non-aggregated columns from S.
We now consider all queries of the form
*
select[all | distinct] A, F (B)
from R, S
where pR ∧ pS ∧ pR,S
group by G
* *
having H0 F0 (B) ∧ HR FR (B)
* *
where F0 and FR are vectors of aggregate functions on the aggregated columns
B.
An alternative way to express such a query is
select[all | distinct] G, F B
from R0 , S
where cS ∧ cR,S ∧ H0 (F0 B)
where R0 (αR , F B, F0 B) ≡
* *
select all αR , F (B) as F B, F0 (B) as F0 B
from R
where cR
group by αR
*
having HR FR (B)
The according
equivalence
is [825]:
ΠG,F σHR ∧H0 Γ * * * σpR ∧pS ∧pR,S (R × S)
G;F : F (B),FR :FR (B),F0 :F0 (B)
≡
ΠG,F σpR,S ∧pS ∧H0 (F0 ) ΠG,F,F0 σHR Γ * * * (R) ×S
G;F : F (B),FR :FR (B)F0 :F0 (B)
the query
select region, sum (total price) as s
from Sales, Department
where did = deptid
group by region
is straightforwardly translated into the following algebraic expression:
Note that Equivalence ?? cannot be applied here. However, if there are many
sales performed by a department, it might be worth reducing the cardinality of
the left join input by introducing an additional group operator. The result is
• Allowed are only sum, min, max. Not allowed are avg and count.
• For any allowed aggregate function we only allow for agg(all . . .).
Forbidden is agg(distinct . . .).
with
G1 = (F (p) ∪ G) ∩ A (R1 )
20.3. COALESCING GROUPING 335
Further, the following condition must hold for all i(1 ≤ i ≤ n):
! !
[ [
2 1
aggi Sk = aggi {aggi (Si )}
k k
Proof :
First, note that [
R1 1p R2 = R1 1p {t2 } (20.2)
t2 ∈R2
ΓG;A (R1 [t1 ]) 1p {t2 } = σp(t1 ◦t2 ) (ΓG;A (R1 [t1 ])) (20.3)
= ΓG;A σp(t1 ◦t2 ) (R1 [t1 ])
= ΓG;A (R1 [t1 ] 1p {t2 })
holds where we have been a little sloppy with t1 . Applying (20.2) and (20.3)
to ΓG1 ;A1 (R1 ) 1p R2 , the inner part of the right-hand side of the equivalence
yields:
[
ΓG1 ;A1 (R1 ) 1p R2 = ΓG1 ;A1 (R1 ) 1p {t2 } (20.4)
t2 ∈R2
[
= ΓG1 ;A1 (R1 1p {t2 })
t2 ∈R2
[
ΓG;A (R1 1p R2 ) = ΓG;A {t1 ◦ t2 |t1 ∈ R1 , p (t1 ◦ t2 )} (20.6)
t2 ∈R2
S
Abbreviate {t1 ◦ t2 |t1 ∈ R1 , p (t1 ◦ t2 )} by Y.
t2 ∈R2
Applying the definition of ΓG;A yields:
{t ◦ a | t ∈ ΠG (Y ), a = (A1 : e1 , . . . , An : en ) , (20.7)
ai = aggi ({ei (s)|s ∈ Y, S|G = t})}
Compare (20.5) and (20.7). Since ΠG (X) = ΠG (Y ), they can only differ in
their values of Ai .
336 CHAPTER 20. GROUPING AND AGGREGATION
20.4 ToDo
[611]
20.4. TODO 337
Γ Γ Γ
1 1 1
1 a e 1 Γc 1
1 b 1 a e 1 a
ec c b c b
339
340 CHAPTER 21. GENERATING PLANS FOR THE FULL ALGEBRA
Chapter 22
Generating DAG-structured
Plans
@misc{ roy-optimization,
author = "Prasan Roy",
title = "Optimization of DAG-Structured Query Evaluation Plans",
url = "citeseer.nj.nec.com/roy98optimization.html" }
341
342 CHAPTER 22. GENERATING DAG-STRUCTURED PLANS
Chapter 23
23.1 Introduction
The most expensive operations (e.g. join, grouping, duplicate elimination) dur-
ing query evaluation can be performed more efficiently if the input is ordered
or grouped in a certain way. Therefore, it is crucial for query optimization to
recognize cases where the input of an operator satisfies the ordering or group-
ing requirements needed for a more efficient evaluation. Since a plan generator
typically considers millions of different plans – and, hence, operators –, this
recognition easily becomes a performance bottleneck for plan generation, often
leading to heuristic solutions.
The importance of exploiting available orderings has already been recog-
nized in the seminal work of Selinger et al [672]. They presented the concept of
interesting orderings and showed how redundant sort operations could be avoid-
ed by reusing available orderings, rendering sort-based operators like sort-merge
join much more interesting.
Along these lines, it is beneficial to reuse available grouping properties, for
example for hash-based operators. While heuristic techniques to avoid redun-
dant group-by operators have been given [129], for a long time groupings have
not been treated as thoroughly as orderings. One reason might be that while
orderings and groupings are related (every ordering is also a grouping), group-
ings behave somewhat differently. For example, a tuple stream grouped on the
attributes {a, b} need not be grouped on the attribute {a}. This is different
from orderings, where a tuple stream ordered on the attributes (a, b) is also
ordered on the attribute (a). Since no simple prefix (or subset) test exists for
groupings, optimizing groupings even in a heuristic way is much more difficult
than optimizing orderings. Still, it is desirable to combine order optimization
and the optimization of groupings, as the problems are related and treated sim-
343
344CHAPTER 23. DERIVING AND DEALING WITH INTERESTING ORDERINGS AND GROUPIN
ilarly during plan generation. Recently, some work in this direction has been
published [790]. However, this only covers a special case of grouping. Instead,
in this chapter we follow the approach presented by Neumann and Moerkotte
[544, 543]
Other existing frameworks usually consider only order optimization, and
experimental results have shown that the costs for order optimization can have
a large impact on the total costs of query optimization [544]. Therefore, some
care is needed when adding groupings to order optimization, as a slowdown of
plan generation would be unacceptable.
In this chapter, we present a framework to efficiently reason about orderings
and groupings. It can be used for the plan generator described in Chapter ??,
but is actually an independent component that could be used in any kind of plan
generator. Experimental results show that it efficiently handles orderings and
groupings at the same time, with no additional costs during plan generation and
only modest one time costs. Actually, the operations needed for both ordering
and grouping optimization during plan generation can be performed in O(1),
basically allowing to exploit groupings for free.
23.2.1 Ordering
During plan generation, many operators require or produce certain orderings.
To avoid redundant sorting, it is required to keep track of the orderings a certain
plan satisfies. The orderings that are relevant for query optimization are called
interesting orders [672]. The set of interesting orders for a given query consists
of
This includes the final ordering requested by the given query, if this is specified.
The interesting orders are logical orderings. This means that they specify a
condition a tuple stream must meet to satisfy the given ordering. In contrast,
the physical ordering of a tuple stream is the actual succession of tuples in
the stream. Note that while a tuple stream has only one physical ordering,
23.2. PROBLEM DEFINITION 345
it can satisfy multiple logical orderings. For example, the stream of tuples
((1, 1), (2, 2)) with schema (a, b) has one physical ordering (the actual stream),
but satisfies the logical orderings a, b, ab and ba.
Some operators, like sort, actually influence the physical ordering of a
tuple stream. Others, like select, only influence the logical ordering. For
example, a sort[a] produces a tuple stream satisfying the ordering (a) by
actually changing the physical order of tuples. After applying select[a=b] to
this tuple stream, the result satisfies the logical orderings (a), (b), (a, b), (b, a),
although the physical ordering did not change. Deduction of logical orderings
can be described by using the well-known notion of functional dependency (FD)
[709]. In general, the influence of a given algebraic operator on a set of logical
orderings can be described by a set of functional dependencies.
We now formalize the problem. Let R = (t1 , . . . , tr ) be a stream (ordered
sequence) of tuples in attributes A1 , . . . , An . Then R satisfies the logical order-
ing o = (Ao1 , . . . , Aom ) (1 ≤ oi ≤ n) if and only if for all 1 ≤ i < j ≤ r the
following condition holds:
Ω0 (O, F ) := O
Ωi (O, F ) := Ωi−1 (O, F ) ∪
[
O0 with o `f O0
f ∈F,o∈Ωi−1 (O,F )
S∞
Let Ω(O, F ) be the prefix closure of i=0 Ωi (O, F ). We write o `F o0 if and
only if o0 ∈ Ω(O, F ).
23.2.2 Grouping
It was shown in [790] that, similar to order optimization, it is beneficial to
keep track of the groupings satisfied by a certain plan. Traditionally, group-by
operators are either applied after the rest of the query has been processed or
are scheduled using some heuristics [129]. However, the plan generator could
take advantage of grouping properties produced e.g. by avoiding re-hashing if
such information was easily available.
Analogous to order optimization, we call this grouping optimization and
define that the set of interesting groupings for a given query consists of
This includes the grouping specified by the group-by clause of the query, if any
exists.
These groupings are similar to logical orderings, as they specify a condition
a tuple stream must meet to satisfy a given grouping. Likewise, functional
dependencies can be used to infer new groupings.
More formally, a tuple stream R = (t1 , . . . , tr ) in attributes A1 , . . . , An
satisfies the grouping g = {Ag1 . . . , Agm } (1 ≤ gi ≤ n) if and only if for all
1 ≤ i < j < k ≤ r the following condition holds:
∀1 ≤ l ≤ m ti .Agl = tk .Agl
⇒ ∀1 ≤ l ≤ m ti .Agl = tj .Agl
Two remarks are in order here. First, note that a grouping is a set of
attributes and not – as orderings – a sequence of attributes. Second, note
that given two groupings g and g 0 ⊂ g and a tuple stream R satisfying the
grouping g, R need not satisfy the grouping g 0 . For example, the tuple stream
((1, 2), (2, 3), (1, 4)) with the schema (a, b) is grouped by {a, b}, but not by {a}.
This is different from orderings, where a tuple stream satisfying an ordering o
also satisfies all orderings that are a prefix of o.
23.2. PROBLEM DEFINITION 347
Ω0 (G, F ) := G
Ωi (G, F ) := Ωi−1 (G, F ) ∪
[
G0 with g `f G0
f ∈F,g∈Ωi−1 (G,F )
S∞
Let Ω(G, F ) be i=0 Ωi (G, F ). We write g `F g 0 if and only if g 0 ∈ Ω(G, F ).
1. key constraints
3. filter predicates
4. simple expressions
23.3 Overview
As we have seen, explicit maintenance of the set of logical orderings and group-
ings can be very expensive. However, the ADT OrderingGrouping required
for plan generation does not need to offer access to this set: It only allows to
test if a given interesting order or grouping is in the set and changes the set
according to new functional dependencies. Hence, it is not required to explicitly
represent this set; an implicit representation is sufficient as long as the ADT
operations can be implemented atop of it. In other words, we need not be able
to reconstruct the set of logical orderings and groupings from the state of the
ADT. This gives us room for optimizations.
The initial idea (see [544]) was to represent sets of logical orderings as states
of a finite state machine (FSM). Roughly, a state of the FSM represents a
current physical ordering and the set of logical orderings that can be inferred
from it given a set of functional dependencies. The edges (transitions) in the
FSM are labeled by sets of functional dependencies. They lead from one state
to another, if the target state of the edge represents the set of logical orderings
that can be derived from the orderings the edge’s source node represents by
applying the set of functional dependencies the edge is labeled with. We have
350CHAPTER 23. DERIVING AND DEALING WITH INTERESTING ORDERINGS AND GROUPIN
abcd
ǫ {b → d}
ǫ ǫ
abc ab a
{b → d} ǫ {b → d}
ǫ
abdc abd
{b → d}
abc abcd
{b → d}
abcd abc abcd
ǫ
ǫ {b → d}
ǫ ǫ
abc ab a
{b → d} ǫ {b → d}
ǫ
abdc abd
{b → d} a,ab,abc
a,ab,abc,{ab} abd,abcd,
abdc,{abd}
grouping can be performed by checking if the node with the ordering or group-
ing is reachable from the current state by following edges (as we will see, this
can be precomputed to yield the O(1) time bound for the ADT operations). If
the state of the ADT must be changed because of functional dependencies, the
state in the FSM is changed by following the edge labeled with the functional
dependency.
However, the non-determinism of this transition is a problem. Therefore, for
practical purposes the NFSM must be converted into a DFSM. The resulting
DFSM is shown in Figure 23.5. Note that although in this simple example the
DFSM is very small, the conversion could lead to exponential growth. There-
fore, additional pruning techniques for groupings are presented in Section 23.4.7.
However, the inclusion of groupings is not critical for the conversion, as the
grouping part of the NFSM is nearly independent of the ordering part. In
Section 23.5 we look at the size increase due to groupings. The memory con-
sumption usually increases by a factor of two, which is the minimum expected
increase, since every ordering is a grouping.
Some operators, like sort, change the physical ordering. In the NFSM, this
is handled by changing the state to the node corresponding to the new physical
ordering. Implied by its construction, in the DFSM this new physical ordering
typically occurs in several nodes. For example, (a, b, c) occurs in both nodes of
the DFSM in Figure 23.5. It is, therefore, not obvious which node to choose.
We will take care of this problem during the construction of the NFSM (see
Section 23.4.3).
4. Precompute values
dependencies
F = {{b → c}, {b → d}},
the interesting groupings
have been extracted from the query. We assume that those in OT = {(a, b, c)}
and GT = {{b, c}} are tested for but not produced by any operator, whereas
those in OP = {(b), (a, b)} and GP = {{b}} may be produced by some algebraic
operators.
b b
a,b b,c
a,b,c
In our example, this creates the states (b, c) and (a), as (b, c) can be inferred
from (b) when considering {b → c} and (a) can be inferred from (a, b), since (a)
is a prefix of (a, b). The result is show in Figure 23.8 (ignore the edges).
Sometimes the ADT has to be explicitly initialized with a certain ordering
or grouping (e.g. after a sort). To support this, artificial edges are added
later on. These point to the requested ordering or grouping (states in QPI ) and
are labeled with the state that they lead to. Therefore, the input alphabet
Σ consists of the sets of functional dependencies and produced orderings and
groupings:
Σ = F ∪ QPI ∪ {}.
In our example, Σ = {{b → c}, {b → d}, (b), (a, b), {b}}.
Accordingly, the domain of the transition relation D is
The edges are formed by the functional dependencies and the artificial edges.
Furthermore, edges exist between orderings and the corresponding groupings,
as orderings are a special case of grouping:
DF D = {(q, f, q 0 ) | q ∈ Q, f ∈ F ∪ {}, q 0 ∈ Q, q ` f q 0 }
DA = {(q0 , q, q) | q ∈ QP
I }
DOG = {(o, , g) | o ∈ Ω(OI , F), g ∈ Ω(GI , F), o ≡ g}
D = DF D ∪ DA ∪ DOG
{b → c}
b b,c b
ǫ
{b → c}
ǫ
q0 a,b a b,c
{b → c} ǫ
a,b,c
b b
{b → c}
ǫ
q0 a,b b,c
a
{b → c} ǫ
a,b,c
states (DOG ), as every ordering is also a grouping. The final NFSM for the
example is shown in Figure 23.10. Note that the states representing (a, b, c)
and {b, c} are not linked by an artificial edge since it is only tested for, as they
are in QTI .
{b}
ǫ
b b
(b)
{b → c}
(a,b)
ǫ
qo a,b a b,c
{b → c} ǫ
a,b,c
{b → c}
{b} 1:{b} 4:{b},{b,c}
(b) {b → c}
qo 2:(b),{b} 5:(b),{b},{b,c}
(a,b)
{b → c}
3:(a),(a,b) 6:(a),(a,b),(a,b,c)
state 1: 2: 3: 4: 5: 6:
(a) (a,b) (a,b,c) (b) {b} {b,c}
1 0 0 0 0 1 0
2 0 0 0 1 1 0
3 1 1 0 0 0 0
4 0 0 0 0 1 1
5 0 0 0 1 1 1
6 1 1 1 0 0 0
state 1: 2: 3: 4:
{b → c} (a, b) (b) {b}
qo - 3 2 1
1 4 - - -
2 5 - - -
3 6 - - -
4 4 - - -
5 5 - - -
6 6 - - -
The precomputation step itself computes two matrices. The first matrix
denotes whether an NFSM state in QI is active, i.e. an interesting order or an
interesting grouping, is contained in a specific DFSM state. This matrix can
be represented as a compact bit vector, allowing tests in O(1). For our running
example, it is given (in a more readable form) in Figure 23.12. The second
matrix contains the transition table for the DFSM relation D. Using it, edges
in the DFSM can be followed in O(1). For the example, the transition matrix
is given in Figure 23.13.
1. All artificial nodes that behave exactly the same (that is, their edges lead
to the same states given the same input) are merged and
2. all edges to artificial states that can reach states in QI only through
edges are replaced with corresponding edges to the states in QI .
{(o1 , o2 ) | o1 ∈ QA , o2 ∈ QA ∧ ∀f ∈ F :
(Ω({o1 }, {f }) \ Ω({o1 }, )) =
(Ω({o2 }, {f }) \ Ω({o2 }, ))}.
The following states can be replaced with the next state reachable by an edge:
{o | o ∈ QA ∧ ∀f ∈ F :
Ω(Ω({o}, ), {f }) \ {o} =
Ω(Ω({o}, ) \ {o}, {f })}.
In the example, this removed the state (b, c), which was artificial and only led
to the state (b).
These techniques reduce the size of the NFSM, but still most states are
artificial states, i.e. they are only created because they can be reached by con-
sidering functional dependencies when a certain ordering or grouping is avail-
able. But many of these states are not relevant for the actual query processing.
For example, given a set of interesting orders which consists only of a single
ordering (a) and a set of functional dependencies which consists only of a → b,
the NFSM will contain (among others) two states: (a) and (a, b). The state
(a, b) is created since it can be reached from (a) by considering the functional
dependency, however, it is irrelevant for the plan generation, since (a, b) is not
360CHAPTER 23. DERIVING AND DEALING WITH INTERESTING ORDERINGS AND GROUPIN
an interesting order and is never created nor tested for. Actually, in the ex-
ample above, the whole functional dependency would be pruned (since b never
occurs in an interesting order), but the problem remains for combinations of
interesting orders: Given the interesting orders (a), (b) and (c) and the func-
tional dependencies {a → b, b → a, b → c, c → b}, the NFSM will contain states
for all permutations of a, b and c. But these states are completely useless, since
all interesting orders consist only of a single attribute and, therefore, only the
first entry of an ordering is ever tested.
Ideally, the NFSM should only contain states which are relevant for the
query; since this is difficult to ensure, a heuristic can be used which greatly
reduces the size of the NFSM and still guarantees that all relevant states are
available: When considering a functional dependency of the form a → b and
an ordering o1 , o2 , . . . , on with oi = a for some i (1 ≤ i ≤ n), the b can be
inserted at any position j with i < j ≤ n + 1 (for the special case of a condition
a = b, i = j is also possible). So, an entry of an ordering can only affect entries
on the right of its own position. This means that it is unnecessary to consider
those parts of an ordering which are behind the length of the longest interesting
order; since that part cannot influence any entries relevant for plan generation,
it can be omitted. Therefore, the orderings created by functional dependencies
can be cut off after the maximum length of interesting orders, which results in
less possible combinations and a smaller NFSM.
The space of possible orderings can be limited further by taking into account
the prefix of the ordering: before inserting an entry b in an ordering o1 , o2 , . . . , on
at the position i, check if there is actually an interesting order with the prefix
o1 , o2 , ...oi−1 , b and stop inserting if no interesting order is found. Also limit the
new ordering to the length of the longest matching interesting order; further
attributes will never be used. If functional dependencies of the form a = b occur,
they might influence the prefix of the ordering and the simple test described
above is not sufficient. Therefore, a representative is chosen for each equivalence
class created by these dependencies, and for the prefix test the attributes are
replaced with their representatives. Since the set of interesting orders with
a prefix of o1 , . . . , on is a superset of the set for the prefix o1 , ...on , on+1 , this
heuristic can be implemented very efficiently by iterating over i and reducing
the set as needed.
Additional techniques can be used to avoid creating superfluous artifical
states for groupings: First, in Step 2.3 (see Figure 23.6) the set of attributes
occurring in interesting groupings is determined:
AG = {a | ∃g ∈ GI : a ∈ g}
Now, for every attribute a occurring on the right-hand side of a functional
dependency the set of potentially reachable relevant attributes is determined:
r(a, 0) = {a}
r(a, n) = r(a, n − 1) ∪
{a0 | ∃(a1 . . . am → a0 ) ∈ F :
{a1 . . . am } ∩ r(a, n − 1) 6= ∅}
r(a) = r(a, |F|) ∩ AG
23.4. DETAILED ALGORITHM 361
select *
from S s, R r
where r.a=s.a and r.b=s.b and
r.c=s.c and r.d=s.d
When answering this query using a sort-merge join, the operator has to
request a certain odering. But there are many orderings that could be used:
The intuitive ordering would be abcd, but adcb or any other premutation could
have been used as well. This is problematic, as checking for an exponential
number of possibilities is not acceptable in general. Note that this problem is
not specific to our approach, the same is true, e.g., for Simmen’s approach.
The problem can be solved by defining a total ordering between the at-
tributes, such that a canonical ordering can be constructed. We give some rules
how to derive such an ordering below, but it can happen that such an order-
ing is unavailable (or rather the construction rules are ambiguous). Given, for
example, two indices, one on abcd and one on adcb, both orderings would be a
reasonable choice. If this happens, the operators have two choices: Either they
accept all reasonable orderings (which could still be an exponential number,
but most likely only a few orderings remaing) or they limit themselves to one
ordering, which could induce unnecessary sort operators. Probably the second
choice is preferable, as the ambiguous case should be rare and does not justify
the complex logic of the first solution.
The attribute ordering can be derived by using the following heuristical
rules:
1. Only attributes that occur in sets without natural ordering (i.e. complex
join predicates or grouping attributes) have to be ordered.
2. Orderings that are given (e.g., indices, user-requested orderings etc.) or-
der some attributes.
The rules must check if they create contradictions. If this happens. the
contradicting ordering must be omitted, resulting in potentially superfluous sort
operators. Note that in some cases these sort operators are simply unavoidable:
If for the example query one index on R exists with the ordering abcd and one
23.5. EXPERIMENTAL RESULTS 363
Figure 23.14: Plan generation for different join graphs, Simmen’s algorithm
(left) vs. our algorithm (middle)
index on S with the ordering dcba, the heuristical rules detect a contradiction
and choose one of the orderings. This results in a sort operator before the
(sort-merge) join, but this sort could not have been avoided anyway.
algorithm is applied, plan generation time can be as high as 200 seconds. This
observation leads to two important conclusions:
For completeness, we also give the memory consumption during plan gen-
eration for the two order optimization algorithms (see Fig. 23.15). For our
approach, we also give the sizes of the DFSM which are included in the to-
tal memory consumption. All memory sizes are in KB. As one can see, our
approach consumes about half as much memory as Simmen’s algorithm.
the additional costs. All experiments were performed on a 2.4 GHz Pentium
IV, using the gcc 3.3.1.
To examine the impact for real queries, we choose a more complex query
from the well-known TPC-R benchmark ([762], Query 8):
select
o year,
sum(case when nation = ’[NATION]’
then volume
else 0
end) / sum(volume) as mkt share
from
(select
extract(year from o orderdate) as o year,
l extendedprice * (1-l discount) as volume,
n2.n name as nation
from part,supplier,lineitem,orders,customer,
nation n1,nation n2,region
where
p partkey = l partkey and
s suppkey = l suppkey and
l orderkey = o orderkey and
o custkey = c custkey and
c nationkey = n1.n nationkey and
n1.n regionkey = r regionkey and
r name = ’[REGION]’ and
s nationkey = n2.n nationkey and
o orderdate between date ’1995-01-01’ and
date ’1996-12-31’ and
p type = ’[TYPE]’
) as all nations
group by o year
order by o year;
When considering this query, all attributes used in joins, group-by and
order-by clauses are added to the set of interesting orders. Since hash-based
solutions are possible, they are also added to the set of interesting groupings.
23.7. INFLUENCE OF GROUPINGS 367
Note that here OIT and GTI are empty, as we assumed that each ordering
and grouping would be produced if beneficial. For example, we might assume
that it makes no sense to intentionally group by o year: If a tuple stream is
already grouped by o year it makes sense to exploit this, however, instead of
just grouping by o year it could make sense to sort by o year, as this is required
anyway (although here it only makes sense if the sort operator performs early
aggregation). In this case, {o year} would move from GPI to GTI , as it would
be only tested for, but not produced.
The set of functional dependencies (and equations) contains all join condi-
tions and constant conditions:
preparation time
10 o+g (n-1)
o (n-1)
o+g (n)
o (n)
8 o+g (n+1)
o (n+1)
duration (ms)
0
4 5 6 7 8 9 10 11
no of relations
Here time and space requirements both increase by a factor of two. Since
all interesting orderings are also treated as interesting groupings, a factor of
about two was expected.
While Query 8 is one of the more complex TPC-R queries, it is not overly
complex when looking at order optimization. It contains 16 interesting order-
ings/groupings and 8 functional dependencies, but they cannot be combined in
many reasonable ways, resulting in a comparatively small DFSM. In order to
get more complex examples, we produced randomized queries with 5 − 10 rela-
tions and a varying number of join predicates. We always started from a chain
query and then randomly added additional edges to the join graph. The results
are shown for n − 1, n and n + 1 additional edges. In the case of 10 relations,
this means that the join graph consisted of 18, 19 and 20 edges, respectively.
The time and space requirements for the preparation step are shown in
Figure 23.16 and Figure 23.17, respectively. For each number of relations, the
requirements for the combined framework (o+g) and the framework ignoring
groupings (o) are shown. The numbers in parentheses (n − 1, n and n + 1) are
the number of additional edges in the join graph.
10 o+g (n-1)
o (n-1)
o+g (n)
o (n)
8 o+g (n+1)
o (n+1)
memory (KB)
0
4 5 6 7 8 9 10 11
no of relations
OaG →bG is first grouped by a and then (within the block of tuples with the same
a value) grouped by b. However, this is a very strong condition that is usually
not satisfied by a hash-based grouping operator. Therefore, their work is not
general enough to capture the full functionality offered by a state-of-the-art
query execution engine.
In this chapter, we followed [544, 543].
372CHAPTER 23. DERIVING AND DEALING WITH INTERESTING ORDERINGS AND GROUPIN
Chapter 24
24.1 Introduction
The plan generator relies on a cost function to evaluate the different plans and to
determine the cheapest one. This chapter is concerned with the development of
cost functions. The main input to cost functions are cardinalities. For example,
assume a scan of a relation, which also applies a selection predicate. Clearly,
the cost of scanning the relation depends on the physical layout of the relation
on disk. Further, the CPU cost for evaluating the predicate depends on the
number of tuples in the relation. Note that the cardinality of a relation is
independent of its physical layout.
In general, the cost of an algebraic operator is estimated by using a profile of
the database. The profile must be small, e.g. a couple of kilobytes per relation1 .
According to the above lines, we distuinguish between the logical and physical
profile. For each database item and its constituents, there exist specialized
logical and physical profiles. They exist for relations, indices, attributes, and
sets of attributes. Fig. ?? shows the typical classes and their associations for the
different profiles. The minimal logical profile of a relation R is its cardinality ToDo
|R|. Its minimal physical profile consists of the number of pages ||R|| on which
it is stored. In Chapter 4, we saw more advanced physical profiles.
The DBMS must be capable to perform several operations to derive profiles
and to deal with them. Fig. 24.1 gives an overview. This figure roughly follows
the approach of Mannino et al. [501, ?]. The first operation is the build op-
eration, that takes as input a specification of the profiles to be build (because
there are many different alternatives, as we will see) and the database. From
that, it builds the according profiles for all database items of all the different
granularities. When updates arrive, the profiles must be updated. This can
either be done by a complete recalculation or by an incremental update opera-
tion on the profiles themselves. The latter is reflected in the operation update.
Unfortunately, not all profiles can have an update operation. Within this book,
1
Given today’s cost for main memory, it may also be reasonable to use a couple of
megabytes.
373
374 CHAPTER 24. CARDINALITY AND COST ESTIMATES
we will not be too concerned about building and updating profiles. At the end
of this chapter, we will provide some references.
The main operations this chapter deals with are among the remaining ones.
The first of them is cardinality estmation. Given an algebraic expression or a
calculus expression together with a logical profile of the database, we estimate
the output/result cardinality of the expression. Why do we say algebraic or
calculus expression? Remember that plan generators generate plans for plan
classes. Each plan class corresponds to a set of equivalent plans. They all pro-
duce the same result and, hence, the same number of output tuples. Thus, one
arbitrary representative of the class of equivalent algebraic expressions should
suffice to calculate the logical profile, as a logical profile depends only on the
outcome. On the other hand, the plan class more directly corresponds to a
calculus expression. Hence, estimating the result cardinality of a calculus ex-
pression is a viable alternative. In the literature, most papers deal with the
first approach while only a few deal with the latter (e.g. [194]).
The second operation we will be concerned with is cost estimation. Given
logical and physical profiles for all inputs and an algebraic operator (tree), this
operation calculates the actual costs.
The third major task is profile propagation. Given a logical or physical
profile and an expression, we must be able to calculate the profile of the result,
since this may be the input to other expressions and thus be needed for further
cardinality estimates. The estimation of a physical profile occurs mostly in
cases where operators write to disk. Given Chapter 4, this task is easy enough
24.1. INTRODUCTION 375
This shows that we can go a far way if we are able to estimate the output
cardinality for duplicate eliminating projections, selections, (bag) joins, and
semijoins. For a certain class of profiles, Richard shows that a profile consist-
ing ‘only’ of the sizes of all duplicate eliminating projections on all subsets of
attributes of all relations is a complete profile under certain assumptions [621].
Since the set of subsets of a set of attributes can be quite large, Richard ex-
ploits functional dependencies to reduce this set by exploiting the fact that
|ΠD D
α∪β (R)| = |Πα (R)| if there exists a functional dependency α → β.
A major differenciator for logical attribute profiles is the kind of the domain
of the attribute. We distinguish between categorial attributes (e.g. color), dis-
crete ordered domains (e.g. integer attributes, decimals, strings), and continous
ordered domains (e.g. float). Categorial domains may be ordered or unordered.
In the first case they are called ordinal, in the latter nominal . We will be main-
ly concerned with integer attributes. Strings are special, and we discuss some
approaches in Sec. ??. Continous domains are also special. The probability
of occurrence of any value in a continous domain in a finite set is zero. The
techniques developed in this section can often easily be adopted to continous
domains, even if we do not mention this explicitly.
376 CHAPTER 24. CARDINALITY AND COST ESTIMATES
where w is the weight which can be adapted to different situations. If, for
example, the system is CPU bound, we should increase w and if it is I/O
bound, we decrease w.
However, it is not totally clear what we are going to optimize under this cost
formula. One interpretation could be the following. Assume w = 0.5. Then,
we could interprete the total costs as response time under the assumption that
fifty percent of the CPU time can be executed in parallel with I/O. Accordingly,
we find other top-most cost formulas. For example, the weight is sometimes
dropped [351]:
C = CI/O + Ccpu (24.2)
Under the above interpretation, this would mean that concurrency is totally
absent. The opposite, total concurrency between I/O and CPU, can also be
found [144]:
C = max(CI/O , Ccpu ) (24.3)
In these green days, an alternative is to calculate the power consumption
during query execution.
However, these formula sometimes raise a problem. For example, the nested
loop join method requires multiple evalutions of its inner part.
Further, in order to count the I/O cost correctly, it is necessary to make
some assumptions when intermediate results are written to and read from disk.
We will use the following assumption: Every operator is responsible for passing
its result to the next operator via main memory. For example, a sort merge
24.2. A FIRST APPROACH 377
join may require sorting its inputs. The sort operators are then responsible for
handing over their result to the merge join via main memory. This means that
the merge join may not require any I/O if the merge can be done purely in
main memory.
24.2.4 Abbreviations
We need some abbreviations to state our cost formulas. A first bunch of them
is summarized in Table 24.1. There, we assume that an index is always a B +
tree.
R,S,T relations
I index
A,B,C attributes or sets of attributes
DA ΠD A (R)
dA |DA |
minA min ΠD A (R) for an attribute A of R
maxA max ΠD A (R) for an attribute A of R
|R| number of tuples of R
||R|| number of pages on which R is stored
||A||B average length of a value of attribute A of R (in bytes)
||A(R)||B average length of a tuple in bytes
||I|| number of leave pages of an index
H(I) depth of the index I minus 1
by
H(T ) + F (p) ∗ (||I|| + ||R||).
EXC Note that with the help of Chapter 4, we can already do better. In the second
case, where the pages containing qualifying tuples do not fit into main memory,
they give the estimate
Next, we have to discuss the costs of different join methods. Selinger et al.
propose cost formulas for the simple nested loop join (1nl ) and the sort merge
join (1sm ). Since summing up the costs of all operators in a tree results in
some problems for nested loop joins, they adhere to a recursive computation of
total costs. Let e1 and e2 be two algebraic expressions. Then they estimate the
cost of the simple nested loop join as follows:
where pagesize is the page size in bytes. The factor 1.2 is called the universal
fudge factor . In the above case, it takes care of the storage overhead incurred
24.2. A FIRST APPROACH 379
by using slotted pages. If we assume that the merge phase of the sort merge
join can be performed in main memory, no additional I/O costs occur and we
are done.
Clearly, in the light of Chapter 4, counting the numbers of pages read is not
sufficient as the discrepancy between random and sequential I/O is tremendous.
Thus, better cost functions should use a more elaborate I/O cost model along
the lines of Chapter 4. In any case, note that the calculation of the I/O or CPU
costs of any operator highly depends on its input and output cardinalities.
|σp (R)|
s(p) = .
|R|
If we know the selectivity of p, we can then easily calculate the result size of a
selection:
|σp (R)| = s(p)|R|
Similarly for joins. Given a join predicate p and two relations R and S, we
define the selectivity of p as
|R 1p S| |R 1p S|
s(p) = =
|R × S| |R| ∗ |S|
The idea of the approach of Selinger et al. is to calculate the result cardinal-
ity for a plan class by the following procedure. First, the sizes of all relations
represented by the plan class are multiplied. This is the result of their cross
product. In a second step, they take a look at the predicate p applied to the
relations in the plan class. For p they calculate a selectivity estimate s(p) and
multiply it with the result of the first step. This then gives the result. Hence,
if a plan class represents the algebraic expression
σp (×ni=1 Ri ),
(dA , dB ) is only known if there exists an according index on the attribute. Let
us give some rational for the selectivity estimation of A IN Q for an attribute A
and a subquery Q. Assume that A is an attribute of relation R and the subquery
Q is of the form select B from S .... Further assume that ΠA (R) ⊆ ΠB (S),
i.e. referential integrity holds. Clearly, if all tuples of S are in the result of Q,
the selectivity is equal to 1. If the output cardinality of Q is restricted by a
factor s0 = |Q|/|S|, then we may assume that the number of distinct values in
Q’s result is restricted by the same factor. Hence, the selectivity factor of the
total predicate is also s0 . Selinger et al. now continue as follows: “With a little
optimism, we can extend this reasoning to include subqueries which are joins
and subqueries in which column [B] is replaced by an arithmetic expression
involving column names. This leads to the formula given above.”
bA = [lA , uA , fA , dA ]
lA = min(ΠA (R))
uA = max(ΠA (R))
fA = |R|
dA = |ΠD
A (R)|
382 CHAPTER 24. CARDINALITY AND COST ESTIMATES
If the attribute A is implicit from the context or does not matter, we may omit
it in the subscript.
24.3.2 Assumptions
The first two assumptions we make are:
Given the above assumptions (and one more to come), the task is to establish
the operations cardinality estimation and logical profile propagation. The latter
implies that we can calculate the logical profile of all attributes of any result
relation established by applying some algebraic operator. Assume we have
solved this task. Then it is clear that the cumulated frequency fA , which equals
|R| in this section, solves the task of cardinality estimation. Hence, we consider
this as done. The use of the cumulated frequency fA instead of the seemingly
simpler cardinality notation |R| is motivated by the fact that a single attribute
will have multiple profiles if histograms are applied. To make the formulas of
this section readily available for histogram use is the main motivation for using
the cumulated frequency.
Exact match queries The first case we consider is σA=c for a constant c.
0 = c, u0 = c. Further,
Clearly, lA A
0 1 if c ∈ ΠA (R)
dA =
0 else
We cannot be sure whether the first or second case occurs. Since no reasonable
cardinality estimation should ever return zero, we always assume c ∈ ΠA (R).
More generally, we assume that all constants in a query are contained in the
database in the according attributes.
As every distinct value occurs about fA /dA times, we conclude that fA0 =
fA /dA . A special case occurs if A is the key. Then, we can immediately conclude
that fA0 = 1.
Let us now consider another attribute C ∈ A(R), C 6= A. Since fC0 = fA0 ,
we only need to establish d0C . For the lack of any further knowledge, we keep
the lower and upper bounds, i.e. lC 0 = l and u0 = u . To derive the number of
C C C
distinct values remaining for attribute B, we can use the formula by Yao/Waters
(see Sec. 4.16.1) Denote by s(p) = |σA=c (R)|/|R| = fA0 /fA the fraction of tuples
that survives the selection with predicate p ≡ A = c. Fix a distinct value for
C. Using the uniform distribution assumption, it occurs in fC /dC tuples of R.
Then, for this value we have fA −ff C0 /dC possibilities to chose fA0 tuples without
A
it. The total number of possibilities to chose fA0 tuples is ffA0 . Thus, we may
A
conclude that
d0C = dC YffCA/dC (fA0 )
384 CHAPTER 24. CARDINALITY AND COST ESTIMATES
Range queries Let us now turn to range queries, i.e. selection predicates of
the form c1 ≤ A ≤ c2 , where lA ≤ c1 < c2 ≤ uA . In all of them, the lower
0 = c and u0 = c . Using the
and upper bounds are given by the range, i.e. lA 1 A 2
System R approach, we can estimate
c2 − c1
fA0 = ∗ fA
uA − lA
c2 − c1
d0A = ∗ dA
uA − lA
In general, we have
n
X
fA0 = fB0 = fA p(xi = A)p(xi = B|xi = A) (24.4)
i=1
24.3. A FIRST LOGICAL PROFILE AND ITS PROPAGATION 385
For ΠB (R) ⊆ ΠA (R), we get fA0 = fB0 = f /dA . Summarizing these cases, we
may conclude that
f
fA0 = fB0 =
max(dA , dB )
which is the formula applied in System R if indices exist on A and B. Clearly,
we can calculate an upper bound on the number of distinct values as
d0A = d0B = min(dA , dB ).
Let us estimate the cumulated frequency after the selection if none of the
above conditions hold and independence of A and B holds. Then, the condi-
tional probability p(xi = B|xi = A) becomes p(xi = B) = 1/n. Thus
n
X f dA 1 f
fA0 = fB0 = =
dA n n n
i=1
dA
X
fA0 = fA p(xi ≤ B|xi = A)
i=1
XdA
= fA p(xi ≤ B)
i=1
dA
X xi − lB
= fA
uB − lB
i=1
dA
1 X
= fA (( xi ) − dA lB )
uB − lB
i=1
dA dA − 1
= fA (lA − lB + ∆A )
uB − lB 2
dA (uA − lA ) (dA − 1)
= fA
uB − lB (dA − 1) 2
uA − lA dA
= fA
uB − lB 2
fA dA
=
dA 2
fA
=
2
As an exercise the reader may verify that fA0 = (dA − 1)fA /(2dA ) under the
type II equal spread assumption. As an additional exercise the reader should
EXC derive d0A and d0B . We conjecture that
or
d0A = dA ∗ YffAA/dA (fA0 ).
The following observation is crucial: Even if in the original relations the values
of A and B are uniformely distributed, which typically is not the case, the
distribution of the values A and B after the selection with A ≤ B is non-
uniform. For example,
xi − lB
p(xi ≤ B) =
uB − lB
for lB ≤ xi ≤ uB . Table 24.3 summarizes our findings about profile propagation
for selections.
24.3. A FIRST LOGICAL PROFILE AND ITS PROPAGATION 387
predicate f0 d0 comment
c2 −c1 c2 −c1
c1 ≤ A ≤ c2 fA0 = uA −lA ∗ fA d0A = uA −lA ∗ dA
(c2 −c1 )
fA0 = d0A ∗ (fA /dA ) d0A = ∆A
⊆
A=B fA0 = f
max(dA ,dB ) d0A = dA ∗ YffAA/dA (fA0 ) ΠA (R) ⊇ ΠB (R)
fA0 = fB0 = fA
n d0A = dA ∗ YffAA/dA (fA0 ) else
Open ranges and functions There are plenty of other cases for selection
predicates, which we have not discussed. Let us briefly mention a few of them.
Clearly, we have:
This helps to estimate the fA0 . The d0A are left to the reader. EXC
Estimating selectivities for (user defined) functions and expressions can be
done by using computed attributes. For example, cardinalities for selections
with predicates like g(A) = c for a function g can be treated by introducing an
additional attribute gA for which a profile can be established.
and
dA dB
d0A =
.
n
For an attribute C ∈ A(R) \ {A, B}, we have fC0 = fA0 and
Regular Join For the regular join R 1A=B S. Let us start with an at-
tribute C ∈ A(R) \ {A, B}. We can apply the formulas for the semijoin because
ΠDC (R 1A=B S) = ΠC (R< S). For attributes C ∈ A(S) \ {A, B} remember
D
Rosenthal showed that this result also holds if the condition of fairness holds
for at least one relation [624]. A relation is called fair with respect to an
attribute A if for the expected value E(|σA=x (R)|) = |R|/nA holds. In this
case, the expected value for the result of the join is (|R||S|)/n. Note that
ΠDA (R 1A=B S) = Π (R<A=B S). Thus, we can estimate the number of
D
distinct values as
dA dB
d0A = d0B = .
n
Selfjoin The above formulas only apply if we are not dealing with a selfjoin.
Of course, R 1A=B R does not pose any problems. However, R 1A=A R does,
because all tuples find a join partner. The estimates are easy to derive:
fA fA
fA0 =
dA
d0A = dA
join f’ d’ comment
fA fB
R 1A=B S fA0 = dB d0A = dA ΠA (R) ⊆ ΠB (S)
fA fB
fA0 = n d0A = dAndB else
fA fA
R 1A=A R fA0 = dA d0A = dA
fA0 = d0A = dA
n
Y
D( nAi , |R|),
i=1
if nAi , the size of the domain of Ai , is known. Otherwise, we can use the
estimate
n
Y
D( dAi , |R|)
i=1
The number of distinct values in any attribute does not change, i.e. d0Ai = dAi .
If we have a functional dependencies and κ → A for a set of attributes A
and κ ⊂ A, then
ΠD D
A (R) = Πκ (R).
Further, if |ΠD D 0 0
A (R)| = |R|, we have |ΠA0 (R)| = |R| for all A with A ⊇ A.
The above estimates for the result size of a duplicate eliminating projection
assumes that the attribute values are uniformly distributed, i.e., every distinct
value occurs with the same probability. As we will not deal with projections any
390 CHAPTER 24. CARDINALITY AND COST ESTIMATES
more in this part of the book, let us complete the subject by giving an approach
where each attribute value can have its own probability of occurrence. This is
not unlikely, and for attributes with few possible values the following approach
proposed by Yu, Zuzarte, and Sevcik is quite reasonable [?]. The assumptions
are that the attributes are independent and the values of each of them are
drawn by independent Bernoulli trials. Under these assumptions, they derive
the following three results: a lower bound, an upper bound, and an estimate
for the expected number of distinct values in the projection. In order to state
these results, we need some additional notation. Let R be a relation and define
N = |R|. Further let G = {A1 , . . . , An } be a subset of the attributes of R.
Define di = |ΠD Ai (R)| to be the number of distinct values occurring in attribute
Ai . We denote values of Ai by ai,1 , . . . , ai,di .
We wish to derive an estimate for DG = |ΠD G (R)|. Therefore, we model each
attribute Ai by a frequency vector fi = (fi,1 , . . . , fi,di ) where fi,j is the number
of occurrences of the j-th distinct value ai,j of Ai divided by N . If, for example,
A1 has three distinct values which occur 90, 9, and 1 times in a relation with
N = 100 elements, then f1 becomes (0.9, 0.09, 0.01).
Let us first look at bounds for DG . Trivially, DG is bounded from above by
n
Y
DG ≤ min{N, di }
i=1
and from below by
n
DG ≥ max di .
i=1
These bounds are very rough. This motivated Yu et al. to derive better ones.
Before we proceed, let us consider another example. Assume we have three
attributes A1 , A2 , and A3 all with frequency vectors fi = (0.9, 0.09, 0.01) for a
relation of size N = 100. Since we assume attribute independence, the proba-
bility of (a1,3 , a2,3 , a3,3 ) is 0.01 ∗ 0.01 ∗ 0.01. Thus, its occurrence in a relation of
size 100 is highly unlikely. Hence, we expect DG to be less than 27 = 3*3*3. In
general, we observe that the probability of occurrence of a tuple (a1,j1 , . . . , an,jn )
is the product of the relative frequencies f1,j1 ∗ . . . ∗ fn,jn . From this, the ba-
sic idea of the approach of Yu et al. becomes clear: we have to systematically
consider all the different possibilities to multiply relative frequencies. This is
nicely captured by the Kronecker product (tensor product).
Before we proceed, let us state the upper and lower bounds in case of two
attributes by giving two theorems developed by Yu et al. [?].
Theorem 24.3.1 (lower bound) For a set of attributes {A1 , A2 } of a rela-
tion R and its frequency vectors, we define li,j for i = 1, 2 and 1 ≤ j ≤ di as the
minimum number of different values that have to be combined with fi,j given
the marginals, i.e.
li,j = min{|F | | F ⊆ {1, . . . , di0 }, ∀q 6∈ F S(F ) ≤ fi,j < S(F ) + fi0 ,q }
where i0 = 3 − i and S(F ) = p∈F fi0 ,p . Further define
P
di
X
⊥
DG = max li,j .
i=1,2
j=1
24.3. A FIRST LOGICAL PROFILE AND ITS PROPAGATION 391
CalculateLowerBoundForNumberOfDistinctValues(f1 , f2 )
/* frequency vectors f1 and f2 */
sort fi (i = 1, 2) in descending order;
for i = 1, 2 {
i0 = 3 − i;
for j = 1, . . . di {
k = 1;
while (fi,j > kl=1 fi0 ,l )
P
++k;
li,j = k;
}
lbi = dj=1
Pi
li,j ;
}
DG⊥ = max
i=1,2 lbi ;
return DG ⊥
⊥
Figure 24.2: Calculating the lower bound DG
The algorithm in Fig. 24.2 calculates the lower bound DG ⊥ . Calculating the
>
upper bound DG is much easier. For each fi,j , we compute ui,j by simply
comparing fi,j N and di0 . Adding up the ui,j for each attribute and taking the
lesser of the two sums gives the desired result.
Let us start by repeating the definition of the Kronecker product of two
matrices A = (ai,j ) and B = (bi,j ) of dimension n × m and n0 × m0 . The result
A ⊗ B is a matrix of dimension nn0 × mm0 . The general definition is
a1,1 B a1,2 B . . . a1,m B
a2,1 B a2,2 B . . . a2,m B
A⊗B = ...
.
... ... ...
an,1 B an,2 B . . . an,m B
The estimate can not be calculated easily. First, we calculate the Kronecker
product fG = f1 ⊗ . . . ⊗ fn of all frequency vectors. Note that to every value
392 CHAPTER 24. CARDINALITY AND COST ESTIMATES
combination v ∈ ΠD D
A1 (R) × . . . × ΠAn (R) there corresponds exactly one compo-
nent in fG , which contains its probability of occurrence. With this observation,
it is easy to derive the following theorem, in whichQwe denote by fG,i the i-th
component of fG and by M its length, i.e. M = ni=1 di . Further remember
that N = |R|.
The algorithm for computing the estimate is given in Fig. 24.3. In the first,
most expensive phase, it constructs the Kronecker product. Then, the simple
calculations according to the theorem follow. A more efficient implementation
would calculate the Kronecker product only implicitly. Further, the frequency
vectors may not be completely known but only a part of it via some histogram.
As was also shown by Yu et al., end-biased histograms (coming soon) are opti-
mal under the following error metrics. Let D̂G,hist be the estimate derived for
a histogram. The error function they consider is
Now let R and S be two relations with A(R) = {A, B} and A(S) = {B}. A
value a ∈ ΠD
A (R) is contained in the result of R÷B if and only if ΠB (σA=a (R)) ⊇
S. Hence, for any such a, fA = fA /dA and nB equal to the size of the common
domain of R.B and S.B, we can calculate the survival probability as
fA nB
/
|S| |S|
24.3. A FIRST LOGICAL PROFILE AND ITS PROPAGATION 393
EstimateNumberOfDistinctValues(f1 , . . . , fn )
/* frequency vectors fi */
/* step 1: calculate fG = f1 ⊗ . . . ⊗ fn */
fG = f1 ;
for (i = 2; i ≤ n; ++i) {
f old = fG ;
fG = ; // empty vector
for (j = 1; j ≤ |f old |; ++j) {
for (k = 1; k ≤ di ; ++k) {
fG = push back(fG , fjold × fi,j ); // append a value to a vector
}
}
}
/* step 2: compute the expected number of distinct value combinations */
S = 0;
for (j = 1, j ≤ M ; ++j) { // M = length(fG )
S += (1 − fj )N ;
}
D̂G = M − S;
return D̂G ;
provided that fA ≥ |S| and R is a set. Denote by fA0 and d0A the cumulated
frequency and the number of distinct values for attribute A in the result of
R ÷ S. Then we have the estimate
0 0 fA nB
fA = dA = dA ∗ /
|S| |S|
in case R is a set.
If R is a bag, we must be prepared to see duplicates in σA=a (R). In this
case we can adjust the above formula to
0 0 xA n
fA = dA = dA ∗ /
|S| |S|
p
q-value max(X) min(X) Eq = maxni=1 max{xi /x̂, x̂/xi }
Keeping ha for every possible a may not be practical. However, if the number
of distinct values in H = {ha |a ∈ ΠDA (R)} is small, we can keep the number of
distinct a values for each possible ha . Assume H = {h1 , . . . , hk } and define
gi = |{a ∈ ΠD
A (R)|ha = hi }|,
24.3.7 Remarks
NULL Values Our profile is not really complete for attributes which can
have NULL values. To deal with these, we need to extend our profiles by the
frequency d⊥A with which NULL occurs in an attribute A of some relation. It is
straightforward to extend the above profile to deal with this additional count.
Sets of Attributes Note that nothing prevents us to use the formulas de-
veloped above for selections and joins if A and B are attribute sets instead of
single attributes. We just have to know or calculate dA for sets of attributes A.
of Table 24.5 show the names and definitions of some possible approximations.
Whereas mean and median are well known, the other two may be not. The
middle is defined as the value exactly between the minimum and maximum of
X. Hence, the distance from the middle to either extreme is the same. The q-
value needs some further restriction: the values in X must be larger than zero.
For our purposes, this restriction is not bad since execution costs are typically
larger than zero and frequencies are mostly larger than zero if they are not
exactly zero. The latter case needs some special attention if we use something
like the q-value, which we could also term geometric or multiplicative middle.
Let us take a look at a simple example. Assume X = {1, 2, 9}. Then we
can easily calculate the approximations summarized in the following table:
median mean middle q-value
2 4 5 3
Which of these approximations is the best one? The answer depends on the error
function we wish to minimize. Therefore, the rightmost column of Table 24.5
shows some error functions, which are minimized by the approximation defined
in the same line. The variable x̂ denotes the estimate whose error is to be
calculated. For E2 there exist plenty of equivalent formulations, where we think
of two error measures as being equivalent, if andPonly if they result inPthe same
minimum. Some important alternatives are 1/n (xi − x̂)2 , 1/(n−1) (xi − x̂)2
(empirical variance), and simply (xi − x̂)2 .
P
A nice property half of the approximations give us are error bounds. These
are E∞ and Eq . Define the spread s of x as max(x) − min(x). Then, given the
middle m of x, we have for every xi ∈ x that
m − s/2 ≤ xi ≤ m + s/2.
Thus, we have a symmetric, additive
p error bound for all elements in x. Define
the geometric spread as s = max(x)/ min(x). Then we have a symmetric,
multiplicative error bound for all elements xi in x given by
(1/s)q ≤ xi ≤ sq
if q is the geometric middle. The following table shows the possible errors for
all approximations of our example set X = {1, 2, 9}:
median mean middle geo. mean
2 4 5 3
E1 8 10 11 9
E2 7.1 6.2 6.4 6.4
E∞ 7 5 4 6
Eq 4.5 4 5 3
Which of these error metrics and, hence, which approximation is the best?
Obviously, this depends on the application. In the query compiler context, E1
plays no role that we are aware of. E2 plays a predominant role as it is used to
approximate values in a given histogram bucket. This has not come by sharp
reasoning about the best possibility but merely by the existence of a huge body
of literature in this area. Currently, the other two error metrics, E∞ and Eq ,
play minor roles. But this will change.
396 CHAPTER 24. CARDINALITY AND COST ESTIMATES
for coefficients cj ∈ R. The estimates yˆi for yi are then derived from fˆ by
n
X
yˆi := fˆ(xi ) = cj Φj (xi ).
j=1
Note that the functions Φj are not necessarily linar functions. For example, we
could use polynomials Φj (x) = xj−1 . Further, there is no need for x to be a
single number. It could as well be a vector ~x.
It is convenient to state our approximation problem in terms of vectors and
matrices. Let (xi , yi ) be the points we want to approximate and Φj , 1 ≤ j ≤ n
be some functions. We define the design matrix A ∈ Rm×n , A = (ai,j ) by
ai,j = Φj (xi )
1 xm
As an example consider the three points
A~c
gives the result of fˆ for all points. Clearly, ~c should be determined such that
the deviation of A~c from ~y = (y1 , . . . , ym )T becomes minimal.
The deviation could be zero, that is A~c = ~y . However, remember our as-
sumption that m > n. This means that we have more equations than variables.
Thus, we have an overdetermined system of equations and it is quite unlikely
that a solution to this system of equations exists. This motivates our goal to
find an approximation as good as possible. Next, we formalize this goal.
Often used measures for deviations or distances of two vectors are based on
norms.
Definition 24.5.1 (norm) Let S be a linear space. Then a function ||x|| :
S → R is called a norm if and only if it has the following three properties:
1. ||x|| > 0 unless x = 0
2. ||λx|| = |λ| ||x||
3. ||x + y|| ≤ ||x|| + ||y||
Various norms, called p norms can be found in the literature. Let x ∈ Rn
and p ≥ 1 where p = ∞ is possible. Then
n
X 1
||x||p = ( |xi |) p .
i=0
398 CHAPTER 24. CARDINALITY AND COST ESTIMATES
Using these norms, we can define distance functions d1 , d2 , and d∞ . For two
vectors x and y in Rn , we define
It should be clear, that these define the error measures E1 , E2 , and E∞ , which
we used in Sec. 24.4. The only missing error function is Eq . We immediately
fill this gap, and start with the one dimensional case.
Note that for x > 0, ||x||Q = max(x, 1/x). The multivariate case is a straight-
forward extension using the maximum over all components:
1. ||x|| ≥ 0
The Q-paranorm is a norm, hence the name. The only missing part is the
distance function stated next. Let x and y be two vectors in Rn , where y =
(y1 , . . . , yn )T with yi > 0. Then we define
dq (x, y) = ||x/y||Q
24.5. APPROXIMATION WITH LINEAR MODELS 399
The next point to consider is the uniqueness of a solution. Proving the unique-
ness of a solution is easy, if the norm is strictly convex.
It is easy to show that all lp norms for p 6= ∞ are strictly convex and that l∞
and lq are convex, but not strictly convex. For strictly convex norms, it is easy
to show that a solution is unique.
Although l∞ and lq are not strictly convex, under certain circumstances a unique
best approximation exists for them. This is discussed in subsequent sections.
Considering the above, one might conjecture that l2 approximation is much
simpler than l∞ or lq approximation. This is indeed the case. We will not repeat
all the findings from approximation theory and the algorithms developed. There
are plenty of excellent textbooks on this matter. We highly recommend the
excellent book of Golub and van Loan [?], which discusses l2 approximation and
several algorithms to solve them (e.g. QR factorization and SVD). Other good
books to refresh one’s knowledge on matrix algebra are [?, ?, ?, ?]. Überhuber
wrote another good book discussing l2 approximation, QR factorization and
SVD [?]. In the context of statistics, many different regression models exist
ToDo to approximate a given set of data. An excellent overview is provided by [?].
Another good reading, not only in this context, is the book by Press, Teukolsky,
Vetterling, and Flannery [597]. Before reading these books, it might be helpful
to repeat some linear algebra and some basics of matrices. An excellent book
for doing so was written by Schmidt and Trenkler [?]. The only book we know
of that discusses approximation under l∞ , is the one by Watson, already cited
above [?]. Approximation under lq is not discussed in any textbook. Hence, we
must refer to the original article [?, ?]. In any case, since mathematics is quite
involved at times, we give explicit algorithms only for the approximation by a
linear function. For all other cases, we refer to the literature.
24.5. APPROXIMATION WITH LINEAR MODELS 401
Since many seeks occur during the processing of a single query, l2 is the appro-
priate norm. On the surface, we seem to have a problem √ using a simple linear
model. However, we can approximate the parts c1 +c2 d and c3 +c4 d for sever-
al distinct c0 either by trying a full range of values for c0 or by a binary search.
The solution for c0 we then favor is the one in which the maximum of the errors √
on both parts becomes minimal. A second problem is the occurrence of d,
√
since this does not look linear. However, choosing Φ1 = 1 and Φ2 (x) = x will
work fine.
Another method is to transform a set of points (xi , yi ) with two (injective)
transformation functions tx and ty into the set of points (tx (xi ), ty (yi )). Then
this set is approximated and the result is transformed back. While using this
approach, special attention has to be paid to the norm, as it can change due to
the transformation. We see examples of this later on in Sec. 24.5.6.
the output cardinality of a selection σA=c (R), we can simply return fˆ(c) as an
estimate. Hence it is a good choice to use lq (see below for strong arguments).
To calculate the result cardinality for a range query of the form σc1 ≤A≤c2 (R),
we distinguish several cases. First, assume that the domain of A is discrete and
the number of values between c1 and c2 is small. Then, we can calculate the
result quite efficiently by X
fˆ(x).
c1 ≤x≤c2
If the number of values between c1 and c2 is too large for an explicit summation,
we can apply speed-up techniques if the function fˆ has a simple form. For
example, if fˆ is a linear function fˆ(x) = α+βx, the above sum can be calculated
EXC very efficiently . If the number of values between c1 and c2 is very large and no
efficient form for the above sum can be found, or if we do not have a discrete
domain, we can use the integral to approximate the sum. Thus, we use the
right-hand side of Z c2
X
ˆ
f (x) ≈ fˆ(x)dx
c1 ≤x≤c2 c1
Denote by fˆi the estimate for the selectivities of the pi and assume that the
join selectivities have been estimated correctly (which, of course, is difficult in
24.5. APPROXIMATION WITH LINEAR MODELS 403
practice). Then the estimated cardinality of the result of joining the relations
in x is
Y Y Y
ŝx = ( fˆi )( fi,j )( |Ri |)
Ri ∈x Ri ,Rj ∈x Ri ∈x
Y Y Y Y
= ( fi /fi )( fˆi )( fi,j )( |Ri |)
Ri ∈x Ri ∈x Ri ,Rj ∈x Ri ∈x
Y Y Y Y
= ( fˆi /fi )( fi )( fi,j )( |Ri |)
Ri ∈x Ri ∈x Ri ,Rj ∈x Ri ∈x
Y
= ( fˆi /fi )sx
Ri ∈x
where some i belong to the category with fˆi /fi < 1 and others to the one
with fˆi /fi > 1. Remember that during dynamic programming, all subsets of
relations are considered. Especially those subsets occur in which all relations
belong to one category only. Hence, building on the cancellation of errors by
mixing them from different categories is not a true option. Instead, we should
minimize Y
max{fi /fˆi , fˆi /fi }
Ri ∈x
in order to minimize errors and error propagation. This product can be mini-
mized by minimizing each of its factors. This means that if we want to minimize
error propagation, we have to minimize the multiplicative error Eq for estimat-
ing the cardinalities of selections based on equality. This finding can obviously
be generalized to any kind of selections. Thus, for cardinality estimations for
selections (and joins, or cardinality estimation in general) the q-error is the
error and the geometric middle the approximation of choice.
f0,i fi |R|, if f0,i is the join selectivity of the join of Ri with the center relation
R0 . Thus, P̂ = P if f and fˆ result in the same ordering of the relations. Since
f (x) = (x − 1)/c is monotonically increasing for constants c, we can conclude
that the ordering is indeed the same as long as for all i 6= j we have
f0,i fi |Ri | < f0,j fj |Rj | ⇐⇒ f0,i fˆi |Ri | < f0,j fˆj |Rj |
which is equivalent to
fi ri fˆi ri
< 1 ⇐⇒ <1
fj rj fˆj rj
for ri = f0,i |Ri |. We now show that if
s
fi fi ri
|| ||Q < min || ||Q
fˆi i6=j fj rj
for all i, then P = P̂ . This condition implies the much weaker condition that
for all i 6= j
fˆi fˆj fi ri
|| ||Q || ||Q < || ||Q (24.9)
fi fj fj rj
To show the claim, it suffices to show that (fi ri )/(fj rj ) < 1 implies (fˆi ri )/(fˆj rj ) <
1. This follows from
fˆi ri fˆi fj fi ri
=
fˆj rj fi fˆj fj rj
fˆi fj fi ri
= ( )/(|| ||Q ) (∗)
fi fˆj fj rj
fˆi fj fi ri
≤ (|| ||Q || ||Q )/(|| ||Q )
fi fˆj fj rj
< 1
implies P̂ = P . For tree queries, things are a little more complex. In the
following, we assume that Ri0 is a relation connected to Ri , which we denote
by Ri0 − Ri . Then
s
fˆi fi fi,i0 |Ri |
|| ||Q < min || ||Q
fi i6=j,Ri0 −Ri ,Rj 0 −Rj fj fj,j 0 |Rj |
implies P̂ = P .
24.5. APPROXIMATION WITH LINEAR MODELS 405
chain query
12 star query
10
0
1 1.2 1.4 1.6 1.8 2 2.2 2.4
For this to work, we have to know where the holes in [l, u] are. If there are only
a few of them, we can memorize them. If they are to many to be stored, we
can approximate them as follows. Let W = {w1 , . . . , wm }. Then, we can use
approximation techniques to approximate the set of points (i, wi ), 1 ≤ i ≤ m.
Depending on the size of the interval [l, u] either l∞ or lq is the appropriate
norm. Similarily, the peaks, i.e. the distinct values occurring in the attribute A
of R, can be approximated if there are only a few of them in the domain of A.
Since we are used to solve equations for x, we rewrite our problem to A~x = b.
That is, the vector ~x replaces the coefficient vector c. Using Theorem 24.5.9, we
must have that A~x∗ − b is orthogonal to the range of A. The range of a matrix
A ∈ Rm×n is defined as R(A) = {Ax|x ∈ Rn }. Let ai be i-th column vector
of A and ~x = (x1 , . . . , xn )T . Then, the best approximation can be found by
solving the following system of linear equations, which is called (Gauß) normal
equations:
Definition 24.5.11 (full rank) A matrix A ∈ Rm×n , m > n has full rank if
its rank is n.
Note that for all matrices A ∈ Rm×n , we always have that AAT and AT A are
symmetric.
A matrix for which the uniquely determined inverse exists is called regular.
where Ai,j ∈ R(n−1)×(n−1) results from A by eliminating the i-th row and the
j-th column.
λ(A) := {λ1 , . . . , λk }
Two similar matrices have the same Eigenvalues, as can be seen from the fol-
lowing theorem.
Theorem 24.5.20 Let A, B ∈ Rn×n be two similar matrices. Then they have
the same characteristic polynomial.
Every matrix and, hence, every vector has a g-inverse. For regular matrices,
the g-inverse and the inverse coincide. In general, the g-inverse is not uniquely
determined. Adding some additional properties makes it unique.
408 CHAPTER 24. CARDINALITY AND COST ESTIMATES
1. AA+ A = A
2. A+ AA+ = A+
3. (A+ A)T = A+ A
4. (AA+ )T = AA+
For every matrix and, hence, every vector there exists a uniquely determined
Moore-Penrose inverse. In case A is regular, A+ = A−1 holds. If A is symmetric,
then A+ A = AA+ . If A is symmetric and idempotent, then A+ = A. Further,
all of A+ A, AA+ , I − A+ A, and I − AA+ are idempotent. Here are some
equalities holding for the Moore-Penrose inverse:
(A+ )+ = A (24.11)
T + + T
(A ) = (A ) (24.12)
T + + T +
(A A) = A (A ) (24.13)
T + T + +
(AA ) = (A ) A (24.14)
T + T
A AA = A (24.15)
+ T T
A AA = A (24.16)
U T AV = S
S = diag(s1 , . . . , sk )
s1 ≥ s2 ≥ . . . ≥ sr > sr+1 = . . . = sk = 0
For a proof and algorithms to calculate the SVD of an arbitrary matrix see
the book by Golub and Loan [?]. Another proof can be found in the book by
Harville [?]. The diagonal elements si of S, which is orthogonal equivalent to
A, are called singular values. From
S T S = (U T AV )T (U T AV ) = V T AT U U T AV = V −1 AT AV
24.5. APPROXIMATION WITH LINEAR MODELS 409
and
AT A~x = AT AA+~b
= AT~b
where we used Eqn. 24.15. Hence, the Moore-Penrose inverse2 solves our prob-
lem. Moreover, the solution can be obtained easily from the singular value
decomposition.
Note that this is a very nice formula as new points arrive or are deleted, only
the sums have to be updated and the quotients to be calculated. There is no
need to look at the other points again.
where
r(~a) = ~b − A~a (24.18)
The components of the vector r(~a) are denoted by ri (~a).
As pointed out earlier, l∞ is a convex norm. Hence, a solution exists. Since
l∞ is not strictly convex, the uniqueness of the solution is not guaranteed. To
solve problem 24.17 by following the approach proposed by Watson [?]. We
start by characterizing the solution, continue with the conditions under which
uniqueness holds, make some more observations, and finally derive an algorithm
for the case n = 2, i.e. we find a best approximation by a linear function.
Although only few applications in databases exist for l∞ , it is very useful to
find a best approximation under lq if we want to approximate by a function
eβ+αx (see Sec. 24.5.6).
Assume we have a best solution ~a. Then, for some indices i, ri (~a) attains the
maximum, i.e. ri (~a) = ||r(~a)||∞ . Otherwise, a better solution would exist. We
denote the set of indices where the maximum is attained by I(~ ¯ a). We further
¯ The
denote by θi (~a) the sign of ri (~a). Thus ri (~a) = θi (~a)||r(~a)||∞ for all i ∈ I.
following theorem gives a characterization of the solution.
1. λi = 0 for all i 6∈ I,
3. AT~λ = ~0.
Corollary 24.5.26 Let ~a solve problem 24.17 and let I be chosen according
to Theorem 24.5.24 such that λi 6= 0 for all i ∈ I. Further let d~ be another
solution to 24.17. Then
~ = ri (~a).
ri (d)
Hence, not surprisingly, any two solutions have the same residuals for compo-
nents where the maximum is attained. The theorem and its first corollary state
that we need at most t + 1 solutions for a matrix A of rank t. The next theorem
shows that at least t + 1 indices exist where the maximum is attained.
Theorem 24.5.27 If A has rank t, a solution to problem 24.17 exists for which
¯ ≥ t + 1.
|I|
Finally, we can derive uniqueness for those A which satisfy the Haar condition:
Obviously, we need to know, whether the Haar condition holds for a matrix
A. Remember that we want to approximate a set of points by a linear combi-
nation of functions Φj , 1 ≤ j ≤ n. From the points (xi , yi ), 1 ≤ i ≤ m, and the
Φj , the design matrix A is derived as shown in Equation 24.5. If the Φj form a
Chebyshev set, the design matrix will fulfill the Haar condition.
Assume the xi are ordered, that is xi < xi+1 for 1 ≤ i < m. Further, it is well-
known that the set of polynomials Φj = xj−1 , 1 ≤ j ≤ n, forms a Chebyshev
set on any interval X. From now on, we assume that our xi are ordered, that
is x1 < . . . < xm . Further, we define X = [x1 , xm ]. We also assume that the
matrix A of Problem 24.17 is defined as given in Equation 24.5, where the Φj
are continous functions from X to R.
We still need some more knowledge in order to build an algorithm. The
next definition will help to derive a solution for subsets I of {1, . . . , m} with
|I| = n + 1.
412 CHAPTER 24. CARDINALITY AND COST ESTIMATES
Consider again the example where we want to approximate the three points
(1, 20), (2, 10), and (3, 60) by a linar function. We saw that the solution to our
problem is fˆl∞ (x) = −15 + 20x. The following table gives the points, the value
of fˆl∞ , the residuals, including their signs.
x y fˆl∞ ri
1 20 5 +15
2 10 25 -15
3 60 45 +15
where
Φ1 (x1 ) . . . Φn (x1 )
∆(x1 , . . . , xn ) = det ... .. .. (24.19)
. .
Φ1 (xn ) . . . Φn (xn )
Then
sign(∆i ) = sign(∆i+1 ), ∀ 1 ≤ i ≤ n.
Let us take a closer look at Theorem 24.5.32 in the special case where m = 3,
i.e. we have exactly three points (xi1 , yi1 ), (xi2 , yi2 ), and (xi3 , yi3 ). We find the
best linear approximation fˆ(x) = α + βx under l∞ by solving the following
equations:
yi1 − (α + βxi1 ) = −1 ∗ λ
yi2 − (α + βxi2 ) = +1 ∗ λ
yi3 − (α + βxi3 ) = −1 ∗ λ
24.5. APPROXIMATION WITH LINEAR MODELS 413
where λ represents the value of ||r(~a)||∞ for the solution ~a to be found. Solving
these equations results in
yi2 − yi1 (yi − yi1 )(xi2 − xi1 )
λ = − 3
2 2(xi3 − xi1 )
yi2 − yi1 2λ
β = −
xi2 − yi1 x i2 − x i1
α = yi1 + λ − xi1 β
The algorithm starts with three arbitrary points with indices i1 , i2 , and i3
with xi1 < xi2 < xi3 . Next, it derives α, β, and λ using the solutions to our
equations 24.20-24.20. Then, the algorithm tries find new indices j1 , j2 , j3 by
exchanging one of the ij with some k such that λ will be increased. Obviously,
we use a k that maximizes the deviation from the best approximation fˆ of
i1 , i2 , i3 , i.e.
||yk − fˆ(xk )||∞ = max ||yi − f (xi )||∞ .
i=1,...,m
BestLinearApproximationUnderChebyshevNorm
3. Find an xk for which the deviation of fˆ from the given data is maximized.
Call this maximal deviation λmax .
5. Return α, β, λ.
minimizes ( )
yi fˆ(xi )
max max , .
i=1,...,m fˆ(xi ) yi
Let ~a and ~b be two vectors in Rn with bi > 0. Then, we define ~a/~b = ~~a =
b
(a1 /b1 , . . . , an /bn )t T .
Let A ∈ Rm×n be a matrix, where m > n and ~b = (b1 , . . . , bm )t T be a vector
in Rm with bi > 0. Then we can state the problem as
under the constraint that αit T > 0, 1 ≤ i ≤ m, for all row vectors αi of A.
24.5. APPROXIMATION WITH LINEAR MODELS 415
Keeping the trick with A0 in mind, it is easy to see that Problem 24.20 can
be solved, if we can solve the general problem
find~a ∈ Rn that minimizes||A~a||Q . (24.22)
The following proposition ensures that a solution to this general problem exists.
Further, since ||A~a||Q is convex, the minimum is a global one.
Proposition 24.5.1 Let A ∈ Rm,n such that R(A) ∩ Rm
>0 6= ∅. Then ||A · ||Q
attains its minimum.
Recall that lq is subadditive and convex. Further it is lower semi-continuous
(see also [?, p. 52]). However, it is not strictly convex. Hence, as with l∞ , we
expect uniqueness to hold only under certain conditions.
We need some more notation. Let A ∈ Rm,n . We denote by R(A) =
{A~a | ~a ∈ Rn } the range of A and by N (A) = {~a ∈ Rn | A~a = 0} the nullspace
of A.
Problem (24.22) can be rewritten as the following constrained minimization
problem:
1
min q subject to ≤ A~a ≤ q and q ≥ 1. (24.23)
(~a,q)∈Rn ×R q
The Lagrangian of (24.23) is given by
1
L(~a, q, λ+ , λ− , µ) := q − (λ+ )T (q − A~a) − (λ− )T (A~a − ) − µ(q − 1).
q
Assume that R(A) ∩ Rm >0 6= ∅. Then the set {(~ a, q) : 1q ≤ A~a ≤ q and q ≥
1} is non-empty and closed and there exists (~a, q) for which we have strong
inequality in all conditions. Then the following Karush-Kuhn-Tucker conditions
are necessary and sufficient for (~aˆ, q̂) to be a minimizer of (24.23), see, e.g., [?,
+ − m
p. 62]: there exist λ̂ , λ̂ ∈ R≥0 and µ̂ ≥ 0 such that
ˆ, q̂, λ̂+ , λ̂− , µ̂) = AT λ+ − AT λ− = 0
∇~a L(~a (24.24)
m m
∂ ˆ + −
X
+ 1 X −
L(~a, q̂, λ̂ , λ̂ , µ̂) = 1 − λ̂i − 2 λ̂i − µ = 0 (24.25)
∂q q
i=1 i=1
416 CHAPTER 24. CARDINALITY AND COST ESTIMATES
and for i = 1, . . . , m,
λ̂+ â − (A ˆ i
~a) = 0, (24.26)
i
λ̂− (A~a)ˆ i−1 = 0, (24.27)
i
q̂
µ̂(q̂ − 1) = 0.
Assume that 1m 6∈ R(A), where 1m is the vector with all components 1. Then
q̂ > 1 and consequently µ̂ = 0. Furthermore, it is clear that not both λ̂+i and
− ˆ 1 ˆ
λ̂i can be positive because the conditions q̂ = (A~a)i and q̂ = (A~a)i cannot be
fulfilled at the same time, since q̂ > 1.
Setting λ̂ := λ̂+ − λ̂− , we can summarize our findings (24.24) - (24.27) in
the following theorem.
Theorem 24.5.34 Let A ∈ Rm,n such that R(A) ∩ Rm >0 6= ∅ and 1m 6∈ R(A).
ˆ
Then (~a, q̂) solves (24.23) if and only if there exists λ̂ ∈ Rm such that
i) AT λ̂ = 0.
P 1 P
ii) q = q λ̂i + q λ̂i .
λ̂i >0 λ̂i <0
iv) if λ̂i > 0 then (A~a) ˆ i = q̂ and if λ̂i < 0 then (A~a)
ˆ i = 1/q̂.
Remark. We see that 1 < q̂ = (A~a ˆ)i implies sign (A~a
ˆ)i − 1 = 1 and that
1 > 1/q̂ = (A~a ˆ)i implies sign (A~a ˆ)i − 1 = −1; whence λ̂i (A~a ˆ)i − 1 ≥ 0.
For our approximation problem (24.20) this means that the residuum fˆ(xi ) − bi
fulfills λ̂i (fˆ(xi ) − bi ) ≥ 0.
Under certain conditions, problem (24.22) has a unique solution which can
be simply characterized. Let us start with some straightforward considerations
ˆ of ||A·||Q that
in this direction. If N (A) 6= {~0}, then we have for any minimizer ~a
ˆ + β, β ∈ N (A) is also a minimizer. In particular, we have that N (A) 6= {~0} if
~a
• m < n,
A+ 1m + N (A),
Proposition 24.5.2 Let A ∈ Rn+1,n such that R(A) ∩ Rn+1 >0 6= ∅, 1m 6∈ R(A)
and rank(A) = n. Then ||A · ||Q has a unique minimizer if and only if the
Lagrange multipliers λ̂i , i = 1, . . . , n + 1 are not zero.
2. The matrix (m, n)–matrix A in (24.21) is the product of the diagonal ma-
trix diag (1/bi )m
i=1 with positive diagonal entries and a Vandermonde matrix.
Hence, it can easily be seen that spark(A) = n + 1. If an (m, n)–matrix A has
spark(A) = n + 1, then A fulfills the Haar condition.
Proposition 24.5.2 can be reformulated as follows:
Corollary 24.5.35 Let A ∈ Rn+1,n such that R(A)∩Rn+1 >0 6= ∅ and 1m 6∈ R(A)
. Then ||A · ||Q has a unique minimizer if and only if spark(A) = n + 1.
Theorem 24.5.36 Let A ∈ Rm,n such that R(A) ∩ Rm >0 6= ∅. Suppose that
spark(A) = n + 1. Then ||A · ||Q has a unique minimizer which is determined
by n + 1 rows of A, i.e., there exists an index set J ⊂ {1, . . . , m} of cardinality
|J| = n + 1 such that ||A · ||Q and ||A|J · ||Q have the same minimum and the
same minimizer. Here A|J denotes the restriction of A to the rows which are
contained in the index set J. We call such index set J an extremal set.
case. For ( 21 , 1)T we have sign(λ̂1 , λ̂2 , λ̂3 , λ̂3 ) = (−1, 0, 1, −1) while the pattern is
(0, 1, 1, −1) for ( 23 , 2)T and (0, 0, 1, −1) within the line bounded by these points.
By Theorem 24.5.36, a method for finding theminimizer of ||A · ||Q would
m
be to compute the unique minimizers of the n+1 subproblems ||A|J · ||Q for
418 CHAPTER 24. CARDINALITY AND COST ESTIMATES
all index sets J of cardinality n + 1 and to take the largest minimum â and
the corresponding ˆ
m
~a as minimizer of the original problem. For our line problem
there exist 3 = O(m3 ) of these subproblems. In the following section, we
give another algorithm which is also based on Theorem 24.5.36, but ensures
that the value a enlarges for each new choice of the subset J. Since there is
only a finite number of such subsets we must reach a stage where no further
increase is possible and J is an extremal set. In normed spaces such methods
are known as ascent methods, see [?].
In this section, we suggest a detailed algorithm for minimizing ||A·||Q , where
we restrict our attention to the line problem
bi β + αxi
max max , . (24.28)
i=1,...,m β + αxi bi
where q
r2
1−r1 if r1 < 0 and r2 > 0,
q
1−r2
q̂1 := r1 if r1 > 0 and r2 < 0, (24.29)
q
1
if r1 > 0 and r2 > 0,
r1 +r2
(
r1
1/q̂1 if r2 < 0,
q̂2 := r1
x̂1 if r2 >0
and
b1 (x2 − x3 ) b2 (x3 − x1 )
r1 := , r2 := .
b3 (x2 − x1 ) b3 (x2 − x1 )
Remark. If the points are ordered, i.e., x1 < x2 < x3 (or alternatively in
descending order), then either A~a ˆ = (q̂, 1/q̂, q̂)T or A~a
ˆ = (1/q̂, q̂, 1/q̂)T . This
means that λ̂ in Theorem 24.5.34 has alternating signs. In other words, the
points f (x1 ), f (x3 ) lie above b1 , b3 and f (x2 ) lies below b2 or conversely.
Later we will show that the alternating sign condition is true for general
best polynomial approximation with respect to the Q-paranorm.
Corollary 24.5.37 is the basis of the Algorithm 24.6, which finds the optimal
line with respect to three points in each step and chooses the next three points
if the minimum corresponding to their line becomes larger.
Proposition 24.5.3 The algorithm computes the line f (x) = β̂ + α̂x which
minimizes (24.28).
24.5. APPROXIMATION WITH LINEAR MODELS 419
1. For i = 1, . . . , m; i 6= i1 , i2 compute
Remark. Alternatively, one can deal with ordered points b1 < b2 < b3
r2
which restricts the effort in (24.29) to q̂1 = 1−r 1
but requires an ascending
ordering of the points xi1 , xi2 , xj in each step of the algorithm.
Finally, we want to generalize the remark on the signs of the Lagrange
multipliers given after Corollary 24.5.37. Remember that the set of polynomials
Φi (x) = xi−1 , i = 1, . . . , n forms a Chebyshev set (see Def. 24.5.30). Applying
again Lemma 24.5.33, one can easily prove the following result.
Theorem 24.5.38 Let Φi : I → R, i = 1, . . . , n be a Chebyshev set and let
x1 < . . . < xn+1 be points in I. Then, for
Φ := (Φj (xi ))n+1,n
i,j=1 ,
n > 2. We only have to provide a routine which solves the following system of
EXC equations:
where
x3 − x1
q13 :=
y3 − y1
g := q13 y3 − x3 + x2
β = 0
α = λy1
p
λ = y2 /y1
Thus, it remains to find the best function nj=1 αj Φj (xi ) with respect to the
P
l∞ norm.
It is now easy to see that we can solve the second problem as follows.
Let (xi , yi ) be the data we want to approximate by a function of the form EXC
ln(p(x)) while minimizing the Chebyshev norm. We can do so by finding the
best approximation of (xi , eyi ) under lq .
422 CHAPTER 24. CARDINALITY AND COST ESTIMATES
Part V
Implementation
423
Chapter 25
Architecture of a Query
Compiler
25.2 Architecture
Figure 25.1 a path of a query through the optimizer. For every step, a single
component is responsible. Providing a facade for the components results in the
overall architecture (Fig. 25.2). Every component is reentrant and stateless.
The information necessary for a component to process a query is passed via
references to control blocks. Control blocks are discussed next, then we discuss
memory management. Subsequent sections describe the components in some
detail.
425
426 CHAPTER 25. ARCHITECTURE OF A QUERY COMPILER
query
parsing CTS
abstract syntax tree
nfst
internal representation
rewrite I query
internal representationoptimizer
plan generation
internal representation
rewrite II
internal representation
code generation
execution plan
a pointer to the schema cache. The schema cache itself allows to look up type
names, relations, extensions, indexes, and so on.
The query control block contains all the information gathered for the current
query so far. It contains the abstract syntax tree, after its construction, the
analyzed and translated query after NFST has been applied, the rewritten plan
25.4. MEMORY MANAGEMENT 427
after the Rewrite I phase, and so on. It also contains a link to the memory
manager that manages memory for this specific query. After the control block
for a query is created, the memory manager is initialized. During the destructor
call, the memory manager is destroyed and memory released.
Some components need helpers. These are also associated with the control
blocks. We discuss them together with the components.
25.6 Driver
25.7 Bibliography
1
Design pattern.
428 CHAPTER 25. ARCHITECTURE OF A QUERY COMPILER
NFST
CodeGenerator
run(NFST_CB*)
Scanner run(CodeGenerator_CB*)
SchemaCache Factorizer
NFST_CB
BlockHandler
Global_CB Rewrite_I_CB
Rewrite_II_CB OpCodeMapper
MemoryManager
CodeGenerator_CB OperatorFactory
RegisterManager
Internal Representations
26.1 Requirements
easy access to information
query representation: overall design goal: methods/functions with semantic
meaning, not only syntactic meaning.
relationships: consumer/producer (occurrance) precedence order informa-
tion equivalence of expressions (transitivity of equality) see also expr.h fuer
andere funktionen/beziehungen die gebraucht werden
2-ebenen repraesentation. 2. ebene materialisiert einige beziehungen und
funktionen, die haeufig gebraucht werden und kompliziert zu berechnen sind an-
derer grund fuer materialisierung: vermeide zuviele geschachtelte forschleifen.
bsp: keycheck: gegeben eine menge von attributen und eine menge von schlues-
seln, ist die menge ein schluessel? teste jeden schluessel, kommt jedes element
in schluessel in menge von attributen vor? (schon drei schleifen!!!)
modellierungsdetail: ein grosser struct mit dicken case oder feine klassen-
hierarchie. wann splitten: nur wenn innerhalb des optimierers verschiedene
abarbeitung erfordert.
Representation: info captured: 1) 1st class information (information ob-
vious in original query+(standard)semantic analysis) 2) 2nd class information
(derived information) 3) historic information (during query optimization itself)
- modified (original expression, modifier) - copied (original expression, copi-
er) 4) information about the expression itselt: (e.g.: is function call, is select)
5) specific representations for specific purposes (optimization algorithms, code
generation, semantic analysis) beziehungen zwischen diesen repraesentationen
info captured for 1) different parts of the optimizer
syntactic/semantic information
garbage collection: 1) manually 2) automatic 3) semi-automatic (collect
references, free at end of query)
431
432 CHAPTER 26. INTERNAL REPRESENTATIONS
• korrelationspraedikate
for blocks: indicator whether they should produce a null-tuple, in case they
do not produce any tuple. this is nice for some rewrite rules. other possibility:
if-statement in algebra.
kosten: diese sind zu berechnen und dienen als grundlage fuer die planbe-
wertung ges-kosten /* gesamt kosten (ressourcenverbrauch) */ ges-kosten +=
cpu-instr / inst/sek ges-kosten += seek-kosten * overhead (waiting/cpu) ges-
kosten += i/o-kosten * io-weight cpu-kosten /* reine cpu-kosten */ i/o-kosten
/* hintergrundspeicherzugriff ( warten auf platte + cpu fuer seitenzugriffe) */
434 CHAPTER 26. INTERNAL REPRESENTATIONS
• ordnung
• boolean properties
• kostenvektor
• cardinalitaeten bewiesen/geschaetzt
• gewuenschter puffer
• schluessel, fds
• menge der objekte, von denen der plan (der ja teilplan sein kann) abhaengt
das folgende ist alles blabla. aber es weisst auf den punkt hin,
das in dieser beziehung etwas getan werden muss.
--index: determine degree of clustering
- lese_rate = #gelesene_seiten / seiten_fuer_relation
ein praedikate erniedrigt die lesen_rate, ein erneutes lesen aufgrund einer verdr
falls TIDs sortiert werden, muss fetch_ration erneut berechnet werden
- seiten koennen in gruppen z.b. auf einem zylinder zusammengefasst werden
und mit einem prefetch befehl geholt werden. anzahl seeks abschaetzen
- cluster_ration(CR)
CR = P(read(t) ohne page read) = (card - anzahl pagefetch)/card
= (card - (#pagefetch - #page))/card
das ist besonderer quark
- cluster_factor(CF)
CF = P(avoid unnecessary pagefetch) = (pagefetch/maxpagefetch)
= card -#fetch / card - #pageinrel
das ist besonderer quark
index retrieval on full key => beide faktoren auf 100% setzen, da
innerhalb eines index die TIDs pro key-eintrag sortiert werden.
26.9 Bibliography
436 CHAPTER 26. INTERNAL REPRESENTATIONS
Chapter 27
27.1 Parsing
Lexical analysis is pretty much the same as for traditional compilers. However,
it is convenient to treat keywords as soft. This allows for example for relation
names like order which is a keyword in SQL. This might be very convenient for
users since SQL has plenty (several hundreds) of keywords. For some keywords
like select there is less danger of it being a relation name. A solution for group
and order would be to lex them as a single token together with the following
by.
Parsing again is very similar to parsing in compiler construction. For both,
lexing and parsing, generators can be used to generate these components. The
parser specification of SQL is quite lengthy while the one for OQL is pretty
compact. In both cases, a LALR(2) grammar suffices. The outcome of the
parser should be an abstract syntax tree. Again the data structure for abstract
syntax trees (ast) as well as operations to deal with them (allocation, deletion,
traversal) can be generated from an according ast specification.
During parsing already some of the basic rewriting techniques can be ap-
plied. For example, between can be eliminated.
In BD II, there are currently four parsers (for SQL, OQL, NQL (a clean
version of XQuery), XQuery). The driver allows to step through the query
compiler and allows to influence its overall behavior. For example, several trace
levels can be switched on and off while within the driver. Single rewrites can
be enabled and disabled. Further, the driver allows to switch to a different
query language. This is quite convenient for debugging purposes. We used the
Cocktail tools to generate the lexer, parser, ast, and NFST component.
437
438CHAPTER 27. DETAILS ON THE PHASES OF QUERY COMPILATION
*
/
1. normalization of expressions,
Although these are different tasks, a single pass over the abstract syntax tree
suffices to perform all these tasks in one step.
Consider the following example query:
Expression
• for a given expression: compute the set of occurring (consumed, free) IUs
• constant folding
• merge and/or (from e.g. binary to n-ary) and push not operations
27.3 Normalization
Fig. 27.3 shows the result after normalization. The idea of normalization is to
introduce intermediate IUs such that all operators take only IUs as arguments.
This representation is quite useful.
27.4 Factorization
Common subexpressions are factorized by replacing them with references to
some IU. For the expressions in TPCD query 1, the result is shown in Fig. 27.4.
440CHAPTER 27. DETAILS ON THE PHASES OF QUERY COMPILATION
IU:-
*
IU:- IU:-
...
select a, b, c
from A, B
where d > e and f = g
...
27.6. SEMANTIC ANALYSIS 441
IU:
*
IU: IU:
*
IU:
- +
Consider the semantic analysis of d . Since SQL provides implicit name look up,
we have to check (formerly analyzed) relations A and B whether they provide
an attribute called d . If none of them provides an attribute d , then we must
check the next upper SFW-block. If at least one of the relations A or B provides
an attribute d, we just check that only one of them provides such an attribute.
Otherwise, there would be an unallowed ambiguity. The blockwise look up is
handled by block handler. For every newly encounterd block (e.g. SFW block),
a new block is opened. All identifiers analyzed within that block are pushed
into the list of identifiers for that block. In case the query language allows for
implicit name resolution, it might also be convenient to push all the attributes
of an analyzed relation into the blocks list. The lookup is then performed
blockwise. Within every block, we have to check for ambiguities. If the lookup
fails, we have to proceed looking up the identifier in the schema. The handling
of blocks and lookups is performed by the BlockHandler component attached
to the control block of the NFST component (Fig. 25.3).
442CHAPTER 27. DETAILS ON THE PHASES OF QUERY COMPILATION
27.7 Translation
The translation step translates the original AST representation into an internal
representation. There are as many internal query representations as there are
query compiler. They all build on calculus expressions, operator graphs build
over some algebra, or tableaux representations [766, 767]. A very powerful
representation that also captures the subtleties of duplicate handling is the
query graph model (QGM) [586].
The representation we use here is a mixture of a typed algebra and calcu-
lus. Algebraic expressions are simple operator trees with algebraic operators
like selection, join, etc. as nodes. These operator trees must be correctly typed.
For example, we are very picky about whether a selection operator returns a
set or a bag. The expression that more resemble a calculus representation than
an algebraic expression is the SFWD block used in the internal representation.
We first clarify our notion of block within the query representation described
here and then give an example of an SFWD block. A block is everything that
produces variable bindings. For example a SFWD-block that pretty directly
corresponds to a SFW-block in SQL or OQL. Other examples of blocks are
quantifier expressions and grouping operators. A block has the following ingre-
dients:
• a list of inputs of type collection of tuples1 (labeled from)
• a set of expressions whose top is an IU (labeled define)
• a selection predicate of type bool (labeled where)
For quantifier blocks and group blocks, the list of inputs is restricted to length
one. The SFWD-block and the grouping block additionally have a projection
list (labeled select) that indicates which IUs are to be projected (i.e. passed to
subsequent operators). Blocks are typed (algebraic) expressions and can thus
be mixed with other expressions and algebraic operator trees.
An example of a SFWD-block is shown in Fig. 27.5 where dashed lines
indicate the produced-by relationship. The graph corresponds to the internal
1
We use a quite general notion of tuple: a tuple is a set of variable (IU) bindings.
27.7. TRANSLATION 443
select
where
>
define
IU: IU: IU: IU:
/ 100 100.000
*
from
key IU key IU
scan IU:e scan IU:d
Relation/Extent Relation/Extent
"Employee" "Department"
• eliminate duplicates
• preserve duplicates
This summary is also attached to every block. Let us illustrate this by a simple
example:
For the inner block, the user specifies that duplicates are to be preserved. How-
ever, duplicates or not does not modify the outcome of exists. Hence, the
contextual information indicates that the outcome for the inner block is a don’t
care. The processing view can determine whether the block produces dupli-
cates. If for all the entries in the from clause, a key is projected in the select
clause, then the query does not produce duplicates. Hence, no special care has
to be taken to remove duplicates produced by the outer block if we assume that
ssno is the key of Employee.
No let us consider the annotations for the arguments in the from clause.
The query
outer part) should be annotated by (OJ). We use (AJ) as the anti-join annota-
tion, and (DJ) for a d-join. To complete annotation, the case of a regular join
can be annotated by (J). If the query language also supports all-quantifications,
that translate to divisions, then the annotation (D) should be supported.
Since the graphical representation of a query is quite complex, we also use
text representations of the result of the NFST phase. Consider the following
OQL query:
select distinct s
from s in Student, c in s.courses
where c.name = “Database”
select distinct s
from s in Student, c in s.courses
where cn = “Database”
define cn = c.name
PROJECT [s]
SELECT [cn=”Database”]
EXPAND [cn:c.name]
s from its left input, the d-join computes the set s.courses. For every course
c in s.courses an output tuple containing the original student s and a single
course c is produced. If the evaluation of the right argument of the d-join is not
dependend on the left argument, the d-join is equivalent with a cross product.
The first optimization is to replace d-joins by cross products whenever possible.
Queries with a group by clause must be translated using the unary grouping
operator GROUP which we denote by Γ. It is defined as
Γg;θA;f (e) = {y.A ◦ [g : G]|y ∈ e,
G = f ({x|x ∈ e, x.Aθy.A})}
where the subscripts have the following semantics: (i) g is a new attribute
that will hold the elements of the group (ii) θA is the grouping criterion for a
sequence of comparison operators θ and a sequence of attribute names A, and
(iii) the function f will be applied to each group after it has been formed. We
often use some abbreviations. If the comparison operator θ is equal to “=”, we
don’t write it. If the function f is identity, we omit it. Hence, Γg;A abbreviates
Γg;=A;id .
Let us complete the discussion on internal query representation. We already
mentioned algebraic operators like selection and join. These are called logical
algebraic operators. There implementations are called physical algebraic opera-
tors. Typically, there exist several possible implementations for a single logical
algebraic operator. The most prominent example being the join operator with
implementations like Grace join, sort-merge join, nested-loop join etc. All the
operators can be modelled as objects. To do so, we extend the expression hi-
erarchy by an algebra hierarchy. Although not shown in Fig 27.7, the algebra
class should be a subclass of the expression class. This is not necessary for SQL
but is a requirement for more orthogonal query languages like OQL.
27.8. REWRITE I 447
Expression
Algebraic Operator
Join
Dup SortUnnestSelectChiProjection AlgIfDivision AlgSetop
Elim
27.8 Rewrite I
27.10 Rewrite II
generated. First program is the init program. It initializes the registers that
will hold the results for the aggregate functions. For example, for an average
operation, the register is initalized with 0. The advance program is executed
once for every tuple to advance the aggregate computation. For example, for
an average operations, the value of some register of the input tuple is added
to the result register holding the average. The finalize program performs post-
processing for aggregate functions. For example for the average, it devides the
sum by the number of tuples. For hash-based grouping, the last two programs
(see Fig.1.6) compute the hash value of the input register set and compare the
group-by attributes of the input registers with those of every group in the hash
bucket.
During the code generation for the subscripts factorization of common subex-
pression has to take place. Another task is register allocation and deallocation.
This task is performed by the register manager. It uses subroutines to de-
termine whether some registers are no longer needed. The register manager
must also keep track in which register some IU is stored (if at all). Another
component used during code generation is a factory that generates new AVM
operations. This factory is associated with a table driven component that maps
the operations used in the internal query representation to AVM opcodes.
27.12 Bibliography
Chapter 28
Hard-Wired Algorithms
28.1.1 Introduction
select e.name
from Employee e, Department d
where e.dno = d.dno and d.name = “shoe”
The bottom level contains two table scans that scan the base tables Employee
and Department. Then, a selection operator is applied to restrict the depart-
ments to those named “shoe”. A nested-loop join is used to select those employ-
ees that work in the selected departments. The projection restricts the output
to the name of the employees, as required by the query block. For such a plan,
a cost function is used to estimate its cost. The goal of plan generation is to
generate the cheapest possible plan. Costing is briefly sketched in Section ??.
The foundation of plan generation are algebraic equivalences. For e, e1 , e2 , . . .
being algebraic expressions and p, q predicates, here are some example equiva-
449
450 CHAPTER 28. HARD-WIRED ALGORITHMS
Project (e.name)
lences:
For more equivalences and conditions that ought to be attached to the equiva-
lences see the appendix 7.2. Note that commutativity and associativity of the
join operator allow an arbitrary ordering. Since the join operator is the most
expensive operation, ordering joins is the most prominent problem in plan gen-
eration.
These equivalences are of course independent of the actual implementation
of the algebraic operators. The total number of plans equivalent to the original
query block is called the potential search space. However, not always is the
total search space considered. The set of plans equivalent to the original query
considered by the plan generator is the actual search space. Since the System R
plan generator [672], certain restrictions are applied. The most prominent are:
• Generate only plans where selections are pushed down as far as possible.
R4
R3
R1 R2 R1 R2 R3 R4
Some comments are in order. Cross products are only necessary, if the query
graph is unconnected where a query graph is defined as follows: the nodes
are the relations and the edges correspond to the predicates (boolean factors 1 )
found in the where clause. More precisely, the query graph is a hypergraph,
since a boolean factor may involve more than two relations. A left-deep tree is
an operator tree where the right argument of a join operator always is a base
relation. A plan with join operators whose both arguments are derived by other
join operators is called bushy tree. Figure 28.2 gives an example of a left-deep
tree and a bushy tree.
If we take all the above restrictions together, the problem boils down to
ordering the join operators or relations. This problem has been studied exten-
sively. The complexity of finding the best (according to some cost function)
ordering (operator tree) was first studied by Ibaraki and Kameda [377]. They
proved that the problem of generating optimal left-deep trees with no cross
products is NP-hard for a special block-wise nested loop join cost function.
This cost function applied in the proof is quite complex. Later is was shown
that even if the cost function is very simple, the problem remains NP-hard
[165]. The cost function (Cout ) used there just adds up intermediate results
sizes. This cost function is interesting in that it is the kernel of many other cost
functions and it fulfills the ASI property of which we now the following: If the
cost function fulfills the ASI property and the query graph is acyclic, then the
problem can be solved in polynomial time [377, 443]. Ono and Lohman gave ex-
amples that considering cross products can substantially improve performance
[553]. However, generating optimal left-deep trees with cross products even
for Cout makes the problem NP-hard [165]. Generating optimal bushy trees is
1
A boolean factor is a disjunction of basic predicates in a conjunctive normal form.
452 CHAPTER 28. HARD-WIRED ALGORITHMS
even harder. Even if there is no predicate, that is only cross products have
to be used, the problem is NP-hard [657]. This is surprising since generating
left-deep trees with cross products as the only operation is very simple: just
sort the relations by increasing sizes.
Given the complexity of the problem, there are only two alternatives to
generate plans: either explore the total search space or use heuristics. The
former can be quite expensive. This is the reason why the above mentioned
restrictions to the search space have traditionally been applied. The latter
approach risks missing good plans. The best-known heuristics is to join the
relation next, that results in the smallest next intermediate result. Estimating
the cardinality of such results is discussed in Section ??.
Traditionally, selections where pushed as far down as possible. However,
for expensive selection predicates (e.g. user defined predicates, those involving
user-defined functions, predicates with subqueries) this does not suffice. For
example, if a computer vision application has to compute the percentage of
snow coverage for a given set of satellite images, this is not going to be cheap. In
fact, it can be more expensive than a join operation. In these cases, pushing the
expensive selection down misses good plans. That is why lately research started
to take expensive predicates into account. However, some of the proposed
solutions do not guarantee to find the optimal plans. Some approaches and their
bugs are discussed in [132, 356, 354, 656, 658]. Although we will subsequently
give an algorithm that incorporates correct predicate placement, not all plan
generators do so. An alternative approach (though less good) is to pull-up
expensive predicates in the Rewrite-II-phase.
There are several approaches to explore the search space. The original ap-
proach is to use dynamic programming [672]. The dynamic programming algo-
rithm is typically hard-coded. Figure 28.3 illustrates the principle of bottom-up
plan generation as applied in dynamic programming. The bottom level consists
of the original relations to be joined. The next level consists of all plans that
join a subset of cardiniality two of the original relations. The next level con-
tains all plans for subsets of cardinality three, and so on. With the advent
of new query optimization techniques, new data models, extensible database
systems, researchers where no longer satisfied with the hard-wired approach.
Instead, they aimed for rule-based plan generation. There exist two differ-
ent approaches for rule-based query optimizers. In the first approach, the al-
gebraic equivalences that span the search space are used to transform some
initial query plan derived from the query block into alternatives. As search
strategies either exhaustive search is used or some stochastic approach such as
simulated annealing, iterative improvement, genetic algorrithms and the like
[66, 382, 385, 386, 723, 747, 746, 749]. This is the transformation-based ap-
proach. This approach is quite inefficient. Another approach is to generate
plans by rules in a bottom-up fashion. This is the generation-based approach.
In this approach, either a dynamic programming algorithm [487] is used or
memoization [306]. It is convenient to classify the rules used into logical and
physical rules. The logical rules directly reflect the algebraic equivalences. The
physical rules or implementation rules transform a logical algebraic operator
into a physical algebraic operator. For example, a join-node becomes a nested-
28.1. HARD-WIRED DYNAMIC PROGRAMMING 453
s = a & -a;
while(s) {
s = a & (s - a);
process(s);
}
proc Optimal-Bushy-Tree(R, P )
1 for k = 1 to n do
2 for all k-subsets Mk of R do
3 for l = 0 to min(k, m) do
4 for all l-subsets Pl of Mk ∩ RS do
5 best cost so far = ∞;
6 for all subsets L of Mk with 0 < |L| < k do
7 L0 =VMk \ L, V = Pl ∩ L, V 0 = Pl ∩ L0 ;
8 p = {pi,j | pi,j ∈ P, Ri ∈ V, Rj ∈ V 0 }; // p=true might hold
9 T = (T [L, V ] 1p T [L0 , V 0 ]);
10 if Cost(T) < best cost so far then
11 best cost so far = Cost(T);
12 T [Mk , Pl ] = T ;
13 fi;
14 od;
15 for all R ∈ Pl do
16 T = σR (T [Mk , Pl \ {R}]);
17 if Cost(T) < best cost so far then
18 best cost so far = Cost(T);
19 T [Mk , Pl ] = T ;
20 fi;
21 od;
22 od;
23 od;
24 od;
25 od;
26 return T [R, S];
bushy trees. Efficient implementation technique for the algorithm can be found
in [778, 658]. As input parameters, the algorithm takes a set of relations R and
a set of predicates P . The set of relations for which a selection predicate exists
is denoted by RS . We identify relations and predicates that apply to these
relations. For all subsets Mk of the relations and subsets Pl of the predicates,
an optimal plan is constructed and entered into the table T . The loops range
over all Mk and Pl . Thereby, the set Mk is split into two disjoint subsets L
and L0 , and the set Pl is split into three parts (line 7). The first part (V )
contains those predicates that apply to relations in L only. The second part
(V 0 ) contains those predicates that apply to relations in L0 only. The third part
(p) is a conjunction of all the join predicates connecting relations in L and L0
(line 8). Line 9 constructs a plan by joining the two plans found for the pairs
[L, V ] and [L0 , V 0 ] in the table T . If this plan has so far the best costs, it is
memoized in the table (lines 10-12). Last, different possibilities of not pushing
predicates in Pl are investigated (lines 15-19).
Another issue that complicates the application of dynamic programming are
certain properties of plans. The most prominent such properties are interesting
orders [672, 709, 710]. Take a look at the following query:
28.2. BIBLIOGRAPHY 455
Here, the user requests the result to be order on d.dno. Incidentally, this is also a
join attribute. During bottom up plan generation, we might think that a Grace
hash join is more efficient than a sort-merge join since the cost of sorting the
relations is too high. However, the result has to be sorted anyway so that this
sort may pay off. Hence, we have have to keep both plans. The approach is the
following. In the example, an ordering on d.dno is called an interesting order.
In general, any order that is helpful for ordering the output as requested by the
user, for a join operator, for a grouping operator, or for duplicate elimination
is called an interesting order . The dymamic programming algorithm is then
modified such that plans are not pruned, if they produce different interesting
orders.
28.2 Bibliography
456 CHAPTER 28. HARD-WIRED ALGORITHMS
Chapter 29
Rule-Based Algorithms
29.3 Bibliography
457
458 CHAPTER 29. RULE-BASED ALGORITHMS
Chapter 30
459
460 CHAPTER 30. EXAMPLE QUERY COMPILER
Globale Kontrolle
Regionen
? ? ?
Kontrolle Kontrolle Kontrolle
? ?
Kontrolle Kontrolle
Transformation Transformation
30.1.4 Ereq
A primary goal of the EREQ project is to define a common architecture for the
next generation of database managers. This architecture now includes
* the query language OQL (a la ODMG), * the logical algebra AQUA (a la
Brown), and * the physical algebra OPA (a la OGI/PSU).
It also includes
* software to parse OQL into AQUA (a la Bolo)
and query optimizers:
* OPT++ (Wisconsin), * EPOQ (Brown), * Cascades (PSU/OGI), and *
Reflective Optimizer (OGI).
In order to test this architecture, we hope to conduct a ”bakeoff” in which
the four query optimizers will participate. The primary goal of this bakeoff is
to determine whether optimizers written in different contexts can accommodate
the architecture we have defined. Secondarily, we hope to collect enough per-
formance statistics to draw some conclusions about the four optimizers, which
have been written using significantly different paradigms.
462 CHAPTER 30. EXAMPLE QUERY COMPILER
Modellbeschreibung
?
Optimierergenerator
?
C-Compiler
?
Anfrage - Synt. Analyse - Optimierer - Interpreter - Antwort
At present, OGI and PSU are testing their optimizers on the bakeoff queries.
Here is the prototype bakeoff optimizer developed at OGI. This set of Web
pages is meant to report on the current progress of their effort, and to define
the bakeoff rules. Please email your suggestions for improvement to Leo Fegaras
[email protected]. Leo will route comments to the appropriate author.
http://www.cse.ogi.edu/DISC/projects/ereq/bakeoff/bakeoff.html
30.1.5 Exodus/Volcano/Cascade
Im Rahmen des Exodus-Projektes wurde ein Optimierergenerator entwickelt
[303]. Einen Überblick über den Exodus-Optimierergenerator gibt Abbildung 30.2.
Ein Model description file enthält alle Angaben, die für einen Optimierer nötig
sind. Da der Exodus-Optimierergenerator verschiedene Datenmodelle unter-
stützen soll, enthält dieses File zunächst einmal die Definition der verfügbaren
Operatoren und Methoden. Dabei werden mit Operatoren die Operatoren der
logischen Algebra bezeichnet und mit Methoden diejenigen der physischen Al-
gebra, also die Implementierungen der Operatoren. Das Model description file
enthält weiterhin zwei Klassen von Regeln. Transformationen basieren auf alge-
braischen Gleichungen und führen einen Operatorbaum in einen anderen über.
Implementierungsregeln wählen für einen gegebenen Operator eine Methode
aus. Beide Klassen von Regeln haben einen linken Teil, der mit einem Teil des
aktuellen Operatorgraphen übereinstimmen muß, einen rechten Teil, der den
Operatorgraphen nach Anwendung der Regel beschreibt, und eine Bedingung,
die erfüllt sein muß, damit die Regel angewendet werden kann. Während die
linke und rechte Seite der Regel als Muster angegeben werden, wird die Be-
dingung durch C-Code beschrieben. Auch für die Tranformation lassen sich
C-Routinen verwenden. In einer abschließenden Sektion des Model description
files finden sich dann die benötigten C-Routinen.
30.1. RESEARCH PROTOTYPES 463
Aus dem Model description file wird durch den Optimierergenerator ein
C-Programm erzeugt, das anschließend übersetzt und gebunden wird. Das
Ergebnis ist dann der Anfrageoptimierer, der in der herkömmlichen Art und
Weise verwendet werden kann. Es wurde ein übersetzender Ansatz für die
Regeln gewählt und kein interpretierender, da in einem von den Autoren vorher
durchgeführten Experiment sich die Regelinterpretation als zu langsam erwiesen
hat.
Die Regelabarbeitung im generierten Optimierer verwaltet eine Liste OPEN,
in der alle anwendbaren Regeln gehalten werden. Ein Auswahlmechanismus
bestimmt dann die nächste anzuwendende Regel und entfernt sie aus OPEN.
Nach deren Anwendung werden die hierdurch ermöglichten Regelanwendungen
detektiert und in OPEN vermerkt. Zur Implementierung des Auswahlmecha-
nismus werden sowohl die Kosten eines aktuellen Ausdrucks als auch eine Ab-
schätzung des Potentials einer Regel in Betracht gezogen. Diese Abschätzung
des Potentials berechnet sich aus dem Quotienten der Kosten für einen Opera-
torbaum vor und nach Regelanwendung für eine Reihe von vorher durchgeführten
Regelanwendungen. Mit Hilfe dieser beiden Angaben, den Kosten des aktuellen
Operatorgraphen, auf den die Regel angewendet werden soll, und ihres Poten-
tials können dann Abschätzungen über die Kosten des erzeugten Operator-
graphen berechnet werden. Die Suchstrategie ist Hill climbing.
Der von den Autoren vermerkte Hauptnachteil ihres Optimierergenerators,
den sie jedoch für alle transformierenden regelbasierten Optimerer geltend machen,
ist die Unmöglichkeit der Abschätzung der absoluten Güte eines Operator-
baumes und des Potentials eines Operatorbaumes im Hinblick auf zukünftige
Optimierungen. Dadurch kann niemals abgeschätzt werden, ob der optimale
Operatorbaum bereits erreicht wurde. Erst nach Generierung aller Alternativ-
en ist die Auswahl des optimalen Operatorbaumes möglich. Weiter bedauern es
die Autoren, daß es nicht möglich ist, den A∗-Algorithmus als Suchfunktion zu
verwenden, da die Abschätzung des Potentials oder der Distanz zum optimalen
Operatorgraphen nicht möglich ist.
Zumindest kritisch gegenüberstehen sollte man auch der Bewertung einzel-
ner Regeln, da diese, basierend auf algebraischen Gleichungen, von zu feiner
Granularität sind, als daß eine allgemeine Bewertung möglich wäre. Die erfol-
greiche Verwendung des Vertauschens zweier Verbundoperationen in einer An-
frage bedeutet noch lange nicht, daß diese Vertauschung auch in der nächsten
Anfrage die Kosten verringert. Die Hauptursache für die kritische Einstel-
lung gegenüber dieser recht ansprechenden Idee ist, daß eine Regelanwendung
zu wenig Information/Kontext berücksichtigt. Würde dieses Manko beseitigt,
wären Regeln also von entschieden gröberer Granularität, so erschiene dieser
Ansatz vielversprechend. Ein Beispiel wäre eine Regel, die alle Verbundoper-
ationen gemäß einer gegebenen Heuristik ordnet, also ein komplexer Algorith-
mus, der mehr Wissen in seine Entscheidungen einbezieht.
Graefe selbst führt einige weitere Nachteile des Exodus-Optimierergenerators
an, die dann zur Entwicklung des Volcano-Optimierergenerators führten [305,
306]. Unzureichend unterstützt werden
• nicht-triviale Kostenmodelle,
464 CHAPTER 30. EXAMPLE QUERY COMPILER
• Eigenschaften,
• Heuristiken und
(select <proj-list>
<sel-pred-list>
<join-pred-list>
<table-list>)
<rel-name>.<attr-name>
30.1. RESEARCH PROTOTYPES 465
Anfrage
?
Generierung des
allg. Ausdrucks
?
Zugriffsplan-
generierung
?
Join-
Reihenfolge und
-Methoden
?
Auswertungsplan
30.1.7 Genesis
Das globale Ziel des Genesisprojektes [52, 53, 54, 57] war es, die gesamte Daten-
banksoftware zu modularisieren und eine erhöhte Wiederverwendbarkeit von
Datenbankmodulen zu erreichen. Zwei Teilziele wurden hierbei angestrebt:
466 CHAPTER 30. EXAMPLE QUERY COMPILER
Wir interessieren uns hier lediglich für die Erreichung der Ziele beim Bau von
Optimierern [50, 55].
Die Standardisierung der Schnittstellen wird durch eine Verallgemeinerung
von Anfragegraphen erreicht. Die Algorithmen selbst werden durch Transfor-
mationen auf Anfragegraphen beschrieben. Man beachte, daß dies nicht be-
deutet, daß die Algorithmen auch durch Transformationregeln implementiert
werden. Regeln werden lediglich als Beschreibungsmittel benutzt, um die Natur
der Wiederverwendbarkeit von Optimierungsalgorithmen zu verstehen.
Die Optimierung wird in zwei Phasen eingeteilt, die Reduktionsphase und
die Verbundphase. Die Reduktionsphase bildet Anfragegraphen, die auf nicht
reduzierten Datenmengen arbeiten, auf solche ab, die auf reduzierten Daten-
mengen arbeiten. Die Reduktionsphase orientiert sich also deutlich an den
Heuristiken zum Durchschieben von Selektionen und Projektionen. Die zweite
Phase bestimmt Verbundordnungen. Damit ist die in den Papieren beschriebene
Ausprägung des Ansatzes sehr konservativ in dem Sinne, daß nur klassische
Datenmodelle betrachtet werden. Eine Anwendung der Methodik auf objekto-
rientierte oder deduktive Datenmodelle steht noch aus.
Folglich lassen sich nur die existierenden klassischen Optimierungsansätze
mit diesen Mitteln hinreichend gut beschreiben. Ebenso lassen sich die ex-
istierenden klassischen Optimierer mit den vorgestellten Mitteln als Zusam-
mensetzung der ebenfalls im Formalismus erfaßten Algorithmen beschreiben.
Die Zusammensetzung selbst wird mit algebraischen Termersetzungen beschrieben.
Durch neue Kompositionsregeln lassen sich dann auch neue Optimierer beschreiben,
die andere Kombinationen von Algorithmen verwenden.
Durch die formale, implementierungsunabhängige Beschreibung sowohl der
einzelnen Optimierungsalgorithmen als auch der Zusammensetzung eines Opti-
mierers wird die Wiederverwendbarkeit von bestehenden Algorithmen optimal
unterstützt. Wichtig dabei ist auch die Verwendung der standardisierten An-
fragegraphen. Dieser Punkt wird allerdings aufgeweicht, da auch vorgesehen ist,
verschiedene Darstellungen von Anfragegraphen zu verwenden [53]. Hierdurch
wird die Wiederverwendung von Implementierungen von Optimierungsalgorith-
men natürlich in Frage gestellt, da diese üblicherweise nur auf einer bestimmten
Darstellung der Anfragegraphen arbeiten.
Wenn neue Optimierungsansätze entwickelt werden, so lassen sie sich eben-
falls im vorgestellten Formalismus beschreiben. Gleiches gilt auch für neue In-
dexstrukturen, da auch diese formal beschrieben werden [51, 56]. Nicht abzuse-
hen ist, in wieweit der standardisierte Anfragegraph Erweiterungen standhält.
Dies ist jedoch kein spezifisches Problem des Genesisansatzes, sondern gilt für
alle Optimierer. Es ist noch offen, ob es gelingt, die Optimierungsalgorithmen
so zu spezifizieren und zu implementieren, daß sie unabhängig von der konkreten
Darstellung oder Implementierung der Anfragegraphen arbeiten. Der objekto-
rientierte Ansatz kann hier nützlich sein. Es erhebt sich jedoch die Frage, ob bei
Einführung eines neuen Operators die bestehenden Algorithmen so implemen-
30.1. RESEARCH PROTOTYPES 467
tierbar sind, daß sie diesen ignorieren können und trotzdem sinnvolle Arbeit
leisten.
Die Beschränkung auf zwei Optimierungsphasen, die Reduktions- und die
Verbundphase, ist keine Einschränkung, da auch sie mittels Termersetzungsregeln
festgelegt wurde, und somit leicht geändert werden kann.
Da die Beschreibungen des Optimierers und der einzelnen Algorithmen un-
abhängig von der tatsächlichen Implementierung sind, sind auch die globale
Kontrolle des Optimierers und die lokalen Kontrollen der einzelnen Algorithmen
voneinander losgelöst. Dieses ist eine wichtige Forderung, um Erweiterbarkeit
zu erreichen. Sie wird oft bei regelbasierten Optimierern verletzt und schränkt
somit deren Erweiterbarkeit ein.
Die Evaluierbarkeit, die Vorhersagbarkeit und die frühe Bewertung von Al-
ternativen sind mit dem vorgestellten Ansatz nicht möglich, da die einzelnen
Algorithmen als Transformationen auf dem Anfragegraphen aufgefaßt werden.
Dieser Nachteil gilt jedoch nicht allein für den hier vorgestellten Genesisansatz,
sondern generell für alle bis auf einen Optimierer. Es ist allerdings nicht ab-
sehbar, ob dieser Nachteil aus dem verwendeten Formalismus resultiert oder
lediglich aus deren Konkretisierung bei der Modellierung bestehender Optimier-
er. Es ist durchaus möglich, daß der Formalismus mit leichten Erweiterungen
auch andere Ansätze, insbesondere den generierenden, beschreiben kann.
Insgesamt handelt es sich beim Genesisansatz um einen sehr brauchbaren
Ansatz. Leider hat er, im Gegensatz zur Regelbasierung, nicht genug Wider-
hall gefunden hat. Er hat höchst wahrscheinlich mehr Möglichkeiten, die An-
forderungen zu erfüllen, als bisher ausgelotet wurde.
30.1.8 GOMbgo
468 CHAPTER 30. EXAMPLE QUERY COMPILER
GOMql-Anfrage
Termrepräsentation
? Heuristik
ASR-Schema - Regelanwendung
Y
Regelbasis
Liste der optimierten Terme
optimierter Term
Code Generator
Auswertungsplan
(QEP)
?
heuristic
evaluator
tool-
box cond rule
mgr application
query optimized
transf query alternatives
pattern mgr
matcher
environment manager
Schema Manager
- types
- access support relations
X
?
Normalisierung
?
Algebraische-
optimierung
1
?
Konstante u.
gemeinsame π χ
Teilausdrücke
?
sort
Übersetzung in
Ausdrucksalgebra
σ head
?
nicht-algebr.
Optimierung
REL
?
30.1.9 Gral
Gral ist ein erweiterbares geometrisches Datenbanksystem. Der für dieses Sys-
tem entwickelte Optimierer, ein regelbasierter Optimierer in Reinkultur, erzeugt
aus einer gegebenen Anfrage in fünf Schritten einen Ausführungsplan (s. Abb. 30.6
a) [60]. Die Anfragesprache ist gleich der verwendeten deskriptiven Algebra
(descriptive algebra). Diese ist eine um geometrische Operatoren erweiterte
relationale Algebra. Als zusätzliche Erweiterung enthält sie die Möglichkeit,
Ausdrücke an Variablen zu binden. Ein Auswertungsplan wird durch einen Aus-
druck der Ausführungsalgebra (executable algebra) dargestellt. Die Ausführungsalgebra
beinhaltet im wesentlichen verschiedene Implementierungen der deskriptiven
Algebra und Scan-Operationen. Die Trennung zwischen deskriptiver Algebra
und Ausführungsalgebra ist strikt, das heißt, es kommen keine gemischten Aus-
drücke vor (außer während der expliziten Konvertierung (Schritt 4)).
Die Schritte 1 und 3 sind durch feste Algorithmen implementiert. Während
30.1. RESEARCH PROTOTYPES 471
wobei
specification von der Form
SPEC spec1 ,. . . ,specn
ist. Dabei sind die speci Range-Spezifikationen wie beispielsweise opi in <
OpSet >.
definition Variablen definiert (bspw. für Attributsequenzen). In Gral ex-
istieren verschiedene Sorten von Variablen für Attribute, Operationen,
Relationen etc.
pattern ein Muster in Form eines Ausdrucks ist, der Variablen und Konstan-
ten enthalten kann. Der Ausdruck kann ein Ausdruck der deskriptiven
Algebra oder der Ausführungsalgebra sein.
conditioni eine Bedingung ist. Diese Bedingung ist ein allgemeiner boolescher
Ausdruck. Spezielle Prädikate wie ExistsIndex (existiert ein Index für eine
Relation?) werden von Gral zur Verfügung gestellt.
resulti wiederum ein Ausdruck ist, der das Ergebnis der Regel beschreibt.
valuationi ist ein arithmetischer Ausdruck, der einen numerischen Wert zurückliefert.
Dieser kann in einer (Gral unterstützt mehrere) Auswahlstrategie herange-
zogen werden: Es wird die Regel mit der kleinsten valuation bevorzugt.
30.1. RESEARCH PROTOTYPES 473
Die Auswertung einer Regel erfolgt standardmäßig. Sei E der Ausdruck auf
den die Regel angewendet werden soll.
Der Gral-Optimierer ist ein reiner regelbasierter Optimierer, der den Trans-
formationsansatz verfolgt. Dementsprechend treffen alle vorher identifizierten
Nachteile derselben zu.
Zu bemängeln sind im einzelnen folgende Punkte:
30.1.10 Lambda-DB
http://lambda.uta.edu/lambda-DB/manual/overview.html
Query Execution Plans QEPs werden als (deep) processing trees repraesen-
tiert.
Cost Model Ziemlich aehnlich dem, das wir verwenden. Sie benutzt auch
solche Sachen wie card(C), size(C), ndist(Ai ), f an(Ai ), share(Ai ). Einzel-
heiten stehen in meiner Ausarbeitung.
30.1.12 Opt++
wisconsin
30.1.13 Postgres
Postgres ist kein Objektbanksystem sondern fällt in die Klasse der erweiterten
relationalen Systeme [733]. Die wesentlichen Erweiterungen sind
• berechenbare Attribute, die als Quel-Anfragen formuliert werden [731],
• Operationen [729],
• Regeln [732].
Diese beiden Punkte sollen uns jedoch an dieser Stelle nicht interessieren. Die
dort entwickelten Optimierungstechniken, insbesondere die Materialisierung der
berechenbaren Attribute, sind in der Literatur beschrieben [400, 344, 342, 343].
Unser Interesse richtet sich vielmehr auf eine neuere Publikation, in der eine
Vorschlag für die Reihenfolgebestimmung von Selektionen und Verbundopera-
tionen unterbreitet wird [356]. Diese soll im folgenden kurz vorgestellt werden.
Zunächst jedoch einige Vorbemerkungen.
Wenn man eine Selektion verzögert, also nach einem Verbund ausführt,
obwohl dies nicht notwendig wäre, so kann es passieren, daß das Selektion-
sprädikat auf mehr Tupeln ausgewertet werden muß. Es kann jedoch nicht
passieren, daß es auf mehr verschiedenen Werten ausgeführt werden muß. Im
Gegenteil, die Anzahl der Argumentewerte wird durch einen Verbund im allge-
meinen verkleinert. Cached man also die bereits errechneten Werte des Selek-
tionsprädikates, so wird die Anzahl der Auswertungen des Selektionsprädikates
30.1. RESEARCH PROTOTYPES 475
nach einem Verbund zumindest nicht größer. Die Auswertung wird dann durch
ein Nachschlagen ersetzt. Da wir hier nur teure Selektionsprädikate betrachten,
ist ein Nachschlagen sehr billig gegenüber der Auswertung. Die Kosten für das
Nachschlagen können sogar vernachläßigt werden. Es bleibt das Problem der
größe des Caches. Liegt Eingabe sortiert nach den Argumenten des Selektion-
sprädikates vor, so kann der die größe des Caches unter Umständen auf 1 re-
duziert werden. Er erübrigt sich ganz, wenn man eine indirekte Repräsentation
des Verbundergebnisses verwendet. Eine mögliche indirekte Repräsentation ist
in Abbildung ?? dargestellt, wobei die linke der abgebildeten Relationen die
Argumente für das betrachtete Selektionsprädikat enthalte.
Für jedes Selektionsprädikat p(a1 , . . . , an ) mit Argumenten ai bezeichne cp
die Kosten der Auswertung auf einem Tupel. Diese setzen sich aus CPU-
und I/O-Kosten zusammen (s. [356]). Ein Plan ist ein Baum, dessen Blätter
scan-Knoten enthalten und dessen innere Knoten mit Selektions- und Verbund-
prädikaten markiert sind. Ein Strom in einem Plan ist ein Pfad von einem Blatt
zur Wurzel. Die zentrale Ide ist nun die Selektions- und Verbundprädikate nicht
zu unterscheiden, sondern gleich zu behandeln. Dabei wird angenommen, daß
alle diese Prädikate auf dem Kreuzprodukt aller Relationen der betrachteten
Anfrage arbeiten. Dies erfordert eine Anpassung der Kosten. Seien a1 , . . . , an
die Relationen der betrachteten Anfrage und p ein Prädikat über den Relationen
a1 , . . . , ak . Dann sind die globalen Kosten von p wie folgt definiert:
C(p) = Qn c p
i=k+1 |ai |
Die globalen Kosten berechnen die Kosten der Auswertung des Prädikates über
der gesamten Anfrage. Hierbei müssen natürlich diejenigen Relationen her-
ausgenommen werden, die das Prädikat nicht beeinflussen. Zur Illustration
nehme man an, p sei ein Selektionsprädikat auf nur einer Relation a1 . Wendet
man p direkt auf a1 an, so entstehen die Kosten cp ∗ |a1 |. Im vereinheitlicht-
en Modell wird angenommen, daß jedes Prädikat auf dem Kreuzprodukt aller
in der Anfrage beteiligten Relationen ausgewertet wird. Es entstehen also die
Kosten C(p)∗|a1 |∗|a2 |∗. . .∗|an |. Diese sind aber gleich cp ∗|a1 |. Dies ist natürlich
nur unter der Verwendung eines Caches für die Werte der Selektionsprädikate
korrekt. Man beachte weiter, daß die Selektivität s(p) eines Prädikates p un-
abhängig von der Lage innerhalb eines Stroms ist.
Der globale Rang eines Prädikates p ist definiert als
s(p)
rank (p) = C(p)
Man beachte, daß die Prädikate innerhalb eines Stroms nicht beliebig umord-
bar sind, da wir gewährleisten müssen, daß die von einem Prädikat benutzten
Argumente auch vorhanden sein müssen. In [356] wir noch eine weitere Ein-
schränkung vorgenommen: Die Verbundreihenfolge darf nicht angetastet wer-
den. Es wird also vorausgesetzt, daß eine optimale Verbundreihenfolge bereits
bestimmt wurde und nur noch die reinen Selektionsprädikate verschoben wer-
den dürfen.
Betrachtet man zunächst einmal nur die Umordnung der Prädikate auf
einem Strom, so erhält man bedingt durch die Umordbarkeitseinschränkungen
476 CHAPTER 30. EXAMPLE QUERY COMPILER
30.1.15 Secondo
Gueting
30.1.16 Squiral
Der erste Ansatz eines regelbasierten Optimierers, Squiral, kann auf das Jahr
1975 zurückgeführt werden [714]. Man beachte, daß dieses Papier vier Jahre
älter ist als das vielleicht am häufigsten zitierte Papier über den System R
Optimierer [672], der jedoch nicht regelbasiert, sondern fest verdrahtet ist.
Abbildung 30.7 gibt einen Überblick über den Aufbau von Squiral. Nach
der syntaktischen Analyse liegt ein Operatorgraph vor. Dieser ist in Squiral
zunächst auf einen Operatorbaum beschränkt. Zur Behandlung von gemein-
samen Teilausdrücken wird das Anlegen von temporären Relationen, die den
30.1. RESEARCH PROTOTYPES 477
query
parsing
operator graph
transformation graph
transformations transformations
rules
optimized
operator graph
operator base
construction procedures
cooperative
concurrent
programs
database
machine
result
eingegangen.
Die wesentliche Aufgabe der Operatorkonstruktion ist die Auswahl der tatsächlichen
Implementierungen der Operatoren im Operatorgraph unter optimaler Aus-
nutzung gegebener Sortierreihenfolgen. Auch diese Phase der Optimierung ist
in Squiral nicht kostenbasiert. Sie wird durch zwei Durchläufe durch den Op-
eratorgraphen realisiert. Der erste Durchlauf berechnet von unten nach oben
die möglichen Sortierungen, die ohne zusätzlichen Aufwand möglich sind, da
beispielsweise Relationen schon sortiert sind, und vorhandene Sortierungen
durch Operatoren nicht zerstört werden. Im zweiten Durchlauf, von oben nach
unten, werden Umsortierungen nur dann vorgenommen, wenn keine der im er-
sten Durchlauf berechneten Sortierungen eine effiziente Implementierung des
zu konvertierenden Operators erlaubt. Beide Durchläufe sind mit Regelsätzen
spezifiziert. Es ist bemerkenswert, daß die Anzahl der Regeln, 32 für den
Aufwärtspaß und 34 für den Abwärtspaß, die Anzahl der Regeln für die Trans-
formationsphase (insgesamt 7 Regeln), bei weitem übertrifft. Auch die Kom-
plexität der Regeln ist erheblich höher.
Beide für uns interessante Phasen, die Operatorgraphtransformation und
Operatorkonstruktion, sind mit Regeln spezifiziert. Es ist jedoch in beiden
Phasen kein Suchprozeß nötig, da die Regeln alle Fälle sehr gezielt auflisten
und somit einen eindeutigen Entscheidungsbaum beschreiben. Eine noch minu-
tiösere Unterscheidung für die Erzeugung von Ausführungsplänen in der Oper-
atorkonstruktionsphase gibt es nur noch bei Yao [836]. Diese haben auch den
Vorteil, durch Kostenrechnungen belegt zu sein.
Da die Regeln in ihren Prämissen die Heuristik ihrer Anwendung mit kodieren
und keine eigene Suchfunktion zur Anwendung der Regeln existiert, ist die Er-
weiterbarkeit sehr schwierig. Das Fehlen jeglicher Kostenbewertung macht eine
Evaluation der Alternativen unmöglich. Daher ist es auch schwer, die einzel-
nen Komponenten des Optimierers, nämlich die Regeln, zu bewerten, zumal der
transformierende Ansatz gewählt wurde. Der Forderung nach Vorhersagbarkeit
und stetiger Leistungsabfall wird in diesem Ansatz ebenfalls nicht nachgegan-
gen.
Zerteilung
?
Anfrage-
transformation
Planoptimierung
Planverfeinerung
?
Auswertungsplan
(F). Knoten, die mit F markiert sind, tragen zur Erzeugung des Ergebnisses
eines Operators bei, die Quantorenmarkierungen zu dessen Einschränkung. Die
Kanten sind mit den Prädikaten markiert. Es ergeben sich also Schleifen für nur
eine Relation betreffende Prädikate. Weitere Operatoren sind insert, update,
intersection, union und group-by. Daneben wird die QGM-Repräsentation ein-
er Anfrage mit Schemainformation und statistischen Daten angereichert. Sie
dient also auch als Sammelbecken für alle die Anfrage betreffende Information.
Die QGM-Repräsentation dient der Anfragetransformation (Abb. 30.8) als
Ausgangspunkt. Die Anfragetransformation generiert zu einer QGM-Repräsentation
verschiedene äquivalente QGM-Repräsentationen. Die Anfragetransformation
läßt sich, abgesehen von den Darstellungsunterschieden von QGM und Hydro-
gen, als eine Variante der Source-level-Transformationen ansehen. Sie wird
regelbasiert implementiert, wobei C die Regelsprache ist. Eine Regel besteht
aus 2 Teilen, einer Bedingung und einer Aktion. Jeder Teil wird durch eine
C-Prozedur beschrieben. Dadurch erübrigt sich die Implementierung eines all-
gemeinen Regelinterpreters mit Pattern-matching. Regeln können in Gruppen
zusammengefaßt werden. Der aktuelle Optimierer umfaßt drei Klassen von
Regeln:
Für die Ausführung der Regeln stehen drei verschiedene Suchstrategien zur
Verfügung:
1. sequentiell,
2. prioritätsgesteuert und
Alternative
deklarative normalisierter Objektalgebra- typkonsistenter optimierter Ausf”uhrungs-
Anfrage Kalk”ulausdruck ausdruck Ausdruck Algebraausdruck pl”ane
• nested loop join, nested loop outer join, index nested loop joins, sort merge
join, sort merge outer join, hash joins, hash outer join, cartesian join, full
outer join, cluster join, anti-joins, semi-joins, uses bitmap indexes for star
queries
• sort group-by,
• index-organized tables
• function-based indexes
30.2. COMMERCIAL QUERY COMPILER 485
• access path: table scan, fast full index scan, index scan, ROWID scans
(access ROW by ROWID), cluster scans, hash scans. [former two with
prefetching] index scans:
• eliminate between
• elminate x in (c1 . . . cn) (also uses IN-LIST iterator as outer table con-
structor in a d-join or nested-loop join like operation.
query transformer:
• view merging
• predicate pushing
• subquery unnesting
remaining subplans for nested query blocks are ordered in an efficient manner
plan generator:
• single row joins are placed first (based on unique and key constraints.
• join statement with outer join: table with outer join operator must come
after the other table in the condition in the join order. optimizer does
not consider join orders that violate this rule.
• histograms
• push-join predicate
• subquery unnesting
• index joins
rest:
parameters:
statistics:
• table statistics
number of rows, number of blocks, average row length
• column statistics
number of distinct values, number of nulls, data distribution
• index statistics
number of keys, (from column statistics?) number of leaf blocks, levels,
clustering factor (collocation amount of the index block/data blocks, 3-17)
• system statistics
I/O performance and utilization, cpu performance and utilization
generating statistics:
• exact computation
histograms:
• value-based histograms
used for number of distinct values ≤ number of buckets
• index-organized tables
• convert b-tree result RID lists to bitmaps for further bitmap anding
• hash clusters
488 CHAPTER 30. EXAMPLE QUERY COMPILER
• continue 5-35
Selected Topics
489
Chapter 31
• disable prefetching
491
492 CHAPTER 31. GENERATING PLANS FOR TOP-N-QUERIES?
Chapter 32
Recursive Queries
493
494 CHAPTER 32. RECURSIVE QUERIES
Chapter 33
SCAN [s:student]
495
496 CHAPTER 33. ISSUES INTRODUCED BY OQL
The algebraic expression in Fig. 33.1 implies a scan of all students and a sub-
sequent dereferentiation of the supervisor attribute in order to access the su-
pervisors. If not all supervisors fit into main memory, this may result in many
page accesses. Further, if there exists an index on the supervisor’s age, and
the selection condition ssa < 30 is highly selective, the index should be applied
in order to retrieve only those supervisors required for answering the query.
Type-based rewriting enables this kind of optimization. For any expression of
certain type with an associated extent, the extent is introduced in the from
clause. For our query this results in
select distinct p
from p in Professor
where p.room.number = 209
Straight forward evaluation of this query would scan all professors. For every
professor, the room relationship would be traversed to find the room where the
professor resides. Last, the room’s number would be retrieved and tested to be
209. Using the inverse relationship, the query could as well be rewritten to
33.2. CLASS HIERARCHIES 497
JOIN [ss=p]
The evaluation of this query can be much more efficient, especially if there
exists an index on the room number. Rewriting queries by exploiting inverse
relationships is another rewrite technique to be applied during Rewrite Phase
I.
Manager
boss: CEO
6
CEO
phisticated possibilities to realize extents and scans over them are needed. The
different possible implementations can be classified along two dimensions. The
first dimension distinguishes between logical and physical extents, the second
distinguishes between strict and (non-strict) extents.
Obviously, the two classifications are orthogonal. Applying them both re-
sults in the four possibilities presented graphically in Fig. 33.4. [166] strongly
argues that strict extents are the method of choice. The reason is that only
this way the query optimizer might exploit differences for extents. For example,
there might be an index on the age of Manager but not for Employee. This
difference can only be exploited for a query including a restriction on age, if we
have strict extents.
However, strict extents result in initial query plans including UNION oper-
ators. Consider the query
select e
from e in Employee
where e.salary > 100.000
33.3. CARDINALITIES AND COST FUNCTIONS 499
C: {id1 } C: {id1 }
logical
C: ob1 C: ob1
physical
C1 : ob2 C2 : ob3 C1 : ob1 , ob2 C2 : ob1 , ob3
excluding including
e1 ∪ e2 ≡ e2 ∪ e1 (33.1)
e1 ∪ (e2 ∪ e3 ) ≡ (e1 ∪ e2 ) ∪ e3 (33.2)
σp (e1 ∪ e2 ) ≡ σp (e1 ) ∪ σp (e2 ) (33.3)
χa:e (e1 ∪ e2 ) ≡ χa:e (e1 ) ∪ χa:e (e2 ) (33.4)
(e1 ∪ e2 ) 1p e3 ≡ (e1 1p e3 ) ∪ (e2 1p e3 ) (33.5)
34.9 Bibliography
501
502 CHAPTER 34. ISSUES INTRODUCED BY XPATH
Chapter 35
35.5 Bibliography
[512] [765] [199]
Numbering: [241] Timber [392] TAX Algebra [393], physical algebra of Tim-
ber [573]
Structural Joins [21, 716]
SAL: [63], TAX: [393], XAL: [249]
• StatiX: [250]
503
504 CHAPTER 35. ISSUES INTRODUCED BY XQUERY
Outlook
What we did not talk about: multiple query optimization, semantic query
optimization, special techniques for optimization in OBMSs, multi-media data
bases, object-relational databases, spatial databases, temporal databases, and
query optimization for parallel and distributed database systems.
Recursive Queries?
505
506 CHAPTER 36. OUTLOOK
Appendix A
Query Languages?
A.2 SQL
A.3 OQL
A.4 XPath
A.5 XQuery
A.6 Datalog
507
508 APPENDIX A. QUERY LANGUAGES?
Appendix B
• Hash-Teams
509
510 APPENDIX B. QUERY EXECUTION ENGINE (?)
Appendix C
pareval Falls ein Glied einer Konjunktion zu false evaluiert, werden die restlichen
Glieder nicht mehr evaluiert. Dies ergibt sich automatisch durch die Ver-
wendung von hintereinanderausgeführten Selektionen.
pushnot Falls ein Prädikat die Form ¬(p1 ∧ p2 ) hat, so ist pareval nicht an-
wendbar. Daher werden Negationen nach innen gezogen. Auf ¬p1 ∨ ¬p2
ist pareval dann wieder anwendbar. Das Durchschieben von Negationen
ist auch im Kontext von NULL-Werten unabdingbar für die Korrektheit.
Dies ist eine Optimierungstechnik, die oft bereits auf der Quellebene
durchgeführt wird.
projpush Die Technik zur Behandlung von Projektionen ist nicht ganz so ein-
fach wie die der Selektion. Zu unterscheiden ist hier, ob es sich um eine
Projektion mit Duplikateliminierung handelt oder nicht. Je nach dem
511
512APPENDIX C. GLOSSARY OF REWRITE AND OPTIMIZATION TECHNIQUES
grouppush Pushing a grouping operation past a join can lead to better plans.
crossjoin Ein Kreuzprodukt, das von einer Selektion gefolgt wird, wird wenn
immer möglich in eine Verbundoperation umgewandelt. Diese Optimierung-
stechnik schränkt den Suchraum ein, da Pläne mit Kreuzprodukten ver-
mieden werden.
joinpush Tables that are guaranteed to produce a single tuple are always
pushed to be joined first. This reduces the search space. The single tuple
condition can be evaluated by determining whether all key attributes of
a relation are fully qualified. [275, 276].
unnest Entschachtelung von Anfragen [161, 162, 268, 424, 429, 430, 586, 719,
721, 722]
pma Predicate Move around moves predicates between queries and subqueries.
Mostly they are duplicated in order to yield as many restrictions in a block
as possible [474]. As a special case, predicates will be pushed into view
definitions if they have to be materialized temporarily [275, 276].
exproj For subqueries with exist prune unnecessary entries in the select clause.
The intention behind is that attributes projected unnecessarily might in-
fluence the optimizer’s decision on the optimal access path [275, 276].
vm View merging expands the view definition within the query such that is
can be optimized together with the query. Thereby, duplicate accesses to
the view are resolved by different copies of the views definition in order
to facilitate unnesting [275, 276, 586].
like1 If the like predicate does not start with %, then a prefix index can be
used.
like2 The pattern is analyzed to see whether a range of values can be extracted
such that the pattern does not have to be evaluated on all tuples. The
result is either a pretest or an index access. [275, 276].
tmplay Das temporäre Ändern eines Layouts eines Objektes kann durchaus
sinnvoll sein, wenn die Kosten, die durch diese Änderung entstehen, durch
den Gewinn der mehrmaligen Verwendung dieses Layouts mehr als kom-
pensiert werden. Ein typisches Beispiel ist Pointer-swizzling.
AggrJoin Joins with non-equi join predicates based on ≤ or <, can be pro-
cessed more efficiently than by a cross product with a subsequent selection
[164].
rid/tidsort When several tuples qualify during an index scan, the resulting
TIDs can be sorted in order to guarantee sequential access to the base
relation.
515
multIDXsplit If two ranges are queried within the same query ([1-10],[20-30])
consider multIDX or use a single scan through the index [1-30] with an
additional qualification predicate.
lock The optimizer should chose the correct locks to set on tables. For example,
if a whole table is scanned, a table lock should be set.
stop Stop evaluation after the first tuple qualifies. This is good for existential
subqueries, universal subqueries (disqualify), semi-joins for distinct results
and the like.
kann auch nach a,b,c sortiert werden. stoert gar nicht, vereinfacht aber
die duplikateliminierung. nur ein sortieren notwendig.
XXX - use keys, inclusion dependencies, fds etc. (all user specified and de-
rived) (propagate keys over joins as fds), (for a function call: derived IU is
functional dependend on arguments of the function call if function is de-
terministic) (keys can be represented as sets of IUs or as bitvectors(given
numbering of IUs)) (numbering inprecise: bitvectors can be used as filters
(like for signatures))
Appendix D
Useful Formulas
The following identities can be found in the book by Graham, Knuth, and
Patashnik [308].
( n!
n k!(n−k)! if 0 ≤ k ≤ n
= (D.1)
k 0 else
n n
= (D.2)
k n−k
n n n−1
= (D.3)
k k k−1
n n−1
k = n (D.4)
k k−1
n n−1
(n − k) = n (D.5)
k k
n n−1
(n − k) = n (D.6)
k n−k−1
n n−1 n−1
= + (D.7)
k k k−1
r m r r−k
= (D.8)
m k k m−k
517
518 APPENDIX D. USEFUL FORMULAS
[4] S. Abiteboul and N. Bidoit. Non first normal form relations: An alge-
bra allowing restructuring. Journal of Computer Science and Systems,
33(3):361, 1986.
[8] A. Aboulnaga and J. Naughton. Building XML statistics for the hidden
web. In Int. Conference on Information and Knowledge Management
(CIKM), pages 358–365, 2003.
519
520 BIBLIOGRAPHY
[12] F. Afrati, C. Li, and J. Ullman. Generating efficient plans for queries
using views. In Proc. of the ACM SIGMOD Conf. on Management of
Data, pages 319–330, 2001.
[20] A.V. Aho, Y. Sagiv, and J.D. Ullman. Equivalence among relational
expressions. SIAM Journal on Computing, 8(2):218–246, 1979.
[22] J. Albert. Algebraic properties of bag data types. In Proc. Int. Conf. on
Very Large Data Bases (VLDB), pages 211–219, 1991.
[24] N. Alon, P. Gibbons, Y. Matias, and M. Szegedy. Tracking join and self-
join sizes in limited storage. J. Comput. Syst. Sci, 35(4):391–432, 2002.
BIBLIOGRAPHY 521
[26] P. Alsberg. Space and time savings through large database compression
and dynamic restructuring. In Proc IEEE 63,8, Aug. 1975.
[31] G. Antoshenkov. Query processing in DEC Rdb: Major issues and future
challenges. IEEE Data Engineering Bulletin, 16:42–52, Dec. 1993.
[33] P.M.G. Apers, A.R. Hevner, and S.B. Yao. Optimization algorithms for
distributed queries. IEEE Trans. on Software Eng., 9(1):57–68, 1983.
[34] P.M.G. Apers, A.R. Hevner, and S.B. Yao. Optimization algorithms for
distributed queries. IEEE Trans. on Software Eng., 9(1):57–68, 1983.
[37] M.M. Astrahan, M.W. Blasgen, D.D. Chamberlin, K.P. Eswaran, J.N.
Gray, P.P. Griffiths, W.F. King, R.A. Lorie, P.R. Mc Jones, J.W. Mehl,
G.R. Putzolu, I.L. Traiger, B.W. Wade, and V. Watson. System R:
relational approach to database management. ACM Transactions on
Database Systems, 1(2):97–137, June 1976.
[63] C. Beeri and Y. Tzaban. SAL: An algebra for semistructured data and
XML. In ACM SIGMOD Workshop on the Web and Databases (WebDB),
1999.
[76] G. Bhargava, P. Goel, and B. Iyer. Efficient processing of outer joins and
aggregate functions. In Proc. IEEE Conference on Data Engineering,
pages 441–449, 1996.
[77] A. Biliris. An efficient database storage structure for large dynamic ob-
jects. In Proc. IEEE Conference on Data Engineering, pages 301–308,
1992.
[78] D. Bitton and D. DeWitt. Duplicate record elimination in large data files.
ACM Trans. on Database Systems, 8(2):255–265, 1983.
[79] J. Blakeley and N. Martin. Join index, materialized view, and hybrid
hash-join: a performance analysis. In Proc. IEEE Conference on Data
Engineering, pages 256–236, 1990.
[83] T. Böhme and E. Rahm. Xmach-1: A benchmark for XML data manage-
ment. In BTW, pages 264–273, 2001.
[84] A. Bolour. Optimal retrieval for small range queries. SIAM J. of Comput.,
10(4):721–741, 1981.
[91] S. Bressan, M. Lee, Y. Li, Z. Lacroix, and U. Nambiar. The XOO7 XML
Management System Benchmark. Technical Report TR21/00, National
University of Singapore, 2001.
[95] P. Buneman, S. Davidson, W. Fan, C. Hara, and W. Tan. Keys for XML.
In WWW Conference, pages 201–210, 2001.
[110] S. Ceri and G. Gottlob. Translating SQL into relational algebra: Op-
timization, semantics and equivalence of SQL queries. IEEE Trans. on
Software Eng., 11(4):324–345, Apr 1985.
BIBLIOGRAPHY 527
[138] P. Cheeseman, B. Kanefsky, and W. Taylor. Where the really hard prob-
lems are. In Int. Joint Conf. on Artificial Intelligence (IJCAI), pages
331–337, 1991.
[147] M. Cherniack and S. Zdonik. Rule languages and internal algebras for
rule-based optimizers. In Proc. of the ACM SIGMOD Conf. on Manage-
ment of Data, pages 401–412, 1996.
[148] T.-Y. Cheung. Estimating block accesses and number of records in file
management. Communications of the ACM, 25(7):484–487, 1982.
[161] S. Cluet and G. Moerkotte. Nested queries in object bases. In Proc. Int.
Workshop on Database Programming Languages, pages 226–242, 1993.
[174] L. Colby. A recursive algebra and query optimization for nested relational
algebra. In Proc. of the ACM SIGMOD Conf. on Management of Data,
pages 273–283, 1989.
[180] D. Cornell and P. Yu. Integration of buffer management and query op-
timization in relational database environments. In Proc. Int. Conf. on
Very Large Data Bases (VLDB), pages 247–255, 1989.
[182] K. Culik, T. Ottmann, and D. Wood. Dense multiway trees. ACM Trans.
on Database Systems, 6(3):486–512, 1981.
[185] D. Das and D. Batory. Praire: A rule specification framework for query
optimizers. In Proc. IEEE Conference on Data Engineering, pages 201–
210, 1995.
[186] C. J. Date. The outer join. In Proc. of the Int. Conf. on Databases,
Cambridge, England, 1983.
[193] D. DeHaan, P.-A. Larson, and J. Zhou. Stacked index views in Microsoft
SQL server. In Proc. of the ACM SIGMOD Conf. on Management of
Data, pages 179–190, 2005.
[196] N. Derrett and M.-C. Shan. Rule-based query optimization in IRIS. Tech-
nical report, Hewlard-Packard Laboratories, 1501 Page Mill Road, Palo
Alto, CA94303, 1990.
[208] P. Dietz. Optimal algorithms for list indexing and subset ranking. In
Workshop on Algorithms and Data Structures (LNCS 382), pages 39–46,
1989.
[228] N. Roussopoulos et al. The maryland ADMS project: Views R Us. IEEE
Data Engineering Bulletin, 18(2), 1995.
[233] C. Farr’e, E. Teniente, and T. Urp’i. The constructive method for query
containment checking. In Inf. Conf. on Database and Expert Systems
Applications (DEXA), pages 583–593, 1999.
[237] L. Fegaras. A new heuristic for optimizing large queries. In DEXA, pages
726–735, 1998.
[238] L. Fegaras and D. Maier. Towards an effective calculus for object query
languages. In Proc. of the ACM SIGMOD Conf. on Management of Data,
pages 47–58, 1995.
[243] T. Fiebig and G. Moerkotte. Algebraic XML construction and its opti-
mization in Natix. World Wide Web Journal, 4(3):167–187, 2002.
[249] F. Frasincar, G.-J. Houben, and C. Pau. XAL: An algebra for XML query
optimization. In Australasian Database Conference (ADC), 2002.
[267] S. Ganguly. On the complexity of finding optimal join order sequence for
star queries without cross products. personal correspondance, 2000.
[271] D. Gardy and L. Nemirovski. Urn models and yao’s formula. In Proc.
Int. Conf. on Database Theory (ICDT), pages 100–112, 1999.
[280] P. Goel and B. Iyer. SLQ query optimization: reordering for a general
class of queries. In Proc. of the ACM SIGMOD Conf. on Management of
Data, pages 47–56, 1996.
[281] D. Goldberg. Genetic Algorithms in Search, Optimization and Machine
Learning. Addison-Wesley, 1989.
[282] J. Goldstein and P. Larson. Optimizing queries using materialized views:
A practical, scalable solution. In Proc. of the ACM SIGMOD Conf. on
Management of Data, pages 331–342, 2001.
[283] J. Goldstein, R. Ramakrishnan, and U. Shaft. Compressing relations and
indexes. In Proc. IEEE Conference on Data Engineering, 1998. to appear.
[284] G. Gorry and S. Morton. A framework for management information sys-
tems. Sloan Management Review, 13(1):55–70, 1971.
[285] G. Gottlob, C. Koch, and R. Pichler. Efficient algorithms for processing
XPath queries. In Proc. Int. Conf. on Very Large Data Bases (VLDB),
pages 95–106, 2002.
[286] G. Gottlob, C. Koch, and R. Pichler. XPath processing in a nutshell.
SIGMOD Record, 2003.
[287] G. Gottlob, C. Koch, and R. Pichler. XPath query evaluation: Improving
time and space efficiency. In Proc. IEEE Conference on Data Engineering,
page to appear, 2003.
[288] M. Gouda and U. Dayal. Optimal semijoin schedules for query processing
in local distributed database systems. In Proc. of the ACM SIGMOD
Conf. on Management of Data, pages 164–175, 1981.
[289] P. Goyal. Coding methods for text string search on compressed databases.
Information Systems, 8(3):231–233, 1983.
[290] G. Graefe. Software modularization with the exodus optimizer generator.
IEEE Database Engineering, 9(4):37–45, 1986.
[291] G. Graefe. Relational division: Four algorithms and their performance.
In Proc. IEEE Conference on Data Engineering, pages 94–101, 1989.
[292] G. Graefe. Encapsulation of parallelism in the Volcano query processing
system. In Proc. of the ACM SIGMOD Conf. on Management of Data,
pages ?–?, 1990.
[293] G. Graefe. Heap-filter merge join: A new algorithm for joining medium-
size inputs. IEEE Trans. on Software Eng., 17(9):979–982, 1991.
[294] G. Graefe. Query evaluation techniques for large databases. ACM Com-
puting Surveys, 25(2), June 1993.
[295] G. Graefe. Query evaluation techniques for large databases. Shortened
version: [294], July 1993.
540 BIBLIOGRAPHY
[297] G. Graefe. The cascades framework for query optimization. IEEE Data
Engineering Bulletin, 18(3):19–29, Sept 1995.
[300] G. Graefe and R. Cole. Dynamic query evaluation plans. In Proc. of the
ACM SIGMOD Conf. on Management of Data, pages ?–?, 1994.
[304] G. Graefe, A. Linville, and L. Shapiro. Sort versus hash revisited. IEEE
Trans. on Knowledge and Data Eng., 6(6):934–944, Dec. 1994.
[307] G. Graefe and K. Ward. Dynamic query evaluation plans. In Proc. of the
ACM SIGMOD Conf. on Management of Data, pages 358–366, 1989.
[310] G. Grahne and A. Thomo. New rewritings and optimizations for regular
path queries. In Proc. Int. Conf. on Database Theory (ICDT), pages
242–258, 2003.
[314] J. Gray and G. Graefe. The five-minute rule ten years later, and other
computer storage rules of thumb. ACM SIGMOD Record, 26(4):63–68,
1997.
[315] J. Gray and F. Putzolu. The 5 minute rule for trading memory for disk
accesses and the 10 byte rule for trading memory for CPU time. In Proc.
of the ACM SIGMOD Conf. on Management of Data, pages 395–398,
1987.
[317] T. Grust. Accelerating XPath location steps. In Proc. of the ACM SIG-
MOD Conf. on Management of Data, pages 109–120, 2002.
[318] T. Grust and M. Van Keulen. Tree awareness for relational database
kernels: Staircase join. In Intelligent Search on XML Data, pages 231–
245, 2003.
[319] T. Grust, M. Van Keulen, and J. Teubner. Staircase join: Teach a rela-
tional dbms to watch its (axis) steps. In Proc. Int. Conf. on Very Large
Data Bases (VLDB), pages 524–525, 2003.
[329] R. Güting, R. Zicari, and D. Choy. An algebra for structured office doc-
uments. ACM Trans. on Information Systems, 7(4):123–157, 1989.
[334] A. Halevy. Answering queries using views: A survey. The VLDB Journal,
10(4):270–294, Dec. 2001.
[344] E.N. Hanson, M. Chaabouni, C.-H. Kim, and Y.-W. Wang. A predi-
cate matching algorithm for database rule systems. In Proc. of the ACM
SIGMOD Conf. on Management of Data, pages 271–?, 1990.
[362] S. Helmer and G. Moerkotte. A study of four index structures for set-
valued attributes of low cardinality. Technical Report 02/99, University
of Mannheim, 1999.
[363] S. Helmer and G. Moerkotte. Compiling away set containment and inter-
section joins. Technical Report 4, University of Mannheim, 2002.
[365] S. Helmer, T. Neumann, and G. Moerkotte. Early grouping gets the skew.
Technical Report 9, University of Mannheim, 2002.
[370] T. Hogg and C. Williams. Solving the really hard problems with coopera-
tive search. In Proc. National Conference on Artificial Intelligence, pages
231–236, 1993.
[375] H.-Y. Hwang and Y.-T. Yu. An analytical method for estimating and
interpreting query time. In Proc. Int. Conf. on Very Large Data Bases
(VLDB), pages 347–358, 1987.
[394] C. Janssen. The visual profiler. perform internet search for this or similar
tools.
BIBLIOGRAPHY 547
[397] M. Jarke and J.Koch. Range nesting: A fast method to evaluate quantified
queries. In Proc. of the ACM SIGMOD Conf. on Management of Data,
pages 196–206, 1983.
[425] J. J. King. Exploring the use of domain knowledge for query processing
efficiency. Technical Report STAN-CS-79-781, Computer Science Depart-
ment, Stanford University, 1979.
[428] M. Klettke, L. Schneider, and A. Heuer. Metrics for XML Document Col-
lections. In EDBT Workshop XML-Based Data Management (XMLDM),
pages 15–28, 2002.
[430] A. Klug. Access paths in the “ABE” statistical query facility. In Proc. of
the ACM SIGMOD Conf. on Management of Data, pages 161–173, 1982.
[435] J. Kollias. An estimate for seek time for batched searching of random or
index sequential structured files. The Computer Journal, 21(2):132–133,
1978.
550 BIBLIOGRAPHY
[439] D. Kossmann. The state of the art in distributed query processing. ACM
Computing Surveys, 32(4):422–469, 2000.
[445] I. Kunen and D. Suciu. A scalable algorithm for query minimization. ask
Dan for more information, year.
[446] S. Kwan and H. Strong. Index path length evaluation for the research
storage system of system r. Technical Report RJ2736, IBM Research
Laboratory, San Jose, 1980.
[449] S.-D. Lang, J. Driscoll, and J. Jou. A unified analysis of batched searching
of sequential and tree-structured files. ACM Trans. on Database Systems,
14(4):604–618, 1989.
BIBLIOGRAPHY 551
[457] P.-Å. Larson and H. Yang. Computing queries from derived relations.
In Proc. Int. Conf. on Very Large Data Bases (VLDB), pages 259–269,
1985.
[458] Y.-N. Law, H. Wang, and C. Zaniolo. Query languages and data models
for database sequences and data streams. In VLDB, pages 492–503, 2004.
[460] C. Lee, C.-S. Shih, and Y.-H. Chen. Optimizing large join queries using
a graph-based approach. IEEE Trans. on Knowledge and Data Eng.,
13(2):298–315, 2001.
[463] M.K. Lee, J.C, Freytag, and G.M. Lohman. Implementing an interpreter
for functional rules in a query optimizer. Research report RJ 6125, IBM,
1988.
552 BIBLIOGRAPHY
[464] T. Lehman and B. Lindsay. The Starburst long field manager. In Proc.
Int. Conf. on Very Large Data Bases (VLDB), pages 375–383, 1989.
[466] A. Lerner and D. Shasha. AQuery: query language for ordered data,
optimization techniques, and experiments. In Proc. Int. Conf. on Very
Large Data Bases (VLDB), pages 345–356, 2003.
[470] M. Levene and G. Loizou. A fully precise null extended nested relational
algebra. Fundamenta Informaticae, 19(3/4):303–342, 1993.
[475] A.Y. Levy and I.S. Mumick. Reasoning with aggregation constraints. In
P. Apers, M. Bouzeghoub, and G. Gardarin, editors, Proc. European Conf.
on Extending Database Technology (EDBT), Lecture Notes in Computer
Science, pages 514–534. Springer, March 1996.
[477] C. Li, K. Chang, I. Ilyas, and S. Song. RankSQL: Query algebra and
optimization for relational top-k queries. In Proc. of the ACM SIGMOD
Conf. on Management of Data, pages 131–142, 2005.
BIBLIOGRAPHY 553
[485] J. W. S. Liu. Algorithms for parsing search queries in systems with in-
verted file organization. ACM Trans. on Database Systems, 1(4):299–316,
1976.
[489] D. Lomet. B-tree page size when caching is considered. ACM SIGMOD
Record, 27(3):28–32, 1998.
[491] H. Lu and K.-L. Tan. On sort-merge algorithms for band joins. IEEE
Trans. on Knowledge and Data Eng., 7(3):508–510, Jun 1995.
[506] R. Marek and E. Rahm. TID hash joins. In Int. Conference on Informa-
tion and Knowledge Management (CIKM), pages 42–49, 1994.
BIBLIOGRAPHY 555
[510] N. May, S. Helmer, and G. Moerkotte. Three Cases for Query Decorre-
lation in XQuery. In Int. XML Database Symp. (XSym), pages 70–84,
2003.
[512] J. McHugh and J. Widom. Query optimization for XML. In Proc. Int.
Conf. on Very Large Data Bases (VLDB), pages 315–326, 1999.
[519] T. Milo and D. Suciu. Index structures for path expressions. In Proc. Int.
Conf. on Database Theory (ICDT), pages 277–295, 1999.
[530] G. Moerkotte and T. Neumann. Analysis of two existing and one new
dynamic programming algorithm for the generation of optimal bushy trees
without cross products. In Proc. Int. Conf. on Very Large Data Bases
(VLDB), pages 930–941, 2006.
[532] C. Mohan, D. Haderle, Y. Wang, and J. Cheng. Single table access using
multiple indexes: Optimization, execution, and concurrency control tech-
niques. In Int. Conf. on Extended Database Technology (EDBT), pages
29–43, 1990.
[551] P. O’Neil and D. Quass. Improved query performance with variant index-
es. In Proc. of the ACM SIGMOD Conf. on Management of Data, pages
38–49, 1997.
[561] G. Ozsoyoglu and H. Wang. A relational calculus with set operators, its
safety and equivalent graphical languages. IEEE Trans. on Software Eng.,
SE-15(9):1038–1052, 1989.
[562] T. Özsu and J. Blakeley. W. Kim (ed.): Modern Database Systems, chap-
ter Query Processing in Object-Oriented Database Systems, pages 146–
174. Addison Wesley, 1995.
BIBLIOGRAPHY 559
[593] N. Polyzotis and M. Garofalakis. Structure and value synopsis for XML
data graphs. In Proc. Int. Conf. on Very Large Data Bases (VLDB),
pages 466–477, 2002.
[600] Y.-J. Qyang. A tight upper bound for the lumped disk seek time for the
SCAN disk scheduling policy. Information Processing Letters, 54:355–358,
1995.
[602] A. Rajaraman, Y. Sagiv, and J.D. Ullman. Answering queries using tem-
plates with binding patterns. In Proc. ACM SIGMOD/SIGACT Conf.
on Princ. of Database Syst. (PODS), PODS, 1995.
[603] Bernhard Mitschang Ralf Rantzau, Leonard D. Shapiro and Quan Wang.
Algorithms and applications for universal quantification in relational
databases. Information Systems, 28(1-2):3–32, 2003.
[612] J. Rao and K. Ross. Reusing invariants: A new strategy for correlated
queries. In Proc. of the ACM SIGMOD Conf. on Management of Data,
pages 37–48, Seattle, WA, 1998.
[613] S. Rao, A. Badia, and D. Van Gucht. Providing better support for a
class of decision support queries. In Proc. of the ACM SIGMOD Conf.
on Management of Data, pages 217–227, 1996.
[615] D. Reiner and A. Rosenthal. Strategy spaces and abstract target machines
for query optimization. Database Engineering, 5(3):56–60, Sept. 1982.
[623] D.J. Rosenkrantz and M.B. Hunt. Processing conjunctive predicates and
queries. In Proc. Int. Conf. on Very Large Data Bases (VLDB), pages
64–74, 1980.
[642] G. Sacco. Index access with a finite buffer. In Proc. Int. Conf. on Very
Large Data Bases (VLDB), pages 301–309, 1887.
[643] G. Sacco and M. Schkolnick. A technique for managing the buffer pool in
a relational system using the hot set model. In Proc. Int. Conf. on Very
Large Data Bases (VLDB), pages 257–262, 1982.
[654] H.-J. Schek and M. Scholl. The relational model with relation-valued
attributes. Information Systems, 11(2):137–147, 1986.
[665] J. W. Schmidt. Some high level language constructs for data of type
relation. ACM Trans. on Database Systems, 2(3):247–261, 1977.
[670] B. Seeger, P.-A. Larson, and R. McFadyen. Reading a set of disk pages.
In Proc. Int. Conf. on Very Large Data Bases (VLDB), pages 592–603,
1993.
[692] G. M. Shaw and S.B. Zdonik. A query algebra for object-oriented databas-
es. Tech. report no. cs-89-19, Department of Computer Science, Brown
University, 1989.
568 BIBLIOGRAPHY
[693] G.M. Shaw and S.B. Zdonik. An object-oriented query algebra. In 2nd Int.
Workshop on Database Programming Languages, pages 111–119, 1989.
[694] G.M. Shaw and S.B. Zdonik. A query algebra for object-oriented databas-
es. In Proc. IEEE Conference on Data Engineering, pages 154–162, 1990.
[696] E. Shekita, H. Young, and K.-L. Tan. Multi-join optimization for sym-
metric multiprocessors. In Proc. Int. Conf. on Very Large Data Bases
(VLDB), pages 479–492, 1993.
[697] P. Shenoy and H. Cello. A disk scheduling framework for next generation
operating systems. In Proc. ACM SIGMETRICS Conf. on Measurement
and Modeling of Computer Systems, pages 44–55, 1998.
[703] A. Shrufi and T. Topaloglou. Query processing for knowledge bases using
join indices. In Int. Conference on Information and Knowledge Manage-
ment (CIKM), 1995.
[706] M. Siegel, E. Sciore, and S. Salveter. A method for automatic rule deriva-
tion to support semantic query optimization. ACM Trans. on Database
Systems, 17(4):53–600, 1992.
BIBLIOGRAPHY 569
[715] R. Sosic, J. Gu, and R. Johnson. The Unison algorithm: Fast evalua-
tion of boolean expressions. ACM Transactions on Design Automation of
Electronic Systems (TODAES), 1:456 – 477, 1996.
[731] M. Stonebraker et al. QUEL as a data type. In Proc. of the ACM SIG-
MOD Conf. on Management of Data, Boston, MA, June 1984.
[734] M. Stonebraker, E. Wong, P. Kreps, and G. Held. The design and imple-
mentation of INGRES. ACM Trans. on Database Systems, 1(3):189–222,
1976.
BIBLIOGRAPHY 571
[735] D. Straube and T. Özsu. Access plan generation for an object algebra.
Technical Report TR 90-20, Department of Computing Science, Univer-
sity of Alberta, June 1990.
[741] D. Suciu. Query decomposition and view maintenance for query languages
for unconstrained data. In Proc. Int. Conf. on Very Large Data Bases
(VLDB), pages 227–238, 1996.
[748] A. Swami and B. Iyer. A polynomial time algorithm for optimizing join
queries. Technical Report RJ 8812, IBM Almaden Research Center, 1992.
[749] A. Swami and B. Iyer. A polynomial time algorithm for optimizing join
queries. In Proc. IEEE Conference on Data Engineering, pages 345–354,
1993.
[750] A. Swami and B. Schiefer. Estimating page fetches for index scans with
finite LRU buffers. In Proc. of the ACM SIGMOD Conf. on Management
of Data, pages 173–184, 1994.
[751] A. Swami and B. Schiefer. On the estimation of join result sizes. In Proc.
of the Int. Conf. on Extending Database Technology (EDBT), pages 287–
300, 1994.
[753] K.-L. Tan and H. Lu. A note on the strategy space of multiway join query
optimization problem in parallel systems. SIGMOD Record, 20(4):81–82,
1991.
[758] J. Teubner, T. Grust, and M. Van Keulen. Bridging the gap between
relational and native XML storage with staircase join. Grundlagen von
Datenbanken, pages 85–89, 2003.
[766] J.D. Ullman. Database and Knowledge Base Systems, volume Volume 1.
Computer Science Press, 1989.
[767] J.D. Ullman. Database and Knowledge Base Systems, volume Volume 2.
Computer Science Press, 1989.
[768] J.D. Ullman. Database and Knowledge Base Systems. Computer Science
Press, 1989.
[769] D. Straube und T. Özsu. Query transformation rules for an object al-
gebra. Technical Report TR 89-23, Department of Computing Science,
University of Alberta, Sept. 1989.
[770] T. Urhan, M. Franklin, and L. Amsaleg. Cost based query scrambling for
initial delays. In Proc. of the ACM SIGMOD Conf. on Management of
Data, pages 130–141, 1998.
[778] B. Vance and D. Maier. Rapid bushy join-order optimization with carte-
sian products. In Proc. of the ACM SIGMOD Conf. on Management of
Data, pages 35–46, 1996.
[785] F. Waas and A. Pellenkoft. Join order selection - good enough is easy. In
BNCOD, pages 51–67, 2000.
[788] W. Wang, H. Jiang, H. Lu, and J. Yu. Containment join size estima-
tion: Models and methods. In Proc. of the ACM SIGMOD Conf. on
Management of Data, pages 145–156, 2003.
[789] W. Wang, H. Jiang, H. Lu, and J. Yu. Bloom histogram: Path selectivity
estimation for xml data with updates. In Proc. Int. Conf. on Very Large
Data Bases (VLDB), pages 240–251, 2004.
[791] S. Waters. File design fallacies. The Computer Journal, 15(1):1–4, 1972.
[803] N. Wilhelm. A general model for the performance of disk systems. Journal
of the ACM, 24(1):14–31, 1977.
[805] C. Williams and T. Hogg. Using deep structure to locate hard problems.
In Proc. National Conference on Artificial Intelligence, pages 472–477,
1992.
576 BIBLIOGRAPHY
[817] M.-C. Wu. Query optimization for selections using bitmaps. In Proc. of
the ACM SIGMOD Conf. on Management of Data, pages 227–238, 1999.
[818] Y. Wu, J. Patel, and H.V. Jagadish. Estimating answer sizes for XML
queries. In Proc. of the Int. Conf. on Extending Database Technology
(EDBT), pages 590–608, 2002.
[819] Y. Wu, J. Patel, and H.V. Jagadish. Estimating answer sizes for XML
queries. Information Systems, 28(1-2):33–59, 2003.
[823] W. Yan and P.-A. Larson. Performing group-by before join. Technical
Report CS 93-46, Dept. of Computer Science, University of Waterloo,
Canada, 1993.
[824] W. Yan and P.-A. Larson. Performing group-by before join. In Proc.
IEEE Conference on Data Engineering, pages 89–100, 1994.
[825] W. Yan and P.-A. Larson. Eager aggregation and lazy aggregation. In
Proc. Int. Conf. on Very Large Data Bases (VLDB), pages 345–357, 1995.
[826] W. Yan and P.-A. Larson. Interchanging the order of grouping and join.
Technical Report CS 95-09, Dept. of Computer Science, University of
Waterloo, Canada, 1995.
[827] H. Yang and P.-A. Larson. Query transformation for PSJ-queries. In Proc.
Int. Conf. on Very Large Data Bases (VLDB), pages 245–254, 1987.
[831] B. Yao and T. Özsu. XBench – A Family of Benchmarks for XML DBMSs.
Technical Report CS-2002-39, University of Waterloo, 2002.
[834] S. B. Yao. An attribute based model for database access cost analysis.
ACM Trans. on Database Systems, 2(1):45–67, 1977.
[837] S.B. Yao, A.R. Hevner, and H. Young-Myers. Analysis of database sys-
tem architectures using benchmarks. IEEE Trans. on Software Eng.,
SE-13(6):709–725, 1987.
[838] Y. Yoo and S. Lafortune. An intelligent search method for query optimiza-
tion by semijoins. IEEE Trans. on Knowledge and Data Eng., 1(2):226–
237, June 1989.
[839] M. Yoshikawa, T. Amagasa, T. Shimura, and S. Uemura. Xrel: A path-
based approach to storage and retrieval of XML documents using relation-
al databases. ACM Transactions on Internet Technology, 1(1):110–141,
June 2001.
[840] K. Youssefi and E. Wong. Query processing in a relational database man-
agement system. In Proc. Int. Conf. on Very Large Data Bases (VLDB),
pages 409–417, 1979.
[841] L. Yu and S. L. Osborn. An evaluation framework for algebraic object-
oriented query models. In Proc. IEEE Conference on Data Engineering,
1991.
[842] J. Zahorjan, B. Bell, and K. Sevcik. Estimating block transfers when
record access probabilities are non-uniform. Information Processing Let-
ters, 16(5):249–252, 1983.
[843] B. T. Vander Zander, H. M. Taylor, and D. Bitton. Estimating block
accesses when attributes are correlated. In Proc. Int. Conf. on Very Large
Data Bases (VLDB), pages 119–127, 1986.
[844] S. Zdonik and G. Mitchell. ENCORE: An object-oriented approach
to database modelling and querying. IEEE Data Engineering Bulletin,
14(2):53–57, June 1991.
[845] N. Zhang, V. Kacholia, and T. Özsu. A succinct physical storage scheme
for efficient evaluation of path queries in XML. In Proc. IEEE Conference
on Data Engineering, pages 54–65, 2004.
[846] N. Zhang and T. Özsu. Optimizing correlated path expressions in XML
languages. Technical Report CS-2002-36, University of Waterloo, 2002.
[847] Y. Zhao, P. Deshpande, and J. Naughton. An array-based algorithm for
simultaneous multidimensional aggregates. In Proc. of the ACM SIGMOD
Conf. on Management of Data, pages 159–170, 1997.
[848] Y. Zhao, P. Deshpande, J. Naughton, and A. Shukla. Simultaneous opti-
mization and evaluation of multiple dimensional queries. In Proc. of the
ACM SIGMOD Conf. on Management of Data, pages 271–282, 1998.
[849] Y. Zhuge, H. Garcia-Molina, J. Hammer, and J. Widom. View mainte-
nance in a warehouse environment. In Proc. of the ACM SIGMOD Conf.
on Management of Data, 1995.
Appendix E
ToDo
• [787]
• [86]
• Bypass Plans
• magic set and semi join reducers [70, 72, 71, 149, 288, 538, 536, 538, 537,
680, 725, 838]
• join indexes and clustering tuples of different relations with 1:n relation-
ship [197, 345, 772, 773, 703]
• Prefetching [793]
579
580 APPENDIX E. TODO
• compression [26, 48, 141, 177, 222, 221, 283, 289] [547, 614, 635, 684, 685,
744, 798, 809]
• semantic QO SQO: [1, 73, 146, 279, 311, 425, 426, 441, 447] [548, 556,
557, 579, 698, 706, 708, 821] [475]
• join+buffer: [806]
• benchmark(ing): Gray Book: [312]; papers: [83, 91, 566, 641, 664, 837,
831, 832]
• BXP: [90, 223, 265, 322, 341, 376, 420, 591, 618, 705, 712, 715, 419]
BXP complexity: [68] BXP var infl: [406]
• joins: [596]
• fragmentation: [645]
581
• indexing+caching: [674]
• dist db: [33, 34, 82, 184, 829] Donald’s state of the art: [439]
• [121, 122]
• nested: [41]
• dupelim: [78]
• early aggregation
• classics: [336]
• Hwang/Yu: [375]
• Kambayashi: [408]
• determine optimal page access sequence and buffer size to access pairs
(x,y) of pages where join partners of one relation lie on x and of the
other on y (Fotouhi, Pramanik [248], Merret, Kambayashi, Yasuura [516],
Omiecinski [549], Pramanik, Ittner [596], Chan, Ooi [117])
• Sigmod05:
• LOCI: [569]
• PostgresExperience: [786]