Course Database Management Systems - Chapter 3: Algorithms for Query Processing and Optimization - Nguyen Thanh Tung

Introduction to Query Processing
 Translating SQL Queries into Relational Algebra
 Algorithms for External Sorting
 Algorithms for SELECT and JOIN Operations
 Algorithms for PROJECT and SET Operations
 Implementing Aggregate Operations and Outer Joins
 Combining Operations using Pipelining
 Using Heuristics in Query Optimization
 Using Selectivity and Cost Estimates in Query Optimization
 Overview of Query Optimization in Oracle
 Semantic Query Optimization 
pdf 81 trang xuanthi 30/12/2022 1640
Bạn đang xem 20 trang mẫu của tài liệu "Course Database Management Systems - Chapter 3: Algorithms for Query Processing and Optimization - Nguyen Thanh Tung", để tải tài liệu gốc về máy hãy click vào nút Download ở trên.

File đính kèm:

  • pdfcourse_database_management_systems_c3_algorithms_for_query_p.pdf

Nội dung text: Course Database Management Systems - Chapter 3: Algorithms for Query Processing and Optimization - Nguyen Thanh Tung

  1. Chapter Outline  Introduction to Query Processing  Translating SQL Queries into Relational Algebra  Algorithms for External Sorting  Algorithms for SELECT and JOIN Operations  Algorithms for PROJECT and SET Operations  Implementing Aggregate Operations and Outer Joins  Combining Operations using Pipelining  Using Heuristics in Query Optimization  Using Selectivity and Cost Estimates in Query Optimization  Overview of Query Optimization in Oracle  Semantic Query Optimization 2
  2. Typical steps when processing a high-level query 4
  3. a 19 Buffer-size = 3, d 31 a 19 1 record/block g 24 g 24 b 14 a 14 a 19 c 33 a 19 d 31 b 14 d 31 b 14 c 33 c 33 e 16 c 33 b 14 e 16 g 24 d 7 e 16 d 21 r 16 d 21 a 14 d 31 d 21 m 3 d 7 e 16 m 3 r 16 d 21 g 24 p 2 m 3 m 3 d 7 a 14 p 2 p 2 a 14 d 7 r 16 r 16 p 2 Tạo run trộn pass-1 trộn pass-2 8
  4. /*Merge phase: merge subfiles until only 1 remains */ set i  1; p  logk-1m ; /* p is the number of passes for the merging phase */ j  m; /* the number of runs */ while (i<= p) do { n  1; q  (j/(k-1) ; /* the number of runs to write in this pass */ while ( n <= q) do { read next k-1 subfiles or remaining subfiles (from previous pass) one block at a time merge and write as new subfile one block at a time; n  n+1; } j  q; i  i+1; } The number of block accesses for the merge phase = 2*(b* logdMnR ) 10
  5. Algorithms for SELECT and JOIN (2) Implementing the SELECT Operation (cont.): Search Methods for Simple 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. (See OP1).  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), use the primary index (or the hash key) to retrieve the record. 12
  6. Algorithms for SELECT and JOIN Operations (4) Implementing the SELECT Operation (cont.): Search Methods for Simple Selection:  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 ) 14
  7. Algorithms for SELECT and JOIN (6) Implementing the SELECT Operation (cont.): Search Methods for Complex Selection:  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 the conjunctive condition and if the indexes include record pointers (rather than block pointers). Each index can be used to retrieve the record pointers that satisfy the individual condition. The intersection of these sets of record pointers gives the record pointers that satisfy the conjunctive condition, which are then used to retrieve those records directly. If only some of the conditions have secondary indexes, each retrieved record is further tested to determine whether it satisfies the remaining conditions. 16
  8. Algorithms for SELECT and JOIN Operations (8) Implementing the JOIN Operation:  Join (EQUIJOIN, NATURAL JOIN) – two–way join: a join on two files e.g. R  A=B S – multi-way joins: joins involving more than two files. e.g. R  A=B S  C=DT  Examples (OP6): EMPLOYEE  DNO=DNUMBERDEPARTMENT (OP7): DEPARTMENT  MGRSSN=SSNEMPLOYEE 18
  9. Algorithms for SELECT and JOIN Operations (10) Implementing the JOIN Operation (cont.): Methods for implementing joins:  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 non-key attributes, in which case the method needs to be modified slightly. 20
  10. R S C A B D 5 4 6 6 9 6 10 10 17 17 20 18 Assume that A is a key of R. Initially, two pointers are used to point to the two tuples of the two relations that have the smallest values of the two joining attributes. 22
  11. R S R(i)[A] < S(j)[B] C A B D 5 4 6 6 9 6 10 10 17 17 20 18 R S C A B D 5 4 6 6 9 6 10 10 17 17 20 18 24
  12. R S R(i)[A] > S(j)[B] C A B D 5 4 6 6 9 6 10 10 17 17 20 18 R S C A B D 5 4 6 6 9 6 10 10 17 17 20 18 26
  13. R S R(i)[A] = S(j)[B] C A B D 5 4 R(4), S(4) 6 6 9 6 10 10 17 17 20 18 R S C A B D 5 4 6 6 9 6 10 10 17 17 20 18 28
  14. R S R(i)[A] > S(j)[B] C A B D 5 4 6 6 9 6 10 10 17 17 20 18 R S C A B D 5 4 6 6 9 6 10 10 17 17 20 18 30
  15. Algorithms for SELECT and JOIN Operations (11) Implementing the JOIN Operation (cont.): Methods for implementing joins:  J4. Hash-join: The records of files R and S are both hashed to the same hash file, using the same hashing function on the join attributes A of R and B of S as hash keys. A single pass through the file with fewer records (say, R) hashes its records to the hash file buckets. A single pass through the other file (S) then hashes each of its records to the appropriate bucket, where the record is combined with all matching records from R. 32
  16. Implementing T  ∏ (R) (b) create a tuple t[ ] in T’ for each tuple t in R; /* T’ contains the projection result before duplicate elimination */ if includes a key of R then T  T’ else { sort the tuples in T’; set i  1, j  2; while i ≤ n do { output the tuple T’[i] to T; while T’[i] = T’[j] and j ≤ n do j  j+1; set i  j, j  i+1; } } /* T contains the projection result after duplicate elimination */ b) Implementing T  ∏ (R) 34
  17. Algorithms for PROJECT and SET Operations (3)  Algorithm for SET operations (Cont.)  UNION (See Figure 15.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.  INTERSECTION (See Figure 15.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.  SET DIFFERENCE R-S (See Figure 15.3e)(keep in the merged results only those tuples that appear in relation R but not in relation S.) 36
  18. Intersection T  R  S (d) sort the tuples in R and S using the same unique sort attributes; set i  1, j  1; while (i ≤ n) and (j ≤ m) do { if R(i) > S(j) then set j  j+1 elseif R(i) < S(j) then set i  i+1 else { output R(i) to T; /* R(i) = S(j), so we skip one of the duplicate tuples */ set i  i+1, j j+1 } } 38
  19. 5. Implementing Aggregate Operations and Outer Joins (1) Implementing Aggregate Operations:  Aggregate operators : MIN, MAX, SUM, COUNT and AVG  Options to implement aggregate operators:  Table Scan  Index  Example SELECT MAX(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 value, which would entail following the right most pointer in each index node from the root to a leaf. 40
  20. Implementing Aggregate Operations and Outer Joins (3)  Implementing Outer Join:  Outer Join Operators : LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN.  The full outer join produces a result which is equivalent to the union of the results of the left and right outer joins.  Example: SELECT FNAME, DNAME FROM ( EMPLOYEE LEFT OUTER JOIN DEPARTMENT ON DNO = DNUMBER);  Note: 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. 42
  21. Implementing Aggregate Operations and Outer Joins (5)  Implementing Outer Join (cont.): Executing a combination of relational algebra operators. Implement the previous left outer join example 1. {Compute the JOIN of the EMPLOYEE and DEPARTMENT tables} TEMP1  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 x 'null' 4. {UNION the temporary tables to produce the LEFT OUTER JOIN result} RESULT  TEMP1  TEMP2 The cost of the outer join, as computed above, would include the cost of the associated steps (i.e., join, projections and union). 44
  22. Combining Operations using Pipelining (2)  Example: For a 2-way join, combine the 2 selections on the input and one projection on the output with the Join.  Dynamic generation of code to allow for multiple operations to be pipelined.  Results of a select operation are fed in a " Pipeline " to the join algorithm.  Also known as stream-based processing. 46
  23. Using Heuristics in Query Optimization (2)  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. 48
  24. Two query trees for the query Q2 50
  25. Using Heuristics in Query Optimization (6) Heuristic Optimization of Query Trees:  The same query could correspond to many different relational algebra expressions — and hence many different query trees.  The task of heuristic optimization of query trees is to find a final query tree that is efficient to execute.  Example : Q: SELECT LNAME FROM EMPLOYEE, WORKS_ON,PROJECT WHERE PNAME = ‘AQUARIUS’ AND PNMUBER=PNO AND ESSN=SSN AND BDATE > ‘1957-12-31’; 52
  26. Apply more restrictive SELECT Replacing Cartesian Product and Select operation first with Join operation. 54
  27. Using Heuristics in Query Optimization (10) General Transformation Rules for Relational Algebra Operations: 1. Cascade of σ : A conjunctive selection condition can be broken up into a cascade (sequence) of individual selection 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)) 56
  28. Using Heuristics in Query Optimization (12)  General Transformation Rules for Relational Algebra Operations (cont.):  7.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  CS ) = (π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. 58
  29. Using Heuristics in Query Optimization (14) General Transformation Rules for Relational Algebra Operations (cont.):  11. The π operation commutes with . πL( R  S ) = (πL(R))  (πL(S))  12. Converting a (σ, ) sequence into  : If the condition c of a σ that follows a corresponds to a join condition, convert the (σ, ) sequence into a  as follows: (σC(R S)) = (R  C S)  13. Other transformations 60
  30. Using Heuristics in Query Optimization (16) Outline of a Heuristic Algebraic Optimization Algorithm (cont.)  5. Using rules 3, 4, 7, and 11 concerning the cascading of project and the commuting of project with other operations, break down and move lists of projection attributes down the tree as far as possible by creating new project operations as needed.  6. Identify subtrees that represent groups of operations that can be executed by a single algorithm. 62
  31. Using Heuristics in Query Optimization (17) Query Execution Plans  An execution plan for a relational algebra 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.  Materialized evaluation: The result of an operation is stored as a temporary relation.  Pipelined evaluation: as the result of an operator is produced, it is forwarded to the next operator in sequence. 64
  32. Using Selectivity and Cost Estimates in Query Optimization (2) Cost Components for Query Execution  1.Access cost to secondary storage  2. Storage cost  3. Computation cost  4. Memory usage cost  5. Communication cost Note: Different database systems may focus on different cost components. 66
  33. Using Selectivity and Cost Estimates in Query Optimization (4) Examples of Cost Functions for SELECT  S1. Linear search (brute force) approach CS1a= b; For an equality condition on a key, C S1b = (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 = 2 for extendible hashing; 68
  34. Using Selectivity and Cost Estimates in Query Optimization (6) Examples of Cost Functions for SELECT (cont.)  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.  Examples of using the cost functions. 70
  35. Example  (op1): σSSN='123456789' (EMPLOYEE)  CS1b = 1000  CS6a = xSSN + 1 = 4+1 = 5  (op2): σDNO>5 (EMPLOYEE)  CS1a = 2000  CS6b = xDNO + (bl1DNO/2) + (r/2) = 2 + 4/2 + 10000/2 = 5004 72
  36. Using Selectivity and Cost Estimates in Query Optimization (7) Examples of Cost Functions for JOIN  Join selectivity (js) js = | (R  C S) | / | R x S | = | (R  C S) | / (|R| * |S |) If condition C does not exist, js = 1; If no tuples from the relations satisfy condition C, js = 0; Usually, 0 <= js <= 1 ; Size of the result file after join operation | (R  C S) | = js * |R| * |S | 74
  37. Using Selectivity and Cost Estimates in Query Optimization (9) Examples of Cost Functions for JOIN (cont.)  J2. Single-loop join (cont.) For a secondary index, CJ2a = bR+ (|R| * (xB+ sB)) + ((js* |R|* |S|)/bfrRS); For a clustering index, CJ2b = bR + (|R| * (xB+ (sB/bfrB))) + ((js* |R|* |S|)/bfrRS); For a primary index, CJ2c = bR + (|R| * (xB+ 1)) + ((js* |R|* |S|)/bfrRS); If a hash key exists for one of the two join attributes — B of S CJ2d = bR + (|R| * h) + ((js* |R|* |S|)/bfrRS); h: the average number of block accesses to retrieve a record, given its hash key value, h>=1  J3. Sort-merge join: CJ3a = CS + bR+ bS + ((js* |R|* |S|)/bfrRS); (CS: Cost for sorting files) 76
  38. Example  (op6): EMPLOYEE  DND=DNUMBER DEPARTMENT  Method J1 with Employee as outer:  CJ1 = bE + (bE * bD) + ((jsOP6 * rE * rD)/bfrED)  = 2000 + (2000 * 13) + (((1/125) * 10,000 * 125)/4) =30,500  Method J1 with Department as outer:  CJ1 = bD + (bE * bD) + (((jsOP6 * rE * rD)/bfrED)  = 13 + (13 * 2000) + (((1/125) * 10,000 * 125/4) = 28,513  Method J2 with EMPLOYEE as outer loop:  CJ2c = bE + (rE * (xDNUMBER + 1)) + ((jsOP6 * rE * rD)/bfrED  = 2000 + (10,000 * 2) + (((1/125) * 10,000 * 125/4) = 24,500  Method J2 with DEPARTMENT as outer loop:  CJ2a = bD + (rD * (xDNO+ sDNO)) + ((jsOP6 * rE * rD)/bfrED)  = 13 + (125 * (2 + 80)) + (((1/125) * 10,000 * 125/4) = 12,763 J1: nested loop join J2: single loop join 78
  39. Using Selectivity and Cost Estimates in Query Optimization (10) Multiple Relation Queries and Join Ordering  A query joining n relations will have n-1 join operations, and hence can have a large number of different join orders when we apply the algebraic transformation rules.  Current query optimizers typically limit the structure of a (join) query tree to that of left-deep (or right- deep) trees.  Left-deep tree : a binary tree where the right child of each non-leaf node is always a base relation.  Amenable to pipelining  Could utilize any access paths on the base relation (the right child) when executing the join. 80