Lecture 5-
Query
Optimization
By Dr. Shaheera Rashwan
Query Optimization
Goal
: Declarative SQL query Imperative query
execution plan:
snam
e
SELECT S.sname
bid=100 rating >
FROM Reserves R, 5
Sailors S
WHERE R.sid=S.sid AND (Simple Nested
R.bid=100 AND sid=si Loops)
d
S.rating>5
Reserves Sailors
2
Ideally: Want to find best plan. Practically: Avoid worst plans!
Query Optimization Issues
• Query rewriting:
– transformations from one SQL query to another
one using semantic properties.
• Selecting query execution plan:
– done on single query blocks (I.e., S-P-J blocks)
– main step: join enumeration
• Cost estimation:
– to compare between plans, we need to estimate
their cost using statistics on the database.
3
Query Rewriting: Predicate
Pushdown
snam
e
snam
rating > e
bid=100
5
sid=si
d
sid=sid (Scan; write to temp T1)
bid=100 rating >
5 (Scan; write
to Temp T2)
Reserves Sailors Reserves Sailors
The earlier we process selections, less tuples we need to manipulate
higher up in the tree (but may cause us to loose an important
ordering
4
of the tuples.
Query Rewrites: Predicate
Pushdown (more complicated)
Select bid, Max(age) Select bid, Max(age)
From Reserves R, Sailors From Reserves R, Sailors
S S
Where R.sid=S.sid Where R.sid=S.sid and
GroupBy bid S.age > 40
Having Max(age) > 40 GroupBy bid
• Advantage: the size of the join will beHaving Max(age) > 40
smaller.
• Requires transformation rules specific to the
grouping/aggregation
operators.
• Won’t work if we replace Max by Min. 5
Query Rewrite:
Predicate Movearound
Sailing wizz dates: when did the youngest of each sailor level rent
boats?
Select sid, date
From V1, V2
Where V1.rating = V2.rating and
V1.age = V2.age
Create View V1 AS Create View V2 AS
Select rating, Select sid, rating, age, date
Min(age) From Sailors S, Reserves
From Sailors S R
Where S.age < 20 Where R.sid=S.sid 6
GroupBy bid
Query Rewrite:
Predicate Movearound
Sailing wizz dates: when did the youngest of each sailor level rent
boats?
Select sid, date
First, move From V1, V2
predicates up the Where V1.rating = V2.rating and
tree. V1.age = V2.age, age < 20
Create View V1 AS Create View V2 AS
Select rating, Select sid, rating, age, date
Min(age) From Sailors S, Reserves
From Sailors S R
Where S.age < 20 Where R.sid=S.sid 7
GroupBy bid
Query Rewrite:
Predicate Movearound
Sailing wizz dates: when did the youngest of each sailor level rent
boats?
Select sid, date
First, move From V1, V2
predicates up the Where V1.rating = V2.rating and
tree. V1.age = V2.age, and age < 20
Then, move them
down.
Create View V1 AS Create View V2 AS
Select rating, Select sid, rating, age, date
Min(age) From Sailors S, Reserves
From Sailors S R
Where S.age < 20 Where R.sid=S.sid, and 8
GroupBy bid S.age < 20.
Query Rewrite Summary
• The optimizer can use any semantically
correct rule to transform one query to
another.
• Rules try to:
– move constraints between blocks (because each
will be optimized separately)
– Unnest blocks
• Especially important in decision support
applications where queries are very
complex. 9
Enumeration of Alternative Plans
• Task: create a query execution plan for a single Select-
project-join block (well, and aggregates).
• Main principle: some sort of search through the set of
plans.
– Assume some cost estimation model; more later.
• Single-relation block case (only select, project,
aggregation):
– Each available access path is considered, and the one
with the least estimated cost is chosen.
– The different operations are essentially carried out
together (e.g., if an index is used for a selection, projection is
done for each retrieved tuple, and the resulting tuples are
10
pipelined into the aggregate computation).
Queries Over Multiple Relations
• In principle, we need to consider all possible join
orderings:
D D
C C
A B C D A B B
A
• As the number of joins increases, the number of alternative
plans grows rapidly; we need to restrict the search space.
• System-R: consider only left-deep join trees.
– Left-deep trees allow us to generate all fully pipelined
plans:Intermediate results not written to temporary files.
• Not all left-deep trees are fully pipelined (e.g., SM join).11
Enumeration of Left-Deep Plans
• Enumerated using N passes (if N relations joined):
– Pass 1: Find best 1-relation plan for each relation.
– Pass 2: Find best way to join result of each 1-relation
plan (as outer) to another relation. (All 2-relation
plans.)
– Pass N: Find best way to join result of a (N-1)-relation
plan (as outer) to the N’th relation. (All N-relation
plans.)
• For each subset of relations, retain only:
– Cheapest plan overall, plus
– Cheapest plan for each interesting order of the tuples.
12
Enumeration of Plans (Contd.)
• ORDER BY, GROUP BY, aggregates etc. handled as a
final step, using either an `interestingly ordered’ plan or
an additional sorting operator.
• An N-1 way plan is not combined with an additional
relation unless there is a join condition between them,
unless all predicates in WHERE have been used up.
– i.e., avoid Cartesian products if possible.
• In spite of pruning plan space, this approach is still
exponential in the # of tables.
• If we want to consider all (bushy) trees, we need only a
slight modification to the algorithm. 13
Sailors:
B+ tree on
rating Example snam
e
Hash on sid
Reserves:
• Pass 1: on
B+ tree sid=si
bid
– Sailors: B+ tree matches rating>5, and is d
probably cheapest. However, if this selection is bid=100 rating > 5
expected to retrieve a lot of tuples, and index is
unclustered, file scan may be cheaper.
• Still, B+ tree plan kept (tuples are in rating order). Reserves Sailors
– Reserves: B+ tree on bid matches bid=100;
cheapest.
• Pass 2: We consider each plan retained from Pass 1
as the outer, and consider how to join it with the
(only) other relation.
● e.g., Reserves as outer: Hash index can be used to
get Sailors tuples that satisfy sid = outer tuple’s sid 14
value.
SELECT S.sname
Nested Queries FROM Sailors S
WHERE EXISTS
(SELECT *
FROM Reserves
• Nested block is optimized R
independently, with the outer tuple WHERE
considered as providing a selection R.bid=103
condition. Nested block to optimize:
AND
SELECT *
• Outer block is optimized with the R.sid=S.sid)
FROM Reserves R
cost of `calling’ nested block
WHERE R.bid=103
computation taken into account.
AND S.sid= outer
• Implicit ordering of these blocks value
means that some good strategies are Equivalent non-nested
query:
not considered. The non-nested
SELECT S.sname
version of the query is typically
FROM Sailors S,
optimized better.
Reserves R 15
WHERE S.sid=R.sid
Cost Estimation
• For each plan considered, must estimate cost:
– Must estimate cost of each operation in plan tree.
• Depends on input cardinalities.
– Must estimate size of result for each operation in tree!
• Use information about the input relations.
• For selections and joins, assume independence of predicates.
• We’ll discuss the System R cost estimation
approach.
– Very inexact, but works ok in practice.
– More sophisticated techniques known now.
16
Statistics and Catalogs
• Need information about the relations and indexes
involved. Catalogs typically contain at least:
– # tuples (NTuples) and # pages (NPages) for each relation.
– # distinct key values (NKeys) and NPages for each index.
– Index height, low/high key values (Low/High) for each tree
index.
• Catalogs updated periodically.
– Updating whenever data changes is too expensive; lots of
approximation anyway, so slight inconsistency ok.
• More detailed information (e.g., histograms of the values
in some field) are sometimes stored.
17
Size Estimation and Reduction
Factors
SELECT attribute list
FROM relation list
• Consider a query block: WHERE term1 AND ... AND
• Maximum # tuples in resulttermkis the product of the
cardinalities of relations in the FROM clause.
• Reduction factor (RF) associated with each term reflects
the impact of the term in reducing result size. Result
cardinality = Max # tuples * product of all RF’s.
– Implicit assumption that terms are independent!
– Term col=value has RF 1/NKeys(I), given index I on col
– Term col1=col2 has RF 1/MAX(NKeys(I1), NKeys(I2))
– Term col>value has RF (High(I)-value)/(High(I)-Low(I)) 18
Any Questions?
19