Chap 13 Query Processing 9 Database System Concepts
Chap 13 Query Processing 中文版:第 9章 “查詢處理” Database System Concepts, 5 th Ed. ©Silberschatz, Korth and Sudarshan See www. db-book. com for conditions on re-use
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 2 ©Silberschatz, Korth and Sudarshan
Basic Steps in Query Processing 1. Parsing and translation (分析和轉譯) 2. Optimization (最佳化) Ch 13 (Alg's) 3. Evaluation (執行運算) Ch 14 (Plans) Metadata: #tuples #attributes Index ? Size estimation etc. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 3 ©Silberschatz, Korth and Sudarshan
Basic Steps in Query Processing (Cont. ) n Parsing and translation l Parser checks syntax, verifies relations. l Translate the query into its internal form. (內建 table or tree) l This is then translated into relational algebra. (代數模式) n Evaluation The query-execution engine l takes a query-evaluation plan, l executes that plan, and l returns the answers to the query. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 4 ©Silberschatz, Korth and Sudarshan
Basic Steps in Query Processing : Optimization n A relational algebra expression may have many equivalent expressions l E. g. , balance 2500( balance(account)) is equivalent to balance( balance 2500(account)) Chap 14 n Each relational algebra operation can be evaluated using one of several different algorithms Chap 13 l Correspondingly, a relational-algebra expression can be evaluated in many ways. n Annotated expression specifying detailed evaluation strategy is called an evaluation-plan. l E. g. , can use an index on balance to find accounts with balance < 2500, l or can perform complete relation scan and discard accounts with balance 2500 Database System Concepts, 5 th Edition, Oct 5, 2006 13. 5 ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 6 ©Silberschatz, Korth and Sudarshan
Measures of Query Cost n Cost is generally measured as total elapsed time for answering query l Many factors contribute to time cost 4 disk accesses, CPU, or even network communication n Typically disk access is the predominant cost, and is also relatively easy to estimate. Measured by taking into account l Number of seeks * average-seek-cost l Number of blocks read * average-block-read-cost l Number of blocks written * average-block-write-cost 4 Cost to write a block is greater than cost to read a block – data is read back after being written to ensure that the write was successful Database System Concepts, 5 th Edition, Oct 5, 2006 13. 7 ©Silberschatz, Korth and Sudarshan
Measures of Query Cost (Cont. ) n For simplicity we just use the number of block transfers from disk and the number of seeks as the cost measures l t. T – time to transfer one block l t. S – time for one seek l Cost for b block transfers plus S seeks b * t. T + S * t. S n We ignore CPU costs for simplicity l Real systems do take CPU cost into account n We do not include cost to writing output to disk in our cost formulae n Several algorithms can reduce disk IO by using extra buffer space Amount of real memory available to buffer depends on other concurrent queries and OS processes, known only during execution 4 We often use worst case estimates, assuming only the minimum amount of memory needed for the operation is available n Required data may be buffer resident already, avoiding disk I/O l But hard to take into account for cost estimation l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 8 ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 9 ©Silberschatz, Korth and Sudarshan
Recall: Sequential Records in File n Deletion – use pointer chains n Insertion –locate the position where the record is to be inserted l if there is free space insert there l if no free space, insert the record in an overflow block l In either case, pointer chain must be updated n Need to reorganize the file from time to restore sequential order Database System Concepts, 5 th Edition, Oct 5, 2006 13. 10 ©Silberschatz, Korth and Sudarshan
Selection Operation n File scan – search algorithms that locate and retrieve records that fulfill a selection condition. n Algorithm A 1 (linear search). Scan each file block and test all records to see whether they satisfy the selection condition. l Assume that the blocks of a relation are stored contiguously l Cost estimate = br block transfers + 1 seek (讓系統得知何處) 4 br denotes number of blocks containing records from relation r l If selection is on a key attribute, can stop on finding record 4 cost l = (br /2) * t. T + t. S Linear search can be applied regardless of 4 selection 4 or condition or ordering of records in the file, availability of indices (有索引亦適用,但非去使用索引) Database System Concepts, 5 th Edition, Oct 5, 2006 13. 11 ©Silberschatz, Korth and Sudarshan
Selection Operation (Cont. ) n A 2 (binary search). Applicable if selection is an equality comparison on the attribute on which file is ordered. l Assume that the blocks of a relation are stored contiguously l Cost estimate (number of disk blocks to be scanned): 4 cost of locating the first tuple by a binary search on the blocks – log 2(br) * (t. T + t. S) 4 If (seek: 讓系統得知何處取得) there are multiple records satisfying selection – Add transfer cost of the number of blocks containing records that satisfy selection condition – Will see how to estimate this cost in Chapter 14 Database System Concepts, 5 th Edition, Oct 5, 2006 13. 12 ©Silberschatz, Korth and Sudarshan
Selections Using Indices n Index scan – search algorithms that use an index selection condition must be on search-key of index. n A 3 (primary index on candidate key, equality). Retrieve a single record that satisfies the corresponding equality condition l Cost = (hi + 1) * (t. T + t. S) n A 4 (primary index on nonkey, equality) Retrieve multiple records. l Records will be on consecutive blocks 4 Let b = number of blocks containing matching records l Cost = hi * (t. T + t. S) + t. S + t. T * b Primary Index 所指鍵值為原生順序 n A 5 (in case of secondary index, equality). l Retrieve a single record if the search-key is a candidate key 4 Cost = (hi + 1) * (t. T + t. S) 和 Primary Index 一樣,足顯示 B+ tree 威力 l Retrieve multiple records if search-key is not a candidate key 4 each of n matching records may be on a different block 4 Cost = (hi + n) * (t. T + t. S) Secondary Index 所指鍵值非原生順序 – Can be very expensive! 所以就必須 one-trans one-seek l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 13 ©Silberschatz, Korth and Sudarshan
Selections Using Indices (cont. ) n Index scan – search algorithms that use an index selection condition must be on search-key of index. n A 3 (primary index on candidate key, equality). Retrieve a single record that satisfies the corresponding equality condition (hi + 1) block transfer l Cost = (hi + 1) * (t. T + t. S) n A 4 (primary index on nonkey, equality) Retrieve multiple records. l Records will be on consecutive blocks 4 Let b = number of blocks containing matching records l Cost = hi * (t. T + t. S) + t. S + t. T * b (hi + b) block transfer n A 5 (in case of secondary index, equality). l Retrieve a single record if the search-key is a candidate key 4 Cost = (hi + 1) * (t. T + t. S) (hi + 1) block transfer l Retrieve multiple records if search-key is not a candidate key 4 each of n matching records may be on a different block 4 Cost = (hi + n) * (t. T + t. S) (hi + n) block transfer – Can be very expensive! l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 14 ©Silberschatz, Korth and Sudarshan
Join Operation n Several different algorithms to implement joins l Nested-loop join l Block nested-loop join l Indexed nested-loop join l Merge-join l Hash-join 只觀察 #(block transfer) nc=10, 000 n Choice based on cost estimate nd=5000 n Examples use the following information l Number of records of customer: 10, 000 depositor: 5000 l Number of blocks of customer: depositor: 100 400 bc=400 Database System Concepts, 5 th Edition, Oct 5, 2006 13. 15 bd=100 ©Silberschatz, Korth and Sudarshan
Nested-Loop Join n To compute theta join r s for each tuple tr in r do begin for each tuple ts in s do begin test pair (tr, ts) to see if they satisfy the join condition if they do, add tr • ts to the result. end n r is called the outer relation and s the inner relation of the join. n Requires no indices and can be used with any kind of join condition. n Expensive since it examines every pair of tuples in the two relations. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 16 ©Silberschatz, Korth and Sudarshan
Nested-Loop Join (Cont. ) n In the worst case, if there is enough memory only to hold one block of each relation, the estimated cost is nr bs + b r block transfers, plus seeks n If the smaller relation fits entirely in memory, use that as the inner relation. l n nr + br Reduces cost to br + bs block transfers and 2 seeks Assuming worst case memory availability cost estimate is l l with depositor as outer relation: 4 5000 400 + 100 = 2, 000, 100 block transfers, 4 5000 + 100 = 5100 seeks with customer as the outer relation 4 10000 100 + 400 = 1, 000, 400 block transfers and 10, 400 seeks n If smaller relation (depositor) fits entirely in memory, the cost estimate will be 500 block transfers. n Block nested-loops algorithm (next slide) is preferable. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 17 ©Silberschatz, Korth and Sudarshan
Block Nested-Loop Join n Variant of nested-loop join in which every block of inner relation is paired with every block of outer relation. for each block Br of r do begin for each block Bs of s do begin for each tuple tr in Br do begin for each tuple ts in Bs do begin Check if (tr, ts) satisfy the join condition if they do, add tr • ts to the result. end end Database System Concepts, 5 th Edition, Oct 5, 2006 13. 18 ©Silberschatz, Korth and Sudarshan
Block Nested-Loop Join (Cont. ) n 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 n Best case: br + bs block transfers + 2 seeks. n Improvements to nested loop and block nested loop algorithms: l In block nested-loop, use M — 2 disk blocks as blocking unit for outer relations, where M = memory size in blocks; use remaining two blocks to buffer inner relation and output l 4 Cost = br / (M-2) bs + br block transfers + 2 br / (M-2) seeks If equi-join attribute forms a key or inner relation, stop inner loop on first match l Scan inner loop forward and backward alternately, to make use of the blocks remaining in buffer (with LRU replacement) l Use index on inner relation if available (next slide) l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 19 ©Silberschatz, Korth and Sudarshan
Indexed Nested-Loop Join n Index lookups can replace file scans if l join is an equi-join or natural join and l an index is available on the inner relation’s join attribute 4 Can construct an index just to compute a join. n 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. n Worst case: buffer has space for only one page of r, and, for each tuple in r, we perform an index lookup on s. n Cost of the join: br (t. T + t. S) + nr c br + nr* (hi+1) block transfer l Where c is the cost of traversing index and fetching all matching s tuples for one tuple or r l c can be estimated as cost of a single selection on s using the join condition. n If indices are available on join attributes of both r and s, use the relation with fewer tuples as the outer relation. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 20 ©Silberschatz, Korth and Sudarshan
Example of Nested-Loop Join Costs n Compute depositor customer, with depositor as the outer relation. n Let customer have a primary B+-tree index on the join attribute customer-name, which contains 20 entries in each index node. n Since customer has 10, 000 tuples, the height of the tree is 4, and one more access is needed to find the actual data n depositor has 5000 tuples nc=10, 000 nd=5000 n Cost of block nested loops join bc=400 bd=100 l 100*400 + 100 = 40, 100 block transfers + 2 * 100 = 200 seeks 4 assuming worst case memory 4 may n be significantly less with more memory Cost of indexed nested loops join l 100 + 5000 * 5 = 25, 100 block transfers and seeks. l CPU cost likely to be less than that for block nested loops join Database System Concepts, 5 th Edition, Oct 5, 2006 13. 21 ©Silberschatz, Korth and Sudarshan
Evaluation of Expressions n So far: we have seen algorithms for individual operations n Alternatives for evaluating an entire expression tree l Materialization: generate results of an expression whose inputs are relations or are already computed, materialize (store) it on disk. Repeat. l Pipelining: pass on tuples to parent operations even as an operation is being executed l Pipelining are not always be possible l Hybrid: generate output even as tuples are received for inputs to the operation. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 22 ©Silberschatz, Korth and Sudarshan
Pipelining n Pipelined evaluation : evaluate several operations simultaneously, passing the results of one operation on to the next. n E. g. , in previous expression tree, don’t store result of l instead, pass tuples directly to the join. . Similarly, don’t store result of join, pass tuples directly to projection. n Much cheaper than materialization: no need to store a temporary relation to disk. n Pipelining may not always be possible – e. g. , sort, hash-join. n For pipelining to be effective, use evaluation algorithms that generate output tuples even as tuples are received for inputs to the operation. n Pipelines can be executed in two ways: demand driven and producer driven Database System Concepts, 5 th Edition, Oct 5, 2006 13. 23 ©Silberschatz, Korth and Sudarshan
n break Database System Concepts, 5 th Edition, Oct 5, 2006 13. 24 ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 25 ©Silberschatz, Korth and Sudarshan
Selection Operation n File scan – search algorithms that locate and retrieve records that fulfill a selection condition. n Algorithm A 1 (linear search). Scan each file block and test all records to see whether they satisfy the selection condition. l Cost estimate = br block transfers + 1 seek (讓系統得知何處) 4 br denotes number of blocks containing records from relation r l If selection is on a key attribute, can stop on finding record 4 cost l = (br /2) * t. T + t. S Linear search can be applied regardless of 4 selection 4 or condition or ordering of records in the file, availability of indices (有索引亦適用,但非去使用索引) Database System Concepts, 5 th Edition, Oct 5, 2006 13. 26 ©Silberschatz, Korth and Sudarshan
Selection Operation (Cont. ) n A 2 (binary search). Applicable if selection is an equality comparison on the attribute on which file is ordered. l Assume that the blocks of a relation are stored contiguously l Cost estimate (number of disk blocks to be scanned): 4 cost of locating the first tuple by a binary search on the blocks – log 2(br) * (t. T + t. S) 4 If (seek: 讓系統得知何處取得) there are multiple records satisfying selection – Add transfer cost of the number of blocks containing records that satisfy selection condition – Will see how to estimate this cost in Chapter 14 Database System Concepts, 5 th Edition, Oct 5, 2006 13. 27 ©Silberschatz, Korth and Sudarshan
Selections Using Indices n Index scan – search algorithms that use an index selection condition must be on search-key of index. n A 3 (primary index on candidate key, equality). Retrieve a single record that satisfies the corresponding equality condition l Cost = (hi + 1) * (t. T + t. S) n A 4 (primary index on nonkey, equality) Retrieve multiple records. l Records will be on consecutive blocks 4 Let b = number of blocks containing matching records l Cost = hi * (t. T + t. S) + t. S + t. T * b Primary Index 所指鍵值為原生順序 n A 5 (in case of secondary index, equality). l Retrieve a single record if the search-key is a candidate key 4 Cost = (hi + 1) * (t. T + t. S) 和 Primary Index 一樣,足顯示 B+ tree 威力 l Retrieve multiple records if search-key is not a candidate key 4 each of n matching records may be on a different block 4 Cost = (hi + n) * (t. T + t. S) Secondary Index 所指鍵值非原生順序 – Can be very expensive! 所以就必須 one-trans one-seek l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 28 ©Silberschatz, Korth and Sudarshan
Selections Involving Comparisons n Can implement selections of the form A V (r) or A V(r) by using a linear file scan or binary search, l or by using indices in the following ways: n A 6 (primary index, comparison). (Relation is sorted on A) 4 For A V(r) use index to find first tuple v and scan relation sequentially from there (找到第一筆之後,就不需要 index) 4 For A V (r) just scan relation sequentially till first tuple > v; do not use index (根本就不需要 index) n A 7 (secondary index, comparison). 4 For A V(r) use index to find first index entry v and scan index sequentially from there, to find pointers to records. 4 For A V (r) just scan leaf pages of index finding pointers to records, till first entry > v 4 In either case, retrieve records that are pointed to – requires an I/O for each record – Linear file scan may be cheaper l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 29 ©Silberschatz, Korth and Sudarshan
Implementation of Complex Selections n Conjunction: 1 2. . . n(r) n A 8 (conjunctive selection using one index). l l 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. n A 9 (conjunctive selection using multiple-key index). l Use appropriate composite (multiple-key) index if available. n A 10 (conjunctive selection by intersection of identifiers). l Requires indices with record pointers. l Use corresponding index for each condition, and take intersection of all the obtained sets of record pointers. l Then fetch records from file l If some conditions do not have appropriate indices, apply test in memory. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 30 ©Silberschatz, Korth and Sudarshan
Algorithms for Complex Selections n Disjunction: 1 2 . . . n (r). n A 11 (disjunctive selection by union of identifiers). l Applicable if all conditions have available indices. 4 Otherwise use linear scan. l Use corresponding index for each condition, and take union of all the obtained sets of record pointers. l Then fetch records from file n Negation: (r) l Use linear scan on file l If very few records satisfy , and an index is applicable to 4 Find satisfying records using index and fetch from file Database System Concepts, 5 th Edition, Oct 5, 2006 13. 31 ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 32 ©Silberschatz, Korth and Sudarshan
Sorting n 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. n 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. Example: 依 ISBN 重整書架 (1) 查卡片一本一本搬 (2) 整車整車拉過來排 Database System Concepts, 5 th Edition, Oct 5, 2006 13. 33 ©Silberschatz, Korth and Sudarshan
External Sort-Merge Let M denote memory size (in pages, i. e. , blocks). 1. 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 2. Merge the runs (next slide)…. . Memory size = M (pages / blocks) Load for sort = N (runs) Relation (Table) Size = M x N Database System Concepts, 5 th Edition, Oct 5, 2006 13. 34 ©Silberschatz, Korth and Sudarshan
External Sort-Merge (Cont. ) 2. Merge the runs (N-way merge). We assume (for now) that N < M. 1. 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 2. repeat 3. 1. Select the first record (in sort order) among all buffer pages 2. Write the record to the output buffer. If the output buffer is full write it to disk. 3. 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: Example: M=6, N=4 (同步重建index, if any) Database System Concepts, 5 th Edition, Oct 5, 2006 13. 35 ©Silberschatz, Korth and Sudarshan
Example: Sort Merge (M>N) "N" Input Buffers B E F M=6, N=4 D G L "1" Output Buffer A B C D E F H P Q A C K M (blocks) x N (runs) if N=3 ? Database System Concepts, 5 th Edition, Oct 5, 2006 13. 36 Mx. N blocks Nonparti cipating Memory Spaces if N=20 ? ©Silberschatz, Korth and Sudarshan
External Sort-Merge (Cont. ) n If N M, several merge passes are required. l In each pass, contiguous groups of M - 1 runs are merged. l A pass reduces the number of runs by a factor of M -1, and creates runs longer by the same factor. 4 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 l Repeated passes are performed till all runs have been merged into one. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 37 ©Silberschatz, Korth and Sudarshan
Example: External Sorting Using Sort-Merge Example: M=3, N=4 Block size 以 1 record 做代表 M-1=2 (1 output buffer) merge 2 runs in a pass N=4 剛好分作 2 passes Database System Concepts, 5 th Edition, Oct 5, 2006 13. 38 ©Silberschatz, Korth and Sudarshan
External Merge Sort (Cont. ) n Cost analysis: l Total number of merge passes required: log. M– 1(br/M). l Block transfers for initial run creation as well as in each pass is 2 br 4 for final pass, we don’t count write cost – we ignore final write cost for all operations since the output of an operation may be sent to the parent operation without being written to disk 4 Thus l total number of block transfers for external sorting: br ( 2 log. M– 1(br / M) + 1) Seeks: next slide Database System Concepts, 5 th Edition, Oct 5, 2006 13. 39 ©Silberschatz, Korth and Sudarshan
External Merge Sort (Cont. ) n Cost of seeks l During run generation: one seek to read each run and one seek to write each run 4 l 2 br / M During the merge phase 4 Buffer size: bb (read/write bb blocks at a time) 4 Need 2 br / bb seeks for each merge pass – except the final one which does not require a write 4 Total number of seeks: 2 br / M + br / bb (2 log. M– 1(br / M) -1) Database System Concepts, 5 th Edition, Oct 5, 2006 13. 40 ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 41 ©Silberschatz, Korth and Sudarshan
Join Operation n Several different algorithms to implement joins l Nested-loop join l Block nested-loop join l Indexed nested-loop join l Merge-join l Hash-join nc=10, 000 n Choice based on cost estimate nd=500 n Examples use the following information l Number of records of customer: 10, 000 depositor: 5000 l Number of blocks of customer: depositor: 100 400 bc=400 Database System Concepts, 5 th Edition, Oct 5, 2006 13. 42 bd=100 ©Silberschatz, Korth and Sudarshan
Nested-Loop Join n To compute theta join r s for each tuple tr in r do begin for each tuple ts in s do begin test pair (tr, ts) to see if they satisfy the join condition if they do, add tr • ts to the result. end n r is called the outer relation and s the inner relation of the join. n Requires no indices and can be used with any kind of join condition. n Expensive since it examines every pair of tuples in the two relations. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 43 ©Silberschatz, Korth and Sudarshan
Nested-Loop Join (Cont. ) n In the worst case, if there is enough memory only to hold one block of each relation, the estimated cost is nr bs + b r block transfers, plus seeks n If the smaller relation fits entirely in memory, use that as the inner relation. l n nr + br Reduces cost to br + bs block transfers and 2 seeks Assuming worst case memory availability cost estimate is l l with depositor as outer relation: 4 5000 400 + 100 = 2, 000, 100 block transfers, 4 5000 + 100 = 5100 seeks with customer as the outer relation 4 10000 100 + 400 = 1, 000, 400 block transfers and 10, 400 seeks n If smaller relation (depositor) fits entirely in memory, the cost estimate will be 500 block transfers. n Block nested-loops algorithm (next slide) is preferable. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 44 ©Silberschatz, Korth and Sudarshan
Block Nested-Loop Join n Variant of nested-loop join in which every block of inner relation is paired with every block of outer relation. for each block Br of r do begin for each block Bs of s do begin for each tuple tr in Br do begin for each tuple ts in Bs do begin Check if (tr, ts) satisfy the join condition if they do, add tr • ts to the result. end end Database System Concepts, 5 th Edition, Oct 5, 2006 13. 45 ©Silberschatz, Korth and Sudarshan
Block Nested-Loop Join (Cont. ) n 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 n Best case: br + bs block transfers + 2 seeks. n Improvements to nested loop and block nested loop algorithms: l In block nested-loop, use M — 2 disk blocks as blocking unit for outer relations, where M = memory size in blocks; use remaining two blocks to buffer inner relation and output l 4 Cost = br / (M-2) bs + br block transfers + 2 br / (M-2) seeks If equi-join attribute forms a key or inner relation, stop inner loop on first match l Scan inner loop forward and backward alternately, to make use of the blocks remaining in buffer (with LRU replacement) l Use index on inner relation if available (next slide) l Database System Concepts, 5 th Edition, Oct 5, 2006 13. 46 ©Silberschatz, Korth and Sudarshan
Indexed Nested-Loop Join n Index lookups can replace file scans if l join is an equi-join or natural join and l an index is available on the inner relation’s join attribute 4 Can construct an index just to compute a join. n 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. n Worst case: buffer has space for only one page of r, and, for each tuple in r, we perform an index lookup on s. n Cost of the join: br (t. T + t. S) + nr c l Where c is the cost of traversing index and fetching all matching s tuples for one tuple or r l c can be estimated as cost of a single selection on s using the join condition. n If indices are available on join attributes of both r and s, use the relation with fewer tuples as the outer relation. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 47 ©Silberschatz, Korth and Sudarshan
Example of Nested-Loop Join Costs n Compute depositor customer, with depositor as the outer relation. n Let customer have a primary B+-tree index on the join attribute customer-name, which contains 20 entries in each index node. n Since customer has 10, 000 tuples, the height of the tree is 4, and one more access is needed to find the actual data n depositor has 5000 tuples n Cost of block nested loops join l 400*100 + 100 = 40, 100 block transfers + 2 * 100 = 200 seeks 4 assuming worst case memory 4 may n 變成 block 數目少的在外圈有利 be significantly less with more memory Cost of indexed nested loops join 先看 index ,條件成立再抓資料 l 100 + 5000 * 5 = 25, 100 block transfers and seeks. l CPU cost likely to be less than that for block nested loops join Database System Concepts, 5 th Edition, Oct 5, 2006 13. 48 ©Silberschatz, Korth and Sudarshan
Merge-Join 1. Sort both relations on their join attribute (if not already sorted on the join attributes). 2. Merge the sorted relations to join them 1. Join step is similar to the merge stage of the sort-merge algorithm. 2. Main difference is handling of duplicate values in join attribute — every pair with same value on join attribute must be matched 3. Detailed algorithm in book Thus the cost of merge join is: br + bs block transfers + br / bb + bs / bb seeks + the cost of sorting if relations are unsorted. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 49 ©Silberschatz, Korth and Sudarshan
Hash-Join n Applicable for equi-joins and natural joins. n A hash function h is used to partition tuples of both relations n h maps Join. Attrs values to {0, 1, . . . , n}, where Join. Attrs denotes the common attributes of r and s used in the natural join. l r 0, r 1, . . . , rn denote partitions of r tuples 4 Each l tuple tr r is put in partition ri where i = h(tr [Join. Attrs]). s 0, s 1. . . , sn denotes partitions of s tuples 4 Each tuple ts s is put in partition si, where i = h(ts [Join. Attrs]). n Note: In book, ri is denoted as Hri, si is denoted as Hsi and n is denoted as nh. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 50 ©Silberschatz, Korth and Sudarshan
Hash-Join (Cont. ) Database System Concepts, 5 th Edition, Oct 5, 2006 13. 51 ©Silberschatz, Korth and Sudarshan
Hash-Join (Cont. ) n r tuples in ri need only to be compared with s tuples in si Need not be compared with s tuples in any other partition, since: l an r tuple and an s tuple that satisfy the join condition will have the same value for the join attributes. l If that value is hashed to some value i, the r tuple has to be in ri and the s tuple in si. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 52 ©Silberschatz, Korth and Sudarshan
Complex Joins n Join with a conjunctive condition: r 1 2. . . n s l Either use nested loops/block nested loops, or l Compute the result of one of the simpler joins r i s 4 final result comprises those tuples in the intermediate result that satisfy the remaining conditions 1 . . . i – 1 i +1 . . . n n Join with a disjunctive condition r 1 2 . . . n s l Either use nested loops/block nested loops, or l Compute as the union of the records in individual joins r s: (r 1 s) (r Database System Concepts, 5 th Edition, Oct 5, 2006 2 s) . . . (r 13. 53 n i s) ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 54 ©Silberschatz, Korth and Sudarshan
Other Operations n Duplicate elimination can be implemented via hashing or sorting. l On sorting duplicates will come adjacent to each other, and all but one set of duplicates can be deleted. l Optimization: duplicates can be deleted during run generation as well as at intermediate merge steps in external sort-merge. l Hashing is similar – duplicates will come into the same bucket. n Projection: l perform projection on each tuple l followed by duplicate elimination. Database System Concepts, 5 th Edition, Oct 5, 2006 13. 55 ©Silberschatz, Korth and Sudarshan
Other Operations : Aggregation n Aggregation can be implemented in a manner similar to duplicate elimination. l 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. l Optimization: combine tuples in the same group during run generation and intermediate merges, by computing partial aggregate values 4 For count, min, max, sum: keep aggregate values on tuples found so far in the group. – When combining partial aggregate for count, add up the aggregates 4 For avg, keep sum and count, and divide sum by count at the end Database System Concepts, 5 th Edition, Oct 5, 2006 13. 56 ©Silberschatz, Korth and Sudarshan
Other Operations : Set Operations Set operations ( , and ): can either use variant of merge-join after sorting, or variant of hash-join. n E. g. , Set operations using hashing: 1. Partition both relations using the same hash function 2. Process each partition i as follows. 1. Using a different hashing function, build an in-memory hash index on ri. 2. Process si as follows l r s: 1. Add tuples in si to the hash index if they are not already in it. 2. At end of si add the tuples in the hash index to the result. l r s: 1. output tuples in si to the result if they are already there in the hash index l r – s: 1. for each tuple in si, if it is there in the hash index, delete it from the index. 2. At end of si add remaining tuples in the hash index to the result. n Database System Concepts, 5 th Edition, Oct 5, 2006 13. 57 ©Silberschatz, Korth and Sudarshan
Outline n Overview n Measures of Query Cost n Example (Selection Operation) n Example (Join Operations) n Example (Evaluation of Expressions) n Selection Operation Self Study n Sorting n Join Operation n Other Operations n Evaluation of Expressions Database System Concepts, 5 th Edition, Oct 5, 2006 13. 58 ©Silberschatz, Korth and Sudarshan
Evaluation of Expressions n So far: we have seen algorithms for individual operations n Alternatives for evaluating an entire expression tree l Materialization: generate results of an expression whose inputs are relations or are already computed, materialize (store) it on disk. Repeat. l Pipelining: pass on tuples to parent operations even as an operation is being executed l Example: Database System Concepts, 5 th Edition, Oct 5, 2006 13. 59 ©Silberschatz, Korth and Sudarshan
Materialization (Cont. ) n Materialized evaluation is always applicable n Cost of writing results to disk and reading them back can be quite high l Our cost formulas for operations ignore cost of writing results to disk, so 4 Overall cost = Sum of costs of individual operations + cost of writing intermediate results to disk n Double buffering: use two output buffers for each operation, when one is full write it to disk while the other is getting filled l Allows overlap of disk writes with computation and reduces execution time Database System Concepts, 5 th Edition, Oct 5, 2006 13. 60 ©Silberschatz, Korth and Sudarshan
Pipelining n Pipelined evaluation : evaluate several operations simultaneously, passing the results of one operation on to the next. n E. g. , in previous expression tree, don’t store result of l instead, pass tuples directly to the join. . Similarly, don’t store result of join, pass tuples directly to projection. n Much cheaper than materialization: no need to store a temporary relation to disk. n Pipelining may not always be possible – e. g. , sort, hash-join. n For pipelining to be effective, use evaluation algorithms that generate output tuples even as tuples are received for inputs to the operation. n Pipelines can be executed in two ways: demand driven and producer driven Database System Concepts, 5 th Edition, Oct 5, 2006 13. 61 ©Silberschatz, Korth and Sudarshan
Pipelining (Cont. ) n In demand driven or lazy evaluation l system repeatedly requests next tuple from top level operation l Each operation requests next tuple from children operations as required, in order to output its next tuple l In between calls, operation has to maintain “state” so it knows what to return next n In producer-driven or eager pipelining l Operators produce tuples eagerly and pass them up to their parents 4 Buffer maintained between operators, child puts tuples in buffer, parent removes tuples from buffer 4 if buffer is full, child waits till there is space in the buffer, and then generates more tuples l System schedules operations that have space in output buffer and can process more input tuples n Alternative name: pull and push models of pipelining Database System Concepts, 5 th Edition, Oct 5, 2006 13. 62 ©Silberschatz, Korth and Sudarshan
End of Chapter Database System Concepts, 5 th Ed. ©Silberschatz, Korth and Sudarshan See www. db-book. com for conditions on re-use
- Slides: 63