Relational Query Optimization: Warih Maharani, ST.,MT
Relational Query Optimization: Warih Maharani, ST.,MT
1
What is Query Optimization and
Why
v Whereas declarative query languages (including
SQL) offer a great comfort for users, they place a
considerable burden on a Query Processor
v A Query Processor is responsible to produce an
execution plan that will guarantee an acceptable
response time
v Choosing a query execution plan is called Query
Optimization and it mainly means making decisions
about data access methods
v Query Optimization strongly relies on File
Organization techniques
2
Overview of Query Optimization
v Plan: Tree of relational op, with choice of alg for each op.
v Two main issues:
– For a given query, what plans are considered?
u Algorithm to search plan space for cheapest (estimated) plan.
– How is the cost of a plan estimated?
v Ideally: Want to find best plan. Practically: Avoid
worst plans!
v We will study the System R approach.
3
Highlights of System R Optimizer
v Impact:
– Most widely used currently; works well for < 10 joins.
v Cost estimation: Approximate art at best.
– Statistics, maintained in system catalogs, used to estimate
cost of operations and result sizes.
– Considers combination of CPU and I/O costs.
v Plan Space: Too large, must be pruned.
4
Basic Steps in Query Processing
1. Parsing and translation
2. Optimization
3. Evaluation
5
Basic Steps in Query Processing
(Cont.)
6
Basic Steps in Query Processing :
Optimization
v A relational algebra expression may have many equivalent
expressions
– E.g., σbalance<2500(∏balance(account)) is equivalent to
∏balance(σbalance<2500(account))
v Each relational algebra operation can be evaluated using one of
several different algorithms
– Correspondingly, a relational-algebra expression can be
evaluated in many ways.
v Annotated expression specifying detailed evaluation strategy is
called an evaluation-plan.
– E.g., can use an index on balance to find accounts with balance <
2500,
– or can perform complete relation scan and discard accounts with
balance ≥ 2500
7
Basic Steps: Optimization (Cont.)
Query Optimizer
Schema Statistics
Query Executor
9
Measures of Query Cost
v Cost is generally measured as total elapsed time for
answering query
– Many factors contribute to time cost
u disk accesses, CPU, or even network communication
10
Measures of Query Cost (Cont.)
v For simplicity we just use the number of block transfers from disk and
the number of seeks as the cost measures
– tT – time to transfer one block
– tS – time for one seek
– Cost for b block transfers plus S seeks
b * tT + S * tS
v We ignore CPU costs for simplicity
– Real systems do take CPU cost into account
v We do not include cost to writing output to disk in our cost
formulae
v Several algorithms can reduce disk IO by using extra buffer space
– Amount of real memory available to buffer depends on other
concurrent queries and OS processes, known only during execution
u We often use worst case estimates, assuming only the minimum
amount of memory needed for the operation is available
v Required data may be buffer resident already, avoiding disk I/O
– But hard to take into account for cost estimation
11
Selection Operation
v File scan – search algorithms that locate and retrieve
records that fulfill a selection condition.
v Algorithm A1 (linear search). Scan each file block and
test all records to see whether they satisfy the
selection condition.
– Cost estimate = br block transfers + 1 seek
u br denotes number of blocks containing records from
relation r
– If selection is on a key attribute, can stop on finding record
u cost = (br /2) block transfers + 1 seek
u availability of indices
18
RA Tree: sname
Motivating Example
bid=100 rating > 5
SELECT S.sname
FROM Reserves R, Sailors S
WHERE R.sid=S.sid AND sid=sid
R.bid=100 AND S.rating>5
Reserves Sailors
v Cost: 1000 + 100*1000*500 I/Os.
(On-the-fly)
v By no means the worst plan! Plan: sname
v Misses several opportunities:
selections could have been bid=100 rating > 5 (On-the-fly)
`pushed’ earlier, no use is made
of any available indexes, etc.
(Simple Nested Loops)
v Goal of optimization: To find more sid=sid
efficient plans that compute the
same answer.
Reserves Sailors
19
(On-the-fly)
sname
Alternative Plans 1
(No Indexes) sid=sid
(Sort-Merge Join)
(Scan; (Scan;
write to bid=100 rating > 5 write to
temp T1) temp T2)
v Main difference: push selects.
Reserves Sailors
v With 5 buffers, cost of plan:
– Scan Reserves (1000) + write temp T1 (10 pages, if we have 100 boats,
uniform distribution).
– Scan Sailors (500) + write temp T2 (250 pages, if we have 10 ratings).
– Sort T1 (2*2*10), sort T2 (2*3*250), merge (10+250)
– Total: 3560 page I/Os.
v If we used BNL join, join cost = 10+4*250, total cost = 2770.
v If we `push’ projections, T1 has only sid, T2 only sid and sname:
– T1 fits in 3 pages, cost of BNL drops to under 250 pages, total < 2000.
20
(On-the-fly)
22
Summary
v Query optimization is an important task in a
relational DBMS.
v Must understand optimization in order to understand
the performance impact of a given database design
(relations, indexes) on a workload (set of queries).
v Two parts to optimizing a query:
– Consider a set of alternative plans.
u Must prune search space; typically, left-deep plans only.
– Must estimate cost of each plan that is considered.
u Must estimate size of result and cost for each plan node.
u Key issues: Statistics, indexes, operator implementations.
23
Query Blocks: Units of Optimization
SELECT S.sname
v An SQL query is parsed into a FROM Sailors S
collection of query blocks, and these WHERE S.age IN
are optimized one block at a time. (SELECT MAX (S2.age)
v Nested blocks are usually treated as FROM Sailors S2
calls to a subroutine, made once per GROUP BY S2.rating)
outer tuple. (This is an over-
simplification, but serves for now.) Outer block Nested block
v For each block, the plans considered are:
– All available access methods, for each reln in FROM clause.
– All left-deep join trees (i.e., all ways to join the relations one-
at-a-time, with the inner reln in the FROM clause, considering
all reln permutations and join methods.)
24
Cost Estimation
v For each plan considered, must estimate cost:
– Must estimate cost of each operation in plan tree.
u Depends on input cardinalities.
u We’ve already discussed how to estimate the cost of operations
(sequential scan, index scan, joins, etc.)
– Must estimate size of result for each operation in tree!
u Use information about the input relations.
u For selections and joins, assume independence of predicates.
v We’ll discuss the System R cost estimation approach.
– Very inexact, but works ok in practice.
– More sophisticated techniques known now.
25
Statistics and Catalogs
v 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.
v Catalogs updated periodically.
– Updating whenever data changes is too expensive; lots of
approximation anyway, so slight inconsistency ok.
v More detailed information (e.g., histograms of the
values in some field) are sometimes stored.
26
Size Estimation and Reduction Factors
SELECT attribute list
FROM relation list
v Consider a query block: WHERE term1 AND ... AND termk
29
Enumeration of Alternative Plans
v There are two main cases:
– Single-relation plans
– Multiple-relation plans
v For queries over a single relation, queries consist of a
combination of selects, projects, and aggregate ops:
– Each available access path (file scan / index) 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 pipelined into the aggregate computation).
30
Cost Estimates for Single-Relation Plans
D D
C C
A B C D A B B
A
33
Enumeration of Left-Deep Plans
v Left-deep plans differ only in the order of relations,
the access method for each relation, and the join
method for each join.
v 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.)
v For each subset of relations, retain only:
– Cheapest plan overall, plus
– Cheapest plan for each interesting order of the tuples.
34
Enumeration of Plans (Contd.)
v ORDER BY, GROUP BY, aggregates etc. handled as a
final step, using either an `interestingly ordered’
plan or an addional sorting operator.
v 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.
v In spite of pruning plan space, this approach is still
exponential in the # of tables.
35
Sailors:
sname
B+ tree on rating
Example Hash on sid
Reserves:
B+ tree on bid
v Pass1: sid=sid
– Sailors: B+ tree matches rating>5,
and is probably cheapest. However,
bid=100 rating > 5
if this selection is expected to
retrieve a lot of tuples, and index is
unclustered, file scan may be cheaper. Reserves Sailors
u Still, B+ tree plan kept (because tuples are in rating order).
– Reserves: B+ tree on bid matches bid=500; cheapest.
v Pass 2:
– We consider each plan retained from Pass 1 as the outer,
and consider how to join it with the (only) other relation.
u e.g., Reserves as outer: Hash index can be used to get Sailors tuples
that satisfy sid = outer tuple’s sid value.
36
SELECT S.sname
FROM Sailors S
Nested Queries WHERE EXISTS
(SELECT *
FROM Reserves R
v Nested block is optimized WHERE R.bid=103
independently, with the outer AND R.sid=S.sid)
tuple considered as providing a
selection condition. Nested block to optimize:
SELECT *
v Outer block is optimized with
FROM Reserves R
the cost of `calling’ nested block
WHERE R.bid=103
computation taken into account.
AND S.sid= outer value
v Implicit ordering of these blocks
means that some good strategies Equivalent non-nested query:
are not considered. The non- SELECT S.sname
nested version of the query is FROM Sailors S, Reserves R
typically optimized better. WHERE S.sid=R.sid
AND R.bid=103
37
Summary
v Query optimization is an important task in a
relational DBMS.
v Must understand optimization in order to understand
the performance impact of a given database design
(relations, indexes) on a workload (set of queries).
v Two parts to optimizing a query:
– Consider a set of alternative plans.
u Must prune search space; typically, left-deep plans only.
– Must estimate cost of each plan that is considered.
u Must estimate size of result and cost for each plan node.
u Key issues: Statistics, indexes, operator implementations.
38
Summary (Contd.)
v Single-relation queries:
– All access paths considered, cheapest is chosen.
– Issues: Selections that match index, whether index key has
all needed fields and/or provides tuples in a desired order.
v Multiple-relation queries:
– All single-relation plans are first enumerated.
u Selections/projections considered as early as possible.