Query Processing Course outlines Basic Steps in Query
Query Processing Course outlines ÊBasic Steps in Query Processing – an overview ÊMeasures of Query Cost ÊQuery Processing- Several algorithms Ê Selection Operation Ê Join Operation : different algorithms to implement joins Ê Nested-loop join - Block nested-loop join Ê Indexed nested-loop join Ê Other Operations – an overview ÊQuery Optimization using Heuristics Ê Query tree, Graph tree Ê Transformation of Relational Expressions Ê Equivalence Rules Ê Pushing Selections, Join Ordering, etc. Ê Choice of Evaluation Plans Ê Structure of Query Optimizers Ê Evaluation of Expressions – Materialization, Pipelining ÊStatistics for Cost Estimation ÊA complement - Sorting
Basic Steps in Query Processing 1. Parsing and translation Ê translate the query into its internal form. This is then translated into relational algebra. C Query Tree, Graph Ê Parser checks syntax, verifies relations SQL query Parser & Translator Relational Algebra Expression Statistics About data 2. Query Optimization: The process of choosing a suitable execution strategy for processing a query. Query Optimizer Execution Plan next slides 3. Evaluation Engine Evaluation Ê The query-execution engine takes a query-evaluation plan, executes that plan, DATA Result 2
Basic Steps in Query Processing : Optimization C A relational algebra expression may have many equivalent expressions balance 2500( balance(account)) is equivalent to balance( balance 2500 (account)) Ê Each relational algebra operation can be evaluated using one of several different algorithms. Correspondingly, C a relational-algebra expression can be evaluated in many ways. Ê Annotated expression specifying detailed evaluation strategy is called an evaluation-plan. Examples: Ê can use an index on balance to find accounts with balance < 2500, Ê or can perform complete relation scan and discard accounts with balance 2500 Query Optimization: Among all equivalent evaluation plans choose the one with lowest cost. Cost is estimated using statistical information from the database catalog 3
Translating SQL Queries into Relational Algebra (1) Ê 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. Ê Nested queries within a query are identified as separate query blocks. Ê Aggregate operators in SQL must be included in the extended SELECT lname, fname FROM Employee WHERE Salary > ( SELECT MAX (Salary ) FROM Employee WHERE DNO = 5); SELECT lname, SELECT MAX fname (Salary) FROM Employee WHERE Salary WHERE DNO > = 5); πlname, fname (σSalary>C(Employee)) ℱMAX Salary (σDNO=5 (Employee)) 4
Measures of Query Cost Ê Cost is generally measured as total elapsed time for answering query. Many factors contribute to time cost: disk accesses, CPU, or even network communication Ê disk access: Typically is the predominant cost, and is also relatively easy Cost to write a block is greater than to estimate. Measured by taking into account cost to read a block P Number of seeks * average-seek-cost C data is read back after being written P Number of blocks read * average-block-read-cost to ensure that the write was P Number of blocks written * average-block-write-cost successful Ê For simplicity, we just use the number of block transfers from disk and the number of seeks as the cost measure t. T : time to transfer one block plus S seeks t. S : time for one seek Cost for b block transfers b * t. T + S * t. S We ignore CPU costs for simplicity - Real systems take CPU cost into account, differentiate between sequential and random I/O, and take buffer size into account Ê Several algorithms can reduce disk IO by using extra buffer space: 5
Algorithms for individual operations Query Processing- Several algorithms can reduce disk IO … Selection Operation balance 2500 File scan: search algorithms that locate and retrieve records that fulfill a selection condition. Algorithm A 1 (linear search): Scan each file block and test all records to see whether they satisfy the selection condition. br denotes number of blocks Ê Cost estimate = br block transfers + 1 seek containing records from relation r Ê If selection is on a key attribute, cost = (br /2) block transfers + 1 seek //stop on finding record P Linear search can be applied regardless of Ê selection condition or Ê ordering of records in the file, or Ê availability of indices Algorithm A 2 (binary search): Applicable if selection is an equality comparison on the attribute on which file is ordered. C Assume that the blocks of a relation are stored contiguously Ê Cost estimate (number of disk blocks to be scanned): cost of locating the first tuple by a binary search on the blocks log 2(br) * (t. T + t. S) + number of blocks containing records that satisfy selection condition 6
Algorithms for individual operations Query Processing- Several algorithms can reduce disk IO … Selections Using Indices Index scan: search algorithms that use an index selection condition must be on search-key of index. A 3 (primary index on candidate key, equality) - Retrieve a single record that satisfies the corresponding equality condition Ê Cost = (hi + 1) * (t. T + t. S) Ê Cost = HTi + 1 i. e. , the height of i. HTi: number of levels in index I A 4 (primary index on nonkey, equality) - Retrieve multiple records. Ê Records will be on consecutive blocks Ê Cost = hi * (t. T + t. S) + t. S + t. T * b where b = number of blocks containing matching records A 5 (equality on search-key of secondary index). Ê Retrieve a single record if the search-key is a candidate key + 1) * (t. T + t. S) Ê Retrieve multiple records if search-key is not a candidate key, each of n matching records may be on a different block + n) * (t. T + t. S) Cost = (hi 7
Algorithms for individual operations Query Processing- Several algorithms can reduce disk IO … Selections of the form Selections Involving Comparisons “ A<V (r) or A > V (r)” Selections can be implemented by using a linear file scan or binary search, or by using indices in the following ways: A 6 (primary index, comparison) - Relation is sorted on A Ê A V(r) use index to find first tuple v and scan relation sequentially from there Ê A V (r) just scan relation sequentially till first tuple > v; do not use index A 7 (secondary index, comparison). Ê A V(r) use index to find first index entry v and scan index sequentially from there, to find pointers to records. Ê A V (r) just scan leaf pages of index finding pointers to records, till first entry > v Ê In either case, retrieve records that are pointed to Ê requires an I/O for each record 8
Algorithms for individual operations Query Processing- Several algorithms can reduce disk IO … Implementation of Complex Selections Conjunction A 8 (conjunctive selection using one index). 1 2. . . n (r) Ê Select a combination of i and algorithms A 1 through A 7 that results in the least cost for i (r). Ê Test other conditions on tuple after fetching it into memory buffer. A 9 (conjunctive selection using multiple-key index) - Use appropriate composite (multiple-key) index if available. A 10 (conjunctive selection by intersection of identifiers). Ê Requires indices with record pointers. Ê Use corresponding index for each condition, and take of all the obtained sets of record pointers. Ê Then fetch records from file Disjunction: Ê If some conditions do not have appropriate indices, apply test in memory. A 11 (disjunctive selection by union of identifiers). 1 2 . . . n (r). Ê Applicable if all conditions have available indices - Otherwise use linear scan. Ê Use corresponding index for each condition, and take of all the obtained sets of record pointers. Ê Then fetch records from file Negation: (r) Ê Use linear scan on file 9
Algorithms for individual operations Join Operation Several different algorithms to implement joins ÊNested-loop join ÊBlock nested-loop join ÊIndexed nested-loop join ÊMerge-join ÊHash-join for more details about Merge and Hash join algorithms Refer to used text. C Choice based on cost estimate books 10
Algorithms for individual operations Algorithms to implement joins Join Operation: Theta join Nested-Loop Join R S for each tuple tr in r do begin for each tuple ts in s do begin ts tr join condition test pair (tr, ts) to see if they satisfy the r s if they do, add tr • ts to the result. inner end relation outer end relation Ê r is called the outer relation and s the inner relation of the join. J Requires no indices and can be used with any kind of join condition. Ê Expensive since it examines every pair of tuples in the two relations. Custo Deposit mer or Number of 10, 000 5000 Analysis records ‘n’ Number of blocks 400 if there is enough memory only to hold one block of each relation, 100 ‘b’ the estimated cost is n *b + b block transfer + (n + b seeks). r s r r r If the smaller relation fits entirely in memory, use that as the inner relation. Reduces cost to br + bs disk accesses. Assuming worst case memory availability cost estimate is Ê with depositor as outer relation: 5000 400 + 100 = 2, 000, 100 + (5000+100 seeks) Ê with customer as the outer relation: 10000 100 + 400 = 1, 000, 400 + (10000+400 11
Algorithms for individual operations Algorithms to implement joins Join Operation: Block Nested-Loop Join For each block Br of r do Variant of nested-loop join in for each block Bs of s do for each tuple tr in Br do which every block of inner relation is paired with every for each tuple ts in block Bs doof outer relation. Check if (tr, ts) satisfy the join condition if they do, add tr • ts to the result. end Previous end case end n *b + r Analysis s br Worst case estimate: br bs + br block transfers + 2 * br seeks Each block in the inner relation s is read once for each block in the outer relation (instead of once for each tuple in the outer relation Best case: br + bs block transfers + 2 seeks. 12
Algorithms for individual operations Algorithms to implement joins Join Operation: Indexed Nested-Loop Join Index lookups can replace file scans if Ê join is an equi-join or natural join Ê and an index is available on the inner relation’s join attribute (Can construct a temporary index). ü For each tuple tr in the outer relation r, use the index to look up tuples in s that satisfy the join condition with tuple tr. Analysis - Worst case: buffer has space for only one page of r, and, for each tuple in r, we perform an index lookup on s. Ê Cost of the join: br + nr c, Ê where c is the cost of traversing index and fetching all matching s tuples for one tuple or r, customer has 10, 000 records, c can be estimated as cost of a single selection on s using the join condition. the tree depth = 4, and one If indices are available on join attributes of both r and s, use theaccess relation with fewer more is needed to find the actual data tuples as the outer relation. depositor has 5000 records Example of Nested-Loop Join Costs: depositor customer With depositor as the outer relation and customer have a primary B+-tree index on the join attribute c-name, which contains 20 entries in each index node. 13
Algorithms for individual operations Complex Joins Join with a conjunctive condition: r 1 2. . . n Ê Either use nested loops/block nested loops, Ê Or, Compute the result of one of the simpler joins (r i s) final result comprises those tuples in the intermediate result that satisfy the remaining conditions s 1 . . . i – 1 i +1 . . . n r Join with a disjunctive condition 1 2 . . . n Ê Either use nested loops/block nested loops, Ê Or, Compute as the union of the records in individual joins (r i s): (r 1 s) (r 2 s) . . . (r n s) 14 s
Algorithms for individual operations Other Operations Duplicate elimination can be implemented via hashing or sorting. Ê On sorting duplicates will come adjacent to each other, and all but one set of duplicates can be deleted. Optimization: duplicates can be deleted during run generation as well as at intermediate merge steps in external sort-merge. Ê Hashing is similar – duplicates will come into the same bucket. Projection is implemented by performing projection on each tuple followed by duplicate elimination. Aggregation can be implemented in a manner similar to duplicate elimination. Ê Sorting or hashing can be used to bring tuples in the same group together, and then the aggregate functions can be applied on each group. Ê Optimization: combine tuples in the same group during run generation and intermediate merges, by computing partial aggregate values Ê For count, min, max, sum: keep aggregate values on tuples found so far in the group. Ê For avg, keep sum and count, and divide sum by count at the end Set operations ( , and ): can either use variant of merge-join after sorting, or hash-join. Outer join: can be computed either as 15
Query Optimization Using Heuristics
Query Optimization Using Heuristics in Query Optimization(1) Process for heuristics optimization 1. 2. 3. The parser of a high-level query generates an initial internal representation; Apply heuristics rules to optimize the internal representation. A query execution plan is generated to execute groups of operations based on the access paths available on the files involved in the query. Ê The main heuristic is to apply first the operations that reduce the size of intermediate results. C E. g. , Apply SELECT and PROJECT operations before applying the JOIN or other binary operations. 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. 17
Query Optimization - using Heuristics An overview Ê Equivalent expressions Ê Different algorithms for each operation Alternative ways of evaluating a given query An evaluation plan defines exactly: Ê what algorithm is used for each operation, Ê and how the execution of the operations is coordinated. Steps in cost-based query optimization Ê Generate logically equivalent expressions using equivalence rules Ê Choose the cheapest plan based on estimated cost Estimation of plan cost based on: Ê Statistical information about relations number of tuples, number of distinct 18 values for an attribute
Generating Equivalent Expressions Transformation of Relational Expressions Equivalence Rules (1/2) 1. Conjunctive selection operations can be deconstructed into a sequence of individual selections. 2. Selection operations are commutative. 3. Only the last in a sequence of projection operations is needed, the others can be omitted. 4. Selections can be combined with Cartesian products and theta joins. (E 1 X E 2) = E 1 E 2 1(E 1 2 E 2) = E 1 1 2 E 2 5. Theta-join operations (and natural joins) are commutative: E 1 E 2 = E 2 E 1 6. (a) Natural join operations are associative: (E 1 E 2) E 3 = E 1 (E 2 E 3) (b) Theta joins are associative in the following manner: (E 1 1 E 2) 2 3 E 3 = E 1 1 3 (E 2 2 E 3) where 2 involves attributes from only E 2 and E 3. 7. The selection operation distributes over theta join operation under the following two conditions: 19
Generating Equivalent Expressions Transformation of Relational Expressions Equivalence Rules (1/2) 8. The projection operation distributes over theta join operation as follows: (a)if involves only attributes from L 1 L 2: L 1 L 2 E 1 E 2) = ( L 1(E 1)) ( L (E 2)) (b)Consider a join E 1 E 2. Ê Ê Ê Let L 1 and L 2 be sets of attributes from E 1 and E 2, respectively. Let L 3 be attributes of E 1 that are involved in join condition , but are not in L 1 L 2, and Let L 4 be attributes of E 2 that are involved in join condition , but are not in L 1 L 2 E 1 E 2) = L 1 L 2 ( ( L 1 L 3 (E 1)) ( L 2 L 4 (E 2)) ) 9. The set operations union and intersection are commutative: E 1 E 2 = E 2 E 1 , E 1 E 2 = E 2 E 1 10. Set union and intersection are associative. (E 1 E 2) E 3 = E 1 (E 2 E 3) , E 1 E 2) E 3 = E 1 (E 2 E 3) 11. The selection operation distributes over , and –. (E 1 – E 2) = (E 1) – (E 2) and similarly for and in place of – Also: (E – E ) = (E ) – E and similarly for in place 20 of
Generating Equivalent Expressions Transformation of Relational Expressions Example- Pushing Selections Query: Find the names of all customers who have an account at some branch located in Brooklyn. customer_name( branch_city = “Brooklyn” branch (account depositor))) Transformation using rule 7 a ( 0 E 1 E 2) = ( 0(E 1)) E 2 ). customer_name (( branch_city =“Brooklyn” (branch)) (account depositor)) 21
Generating Equivalent Expressions Example - with Multiple Transformations Query: Find the names of all customers with an account at a Brooklyn branch whose account balance is over $1000. customer_name ( branch_city = “Brooklyn” balance > 1000 (branch (account depositor))) Transformation using join associatively (Rule 6 a): customer_name(( branch_city = “Brooklyn” balance > 1000 (branch account)) depositor) Second form provides an opportunity to apply the “perform selections early” rule, resulting in the subexpression branch_city = “Brooklyn” (branch) balance > 1000 (account) 22
Query Optimization Join Ordering For all relations r 1, r 2, and r 3, (r 1 r 2) r 3 = r 1 (r 2 r 3 ) If r 2 r 3 is quite large and r 1 r 2 is small, we choose (r 1 r 2) r 3 Example: Consider the expression customer_name (( branch_city = “Brooklyn” (branch)) (account depositor)) Ê Could compute (account depositor) first, and join result with ( branch_city = “Brooklyn” (branch) Ê but (account depositor) is likely to be a large relation. Only a small fraction of the bank’s customers are likely to have accounts in branches located in Brooklyn 23
Query Optimization- Using Heuristics Summary of Heuristics for Algebraic Optimization: 1. The main heuristic is to apply first the operations that reduce the size of intermediate results. 2. Perform select operations as early as possible to reduce the number of tuples and perform 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. ) 3. The select and join operations that are most restrictive 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. ) 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. 24
Choice of Evaluation Plans ÊMust consider the interaction of evaluation techniques when choosing evaluation plans Ê choosing the cheapest algorithm for each operation independently may not yield best overall algorithm. Ê Practical query optimizers incorporate elements of the following two broad approaches: 1. Search all the plans and choose the best plan in a cost-based fashion. 2. Uses heuristics to choose a plan. ÊCost-Based Optimization Ê Consider finding the best join-order for r 1 r 2 . . . rn. Ê There are (2(n – 1))!/(n – 1)! different join orders for above expression. With n = 7, the number is 665280, with n = 10, the number is greater than 176 billion! C No need to generate all the join orders. C Using dynamic programming, the least-cost join order for any subset of {r 1, r 2, 25. . . rn} is computed only once and stored for future use.
Structure of Query Optimizers Ê Many optimizers considers only left-deep join orders. Ê Plus heuristics to push selections and projections down the query tree Ê Reduces optimization complexity and generates plans amenable to pipelined evaluation. Ê Heuristic optimization used in some versions of Oracle Ê Intricacies of SQL complicate query optimization. E. g. nested subqueries Ê Some query optimizers integrate heuristic selection and the generation of alternative access plans. Ê Frequently used approach Ê heuristic rewriting of nested block structure and aggregation Ê followed by cost-based join-order optimization for each block Ê Some optimizers (e. g. SQL Server) apply transformations to entire query and do not depend on block structure Ê Even with the use of heuristics, cost-based query optimization imposes a substantial overhead. Ê But is worth it for expensive queries Ê Optimizers often use simple heuristics for very cheap queries, and perform exhaustive enumeration for more expensive queries 26
Evaluation of Expressions Alternatives for evaluating an entire expression tree ÊMaterialization: generate results of an expression whose inputs are relations or are already computed, materialize (store) it on disk. Repeat. ÊPipelining: pass on tuples to parent operations even as an operation is being executed 27
Alternatives for evaluating an expression tree Evaluation of Expressions Materialization Materialized evaluation: Ê Ê Ê Evaluate one operation at a time, Starting at the lowest-level. Use intermediate results materialized into temporary relations to evaluate next-level operations. E. g. , in figure below, “ customer-name( balance 2500 1. compute and store “ balance 2500 (account)" 2. 3. (account) customer)" then compute the store its join with customer, and finally compute the projections on customer-name. Ê Materialized evaluation is always applicable Ê Cost of writing results to disk and reading them back can be quite high Overall cost = Sum of costs of individual operations + cost of writing intermediate results to disk Ê Double buffering: use two output buffers for each operation, when one is full write it to disk while the other is getting filled 28
Alternatives for evaluating an expression tree Evaluation of Expressions Pipelining evaluation (1/2) evaluate several operations simultaneously, passing the results of one operation on to the next. Ê E. g. , in expression tree, Ê don’t store result of “ balance 2500 (account)" Ê instead, pass tuples directly to the join. . Similarly, don’t store result of join, pass tuples directly to projection. Evaluations: Ê Much cheaper than materialization: no need to store a temporary relation to disk. Ê Pipelining may not always be possible – e. g. , sort, hash-join. Ê For pipelining to be effective, use evaluation algorithms that generate output tuples even as tuples are received for inputs to the operation. Ê Pipelines can be executed in two ways: demand driven and producer 29
Alternatives for evaluating an expression tree Evaluation of Expressions Pipelines can be executed in two ways: demand driven and producer driven Ê In demand driven or lazy evaluation Pipelining (2/2) Ê system repeatedly requests next tuple from top level operation Ê Each operation requests next tuple from children operations as required, in order to output its next tuple Ê In between calls, operation has to maintain “state” so it knows what to return next Ê Each operation is implemented as an iterator implementing open/next/close operations Ê In produce-driven or eager pipelining Ê Operators produce tuples eagerly and pass them up to their parents Ê Buffer maintained between operators, child puts tuples in buffer, parent removes tuples from buffer Ê if buffer is full, child waits till there is space in the buffer, and then generates more tuples Ê System schedules operations that have space in output buffer and can process more input tuples Evaluation Ê Some algorithms are not able to output results even as they get input tuples Ê E. g. merge join, or hash join 30
Assignment - Complex Join involving three rela Joins loan depositor c Strategy 1. Compute “depositor customer”; use result to compute loan customer) Strategy 2. Computer “loan result with customer. (depositor depositor” first, and then join the customer Indexed on loan-number depositor Strategy 3. Ê Perform the pair of joins at once. each t loan Indexed on customer-na Ê Build and index on loan for loan-number, and on customer for customer-name. Ê For each tuple t in depositor, look up the corresponding tuples in customer and the corresponding tuples in loan. Ê Each tuple of deposit is examined exactly once. Evaluation: 31
Information for Cost Estimation Statistics for Cost Estimation nr: number of tuples in a relation r. br: number of blocks containing tuples of r. sr: size of a tuple of r. fr: blocking factor of r. i. e. , the number of tuples of r that fit into one block. V(A, r): number of distinct values that appear in r for attribute A; same as the size of A(r). SC(A, r): selection cardinality of attribute A of relation r; average number of records that satisfy equality on A. If tuples of r are stored together physically in a file, then:
Selection Size Estimation Ê A=v(r) selection nr / V(A, r) : number of records that will satisfy the equality condition on a key attribute: size estimate = 1 Ê A V(r) (case of A V(r) is symmetric) Ê Let c denote the estimated number of tuples satisfying the condition. Ê If min(A, r) and max(A, r) are available in catalog Ê c = 0 if v < min(A, r) Ê c= Ê In absence of statistical information c is assumed to be nr / 2. Size Estimation of Complex Selections The selectivity of a condition i is the probability that a tuple in the relation r satisfies i. If si is the number of satisfying tuples in r, the selectivity of i is given by si /nr. Ê Conjunction: 1 2. . . n (r). Ê Assuming impendence, estimate of tuples in the result is: Ê Disjunction: 1 2 . . . n (r). Estimated number of tuples: 33
Join Operation: Running Example Running example: depositor customer Catalog information for join examples: ncustomer = 10, 000. fcustomer = 25, which implies that bcustomer =10000/25 = 400. ndepositor = 5000. fdepositor = 50, which implies that bdepositor = 5000/50 = 100. V(customer-name, depositor) = 2500, which implies that , on average, each customer has two accounts. Also assume that customer-name in depositor is a foreign key on customer. V(customer_name, customer) = 10000 (primary key!) 34
Estimation of the Size of Joins Ê The Cartesian product r x s contains nr. ns tuples; each tuple occupies sr + ss bytes. Ê If R S = , then r s is the same as r x s. Ê If R S is a key for R, then a tuple of s will join with at most one tuple from r Ê therefore, the number of tuples in r s is no greater than the number of tuples in s. Ê If R S in S is a foreign key in S referencing R, then the number of tuples in r s is exactly the same as the number of tuples in s. Ê The case for R S being a foreign key referencing S is symmetric. Ê In the example query depositor customer, customer_name in depositor is a foreign key of customer Ê hence, the result has exactly ndepositor tuples, which is 5000 Ê If R S = {A} is not a key for R or S. If we assume that every tuple t in R produces tuples in R S, the number of tuples in R S, is estimated to be: Ê If the reverse is true, the estimate obtained will be: The lower of these two estimates is probably the more accurate one. Ê Compute the size estimates for depositor customer without using information about foreign keys: Ê V(customer_name, depositor) = 2500, and V(customer_name, customer) = 10000 35
A complement Sorting Ê We may build an index on the relation, and then use the index to read the relation in sorted order. May lead to one disk block access for each tuple. Ê For relations that fit in memory, techniques like quicksort can be used. Ê For relations that don’t fit in memory, external sort-merge is a good choice.
A complement - Sorting External Sort-Merge Let M denote memory size (in pages). Create sorted runs. Let i be 0 initially. Repeatedly do the following till the end of the relation: (a) Read M blocks of relation into memory (b) Sort the in-memory blocks (c) Write sorted data to run Ri; increment i. Let the final value of I be N Merge the runs (N-way merge). We assume (for now) that N < M. Ê Ê Use N blocks of memory to buffer input runs, and 1 block to buffer output. Read the first block of each run into its buffer page repeat 1. 2. 3. Ê Select the first record (in sort order) among all buffer pages Write the record to the output buffer. If the output buffer is full write it to disk. Delete the record from its input buffer page. If the buffer page becomes empty then read the next block (if any) of the run into the buffer. until all input buffer pages are empty: If i M, several merge passes are required. Ê Ê In each pass, contiguous groups of M - 1 runs are merged. A pass reduces the number of runs by a factor of M -1, and creates runs longer by the same factor. E. g. If M=11, and there are 90 runs, one pass reduces the number of runs to 9, each 10 times the size of the initial runs Ê Repeated passes are performed till all runs have been merged into one. 37
A complement - Sorting Sort-Merge, an External example Sorting Using Cost analysis: Sort-Merge Ê Total number of merge passes required: log. M– 1(br/M). Ê Disk accesses for initial run creation as well as in each pass is 2 br Ê Thus total number of disk accesses for external sorting: br ( 2 log. M– 1(br / M) + 1) Cost of seeks Ê During run generation: one seek to read each run and one seek to write each run 2 br / M Ê During the merge phase Ê Buffer size: bb (read/write bb blocks at a time) Ê Need 2 br/bb seeks for each merge pass Ê except the final one which does not 38
- Slides: 38