Professional Documents
Culture Documents
2 3 PDF
2 3 PDF
1
Query Processing + Optimization
• Operator Evaluation Strategies
Selection
Join
• Query Optimization
• Query Tuning
2
Architectural Context
Application Programmers
DBA Staff Casual Users Application Parametric
Programs
Users
DDL Privileged Interactive Precompiler
Statements Commands Query
Host Language
Compiler
Query Canned
Compiler Transactions
Query Execution DDL
DDL Plan Statements
Compiler
Run-time
Evaluator
Transaction and
DBMS Data Manager
Data Dictionary
Data Files
3
Evaluation of SQL Statement
• The query is evaluated in a different order.
The tables in the from clause are combined using Cartesian
products.
The where predicate is then applied.
The resulting tuples are grouped according to the group by
clause.
The having predicate is applied to each group, possibly
eliminating some groups.
The aggregates are applied to each remaining group.
The select clause is performed last.
4
Overview of Query Processing
Query in high-level language
1. Parsing and translation
Scanning, Parsing, and
2. Optimization
Semantic Analysis
3. Evaluation
Intermediate form of query
4. Execution
Query Optimization
Execution Plan
Result of query
5
Selection Queries
• Primary key, point
σFilmID = 2 (Film)
• Point
σTitle = ‘Terminator’ (Film)
• Range
σ1 < RentalPrice < 4 (Film)
• Conjunction
σType = ‘M’ ∧ Distributor = ‘MGM’ (Film)
• Disjunction
σPubDate < 2004 ∨ Distributor = ‘MGM’ (Film)
6
Selection Strategies
• Linear search
Expensive, but always applicable.
• Binary search
Applicable only when the file is appropriately ordered.
• Hash index search
Single record retrieval; does not work for range queries.
Retrieval of multiple records.
• Clustering index search
Multiple records for each index item.
Implemented with single pointer to block with first
associated record.
• Secondary index search
Implemented with dense pointers, each to a single record.
7
Selection Strategies for Conjunctive Queries
• Use any available indices for attributes involved in
simple conditions.
If several are available, use the most selective index. Then
check each record with respect to the remaining conditions.
• Attempt to use composite indices.
This can be very efficient.
• Do intersection of record pointers.
If several indices with record pointers are applicable to the
selection predicate, retrieve and intersect the pointers. Then
retrieve (and check) the qualifying records.
9
Nested Loop Join and Index-Based Join
• Nested loop join
Exhaustive comparison (i.e., brute force approach)
The ordering (outer/inner) of files and allocation of buffer
space is important.
• Index-based join
Requires (at least) one index on a join attribute.
At times, a temporary index is created for the purpose of a
join.
The ordering (outer/inner) of files is important.
10
Nested Loop
• Basically, for each block of the outer table (r), scan the
entire inner table (s).
Requires quadratic time, O(n2)
Improved when buffer is used.
Outer Main Memory
Buffer
r
spill Output
Scan Inner when full
ss
11
Example of Nested-Loop Join
Customer nC.CustomerID = CO.EmpId CheckedOut
• Parameters
rCheckedOut = 40.000 rCustomer = 200
bCheckedOut = 2.000 bCustomer = 10
nB = 6 (size of main memory buffer)
• Algorithm:
repeat: read (nB - 2) blocks from outer relation
repeat: read 1 block from inner relation
compare tuples
• Cost: bouter + ( ⎡bouter/ (nB -2)⎤ ) × binner
• CheckedOut as outer: 2.000 + ⎡2.000/4⎤ × 10 = 7.000
• Customer as outer: 10 + ⎡10/4⎤ × 2.000 = 6.010
12
Index-based Join
• Requires (at least) one index on a join attribute
A temporary index can be created
if joins
s
Output
spill
when full
Main Memory
13
Example of Index-Based Join
Customer nC.CustomerID = CO.EmpId CheckedOut
• Cost: bouter + router × cost use of index
• Assume that the video store has 10 employees.
There are 10 distinct EmpIDs in CheckedOut.
• Assume 1-level index on CustomerID of Customer.
• Iterate through all 40.000 tuples in CheckedOut (outer
rel.)
2.000 disk reads (bCheckedOut) to scan CheckedOut
For each CheckedOut tuple, search for matching Customer
tuples using index.
0 disk reads for index (in main memory) + 1 disk read for actual data
block
• Cost: 2.000 + 40.000 × (0 + 1) = 42.000
14
Sort-Merge Join
• Sort each relation using multiway merge-sort
• Perform merge-join
Scan
sorted
Main Memory
r1 r
•••
unsorted r2 sorted ••• Match
r
••• r •••
Scan •••
rn
sorted
s
Output
15
External or Disk-based Sorting
• Relation on disk often too large to fit into memory
• Sort in pieces, called runs
Main Memory r1
Buffer (N blocks)
Scan Output r2
when sorted
r •••
rM div N
Initial runs
5 121732 1 3 8 14 23263031 2 112529 6 7 1516 4 9 2228 10182021 13192427
First merge
1 3 5 8 1214172326303132 2 4 6 7 9 11151622252829 1013181920202427
Second merge
1 2 3 4 5 6 7 8 9 1011121314151617181920212223242526272829303132
19
Hash Join
• Hash each relation on the join attributes
• Join corresponding buckets from each relation
Buckets from r Buckets from s
r1 r1 n s1 r1 n s1
r2 n s2
Relation
r2 r2 n s2
r
••• ••• •••
rn rn n sn rn n sn
1
2
Relation INPUT
r or s hash 2
...
function
h
nB -1
nB -1
Disk nB main memory buffers Disk
21
Joining Phase
• Joining (or probing) phase: nh iterations where ri n si.
Load ri into memory and build an in-memory hash index on it using the
join attribute. (h2 needed, ri called build input)
Load si, for each tuple in it, join it with ri using h2. (si called probe input)
I/O cost: br + bs + 4 × nh (each partition may have a partially filled block)
One write and one read for each partially filled block
Relation INPUT 2
r or s hash
...
function
nB
h
nB -1
26
Query Optimization
• Aim: Transform query into faster, equivalent query
equivalent query 1
equivalent query 2 faster
query
... query
equivalent query n
×
× Note the use of
F
Cartesian product!
CU CH
28
Apply Selections Early
πName
σ F.FilmId = CH.FilmID
×
× F
σStreet = ‘Elm’ CH
CU
29
Apply More Restrictive Selections Early
πName
σ CU.CustomerID = CH.CustomerID
× CU
σTitle = ‘Terminator’ CH
F
30
Form Joins
πName
n CU.CustomerID = CH.CustomerID
σTitle = ‘Terminator’ CH CU
31
Apply Projections Early
πName
n CU.CustomerID = CH.CustomerID
σTitle = ‘Terminator’ CU
CH
F
32
Some Transformation Rules
• Cascade of σ: σc1 ∧ c2 ∧ ... ∧ cn(R) = σc1(σc2(...(σcn(R))...))
• Commutativity of σ: σc1(σc2(R)) = σc2(σc1(R))
• Commuting σ with π: πL(σc (R)) = σc(πL(R))
Only if c involves solely attributes in L.
• Commuting σ with n : σc (R n S) = σc (R) n S
Only if c involves solely attributes in R.
• Commuting σ with set operations: σc(R θ S) = σc(R) θ σc(S)
Where θ is one of ∪, ∩, or -.
• Commutativity of ∪, ∩, and n: R θ S = S θ R
Where θ is one of ∪, ∩ and n.
• Associativity of n, ∪, ∩: (R θ S) θ T = R θ (S θ T)
33
Transformation Algorithm Outline
• Transform a query represented in relational algebra to
an equivalent one (generates the same result.)
34
Heuristic Query Optimization Summary
• Heuristic optimization transforms the query-tree by
using a set of rules (Heuristics) that typically (but not
in all cases) improve execution performance.
Perform selection early (reduces the number of tuples)
Perform projection early (reduces the number of attributes)
Perform most restrictive selection and join operations (i.e.
with smallest result size) before other similar operations.
36
Relevant Statistics
• Per relation
Tuple size
Number of tuples (records): r
Load factor (fill factor), percentage of space used in each
block
Blocking factor (number of records per block): bfr
Relation size in blocks: b
Relation organization
Number of overflow blocks
37
Relevant Statistics, cont.
• Per attribute
Attribute size and type
Number of distinct values for attribute A: dA
Probability distribution over the values
Representation, e.g., compressed
Selection cardinality specifies the average size of
σA = a(R) for an arbitrary value a. (sA)
Could be maintained for the “average” attribute value, or on a per-
value basis, as a histogram.
38
Relevant Statistics, cont.
• Per Index
Base relation
Indexed attribute(s)
Organization, e.g., B+-Tree, Hash, ISAM
Clustering index?
On key attribute(s)?
Sparse or dense?
Number of levels (if appropriate)
Number of first-level index blocks: b1
• General
Available main memory blocks: N
39
Cost Estimation Example
πName
4
⋈CU.CustomerID = R.CustomerID
σTitle = ‘Terminator’ CU
R
F
40
Operation 1: σ followed by a π
• Statistics
Relation statistics: rFilm= 5,000 bFilm= 50
Attribute statistics: sTitle= 1
Index statistics: Secondary Hash Index on Title.
• Cost: C2 = 1 +1 + 8 = 10
42
Operation 3: σ followed by a π
• Statistics
Relation statistics: rCustomer= 200 bCustomer= 10
Attribute statistics:sStreet= 10
• Cost: C3 = 10
43
Operation 4: n followed by a π
• Operation: Main memory join on relations in main
memory.
• Cost: C4 = 0
4
• Total cost: C = ∑Ci = 2 + 10 + 10 + 0 = 22
i =1
44
Comparison
• Heuristic query optimization
Sequence of single query plans
Each plan is (presumably) more efficient than the previous.
Search is linear.
• Cost-based query optimization
Many query plans generated.
The cost of each is estimated, with the most efficient chosen.
Search is multi-dimensional, usually using dynamic
programming. Still can be very expensive.
• Hybrid way
Systems may use heuristics to reduce the number of choices
that must be made in a cost-based fashion.
45
Query Processing + Optimization
• Operator Evaluation Strategies
• Query Optimization
• Query Tuning
46
Query Tuning
• Query optimization is a very complex task.
Combinatorial explosion.
The task is to find one good query evaluation plan, not the
best one.
• No optimizer optimizes all queries adequately.
• There is a need for query tuning.
All optimizers differ in their ability to optimize queries,
making it difficult to prescribe principles.
• Having to tune queries is a fact of life.
Query tuning has a localized effect and is thus relatively
attractive.
It is a time-consuming and specialized task.
It makes the queries harder to understand.
However, it is often a necessity.
This is not likely to change any time soon.
47
Query Tuning Issues
• Need too many disk accesses (eg. Scan for a point
query)?
• Need unnecessary computation?
Redundant DISTINT
SELECT DISTINCT cpr#
FROM Employee
WHERE dept = ‘computer’
• Relevant indexes are not used? (Next slide)
• Unnecessary nested subqueries?
• ……
48
Join on Clustering Index, and Integer
SELECT Employee.cpr#
FROM Employee, Student
WHERE Employee.name = Student.name
-->
SELECT Employee.cpr#
FROM Employee, Student
WHERE Employee.cpr# = Student.cpr#
49
Nested Queries
• Nested block is optimized independently, with the outer tuple
considered as providing a selection condition.
• Outer block is optimized with the cost of ‘calling’ nested block
computation taken into account.
• Implicit ordering of these blocks means that some good
strategies are not considered. The non-nested version of the
query is typically optimized better.
Nested block to optimize:
SELECT S.sname SELECT *
FROM Sailors S FROM Reserves R
WHERE EXISTS WHERE R.bid=103
(SELECT * AND S.sid= outer value
FROM Reserves R
Equivalent non-nested query:
WHERE R.bid=103
SELECT S.sname
AND R.sid=S.sid)
FROM Sailors S, Reserves R
WHERE S.sid=R.sid
AND R.bid=103 50
Unnesting Nested Queries
• Uncorrelated sub-queries with aggregates.
Most systems would compute the average only once.
SELECT ssn
FROM emp
WHERE salary > (SELECT AVG(salary) FROM emp)
51
Unnesting Nested Queries, cont.
• Watch out for duplicates! Consider a query and its
rewritten counterpart.
SELECT AVG(salary)
FROM emp
WHERE manager IN (SELECT manager FROM techdept)
Unnested version, with problems: (what’s the problem?)
SELECT AVG(salary)
FROM emp, techdept
WHERE emp.manager = techdept.manager
This query may yield wrong results! A solution:
SELECT DISTINCT (manager) INTO temp
FROM techdept
SELECT AVG(salary)
FROM emp, temp
WHERE emp. manager = temp. manager
52
Summary
• Query processing & optimization is the heart of a
relational DBMS.
• Heuristic optimization is more efficient to generate, but
may not yield the optimal query evaluation plan.
• Cost-based optimization relies on statistics gathered on
the relations (the default in most DBMSs).
• Until query optimization is perfected, query tuning will
be a fact of life.
53