Database System Concepts, 7th Ed. ©Silberschatz, Korth and Sudarshan See www.db-book.com for conditions on re-use Chapter 10: Query Processing ©Silberschatz, Korth and Sudarshan10.2Database System Concepts - 7th Edition Chapter 10: Query Processing ▪ Overview ▪ Measures of Query Cost ▪ Selection Operation ▪ Sorting ▪ Join Operation ▪ Other Operations ▪ Evaluation of Expressions ©Silberschatz, Korth and Sudarshan10.3Database System Concepts - 7th Edition Basic Steps in Query Processing 1. Parsing and translation 2. Optimization 3. Evaluation ©Silberschatz, Korth and Sudarshan10.4Database System Concepts - 7th Edition Basic Steps in Query Processing (Cont.) ▪ Parsing and translation • translate the query into its internal form. This is then translated into relational algebra expression. • Parser checks syntax and verifies validity relations. ▪ Evaluation • The query-execution engine takes a query-evaluation plan, executes that plan, and returns the answers to the query. ©Silberschatz, Korth and Sudarshan10.5Database System Concepts - 7th Edition Basic Steps in Query Processing: Optimization ▪ A relational algebra expression may have many equivalent forms • E.g., salary75000(salary(instructor)) is equivalent to salary(salary75000(instructor)) ▪ Each relational algebra operation can be evaluated using one of several different algorithms • Correspondingly, a relational-algebra expression can be evaluated in many ways. ▪ Annotated expression specifying a detailed evaluation strategy is called an evaluation plan. E.g.: • Use an index on salary to find instructors with a salary < 75000, • Or perform a complete relation scan and discard instructors with salary  75000 ©Silberschatz, Korth and Sudarshan10.6Database System Concepts - 7th Edition Basic Steps: Optimization (Cont.) ▪ Query Optimization: Amongst all equivalent evaluation plans choose the one with the lowest execution cost. • Cost is estimated using statistical information from the database catalog ▪ e.g. number of tuples in each relation, size of tuples, etc. ▪ In this chapter we study • How to measure query costs • Algorithms for evaluating relational algebra operations • How to combine algorithms for individual operations in order to evaluate a complete expression ▪ In the next chapter • We study how to optimize queries, that is, how to find an evaluation plan with the lowest estimated cost ©Silberschatz, Korth and Sudarshan10.7Database System Concepts - 7th Edition Measures of Query Cost ▪ Many factors contribute to time cost • disk access, CPU, and network communication ▪ Cost can be measured based on • response time, i.e., total elapsed time for answering a query, or • total resource consumption ▪ We use total resource consumption as a cost metric • Response time is harder to estimate, and minimizing resource consumption is a good idea in a shared database ▪ We ignore CPU costs for simplicity • Real systems do take CPU cost into account • Network costs must be considered for parallel systems ▪ We describe how to estimate the cost of each operation • We do not include the cost of writing output to disk ©Silberschatz, Korth and Sudarshan10.8Database System Concepts - 7th Edition Measures of Query Cost ▪ Disk cost can be estimated as: • Number of seeks * average-seek-cost • Number of blocks read * average-block-read-cost • Number of blocks written * average-block-write-cost ▪ For simplicity we just use the number of block transfers from disk and the number of seeks as the cost measures • tT – time to transfer one block ▪ Assuming for simplicity that the write cost is the same as the cost to read • tS – time for one seek • Cost for b block transfers plus S seeks b * tT + S * tS ▪ tS and tT depend on where data is stored; with 4 KB blocks: • High end magnetic disk: tS = 4 msec and tT =0.1 msec • SSD: tS = 20-90 microsec and tT = 2-10 microsec for 4KB ©Silberschatz, Korth and Sudarshan10.9Database System Concepts - 7th Edition Measures of Query Cost (Cont.) ▪ Required data may be buffer resident already, avoiding disk I/O • But hard to consider for cost estimation ▪ 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 ▪ Worst case estimates assume that no data is initially in the buffer and only the minimum amount of memory needed for the operation is available • But more optimistic estimates are used in practice ©Silberschatz, Korth and Sudarshan10.10Database System Concepts - 7th Edition Selection Operation ▪ File scan ▪ Algorithm A1 (linear search). Scan each file block and test all records to see whether they satisfy the selection condition. • Cost estimate = br block transfers + 1 seek ▪ br denotes the number of blocks containing records of relation r • If selection is on a key attribute, we can stop finding the record ▪ cost = (br /2) block transfers + 1 seek • Linear search can be applied regardless of ▪ selection condition or ▪ ordering of records in the file, or ▪ availability of indices ▪ Note: binary search generally does not make sense since data is not stored consecutively • except when there is an index available, • and binary search requires more seeks than index search ©Silberschatz, Korth and Sudarshan10.11Database System Concepts - 7th Edition Selections Using Indices ▪ Index scan – search algorithms that use an index • selection condition must be on search-key of the index. ▪ A2 (clustering index, equality on key). Retrieve a single record that satisfies the corresponding equality condition • Cost = (hi + 1) * (tT + tS) ▪ A3 (clustering index, equality on a non-key) Retrieve multiple records. • Records will be on consecutive blocks ▪ Let b = number of blocks containing matching records • Cost = hi * (tT + tS) + tS + tT * b ©Silberschatz, Korth and Sudarshan10.12Database System Concepts - 7th Edition Selections Using Indices ▪ A4 (secondary index, equality on key/non-key). • Retrieve a single record if the search-key is a candidate key ▪ Cost = (hi + 1) * (tT + tS) • Retrieve multiple records if search-key is not a candidate key ▪ each of n matching records may be on a different block ▪ Cost = (hi + n) * (tT + tS) • Can be very expensive! ©Silberschatz, Korth and Sudarshan10.13Database System Concepts - 7th Edition Selections Involving Comparisons ▪ Can implement selections of the form AV (r) or A  V(r) by using • a linear file scan, • or by using indices in the following ways: ▪ A5 (clustering index, comparison). (Relation is sorted on A) ▪ For A  V(r) use index to find the first tuple  v and scan the relation sequentially from there ▪ For AV ® just scan the relation sequentially till first tuple > v; do not use index ▪ A6 (non-clustering index, comparison). (Relation is not sorted on A) ▪ For A  V(r) use index to find the first index entry  v and scan index sequentially from there, to find pointers to records. ▪ For AV ® just scan leaf pages of the index finding pointers to records, till the first entry > v ▪ In either case, retrieve records that are pointed to ▪ requires an I/O per record; Linear file scan may be cheaper! ©Silberschatz, Korth and Sudarshan10.14Database System Concepts - 7th Edition Implementation of Complex Selections ▪ Conjunction: 1 2. . . n(r) ▪ A7 (conjunctive selection using one index). • Select a combination of i and algorithms A1 through A7 that results in the least cost for i (r). • Test other conditions on the tuples fetched into the memory buffer. ▪ A8 (conjunctive selection using a composite index). • Use appropriate composite (multiple-key) index if available. ▪ A9 (conjunctive selection by intersection of identifiers). • Requires indices with record pointers. • Use the corresponding index for each condition and take the intersection of all the obtained sets of record pointers. • Then fetch records from the file • If some conditions do not have appropriate indices, apply the test in memory. ©Silberschatz, Korth and Sudarshan10.15Database System Concepts - 7th Edition Algorithms for Complex Selections ▪ Disjunction:1 2 . . . n (r). ▪ A10 (disjunctive selection by union of identifiers). • Applicable if all conditions have available indices. ▪ Otherwise use linear scan. • Use the corresponding index for each condition, and take the union of all the obtained sets of record pointers. • Then fetch records from the file ▪ Negation: (r) • Use linear scan on file • If very few records satisfy , and an index is applicable to  ▪ Find satisfying records using index and fetch from file ©Silberschatz, Korth and Sudarshan10.16Database System Concepts - 7th Edition Sorting ▪ We may build an index on the relation, and then use the index to read the relation in sorted order. This 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. ©Silberschatz, Korth and Sudarshan10.17Database System Concepts - 7th Edition Example: External Sorting Using Sort-Merge g a d 31 c 33 b 14 e 16 r 16 d 21 m 3 p 2 d 7 a 14 a 14 a 19 b 14 c 33 d 7 d 21 d 31 e 16 g 24 m 3 p 2 r 16 a 19 b 14 c 33 d 31 e 16 g 24 a 14 d 7 d 21 m 3 p 2 r 16 a 19 d 31 g 24 b 14 c 33 e 16 d 21 m 3 r 16 a 14 d 7 p 2 initial relation create runs merge pass–1 merge pass–2 runs runs sorted output 24 19 ©Silberschatz, Korth and Sudarshan10.18Database System Concepts - 7th Edition External Sort-Merge 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)….. Let M denote memory size (in pages). ©Silberschatz, Korth and Sudarshan10.19Database System Concepts - 7th Edition 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 the output. Read the first block of each run into its buffer page 2. repeat 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 following block (if any) of the run into the buffer. 3. until all input buffer pages are empty: ©Silberschatz, Korth and Sudarshan10.20Database System Concepts - 7th Edition External Sort-Merge (Cont.) ▪ If N  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 of them 10 times the size of the initial runs • Repeated passes are performed till all runs have been merged into one. ©Silberschatz, Korth and Sudarshan10.21Database System Concepts - 7th Edition External Merge Sort (Cont.) ▪ Cost analysis: • 1 block per run leads to too many seeks during the merge ▪ Instead use bb buffer blocks per run ➔ read/write bb blocks at a time ▪ Can merge M/bb–1 runs in one pass • Total number of merge passes required: log M/bb–1(br/M). • Block transfers for initial run creation as well as in each pass is 2br ▪ For the final pass, we don’t count the write cost • We ignore the final write cost for all operations since the output of an operation may be sent to the parent operation without being written to disk ▪ Thus, the total number of block transfers for external sorting is: br ( 2 log M/bb–1 (br / M) + 1)  • Seeks: next slide ©Silberschatz, Korth and Sudarshan10.22Database System Concepts - 7th Edition External Merge Sort (Cont.) ▪ 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 ▪ Need 2 br / bb seeks for each merge pass • except the final one which does not require a write ▪ Total number of seeks: 2 br / M + br / bb (2 logM/bb–1(br / M) -1) ©Silberschatz, Korth and Sudarshan10.23Database System Concepts - 7th Edition Join Operation ▪ Several different algorithms to implement joins • Nested-loop join • Block nested-loop join • Indexed nested-loop join • Merge-join • Hash-join ▪ Choice based on the cost estimate ▪ Examples use the following information • Number of records of student: 5,000 takes: 10,000 • Number of blocks of student: 100 takes: 400 ©Silberschatz, Korth and Sudarshan10.24Database System Concepts - 7th Edition Nested-Loop Join ▪ To compute the 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 end ▪ r is called the outer relation and s is the inner relation of the join. ▪ 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. ©Silberschatz, Korth and Sudarshan10.25Database System Concepts - 7th Edition Nested-Loop Join (Cont.) ▪ In the worst case, if there is enough memory only to hold one block of each relation, the estimated cost is nr  bs + br block transfers, plus nr + br seeks ▪ If the smaller relation fits entirely in memory, use that as the inner relation. • Reduces cost to br + bs block transfers and 2 seeks ▪ Assuming the worst-case memory availability, the cost estimate is • with student as outer relation: ▪ 5000  400 + 100 = 2,000,100 block transfers, ▪ 5000 + 100 = 5100 seeks • with takes as the outer relation ▪ 10000  100 + 400 = 1,000,400 block transfers and 10,400 seeks ▪ If smaller relation (student) fits entirely in memory, the cost estimate will be 500 block transfers. ▪ Block nested-loops algorithm (next slide) is preferable. ©Silberschatz, Korth and Sudarshan10.26Database System Concepts - 7th Edition Block Nested-Loop Join ▪ 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 end end ©Silberschatz, Korth and Sudarshan10.28Database System Concepts - 7th Edition Indexed Nested-Loop Join ▪ Index lookups can replace file scans if • join is the equi or natural join and • an index is available on the inner relation’s join attribute ▪ Can construct an index just to compute a join. ▪ 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. ▪ 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 (tT + tS) + nr  c • Where c is the cost of traversing the index and fetching all matching s tuples for one tuple or r • C can be estimated as the cost of a single selection on s using the join condition. ▪ If indices are available on join attributes of both r and s, use the relation with fewer tuples as the outer relation. ©Silberschatz, Korth and Sudarshan10.30Database System Concepts - 7th Edition 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 the handling of duplicate values in the join attribute — every pair with the same value on the join attribute must be matched 3. Detailed algorithm in the book ©Silberschatz, Korth and Sudarshan10.31Database System Concepts - 7th Edition Merge-Join (Cont.) ▪ Can be used only for the equi and natural joins ▪ Each block needs to be read only once - assuming all tuples for any given value of the join attributes fit in memory ▪ Thus, the cost of merge join is: br + bs block transfers + br / bb + bs / bb seeks + the cost of sorting if relations are unsorted. ▪ hybrid merge-join: If one relation is sorted, and the other has a secondary B+-tree index on the join attribute • Merge the sorted relation with the leaf entries of the B+-tree . • Sort the result on the addresses of the unsorted relation’s tuples • Scan the unsorted relation in physical address order and merge with previous result, to replace addresses by the actual tuples ▪ Sequential scan more efficient than random lookup ©Silberschatz, Korth and Sudarshan10.32Database System Concepts - 7th Edition Hash-Join ▪ Applicable for the equi and natural joins. ▪ A hash function h is used to partition tuples of both relations ▪ h maps JoinAttrs values to {0, 1, ..., n}, where JoinAttrs denotes the common attributes of r and s used in the natural join. • r0, r1, . . ., rn denote partitions of r tuples ▪ Each tuple tr  r is put in partition ri where i = h(tr [JoinAttrs]). • s0,, s1. . ., sn denotes partitions of s tuples ▪ Each tuple ts s is put in partition si, where i = h(ts [JoinAttrs]). ▪ Note: In book, Figure 12.10 ri is denoted as Hri, si is denoted as Hsi and n is denoted as nh. ©Silberschatz, Korth and Sudarshan10.33Database System Concepts - 7th Edition Hash-Join (Cont.) ©Silberschatz, Korth and Sudarshan10.35Database System Concepts - 7th Edition Hash-Join Algorithm 1. Partition the relation s using hashing function h. When partitioning a relation, one block of memory is reserved as the output buffer for each partition. 2. Partition r similarly. 3. For each i: (a)Load si into memory and build an in-memory hash index on it using the join attribute. This hash index uses a different hash function than the earlier one h. (b)Read the tuples in ri from the disk one by one. For each tuple tr locate each matching tuple ts in si using the in-memory hash index. Output the concatenation of their attributes. The hash-join of r and s is computed as follows. Relation s is called the build input and r is called the probe input. ©Silberschatz, Korth and Sudarshan10.37Database System Concepts - 7th Edition Complex Joins ▪ Join with a conjunctive condition: r ⨝ 1  2...   n s • 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 1  . . .  i –1  i +1  . . .  n ▪ Join with a disjunctive condition r ⨝ 1  2 ...  n s • 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) ©Silberschatz, Korth and Sudarshan10.38Database System Concepts - 7th Edition 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: • perform projection on each tuple • followed by duplicate elimination. ©Silberschatz, Korth and Sudarshan10.39Database System Concepts - 7th Edition Other Operations : Aggregation ▪ 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 to each group. • Optimization: partial aggregation ▪ 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. • When combining partial aggregate for the count function, add up the partial aggregates ▪ For avg, keep sum and count, and divide the sum by count at the end ©Silberschatz, Korth and Sudarshan10.40Database System Concepts - 7th Edition Other Operations : Set Operations ▪ Set operations (,  and ⎯): can either use variant of merge-join after sorting, or variant of hash-join. ▪ 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 • 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. ©Silberschatz, Korth and Sudarshan10.41Database System Concepts - 7th Edition Other Operations : Set Operations ▪ E.g., Set operations using hashing: 1. as before partition r and s, 2. as before, process each partition i as follows 1. build a hash index on ri 2. Process si as follows • r  s: 1. output tuples in si to the result if they are already there in the hash index • r – s: 1. for each tuple in si, if it is there in the hash index, delete it from the index. 2. At the end of si add the remaining tuples in the hash index to the result. ©Silberschatz, Korth and Sudarshan10.42Database System Concepts - 7th Edition Answering Keyword Queries ▪ Indices mapping keywords to documents • For each keyword, store a sorted list of document IDs that contain the keyword ▪ Commonly referred to as an inverted index ▪ E.g.,: database: d1, d4, d11, d45, d77, d123 distributed: d4, d8, d11, d56, d77, d121, d333 • To answer a query with several keywords, compute the intersection of lists corresponding to those keywords ▪ To support ranking, inverted lists store extra information • “Term frequency” of the keyword in the document • “Inverse document frequency” of the keyword • Page rank of the document/web page ©Silberschatz, Korth and Sudarshan10.43Database System Concepts - 7th Edition Other Operations : Outer Join ▪ Outer join can be computed either as • A join followed by the addition of null-padded non-participating tuples. • by modifying the join algorithms. ▪ Modifying merge join to compute r ⟕ s • In r ⟕ s, nonparticipating tuples are those in r – R(r ⨝ s) • Modify merge-join to compute r ⟕ s: ▪ During merging, for every tuple tr from r that does not match any tuple in s, output tr padded with nulls. • Right outer-join and full outer-join can be computed similarly. ©Silberschatz, Korth and Sudarshan10.44Database System Concepts - 7th Edition Other Operations : Outer Join ▪ Modifying hash join to compute r ⟕ s • If r is probe relation, output non-matching r tuples padded with nulls • If r is the build relation when probing keep track of which r tuples matched s tuples. At the end of si output non-matched r tuples padded with nulls ©Silberschatz, Korth and Sudarshan10.45Database System Concepts - 7th Edition Evaluation of Expressions ▪ So far: we have seen algorithms for individual operations ▪ Alternatives for evaluating an entire expression tree are: • 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 ▪ We study the above alternatives in more detail in the following ©Silberschatz, Korth and Sudarshan10.46Database System Concepts - 7th Edition 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 the figure below, compute and store then compute the store its join with instructor, and finally compute the projection on name. )("Watson" departmentbuilding= ©Silberschatz, Korth and Sudarshan10.47Database System Concepts - 7th Edition Materialization (Cont.) ▪ Materialized evaluation is always applicable ▪ Cost of writing results to disk and reading them back can be quite high • Our cost formulas for operations ignore the cost of writing results to disk, so ▪ 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 • Allows overlap of disk writes with computation and reduces execution time ©Silberschatz, Korth and Sudarshan10.48Database System Concepts - 7th Edition Pipelining ▪ Pipelined evaluation: evaluate several operations simultaneously, passing the results of one operation on to the next. ▪ E.g., in the previous expression tree, don’t store the result of • instead, pass tuples directly to the join. Similarly, don’t store the result of join, pass tuples directly to projection. ▪ Much cheaper than materialization: no need to store a temporary relation to disk. ▪ Pipelining may not always be possible – e.g., sort, hash-join. ▪ 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- driven )("Watson" departmentbuilding = ©Silberschatz, Korth and Sudarshan10.49Database System Concepts - 7th Edition Pipelining (Cont.) ▪ In demand-driven or lazy evaluation • System repeatedly requests the next tuple from the top-level operation • Each operation requests the next tuple from children operations as required, in order to output its next tuple • In between calls, the operation has to maintain “state” so it knows what to return next ▪ In producer-driven or eager pipelining • Operators produce tuples eagerly and pass them up to their parents ▪ Buffer maintained between operators, the child puts tuples in the buffer, parent removes tuples from the buffer ▪ If the buffer is full, the child waits till there is space in the buffer, and then generates more tuples • System schedules operations that have space in the output buffer and can process more input tuples ▪ Alternative names: pull and push models of pipelining ©Silberschatz, Korth and Sudarshan10.50Database System Concepts - 7th Edition Pipelining (Cont.) ▪ Implementation of demand-driven pipelining • Each operation is implemented as an iterator implementing the following operations ▪ open() • E.g., file scan: initialize file scan ▪ state: pointer to the beginning of the file • E.g., merge join: sort relations; ▪ state: pointers to the beginning of sorted relations ▪ next() • E.g., for file scan: Output next tuple, and advance and store file pointer • E.g., for merge join: continue with the merge from the earlier state till the next output tuple is found. Save pointers as iterator state. ▪ close() ©Silberschatz, Korth and Sudarshan10.51Database System Concepts - 7th Edition End of Chapter 10