Query Processing n Overview n Measures of Query

  • Slides: 74
Download presentation
Query Processing n Overview n Measures of Query Cost n Selection Operation n Sorting

Query Processing n Overview n Measures of Query Cost n Selection Operation n Sorting n Join Operation n Other Operations n Evaluation of Expressions 1

Basic Steps in Query Processing 1. Parsing and translation 2. Optimization 3. Evaluation 2

Basic Steps in Query Processing 1. Parsing and translation 2. Optimization 3. Evaluation 2

Basic Steps in Query Processing n Parsing and translation ê translate the query into

Basic Steps in Query Processing n Parsing and translation ê translate the query into its internal form. This is then translated into relational algebra. ê Parser checks syntax, verifies relations n Evaluation ê The query-execution engine takes a query-evaluation plan, executes that plan, and returns the answers to the query. 3

Basic Steps in Query Processing : Optimization n A relational algebra expression may have

Basic Steps in Query Processing : Optimization n A relational algebra expression may have many equivalent expressions êE. g. , balance 2500( balance(account)) is equivalent to balance( balance 2500(account)) n Each relational algebra operation can be evaluated using one of several different algorithms êCorrespondingly, a relational-algebra expression can be evaluated in many ways. n Annotated expression specifying detailed evaluation strategy is called an evaluation-plan. êE. g. , can use an index on balance to find accounts with balance < 2500, êor can perform complete relation scan and discard accounts with balance 2500 4

Optimization n Query Optimization: Amongst all equivalent evaluation plans choose the one with lowest

Optimization n 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. 5

Measures of Query Cost n Cost is generally measured as total elapsed time for

Measures of Query Cost n Cost is generally measured as total elapsed time for answering query êMany factors contribute to time cost: disk accesses, CPU, or even network communication n Typically disk access is the predominant cost, and is also relatively easy to estimate. It is measured by taking into account êNumber of seeks * average-seek-cost êNumber of blocks read * average-block-read -cost êNumber of blocks written * average-blockwrite-cost 6

Measures of Query Cost n For simplicity we just use number of block transfers

Measures of Query Cost n For simplicity we just use number of block transfers from disk as the cost measure n Costs depends on the size of the buffer in main memory êHaving more memory reduces need for disk access êAmount of real memory available to buffer depends on other concurrent OS processes, and hard to determine ahead of actual execution êWe often use worst case estimates, assuming only the minimum amount of memory needed for the operation is available n Real systems take CPU cost into account, differentiate between sequential and random I/O, and take buffer size into account 7

Selection Operation n File scan – search algorithms that locate and retrieve records that

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. ê Cost estimate (number of disk blocks scanned) = br èbr denotes number of blocks containing records from relation r ê If selection is on a key attribute, cost = (br /2) èstop on finding record ê Linear search can be applied regardless of èselection condition or èordering of records in the file, or èavailability of indices 8

Selection Operation n A 2 (binary search). Applicable if selection is an equality comparison

Selection Operation n A 2 (binary search). Applicable if selection is an equality comparison on the attribute on which file is ordered. êAssume that the blocks of a relation are stored contiguously êCost estimate (number of disk blocks to be scanned): è log 2(br) — cost of locating the first tuple by a binary search on the blocks èPlus number of blocks containing records that satisfy selection condition 9

Selections Using Indices n Index scan – search algorithms that use an index n

Selections Using Indices n Index scan – search algorithms that use an index n A 3 (primary index on candidate key, equality). Retrieve a single record that satisfies the corresponding equality condition ê Cost = HTi + 1 n A 4 (primary index on nonkey, equality) Retrieve multiple records. ê Records will be on consecutive blocks ê Cost = HTi + number of blocks containing retrieved records n A 5 (equality on search-key of secondary index). ê Retrieve a single record if the search-key is a candidate key èCost = HTi + 1 ê Retrieve multiple records if search-key is not a candidate key èCost = HTi + number of records retrieved – Can be very expensive! èeach record may be on a different block – one block access for each retrieved record 10

