Download Query Processing and Optimization - Examination | CS 6400 and more Exams Computer Science in PDF only on Docsity!
Fundamentals of Database Systems 18-
QUERY PROCESSING AND OPTIMIZATION
Insert Figure 18.
Implementing the SELECT Operation
Examples:
(OP1): σSSN='123456789' (EMPLOYEE)
(OP2): σDNUMBER>5(DEPARTMENT)
(OP3): σDNO=5 (EMPLOYEE)
(OP4): σDNO=5 AND SALARY>30000 AND SEX=F (EMPLOYEE)
(OP5): σESSN=123456789 AND PNO=10 (WORKS_ON)
Search Methods for Selection
S1. Linear search (brute force): Retrieve every record in the file, and
test whether its attribute values satisfy the selection condition.
S2. Binary search : If the selection condition involves an equality
comparison on a key attribute on which the file is ordered,
binary search (which is more efficient than linear search) can be
used. An example is OP 1 if SSN is the ordering attribute for the
EMPLOYEE file.
S3. Using a primary index or hash key to retrieve a single record: If
the selection condition involves an equality comparison on a key
attribute with a primary index (or a hash key)ófor example, SSN
= 123456789 in OP 1óuse the primary index (or the hash key) to
retrieve the record.
S4. Using a primary index to retrieve multiple records: If the
comparison condition is >, ≥, <, or ≤ on a key field with a
primary indexófor example, DNUMBER > 5 in OP 2óuse the index
to find the record satisfying the corresponding equality condition
( DNUMBER = 5); then retrieve all subsequent records in the
(ordered) file. For the condition DNUMBER < 5, retrieve all the
preceding records. (FOR RANGE QUERIES )
Fundamentals of Database Systems 18-
S5. Using a clustering index to retrieve multiple records: If the
selection condition involves an equality comparison on a nonkey
attribute with a clustering indexófor example, DNO = 5 in
OP 3óuse the clustering index to retrieve all the records satisfying
the selection condition.
S6. Using a secondary (B+-tree) index : On an equality comparison,
this search method can be used to retrieve a single record if the
indexing field has unique values (is a key) or to retrieve multiple
records if the indexing field is not a key. In addition, it can be
used to retrieve records on conditions involving >,>=, <, or <=.
(FOR RANGE QUERIES )
RANGE QUERY EXAMPLE:
30000<=SALARY<=35000.
CONJUNCTIVE QUERY EXAMPLE:
(OP4): σDNO=5 AND SALARY>30000 AND SEX=F(EMPLOYEE)
S7. Conjunctive selection : If an attribute involved in any single
simple condition in the conjunctive condition has an access path
that permits the use of one of the methods S2 to S6, use that
condition to retrieve the records and then check whether each
retrieved record satisfies the remaining simple conditions in the
conjunctive condition.
S8. Conjunctive selection using a composite index : If two or more
attributes are involved in equality conditions in the conjunctive
condition and a composite index (or hash structure) exists on the
combined fieldsófor example, if an index has been created on the
composite key (ESSN, PNO) of the WORKS _ ON file for OP 5ówe can
use the index directly.
S9. Conjunctive selection by intersection of record pointers :* This
method is possible if secondary indexes are available on all (or
some of) the fields involved in equality comparison conditions in
Fundamentals of Database Systems 18-
Whenever a single condition specifies the selectionósuch as OP 1, OP 2, or OP 3ówe can only check whether an access path exists on the attribute involved in that condition. If an access path exists, the method corresponding to that access path is used; otherwise, the “brute force” linear search approach of method S1 is used.
Query optimization for a SELECT operation is needed mostly for conjunctive select conditions whenever more than one of the attributes involved in the conditions have an access path. The optimizer should choose the access path that retrieves the fewest records in the most efficient way.
In choosing between multiple simple conditions in a conjunctive select condition, it is important to consider the selectivity of each condition; this is defined as the ratio of the number of records (tuples) that satisfy the condition to the total number of records (tuples) in the file (relation). The smaller the selectivity, the fewer tuples the condition selects and the higher the desirability of using that condition first to retrieve records. Although exact selectivities of all conditions may not be available, estimates of selectivities are often kept in the DBMS catalog and used by the optimizer. For example, the selectivity of an equality condition on a key attribute of relation r(R) is 1/|r(R)|, where |r(R)| is the number of tuples in relation r(R). The selectivity of an equality condition on an attribute with i distinct values is estimated by (|r(R)|/i)/|r(R)| or 1/i, assuming that the records are evenly distributed among the distinct values. Under this assumption, |r(R)|/i records will satisfy an equality condition on this attribute.
Compared to a conjunctive selection condition, a disjunctive condition (where simple conditions are connected by the OR logical connective rather than by AND) is much harder to process and optimize. For example, consider OP 4 Í:
(OP4’): σDNO=5 OR SALARY>30000 OR SEX=F (EMPLOYEE)
With such a condition, little optimization can be done, because the records satisfying the disjunctive condition are the union of the records satisfying the individual conditions. Hence, if any one of the conditions does not have an access path, we are compelled to use the brute force linear search approach. Only if an access path exists on every condition can we optimize the selection by retrieving the records satisfying each condition and then applying the union operation to eliminate duplicate records. We can apply the union to record pointers rather than to records if the appropriate access paths that provide record pointers exist for every condition.
Fundamentals of Database Systems 18-
Implementing the JOIN Operation
TWO WAY JOIN:
R A=B S
MULTI-WAY JOIN:
R A=B S C=D T ......
Example operations:
(OP6): EMPLOYEE DNO=DNUMBER DEPARTMENT
(OP7): DEPARTMENT MGRSSN=SSN EMPLOYEE
J1. Nested (inner-outer) loop approach (brute force): For each
record t in R(outer loop), retrieve every record s from S (inner
loop) and test whether the two records satisfy the join condition
t[A] = s[B].
J2. Using an access structure to retrieve the matching record(s): If
an index (or hash key) exists for one of the two join
attributesósay, B of Sóretrieve each record t in R, one at a time,
and then use the access structure to retrieve directly all matching
records s from S that satisfy s[B] = t[A].
J3. Sortñmerge join: If the records of R and S are physically sorted
(ordered) by value of the join attributes A and B, respectively, we
can implement the join in the most efficient way possible. Both
files are scanned in order of the join attributes, matching the
records that have the same values for A and B. In this method,
the records of each file are scanned only once each for matching
with the other fileóunless both A and B are nonkey attributes, in
which case the method needs to be modified slightly.
Fundamentals of Database Systems 18-
FACTORS AFFECTING JOIN PERFORMANCE:
ï AVAILABLE BUFFER SPACE
ï CHOICE OF INNER VS. OUTER RELATION
ï JOIN SELECTION FACTOR
OTHER TYPES OF JOIN ALGORITHMS:
A. PARTITION HASH JOIN:
1) PARTITIONING PHASE : EACH FILE (R AND S) FIRST
PARTITIONED INTO M PARTITIONS USING A PARTITIONING
HASH FUNCTION ON THE JOIN ATTRIBUTES:
R1 , R2 , R3 , R4 , ......Rm and
S1 , S2 , S3 , S4 , ......Sm
MINIMUM NUMBER OF IN-MEMORY BUFFERS NEEDED: M (One
Per Partition). A DISK SUB-FILE IS CREATED PER PARTITION TO
STORE THE TUPLES FOR THAT PARTITION.
2) JOINING OR PROBING PHASE : INVOLVES M ITERATIONS,
ONE PER PARTITIONED FILE.
ITERATION i involves joining partitions Ri and Si.
Partitioned Hash Join Procedure:
Assume Ri is smaller than Si.
Fundamentals of Database Systems 18-
Copy records from Ri into memory buffers.
Read all blocks from Si, one at a time and each record from Si is used
to probe for a matching record(s) from partition Si.
Write matching record from Ri after joining to the recoed from Si
into the result file.
Cost:
Reading and writing each record from R and S during the
partitioning phase: (b R + b S ), (b R + b S )
Reading each record during the joining phase: (b R + b S )
Writing the result of join: b RES
Total Cost: 3* (b^ R + b^ S ) + b^ RES
B. HYBRID HASH JOIN:
Same as partitioned hash join except:
Joining phase of one of the partitions is included during the
partitioning phase.
Partitioning Phase: Allocate buffers for smaller relation- one block for
each of the M-1 partitions, remaining blocks to partition 1. Repeat for
the larger relation in the pass through S.)
Joining phase: M-1 iterations are needed for the partitions
R2 , R3 , R4 , ......Rm and S2 , S3 , S4 , ......Sm.
R1 and S1 are joined during the partitioning of S1 , and results of
joining R1 and S1 are already written to the disk by the end of
partitioning phase.
Fundamentals of Database Systems 18-
Implementing Outer Join
SELECT FNAME, DNAME
FROM (EMPLOYEE LEFT OUTER JOIN DEPARTMENT
ON DNO = DNUMBER);
The result of this query is a table of employee names and their
associated departments. It is similar to a regular join result, with the
exception that if an employee does not have an associated
department, the employee's name will still appear in the resulting
table, although the department name would be indicated as null.
The full outer join produces a result which is equivalent to the
union of the results of the left and right outer joins.
a. Modifying Join Algorithms : Nested Loop or Sort-Merge joins
can be modified. e.g., for left outer join, use the left relation as outer
relation and construct result from every tuple in the left relation. If
there is a match, the concatenated tuple is saved in the result.
However, if an outer tuple does not match, then the tuple is still
included in the result but is padded with a null value(s).
b. Executing a combination of relational algebra operators. For
the left outer join, shown above, we have the following:
1.{Compute the JOIN of the EMPLOYEE and DEPARTMENT tables}
TEMP
FNAME,DNAME(EMPLOYEE DNO=DNUMBER
DEPARTMENT)
2. {Find the EMPLOYEEs that do not appear in the JOIN}
TEMP2 FNAME(EMPLOYEE) FNAME(Temp1)
3. {Pad each tuple in TEMP2 with a null DNAME field}
TEMP2 TEMP2 'null'
4. {UNION the temporary tables to produce the LEFT OUTER JOIN
result}
RESULT TEMP1 TEMP
Fundamentals of Database Systems 18-
The cost of the outer join, as computed above, would include the
cost of the associated steps (i.e., join, projections and union).
- step 3 can be done as the temporary relation is being
constructed in step 2. That is, we can simply pad the result at that
time.
- in step 4, we know that the union is a union of disjoint sets, so
there is no need for duplicate elimination.
Fundamentals of Database Systems 18-
HEURISTIC OPTIMIZATION
Mapping queries into alternative algebraic forms for more
efficient execution
Fundamentals of Database Systems 18-
General Transformation Rules for Relational Algebra Operations.
There are many rules for transforming relational algebra operations into equivalent ones. Here we are interested in the meaning of the operations and the resulting relations. Hence, if two relations have the same set of attributes in a different order but the two relations represent the same information, we consider the relations equivalent. In Section 7.1.2 we gave an alternative definition of relation that makes order of attributes unimportant; we will use this definition here. We now state some transformation rules, without proving them:
- Cascade of σ: A conjunctive selection condition can be broken up into a cascade (sequence) of individual s operations: σ (^) c1 AND c2 AND ... AND cn(R) + σc1 (σc2 (...(σcn(R))...) )
- Commutativity of σ: The σ operation is commutative:
σc1 (σc2 (R)) + σc2 (σc1 (R))
- Cascade of π: In a cascade (sequence) ofp operations, all but the last one can be ignored: πList1 (πList2 (...(πListn(R))...) ) = πList1 (R)
- 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))
- Commutativity of (or ∞): The operation is commutative:
R (^) c S + S (^) c R Notice that, although the order of attributes may not be the same in the relations resulting from the two joins, the “meaning” is the same because order of attributes is not important in the alternative definition of relation that we use here. The ∞ operation is commutative in the same sense as the operation.
- Commuting σ with (or ∞): If all the attributes in the selection condition c involve only the attributes of one of the relations being joined—say, R—the two operations can be commuted as follows: σc ( R S ) + (σc (R)) S Alternatively, if the selection condition c can be written as (c1 and c2), where condition c1 involves only the attributes of R and condition c involves only the attributes of S, the operations commute as follows: σc ( R S ) + (σc1 (R)) (σc2 (S))
Fundamentals of Database Systems 18-
The same rules apply if the is replaced by a ∞ operation. These transformations are very useful during heuristic optimization.
- Commuting π with (or ∞): Suppose that the projection list is L = {A1, ..., An, B1, ..., Bm}, where A1, ..., An are attributes of R and B1, ..., Bm are attributes of S. If the join condition c involves only attributes in L, the two operations can be commuted as follows: πL ( R (^) c S ) + (πA1, ..., An (R)) (^) c (πB1, ..., Bm (S)) If the join condition c contains additional attributes not in L, these must be added to the projection list, and a final π operation is needed. For example, if attributes An + 1, ..., An + k of R and Bm + 1, ..., Bm + p of S are involved in the join condition c but are not in the projection list L, the operations commute as follows: πL ( R (^) c S ) + πL ( (πA1,.. .,An,An+1,.. .,An+k(R)) (^) c (πB1,...,Bm,Bm+1,...,Bm+p (S)) ) For ∞, there is no condition c, so the first transformation rule always applies by replacing (^) c with ∞.
- Commutativity of set operations: The set operations ≈ and ↔ are commutative but – is not.
- Associativity of , ∞, ≈, and ↔: These four operations are individually associative; that is, if θ stands for any one of these four operations (throughout the expression), we have ( R θ S ) θ T + R θ ( S θ T )
- Commuting σ with set operations: The σ operation commutes with ≈, ↔, and –. If θ stands for any one of these three operations, we have σc ( R θ S ) + (σc (R)) θ (σc (S))
- The π operation commutes with ≈. If θ stands for ≈, we have
πL ( R θ S ) + (πL (R)) θ (πL (S))
- Other transformations: There are other possible transformations. For example, a selection or join condition c can be converted into an equivalent condition by using the following rules (known as DeMorgan’s laws):
c ≡ NOT ( c1 AND c2 ) ≡ ( NOT c1) OR ( NOT c2 ) c ≡ NOT ( c1 OR c2 ) ≡ ( NOT c1) AND ( NOT c2 )
Additional transformations discussed in Chapter 7 are not repeated here. We discuss next how these rules are used in heuristic optimization.
Fundamentals of Database Systems 18-
Summary of Heuristics for Algebraic Optimization.
We now summarize the basic heuristics for algebraic optimization. The main heuristic is to apply first the operations that reduce the size of intermediate results. This includes performing SELECT operations as early as possible to reduce the number of tuples and performing PROJECT operations as early as possible to reduce the number of attributes. This is done by moving SELECT and PROJECT operations as far down the tree as possible. In addition, the SELECT and JOIN operations that are most restrictive—that is, result in relations with the fewest tuples or with the smallest absolute size—should be executed before other similar operations. This is done by reordering the leaf nodes of the tree among themselves and adjusting the rest of the tree appropriately.
Fundamentals of Database Systems 18-
Query Execution Plans
An execution plan for a relational algebra query (or an initial SQL
query converted into an algebraic query) consists of a combination
of the relational algebra query tree and information about the access
methods to be used for each relation as well as the methods to be
used in computing the relational operators stored in the tree. A
simple example of a query tree, for the query Q1 from Chapter 7,
πFNAME,LNAME,ADDRESS (σDNAME=’RESEARCH’(DEPARTMENT EMPLOYEE))
is shown in Figure 18.6.
To complete the execution plan, the optimizer might choose a
table scan for the access method for each of the two relations, a
nested-block join algorithm for the join, a scan of the join result for
the select operation and a scan of the select result for the project
operator. In addition, the approach taken for the execution of the
query may follow a materialized evaluation or possibly a pipelined
evaluation. With the materialized evaluation the result of an
operation is stored as a temporary relation (i.e., materialized). For
instance, the join operation can be computed and the entire result
stored as a temporary relation. This temporary relation can then be
read as input by the algorithm that computes the select operation,
which in turn, would produce a second temporary table. On the
other hand, with a pipelined evaluation , as the result of an operator
is produced, it is forwarded to the next operator in sequence. For
example, as the joining tuples are produced, they are placed in a
buffer. The selection operator algorithm would then consume the
tuples from the buffer and tuples that satisfy the condition of the
selection would be pipelined to the projection operator algorithm.
The advantage of pipelining is the cost savings in not having to
write the intermediate results to disk and not having to read them
back for the next operator.
Insert Figure 18.