CSH 2 D 3 Database System 06 Query
CSH 2 D 3 - Database System 06 | Query Processing (2) Query Processing
Goals of the Meeting 01 02 Students know how to measures query costs Students know various algorithms for selection and join operations Query Processing 2
Outline Measures of Query Costs Selection Algorithms Join Algorithms Query Processing
Steps of Query Processing 4
Basic Steps in Query Processing 1. 2. 3. Parsing and translation Optimization Evaluation Query Processing
Basic Steps in Query Processing: Optimization • A relational algebra expression may have many equivalent expressions • 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 detailed evaluation strategy is called an evaluation-plan. E. g. , : • Use an index on salary to find instructors with salary < 75000, • Or perform complete relation scan and discard instructors with salary 75000 Query Processing
Basic Steps: Optimization (Cont. ) • Query Optimization: Amongst all equivalent evaluation plans choose the one with lowest 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 Query Processing
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 query, or • total resource consumption • We use total resource consumption as cost metric • Response time 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 estimate the cost of each operation • We do not include cost to writing output to disk Query Processing
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 • t. T – time to transfer one block • Assuming for simplicity that write cost is same as read cost • t. S – time for one seek • Cost for b block transfers plus S seeks b * t. T + S * t. S • t. S and t. T depend on where data is stored; with 4 KB blocks: • High end magnetic disk: t. S = 4 msec and t. T =0. 1 msec • SSD: t. S = 20 -90 microsec and t. T = 2 -10 microsec for 4 KB Query Processing
Measures of Query Cost (Cont. ) • Required data may be buffer resident already, avoiding disk I/O • But hard to take into account 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 buffer and only the minimum amount of memory needed for the operation is available • But more optimistic estimates are used in practice Query Processing
Selection Operation • File scan • Algorithm A 1 (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 number of blocks containing records from relation r • If selection is on a key attribute, can stop on finding 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 Query Processing
Selections Using Indices • Index scan – search algorithms that use an index • selection condition must be on search-key of index. • A 2 (clustering index, equality on key). Retrieve a single record that satisfies the corresponding equality condition • Cost = (hi + 1) * (t. T + t. S) • A 3 (clustering index, equality on nonkey) Retrieve multiple records. • Records will be on consecutive blocks • Let b = number of blocks containing matching records • Cost = hi * (t. T + t. S) + t. S + t. T * b Query Processing
Selections Using Indices • A 4 (secondary index, equality on key/non-key). • Retrieve a single record if the search-key is a candidate key • Cost = (hi + 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 • Cost = (hi + n) * (t. T + t. S) • Can be very expensive! Query Processing
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: • A 5 (clustering index, comparison). (Relation is sorted on A) • For A V(r) use index to find first tuple v and scan relation sequentially from there • For A V (r) just scan relation sequentially till first tuple > v; do not use index • A 6 (clustering index, comparison). • For A V(r) use index to find first index entry v and scan index sequentially from there, to find pointers to records. • For 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 per record; Linear file scan may be cheaper! Query Processing
Examples 1 Employees table have 10. 000 records and 100 blocks. Key attribute : employee_id, size : 4 byte Pointer size : 1 byte, Block size = 8024 byte Query: SELECT first_name FROM Employees WHERE employee_id = 101; The query shows selection operation involving equality which have two alternative algorithms : A 1 (linear search, equality on key) and A 2 (Primary B+Tree index, equality on key) 9/12/2021 Query Processing 15 CSH 2 D 3 - Database System
Step 1: RAE & Equivalent Expressions • In query before we can get only one RAE: first_name (σemployee_id = 101(Employees)) 9/12/2021 Query Processing 16
Step 2: Create QEP & Annotate to Evaluation Plan • We can use two algorithms, A 1 (linear search, equality on key) and A 2 (primary B+Tree index, equality on key). So we will have 2 annotated QEPs (evaluation plans). For the simple case, operation can be evaluated on the fly (assume blocks already in buffer so we don’t have to fetch the block from disk again, so no block transfers) #1 first_name (on-the-fly) #2 σemployee_id = 101 (A 1 eq key) first_name (on-the-fly) σemployee_id = 101 (A 2) Employees 9/12/2021 Employees Query Processing 17
Step 3: Calculate the cost • 9/12/2021 Query Processing 18
Pick the best Evaluation plan I/O cost #1: A 1 equivalent key 50 block transfers 1 seek #2: A 2 2 block transfers 2 seeks Pick! Seek time is smaller than block transfer time, so we can assume that #2 is the best plan 9/12/2021 Query Processing 19
Implementation of Complex Selections • Conjunction: 1 2. . . n(r) • A 7 (conjunctive selection using one index). • 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 8 (conjunctive selection using composite index). • Use appropriate composite (multiple-key) index if available. • A 9 (conjunctive selection by intersection of identifiers). • Requires indices with record pointers. • Use corresponding index for each condition, and take intersection of all the obtained sets of record pointers. • Then fetch records from file • If some conditions do not have appropriate indices, apply test in memory. Query Processing
Algorithms for Complex Selections • Disjunction: 1 2 . . . n (r). • A 10 (disjunctive selection by union of identifiers). • Applicable if all conditions have available indices. • Otherwise use linear scan. • Use corresponding index for each condition, and take union of all the obtained sets of record pointers. • Then fetch records from 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 Query Processing
Examples 2 Employees table have 10. 000 records and 50. 000 blocks. Key attribute : employee_id, size : 4 byte Pointer size : 1 byte, Block size = 1000 byte Query: SELECT first_name FROM Employees WHERE employee_id < 300 AND salary > 5000; The query shows selection operation involving conjuction (AND), so we can use A 7. In A 7, only first condition is used for query cost, because we can assume after first condition is applied, the other conditions is applied in buffer (no block transfer). So, we must calculate all conditions separately with the most appropriate algorithm (A 1 -A 6) to find the lowest cost 9/12/2021 Query Processing 22 CSH 2 D 3 - Database System
Step 1: RAE & Equivalent Expressions • In query before we can get only one RAE: first_name (σemployee_id < 300 salary > 5000 (Employees)) 9/12/2021 Query Processing 23
Step 2: Create QEP & Annotate to Evaluation Plan • Condition 1 (employee_id < 300) is key column comparison, we can calculate using A 1 (linear search, works for any problem) or A 5 (primary B+Tree index, comparison). Condition 2 (salary > 5000) is non-key column comparison, we can calculate using just A 1. So, we will have 2 annotated QEPs / evaluation plans (using A 1 in different comparison has same result, so one A 1 plan is enough). For the simple case, operation can be evaluated on the fly (blocks already in buffer) #1 first_name (on-the-fly) #2 σemployee_id < 300 salary > 5000 first_name (on-the-fly) σemployee_id < 300 salary > 5000 Employees (A 5) (A 1) 9/12/2021 Query Processing 24
Step 3: Calculate the cost • 9/12/2021 Query Processing 25
Pick the best Evaluation plan I/O cost #1: A 1 50000 block transfers 1 seek #2: A 5 302 block transfers 3 seeks Pick! 9/12/2021 Query Processing 26
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 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 Query Processing
Nested-Loop Join • 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 • r is called the outer relation and s 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. Query Processing
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 worst case memory availability 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. Query Processing
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 Query Processing
Block Nested-Loop Join (Cont. ) • 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 • Best case: br + bs block transfers + 2 seeks. • Improvements to nested loop and block nested loop algorithms: • 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 • 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 • Scan inner loop forward and backward alternately, to make use of the blocks remaining in buffer (with LRU replacement) • Use index on inner relation if available Query Processing
Example 1 • Assume two relations Customer and Order with the following data § Customer has 5000 records and 100 blocks § Order has 10000 records and 300 blocks • The query: SELECT name, order_id FROM Customer JOIN Order USING (customer_id) • Estimate the query cost! 9/12/2021 Query Processing 32
Step 1: RAEs & Equivalent Expressions • In query before we can get two equivalent RAEs: name, order_id (Customer ⋈customer_id Order) name, order_id (Order ⋈customer_id Customer) 9/12/2021 Query Processing 33
Step 2: Create QEPs & Annotate to Evaluation Plans • We can use two algorithms in each of RAEs (nested-loop and block nestedloop), so we will have 4 annotated QEPs (evaluation plans). For the simple case, operation can be evaluated on the fly (blocks already in buffer) #1 name, order_id (on-the-fly) #2 name, order_id (on-the-fly) ⋈customer_id (nested-loop) Customer 9/12/2021 Order ⋈customer_id (nested-loop) Order Customer Query Processing 34
Step 2: Create QEPs & Annotate to Evaluation Plans #3 name, order_id (on-the-fly) #4 name, order_id (on-the-fly) ⋈customer_id (block nested-loop) Customer 9/12/2021 Order ⋈customer_id (block nested-loop) Customer Query Processing 35
Step 3: Calculate the cost • Evaluation Plan #1 • Worst case: nr * bs + br block transfers & nr + br seeks 5000 * 300 + 100 = 1500100 block transfers & 5000 + 100 = 5100 seeks • Best case: br + bs block transfers and 2 seeks 100 + 300 = 400 block transfers & 2 seeks • Evaluation Plan #2 • Worst case: 10000 * 100 + 300 = 1000300 block transfers & 10000 + 300 = 10300 seeks • Best case: same with #1 9/12/2021 Query Processing 36
Step 3: Calculate the cost • Evaluation Plan #3 • Worst case: br * bs + br block transfers and 2 * br seeks 100 * 300 + 100 = 30100 block transfers & 2 * 100 = 200 seeks • Best case: same with #1 • Evaluation Plan #4 • Worst case: 300 * 100 + 300 = 30300 block transfers & 2 * 300 = 600 seeks • Best case: same with #1 9/12/2021 Query Processing 37
Pick the best Because the best case is same for all plans, we consider the worst case Evaluation plan I/O cost #1: Customer in outer relation, nested-loop join 1500100 block transfers 5100 seeks #2: Order in outer relation, nested-loop join 1000300 block transfers 10300 seeks #3: Customer in outer relation, block nested-loop join 30100 block transfers 200 seeks #4: Order in outer relation, block nested-loop join 30300 block transfers 600 seeks 9/12/2021 Query Processing Pick! 38
Evaluation of Expressions • So far: we have seen algorithms for individual operations • 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 Query Processing
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, compute and store then compute the store its join with instructor, and finally compute the projection on name. Query Processing
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 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 Query Processing
Pipelining • Pipelined evaluation: evaluate several operations simultaneously, passing the results of one operation on to the next. • E. g. , in previous expression tree, don’t store result of • instead, pass tuples directly to the join. . Similarly, don’t store 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 Query Processing
Pipelining (Cont. ) • In demand driven or lazy evaluation • 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 • In producer-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 • Alternative name: pull and push models of pipelining Query Processing
Exercise Bank Database branch(branch_name, branch_city, assets) customer (customer_number, customer_name, customer_street, customer_city) loan (loan_number, branch_name, amount) borrower (customer_number, loan_number) account (account_number, branch_name, balance) depositor (customer_number, account_number) Query Processing 44
Consider the bank database, where the primary keys are underlined, and the following SQL query: select T. branch name from branch T, branch S where T. assets > S. assets and S. branch city = “Brooklyn” Write an efficient relational-algebra expression that is equivalent to this query. Justify your choice. Query Processing 45
Let relations r 1(A, B, C) and r 2(C, D, E) have the following properties: r 1 has 20, 000 tuples, r 2 has 45, 000 tuples, 25 tuples of r 1 fit on one block, and 30 tuples of r 2 fit on one block. Estimate the number of block transfers and seeks required using each of the following join strategies for r 1 ⋈ r 2: a. Nested-loop join. b. Block nested-loop join. Query Processing 46
References Silberschatz, Korth, and Sudarshan. Database System Concepts – 7 th Edition. Mc. Graw-Hill. 2019. Slides adapted from Database System Concepts Slide. Source: https: //www. db-book. com/db 7/slides-dir/index. html Query Processing 47
Query Processing 48
- Slides: 48