Selections Involving Comparisons n Can implement selections of the form A V (r) or

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, ê or by using indices in the following ways: n A 6 (primary 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 n A 7 (secondary 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 for each record – Linear file scan may be cheaper if many records are 11 to be fetched!

Implementation of Complex Selections n Conjunction: 1 2. . . n(r) n A 8

Implementation of Complex Selections n Conjunction: 1 2. . . n(r) n A 8 (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. n A 9 (conjunctive selection using multiple-key index). ê Use appropriate composite (multiple-key) index if available. n A 10 (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. 12

Algorithms for Complex Selections n Disjunction: 1 2 . . . n (r). n

Algorithms for Complex Selections n Disjunction: 1 2 . . . n (r). n A 11 (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 n 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 13

Sorting n We may build an index on the relation, and then use the

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. 14

Example Each block consists of r records. M number of blocks available in the

Example Each block consists of r records. M number of blocks available in the memory for sorting 1 2 3 4 5 6 7 8 9 10 11 12 M=3 Run 0: read 3 consecutive blocks, sort them in memory and write them back. After run 0 Each three consecutive blocks are sorted. Run 1: Read blocks 1 and 4 (keep one block for output buffer) 1 4 If block 1 (4) is exhausted read block 2(5) and continue the merge until all blocks in the First three blocks and in the second three blocks are finished. Thus, we obtained run 1 where six consecutive blocks are sorted. Repeat the same procedure with blocks 7, 8, 9 and 10, 11, 12 Run 2: repeat the same procedure for blocks in run 1. After run 2, the file is sorted! Number of accesses: 12(run 0)+12(run 1) +12(run 2). If we count writing, then the Number of accesses is doubled 15

External Sort-Merge Let M denote memory size (in pages). 1. Create sorted runs. Let

External Sort-Merge Let M denote memory size (in pages). 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 and write them back. (c) i=i++ Merge the runs ((M-1)-way merge). 1. Use M-1 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 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. And delete the record from its input buffer page. 3. If the buffer page becomes empty then read the next block (if any) of the run into the buffer. 16 empty: 3. until all input buffer pages are

External Sort-Merge n If i M, several merge passes are required. êIn each pass,

External Sort-Merge n 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. 17

Example: External Sorting Using Sort-Merge 18

Example: External Sorting Using Sort-Merge 18

External Merge Sort n Cost analysis: êTotal number of merge passes required: log. M

External Merge Sort n Cost analysis: ê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 è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 Thus total number of disk accesses for external sorting: br ( 2 log. M– 1(br / M) + 1) 19

Join Operation n Several different algorithms to implement joins êNested-loop join êBlock nested-loop join

Join Operation n Several different algorithms to implement joins êNested-loop join êBlock nested-loop join êIndexed nested-loop join êMerge-join êHash-join n Choice based on cost estimate n Examples use the following information êNumber of records of customer: 10, 000 depositor: 5000 êNumber of blocks of customer: depositor: 100 20 400

Nested-Loop Join n To compute theta join r s for each tuple tr in

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. 21

Nested-Loop Join n In the worst case, if there is enough memory only to

Nested-Loop Join 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 disk accesses. n If the smaller relation fits entirely in memory, use that as the inner relation. Reduces cost to br + bs disk accesses. n Assuming worst case memory availability cost estimate is ê 5000 400 + 100 = 2, 000, 100 disk accesses with depositor as outer relation, and ê 1000 100 + 400 = 1, 000, 400 disk accesses with customer as the outer relation. n If smaller relation (depositor) fits entirely in memory, the cost estimate will be 500 disk accesses. 22

Block Nested-Loop Join n Variant of nested-loop join in which every block of inner

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 23

Block Nested-Loop Join n Worst case estimate: br bs + br block accesses. ê

Block Nested-Loop Join n Worst case estimate: br bs + br block accesses. ê 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 accesses. n 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 ê 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 (next slide) 24

Indexed Nested-Loop Join n Index lookups can replace file scans if ê join is

Indexed Nested-Loop Join n 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 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 + nr c ê Where c is the cost of traversing index and fetching all matching s tuples for one tuple or r ê 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. 25

Example of Nested-Loop Join Costs n Compute depositor customer, with depositor as the outer

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 ê 400*100 + 100 = 40, 100 disk accesses assuming worst case memory (may be significantly less with more memory) n Cost of indexed nested loops join ê 100 + 5000 * 5 = 25, 100 disk accesses. ê CPU cost likely to be less than that for block nested loops join 26

Merge-Join 1. Sort both relations on their join attribute (if not already sorted on

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 27

Merge-Join n Can be used only for equi-joins and natural joins n Each block

Merge-Join n Can be used only for equi-joins and natural joins n Each block needs to be read only once (assuming all tuples for any given value of the join attributes fit in memory n Thus number of block accesses for merge-join is br + bs + the cost of sorting if relations are unsorted. 28

Hash-Join n Applicable for equi-joins and natural joins. n A hash function h is

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. ê r 0, r 1, . . . , rn denote partitions of r tuples è Each tuple tr r is put in partition ri where i = h(tr [Join. Attrs]). ê r 0, , r 1. . . , rn denotes partitions of s tuples è 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. 29

Hash-Join 30

Hash-Join 30

Hash-Join n r tuples in ri need only to be compared with s tuples

Hash-Join 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: ê an r tuple and an s tuple that satisfy the join condition will have the same value for the join attributes. ê If that value is hashed to some value i, the r tuple has to be in ri and the s tuple in si. 31

Hash-Join Algorithm The hash-join of r and s is computed as follows. 1. Partition

Hash-Join Algorithm The hash-join of r and s is computed as follows. 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. Relation s is called the build input and r is called the probe input. 32

Handling of Overflows n Hash-table overflow occurs in partition si if si does not

Handling of Overflows n Hash-table overflow occurs in partition si if si does not fit in n n memory. Reasons could be ê Many tuples in s with same value for join attributes ê Bad hash function Partitioning is said to be skewed if some partitions have significantly more tuples than some others Overflow resolution can be done in build phase ê Partition si is further partitioned using different hash function. ê Partition ri must be similarly partitioned. Overflow avoidance performs partitioning carefully to avoid overflows during build phase ê E. g. partition build relation into many partitions, then combine them Both approaches fail with large numbers of duplicates ê Fallback option: use block nested loops join on overflowed partitions 33

Complex Joins n Join with a conjunctive condition: r 1 2. . . n

Complex Joins n 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 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 s: (r 1 s) (r 2 s) . . . (r 34 n s) i

Other Operations n Duplicate elimination can be implemented via hashing or sorting. ê On

Other Operations n 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. n Projection is implemented by performing projection on each tuple followed by duplicate elimination. 35

Other Operations : Aggregation n Aggregation can be implemented in a manner similar to

Other Operations : Aggregation n 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. – When combining partial aggregate for count, add up the aggregates è For avg, keep sum and count, and divide sum by count at the end 36

Other Operations : Set Operations n Set operations ( , and ): can either

Other Operations : Set Operations n 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, thereby creating, r 1, . . , rn r 0, and s 1, s 2. . , sn 2. Process each partition i as follows. Using a different hashing function, build an in-memory hash index on ri after it is brought into memory. 3. – r s: Add tuples in si to the hash index if they are not already in it. At end of si add the tuples in the hash index to the result. – r s: output tuples in si to the result if they are already there in the hash index. – r – s: for each tuple in si, if it is there in the hash index, delete it from the index. At end of si add remaining tuples in the hash index to the result. 37

Optimization n Generation of query-evaluation plans for an expression involves several steps: 1. Generating

Optimization n Generation of query-evaluation plans for an expression involves several steps: 1. Generating logically equivalent expressions è Use equivalence rules to transform an expression into an equivalent one. 2. Annotating resultant expressions to get alternative query plans 3. Choosing the cheapest plan based on estimated cost n The overall process is called cost based optimization. 38

n Statistical Information for Cost Estimation n : number of tuples in a relation

n Statistical Information for Cost Estimation n : number of tuples in a relation r. r n br: number of blocks containing tuples of r. n sr: size of a tuple of r. n fr: blocking factor of r — i. e. , the number of tuples of r that fit into one block. n V(A, r): number of distinct values that appear in r for attribute A; same as the size of A(r). n SC(A, r): selection cardinality of attribute A of relation r; average number of records that satisfy equality on A. n If tuples of r are stored together physically in a file, then: 39

Catalog Information about Indices n fi: average fan-out of internal nodes of index i,

Catalog Information about Indices n fi: average fan-out of internal nodes of index i, for tree-structured indices such as B+-trees. n HTi: number of levels in index i — i. e. , the height of i. ê For a balanced tree index (such as B+-tree) on attribute A of relation r, HTi = logfi(V(A, r)). ê For a hash index, HTi is 1. ê LBi: number of lowest-level index blocks in i — i. e, the number of blocks at the leaf level of the index. 40

Selection Size Estimation n Equality selection A=v(r) è SC(A, r) : number of records

Selection Size Estimation n Equality selection A=v(r) è SC(A, r) : number of records that will satisfy the selection è SC(A, r)/fr — number of blocks that these records will occupy è E. g. Binary search cost estimate becomes ê Equality condition on a key attribute: SC(A, r) = 1 41

Statistical Information for Examples n faccount= 20 (20 tuples of account fit in one

Statistical Information for Examples n faccount= 20 (20 tuples of account fit in one block) n V(branch-name, account) = 50 (50 branches) n V(balance, account) = 500 (500 different balance values) n account = 10000 (account has 10, 000 tuples) n Assume the following indices exist on account: ê A primary, B+-tree index for attribute branch-name ê A secondary, B+-tree index for attribute balance 42

Selections Involving Comparisons n Selections of the form A V(r) (case of A V(r)

Selections Involving Comparisons n Selections of the form A V(r) (case of A V(r) is symmetric) n 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. 43

Implementation of Complex Selections n The selectivity of a condition i is the probability

Implementation of Complex Selections n 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. n Conjunction: 1 2. . . n (r). The estimate for number of tuples in the result is: n Disjunction: 1 2 . . . n (r). Estimated number of tuples: n Negation: (r). Estimated number of tuples: nr – size( (r)) 44

Join Operation: Running Example Running example: depositor customer Catalog information for join examples: n

Join Operation: Running Example Running example: depositor customer Catalog information for join examples: n ncustomer = 10, 000. n fcustomer = 25, which implies that bcustomer =10000/25 = 400. n ndepositor = 5000. n fdepositor = 50, which implies that bdepositor = 5000/50 = 100. n 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. 45

Estimation of the Size of Joins n The Cartesian product r x s contains

Estimation of the Size of Joins n The Cartesian product r x s contains nr. ns tuples; each tuple occupies sr + ss bytes. n If R S = , then r s is the same as r x s. n 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. n If R S in S is a foreign key in S referencing R, then the number of tuples in r tuples in s. s is exactly the same as the number of è The case for R S being a foreign key referencing S is symmetric. n 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 46

Estimation of the Size of Joins n If R S = {A} is not

Estimation of the Size of Joins n 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 number of tuples in R S is estimated to be: S, the If the reverse is true, the estimate obtained will be: The lower of these two estimates is probably the more accurate one. 47

Estimation of the Size of Joins n Compute the size estimates for depositor customer

Estimation of the Size of Joins n Compute the size estimates for depositor customer without using information about foreign keys: ê V(customer-name, depositor) = 2500, and V(customer-name, customer) = 10000 ê The two estimates are 5000 * 10000/2500 - 20, 000 and 5000 * 10000/10000 = 5000 ê We choose the lower estimate, which in this case, is the same as our earlier computation using foreign keys. 48

Size Estimation for Other Operations n Projection: estimated size of A(r) = V(A, r)

Size Estimation for Other Operations n Projection: estimated size of A(r) = V(A, r) n Aggregation : estimated size of g. F(r) A = V(A, r) n Set operations ê For unions/intersections of selections on the same relation: rewrite and use size estimate for selections è E. g. 1 (r) 2 (r) can be rewritten as 1 2 (r) ê For operations on different relations: è estimated size of r s = size of r + size of s. è estimated size of r s = minimum size of r and size of s. è estimated size of r – s = r. è All the three estimates may be quite inaccurate, but provide upper bounds on the sizes. 49

Estimation of Number of Distinct Values Selections: (r) n If forces A to take

Estimation of Number of Distinct Values Selections: (r) n If forces A to take a specified value: V(A, (r)) = 1. è e. g. , A = 3 n If forces A to take on one of a specified set of values: V(A, (r)) = number of specified values. è (e. g. , (A = 1 V A = 3 V A = 4 )), n If the selection condition is of the form A op r estimated V(A, (r)) = V(A. r) * s è where s is the selectivity of the selection. n In all the other cases: use approximate estimate of min(V(A, r), n (r) ) ê More accurate estimate can be got using probability theory, but this one works fine generally 50

Estimation of Distinct Values Joins: r s n If all attributes in A are

Estimation of Distinct Values Joins: r s n If all attributes in A are from r estimated V(A, r s) = min (V(A, r), n r s) n If A contains attributes A 1 from r and A 2 from s, then estimated V(A, r s) = min(V(A 1, r)*V(A 2 – A 1, s), V(A 1 – A 2, r)*V(A 2, s), nr s) ê More accurate estimate can be obtained using probability theory, but this one works generally fine 51

Estimation of Distinct Values n Estimation of distinct values are straightforward for projections. ê

Estimation of Distinct Values n Estimation of distinct values are straightforward for projections. ê They are the same in A (r) as in r. n The same holds for grouping attributes of aggregation. n For aggregated values ê For min(A) and max(A), the number of distinct values can be estimated as min(V(A, r), V(G, r)) where G denotes grouping attributes ê For other aggregates, assume all values are distinct, and use V(G, r) 52

Transformation of Relational Expressions n Two relational algebra expressions are said to be equivalent

Transformation of Relational Expressions n Two relational algebra expressions are said to be equivalent if on every legal database instance the two expressions generate the same set of tuples n In SQL, inputs and outputs are multisets of tuples ê Two expressions in the multiset version of the relational algebra are said to be equivalent if on every legal database instance the two expressions generate the same multiset of tuples n An equivalence rule says that expressions of two forms are equivalent ê Can replace expression of first form by second, or vice versa 53

Equivalence Rules 1. Conjunctive selection operations can be deconstructed into a sequence of individual

Equivalence Rules 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. a. (E 1 X E 2) = E 1 E 2 b. 1(E 1 2 E 2) = E 1 1 2 E 2 54

Pictorial Depiction of Equivalence Rules 55

Pictorial Depiction of Equivalence Rules 55

Equivalence Rules 5. Theta-join operations (and natural joins) are commutative. E 1 E 2

Equivalence Rules 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 2 3 (E 2 2 E 3) where 2 involves attributes from only E 2 and E 3. 56

Equivalence Rules 7. The selection operation distributes over theta join operation under the following

Equivalence Rules 7. The selection operation distributes over theta join operation under the following two conditions: (a) When all the attributes in 0 involve only the attributes of one of the expressions (E 1) being joined. 0 E 1 E 2) = ( 0(E 1)) E 2 (b) When 1 involves only the attributes of E 1 and 2 involves only the attributes of E 2. 1 E 2) = ( 1(E 1)) 57 ( (E 2))

Equivalence Rules 8. The projections operation distributes over theta join operation as follows: (a)

Equivalence Rules 8. The projections operation distributes over theta join operation as follows: (a) if involves only attributes from L 1 L 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. 58

Equivalence Rules 9. Set operations union and intersection are commutative E 1 E 2

Equivalence Rules 9. Set operations union and intersection are commutative 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) 11. Selection operation distributes over , and –. (E 1 – E 2) = (E 1) – (E 2) and similarly for and in place of – Also: (E 1 – E 2) = (E 1) – E 2 and similarly for in place of –, but not for 12. The projection operation distributes over union L(E 1 E 2) = ( L(E 1)) ( L(E 2)) 59

Transformation Example n Query: Find the names of all customers who have an account

Transformation Example n 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))) n Transformation using rule 7 a. customer-name (( branch-city =“Brooklyn” (branch)) (account depositor)) n Performing the selection as early as possible reduces the size of the relation to be joined. 60

Example with Multiple Transformations n Query: Find the names of all customers with an

Example with Multiple Transformations n 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))) n Transformation using join associatively (Rule 6 a): customer-name(( branch-city = “Brooklyn” (branch (account)) balance > 1000 depositor) n Second form provides an opportunity to apply the “perform selections early” rule, resulting in the subexpression branch-city = “Brooklyn” (branch) balance > 1000 (account) n Thus a sequence of transformations can be useful 61

Multiple Transformations 62

Multiple Transformations 62

Projection Operation Example customer-name(( branch-city = “Brooklyn” (branch) account) depositor) n When we compute

Projection Operation Example customer-name(( branch-city = “Brooklyn” (branch) account) depositor) n When we compute ( branch-city = “Brooklyn” (branch) account ) we obtain a relation whose schema is: (branch-name, branch-city, assets, account-number, balance) n Push projections using equivalence rules 8 a and 8 b; eliminate unneeded attributes from intermediate results to get: customer-name (( account-number ( ( branch-city = “Brooklyn” (branch) account )) depositor) 63

Join Ordering Example n For all relations r 1, r 2, and r 3,

Join Ordering Example n For all relations r 1, r 2, and r 3, (r 1 n If r 2 ) r 3 = r 1 (r 2 r 3 is quite large and r 1 (r 1 r 2 ) r 3 ) r 2 is small, we choose r 3 so that we compute and store a smaller temporary relation. 64

Join Ordering Example n Consider the expression customer-name (( branch-city = “Brooklyn” (branch)) account

Join Ordering Example n Consider the expression customer-name (( branch-city = “Brooklyn” (branch)) account depositor) n Could compute account depositor first, and join result with branch-city = “Brooklyn” (branch) but account depositor is likely to be a large relation. n Since it is more likely that only a small fraction of the bank’s customers have accounts in branches located in Brooklyn, it is better to compute branch-city = “Brooklyn” (branch) 65 account first.

Enumeration of Equivalent Expressions n Query optimizers use equivalence rules to systematically generate expressions

Enumeration of Equivalent Expressions n Query optimizers use equivalence rules to systematically generate expressions equivalent to the given expression n Conceptually, generate all equivalent expressions by repeatedly executing the following step until no more expressions can be found: ê for each expression found so far, use all applicable equivalence rules, and add newly generated expressions to the set of expressions found so far n The above approach is very expensive in space and time n Space requirements reduced by sharing common subexpressions: ê when E 1 is generated from E 2 by an equivalence rule, usually only the top level of the two are different, subtrees below are the same and can be shared è E. g. when applying join associativity n Time requirements are reduced by not generating all expressions ê More details shortly 66

Evaluation Plan n An evaluation plan defines exactly what algorithm is used for each

Evaluation Plan n An evaluation plan defines exactly what algorithm is used for each operation, and how the execution of the operations is coordinated. 67

Choice of Evaluation Plans n Must consider the interaction of evaluation techniques when choosing

Choice of Evaluation Plans n 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. E. g. ê merge-join may be costlier than hash-join, but may provide a sorted output which reduces the cost for an outer level aggregation. ê nested-loop join may provide opportunity for pipelining n 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. 68

Cost-Based Optimization n Consider finding the best join-order for r 1 r 2 .

Cost-Based Optimization n Consider finding the best join-order for r 1 r 2 . . . rn. n 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! n No need to generate all the join orders. Using dynamic programming, the least-cost join order for any subset of {r 1, r 2, . . . rn} is computed only once and stored for future use. 69

Dynamic Programming in Optimization n To find best join tree for a set of

Dynamic Programming in Optimization n To find best join tree for a set of n relations: ê To find best plan for a set S of n relations, consider all possible plans of the form: S 1 subset of S. (S – S 1) where S 1 is any non-empty ê Recursively compute costs for joining subsets of S to find the cost of each plan. Choose the cheapest of the 2 n – 1 alternatives. ê When plan for any subset is computed, store it and reuse it when it is required again, instead of recomputing it è Dynamic programming 70

Join Order Optimization Algorithm procedure findbestplan(S) if (bestplan[S]. cost ) return bestplan[S] // else

Join Order Optimization Algorithm procedure findbestplan(S) if (bestplan[S]. cost ) return bestplan[S] // else bestplan[S] has not been computed earlier, compute it now for each non-empty subset S 1 of S such that S 1 S P 1= findbestplan(S 1) P 2= findbestplan(S - S 1) A = best algorithm for joining results of P 1 and P 2 cost = P 1. cost + P 2. cost + cost of A if cost < bestplan[S]. cost = cost bestplan[S]. plan = “execute P 1. plan; execute P 2. plan; join results of P 1 and P 2 using A” return bestplan[S] 71

Cost of Optimization n With dynamic programming time complexity of optimization with bushy trees

Cost of Optimization n With dynamic programming time complexity of optimization with bushy trees is O(3 n). ê With n = 10, this number is 59000 instead of 176 billion! n Space complexity is O(2 n) n Cost-based optimization is expensive, but worthwhile for queries on large datasets (typical queries have small n, generally < 10) 72

Heuristic Optimization n Cost-based optimization is expensive, even with dynamic programming. n Systems may

Heuristic Optimization n Cost-based optimization is expensive, even with dynamic programming. n Systems may use heuristics to reduce the number of choices that must be made in a cost-based fashion. n Heuristic optimization transforms the query-tree by using a set of rules that typically (but not in all cases) improve execution performance: ê Perform selection early (reduces the number of tuples) ê Perform projection early (reduces the number of attributes) ê Perform most restrictive selection and join operations before other similar operations. ê Some systems use only heuristics, others combine heuristics with partial cost-based optimization. 73

Steps in Typical Heuristic Optimization 1. Deconstruct conjunctive selections into a sequence of single

Steps in Typical Heuristic Optimization 1. Deconstruct conjunctive selections into a sequence of single selection operations (Equiv. rule 1. ). 2. Move selection operations down the query tree for the earliest possible execution (Equiv. rules 2, 7 a, 7 b, 11). 3. Execute first those selection and join operations that will produce the smallest relations (Equiv. rule 6). 4. Replace Cartesian product operations that are followed by a selection condition by join operations (Equiv. rule 4 a). 5. Deconstruct and move as far down the tree as possible lists of projection attributes, creating new projections where needed (Equiv. rules 3, 8 a, 8 b, 12). 74