Introduction To Query Processing and Query Optimization Techniques
Introduction To Query Processing and Query Optimization Techniques
1
Introduction to Query Processing
Query optimization:
The process of choosing a suitable execution
strategy for processing a query.
Amongst all equivalent evaluation plans choose
the one with lowest cost.
Cost is estimated using statistical information
from the database catalog
e.g. number of tuples in each relation, size of tuples
2
Basic Steps in Query Processing
3
Basic Steps in Query Processing
is equivalent to
balance(balance2500(account))
4
Measures of Query Cost
5
Translating SQL Queries into Relational
Algebra
Query Block:
The basic unit that can be translated into the
algebraic operators and optimized.
A query block contains a single SELECT-FROM-
WHERE expression, as well as GROUP BY and
HAVING clause if these are part of the block.
6
Translating SQL Queries into Relational
Algebra
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE SALARY > ( SELECT MAX (SALARY)
FROM EMPLOYEE
WHERE DNO = 5);
7
Algorithms for External Sorting
Sorting is needed in
Order by, join, union, intersection, distinct, …
For relations that fit in memory, techniques like
quicksort can be used.
External sorting:
Refers to sorting algorithms that are suitable for
large files of records stored on disk that do not
fit entirely in main memory, such as most
database files.
Example:
nB = 5 blocks and file size b = 1024 blocks, then
nR = (b/nB) = 1024/5 = 205 initial sorted runs
each of size 5 bocks (except the last run which
will have 4 blocks)
nB = 2, b = 7, nR = b/nB = 4
run
10
External Sort-Merge
nR = i
11
External Sort-Merge
Merging phase:
The sorted runs are merged during one or more
passes.
The degree of merging (dM) is the number of
runs that can be merged in each pass.
dM = Min (nB-1, nR)
nP = (logdM(nR))
nP: number of passes.
In each pass,
One buffer block is needed to hold one block
from each of the runs being merged, and
One block is needed for containing one block of
the merged result.
12
External Sort-Merge
14
External Sort-Merge
Degree of merging (dM)
# of runs that can be merged together in each pass = min
(nB - 1, nR)
Number of passes nP = (logdM(nR))
In our example
d = 4 (four-way merging)
M
min (nB-1, nR) = min(5-1, 205) = 4
Number of passes nP = (logdM(nR)) = (log4(205)) = 4
First pass:
– 205 initial sorted runs would be merged into 52 sorted runs
Second pass:
– 52 sorted runs would be merged into 13
Third pass:
– 13 sorted runs would be merged into 4
Fourth pass:
– 4 sorted runs would be merged into 1
15
External Sort-Merge
Blocking factor bfr = 1 record, nB = 3, b = 12, nR = 4, dM = min(3-1, 4) = 2
16
External Sort-Merge
17
External Sort-Merge
External Sort-Merge: Cost Analysis
Disk accesses for initial run creation (sort phase) as well as
in each merge pass is 2b
reads every block once and writes it out once
19
Catalog Information
File
r: # of records in the file
R: record size
b: # of blocks in the file
bfr: blocking factor
Index
x: # of levels of a multilevel index
bI1: # of first-level index blocks
20
Catalog Information
Attribute
d: # of distinct values of an attribute
sl (selectivity):
the ratio of the # of records satisfying the condition to
the total # of records in the file.
s (selection cardinality) = sl * r
average # of records that will satisfy an equality
condition on the attribute
For a key attribute:
d = r, sl = 1/r, s=1
For a nonkey attribute:
assuming that d distinct values are uniformly
distributed among the records
the estimated sl = 1/d, s = r/d
21
File Scans
Types of scans
File scan – search algorithms that locate and
retrieve records that fulfill a selection condition.
22
Algorithms for SELECT Operations
Implementing the SELECT Operation
Examples:
(OP1): SSN='123456789' (EMP)
(OP2): DNUMBER>5(DEPT)
(OP3): DNO=5(EMP)
(OP4): DNO=5 AND SALARY>30000 AND SEX=F(EMP)
(OP5): ESSN=123456789 AND PNO=10(WORKS_ON)
23
Algorithms for Selection Operation
Search Methods for Simple Selection:
S1 (linear search)
Retrieve every record in the file, and test whether
its attribute values satisfy the selection condition.
24
Algorithms for Selection Operation
S2 (binary search)
Applicable if selection is an equality
comparison on the attribute on which file is
ordered.
Assume that the blocks of a relation are stored
contiguously
If selection is on a nonkey attribute:
25
Selections Using Indices
Hash index:
C = 1: for static or linear hashing
C = 2: for extendable hashing
26
Selections Using Indices
S4 (primary index on a key, range selection)
S4 Using a primary index to retrieve multiple
records:
If the comparison condition is >, ≥, <, or ≤ on a key field with a
primary index, use the index to find the record satisfying the
corresponding equality condition, then retrieve all subsequent
records in the (ordered) file.
Assuming relation is sorted on A
For Av(r) use index to find 1st tuple = v and retrieve all
subsequent records.
For Av(r) use index to find 1st tuple = v and retrieve all
preceding records.
– OR just scan relation sequentially till 1st tuple v; do not use index
with average cost C = b/2
27
Selections Using Indices
28
Selections Using Indices
29
Selections Using Indices
S6-2 (secondary index B+-tree, comparison)
For Av(r) use index to find 1st index entry = v
and scan index sequentially from there, to find
pointers to records.
For Av(r) just scan leaf pages of index finding
pointers to records, till first entry v
30
Complex Selections: 12…n(r)
31
Complex Selections: 12…n(r)
32
Complex Selections: 12…n(r)
S9 (conjunctive selection by intersection of record
pointers)
Requires indices with record pointers.
Use corresponding index for each condition, and
take intersection of all the obtained sets of record
pointers, then fetch records from file
If some conditions do not have appropriate
indices, apply test in memory.
Cost is the sum of the costs of the individual
index scan plus the cost of retrieving records
from disk.
33
Complex Selections: 12… n(r)
S10 (disjunctive selection by union of identifiers)
Applicable if all conditions have available indices.
READ
“Examples of Using the Cost Functionst”
page 569--570.
page 694-695
34
Duplicate Elimination
35
Algorithms for PROJECT Operation
Algorithm for PROJECT operations (Figure 15.3b)
<attribute list>(R)
1. If <attribute list> has a key of relation R, extract all
tuples from R with only the values for the attributes in
<attribute list>.
2. If <attribute list> does NOT include a key of relation R,
duplicated tuples must be removed from the results.
36
Algorithms for SET Operations
Algorithm for SET operations
Set operations:
UNION, INTERSECTION, SET DIFFERENCE and
CARTESIAN PRODUCT
CARTESIAN PRODUCT of relations R and S include all
possible combinations of records from R and S. The
attribute of the result include all attributes of R and S.
Cost analysis of CARTESIAN PRODUCT
If R has n records and j attributes and S has m records
and k attributes, the result relation will have n*m
records and j+k attributes.
CARTESIAN PRODUCT operation is very expensive and
should be avoided if possible.
37
Set Operations
R S: (See Figure 18.3c)
1. Sort the two relations on the same attributes.
2. Scan and merge both sorted files concurrently,
whenever the same tuple exists in both relations, only
one is kept in the merged results.
R S: (See Figure 18.3d)
1. Sort the two relations on the same attributes.
2. Scan and merge both sorted files concurrently,
keep in the merged results only those tuples that
appear in both relations.
R – S: (See Figure 18.3e)
keep in the merged results only those tuples that
appear in relation R but not in relation S.
38
b. Project
c. Union
39
d. Intersection e. Different
40
Aggregate Operations
The aggregate operations MIN, MAX, COUNT,
AVERAGE, and SUM can be computed by scanning
the whole records (the worst case)
If index exists on the attribute of MAX , MIN
operation, then these operations can be done in a
much more efficient way: select max/min (salary)
from employee
If an (ascending) index on SALARY exists for
the employee relation, then the optimizer could
decide on traversing the index for the
largest/smallest value, which would entail
following the right/left most pointer in each
index node from the root to a leaf.
41
Aggregate Operations
SUM, COUNT and AVG
For a dense index (each record has one index entry):
Apply the associated computation to the values in the index.
For a non-dense index:
Actual number of records associated with each index entry
must be accounted for
With GROUP BY: the aggregate operator must be applied separately
to each group of tuples.
Use sorting or hashing on the group attributes to partition the
file into the appropriate groups;
Computes the aggregate function for the tuples in each
group.
What if we have Clustering index on the grouping attributes?
42
Combining Operations using Pipelining
Motivation
A query is mapped into a sequence of operations.
Each execution of an operation produces a
temporary result (Materialization).
Generating & saving temporary files on disk is
time consuming.
Alternative:
Avoid constructing temporary results as much as
possible.
Pipeline the data through multiple operations
44
Pipelining
Pipelined evaluation
evaluate several operations simultaneously,
passing the results of one operation on to the next.
E.g., in previous expression tree, don’t store result
of balance2500 (account )
instead, pass tuples directly to the join.
Similarly, don’t store result of join, pass tuples
directly to projection.
Much cheaper than materialization:
no need to store a temporary relation to disk.
Pipelining may not always be possible
e.g., sort, hash-join.
45
Using Heuristics in Query Optimization
46
Using Heuristics in Query Optimization
Query tree:
A tree data structure that corresponds to a relational
algebra expression. It represents the input relations of
the query as leaf nodes of the tree, and represents the
relational algebra operations as internal nodes.
An execution of the query tree consists of executing an
internal node operation whenever its operands are available
and then replacing that internal node by the relation that
results from executing the operation.
Query graph:
A graph data structure that corresponds to a relational
calculus expression. It does not indicate an order on
which operations to perform first. There is only a single
graph corresponding to each query.
47
Using Heuristics in Query Optimization
Example:
For every project located in ‘Stafford’, retrieve the project
number, the controlling department number and the
department manager’s last name, address and birthdate.
Relation algebra:
PNUMBER, DNUM, LNAME, ADDRESS, BDATE
(((PLOCATION=‘STAFFORD’(PROJECT))
DNUM=DNUMBER (DEPARTMENT)) MGRSSN=SSN
(EMPLOYEE))
SQL query:
Q2: SELECT P.NUMBER,P.DNUM,E.LNAME, E.ADDRESS,
E.BDATE FROM PROJECT AS P,DEPARTMENT AS D,
EMPLOYEE AS E WHERE P.DNUM=D.DNUMBER AND
D.MGRSSN=E.SSN AND P.PLOCATION=‘STAFFORD’;
48
Using Heuristics in Query Optimization
49
Using Heuristics in Query Optimization
50
Using Heuristics in Query Optimization
51
Using Heuristics
in Query
Optimization
52
Using Heuristics
in Query
Optimization
53
Using Heuristics in
Query
Optimization
54
Transformation Rules for RA Operations
1. Cascade of :
A conjunctive selection condition can be broken up into a cascade (sequence) of
individual operations:
c1 AND c2 AND ... AND cn(R) c1(c2(...(cn(R))...))
2. Commutativity of :
The operation is commutative:
c1(c2(R)) c2(c1(R))
3. Cascade of :
In a cascade (sequence) of operations, all but the last one can be ignored:
List1(List2(...(Listn(R))...)) = List1(R)
4. Commuting with :
If the selection condition c involves only the attributes A1, ..., An in the
projection list, the two operations can be commuted:
A1, A2, ..., An(c(R)) = c(A1, A2, ..., An(R))
55
Transformation Rules for RA Operations
56
Transformation Rules for RA Operations
57
Transformation Rules for RA Operations
58
Transformation Rules for RA Operations
59
Heuristic Algebraic Optimization Algorithm
60
Heuristic Algebraic Optimization Algorithm
61
Summary of Heuristics for Algebraic
Optimization
The main heuristic is to apply first the operations that
reduce the size of intermediate results.
62
Query Execution Plans
63
Using Selectivity and Cost Estimates in
Query Optimization
Cost-based query optimization:
Estimate and compare the costs of executing a
query using different execution strategies and
choose the strategy with the lowest cost
estimate.
(Compare to heuristic query optimization)
Issues
Cost function
Number of execution strategies to be
considered
64
Using Selectivity and Cost Estimates in
Query Optimization
Cost Components for Query Execution
1. Access cost to secondary storage
2. Storage cost
3. Computation cost
4. Memory usage cost
5. Communication cost
65
Using Selectivity and Cost Estimates in
Query Optimization
Catalog Information Used in Cost Functions
Information about the size of a file
number of records (tuples) (r),
record size (R),
number of blocks (b)
blocking factor (bfr)
Information about indexes and indexing attributes of a
file
Number of levels (x) of each multilevel index
Number of first-level index blocks (bI1)
Number of distinct values (d) of an attribute
Selectivity (sl) of an attribute
Selection cardinality (s) of an attribute. (s = sl * r)
66
Using Selectivity and Cost Estimates in
Query Optimization
Examples of Cost Functions for SELECT
S1. Linear search (brute force) approach
CS1a = b;
For an equality condition on a key, CS1a = (b/2) if the
record is found; otherwise CS1a = b.
S2. Binary search:
CS2 = log2b + (s/bfr) –1
For an equality condition on a unique (key) attribute,
CS2 =log2b
S3. Using a primary index (S3a) or hash key (S3b) to
retrieve a single record
CS3a = x + 1; CS3b = 1 for static or linear hashing;
CS3b = 1 for extendible hashing;
67
Using Selectivity and Cost Estimates in
Query Optimization
Examples of Cost Functions for SELECT (contd.)
S4. Using an ordering index to retrieve multiple records:
For the comparison condition on a key field with an
ordering index, CS4 = x + (b/2)
S5. Using a clustering index to retrieve multiple records:
CS5 = x + ┌ (s/bfr) ┐
S6. Using a secondary (B+-tree) index:
For an equality comparison, CS6a = x + s;
For an comparison condition such as >, <, >=, or <=,
CS6a = x + (bI1/2) + (r/2)
68
Using Selectivity and Cost Estimates in
Query Optimization
Examples of Cost Functions for SELECT (contd.)
S7. Conjunctive selection:
Use either S1 or one of the methods S2 to S6 to solve.
For the latter case, use one condition to retrieve the
records and then check in the memory buffer whether
each retrieved record satisfies the remaining conditions
in the conjunction.
S8. Conjunctive selection using a composite index:
Same as S3a, S5 or S6a, depending on the type of
index.
69
10. Semantic Query Optimization
Semantic Query Optimization:
Uses constraints specified on the database schema in order to
modify one query into another query that is more efficient to
execute.
Consider the following SQL query,
SELECT E.LNAME, M.LNAME
FROM EMPLOYEE E M
WHERE E.SUPERSSN=M.SSN AND E.SALARY>M.SALARY
Explanation:
Suppose that we had a constraint on the database schema that
stated that no employee can earn more than his or her direct
supervisor. If the semantic query optimizer checks for the
existence of this constraint, it need not execute the query at
all because it knows that the result of the query will be
empty. Techniques known as theorem proving can be used
for this purpose.
70
Example (1)
71
Example (2)
Initial query tree:
Name
GPA 3.5 and Title = 'Ada Programming Language’
and Students.SSN = Enrollment.SSN
Courses
Students Enrollment
72
Example (3)
Name
Courses
75
Example (6)
Project out useless attributes early.
Name
SSN, Name SSN
GPA 3.5
SSN, Course_no Course_no
Students Title = 'Ada Programming
Enrollment Language’
76
Courses
Example (7)
77