MDA104 Introduction to Databases 5. Query Processing Vlastislav Dohnal MDA104, Vlastislav Dohnal, FI MUNI, 2024 2 Query Processing Overview Evaluation of Expressions Measures of Query Cost Evaluation algorithms Sorting Join Operation MDA104, Vlastislav Dohnal, FI MUNI, 2024 3 Basic Steps in Query Processing 1. Parsing and translation 2. Optimization 3. Evaluation MDA104, Vlastislav Dohnal, FI MUNI, 2024 4 Basic Steps in Query Processing (Cont.) Parsing and translation Translate the SQL query into its internal form. This is then translated into relational algebra. Parser checks syntax, verifies relations Optimization Generate a query-evaluation plan and choose algorithms for evaluating individual operations Evaluation The query-execution engine takes a query-evaluation plan, executes that plan, and returns the answers to the query. Basic Steps in Query Processing (Cont.) Example of query: List salary of all instructors that earn less than $75,000. SQL query SELECT salary FROM instructor WHERE salary < 75000 Conversion to rel. algebra salary(salary75000(instructor)) MDA104, Vlastislav Dohnal, FI MUNI, 2024 5 MDA104, Vlastislav Dohnal, FI MUNI, 2024 6 Basic Steps: Optimization A relational-algebra expression may have many equivalent expressions: salary(salary75000(instructor)) salary75000(salary(instructor)) For a relational-algebra expression, an expression tree is created instructor salary75000 salary instructor salary salary75000 MDA104, Vlastislav Dohnal, FI MUNI, 2024 7 Basic Steps: Optimization (Cont.) 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 execution-plan or evaluation-plan. E.g., to find instructors with salary < 75000 use an index on salary, or perform complete relation scan and discard instructors with salary  75000 MDA104, Vlastislav Dohnal, FI MUNI, 2024 8 Basic Steps: Optimization (Cont.) Example of an evaluation-plan instructor salary75000 salary Use index scan with index on salary Eliminate duplicates by sorting Use pipelining MDA104, Vlastislav Dohnal, FI MUNI, 2024 9 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. There is a huge number of possible evaluation plans Optimization uses some heuristics 1. Perform selection early reduce the number of tuples (by using an index, e.g.) 2. Perform projection early reduce the number of attributes 3. Perform most restrictive operations early such as join and selection. MDA104, Vlastislav Dohnal, FI MUNI, 2024 10 Evaluation of Expressions Alternatives for evaluating an entire expression tree Materialization Evaluate one operation at a time, starting at the lowest-level. Use intermediate results materialized into temporary relations to evaluate next-level operations. Pipelining pass on tuples to parent operations even as an operation is being executed MDA104, Vlastislav Dohnal, FI MUNI, 2024 11 Evaluation of Expressions (Cont.) Materialized evaluation Compute σbuilding=`Watson’(department) and store it Then read from stored intermediate result and compute its join with instructor, store it Finally read it and compute the projection on name and output it. This step can be conveniently evaluated using pipelining on join result. MDA104, Vlastislav Dohnal, FI MUNI, 2024 12 Measures of Query Cost Cost is generally measured as total elapsed time for answering query Many factors contribute to time cost disk accesses, CPU, or even network communication Typically disk access is the predominant cost and is also relatively easy to estimate. Measured by taking into account Number of seeks * average-seek-cost Number of blocks read * average-block-read-cost Number of blocks written * average-block-write-cost 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 MDA104, Vlastislav Dohnal, FI MUNI, 2024 13 Measures of Query Cost (Cont.) 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 tS – time for one seek Cost for b block transfers plus S seeks b * tT + S * tS We ignore CPU costs for simplicity Real systems do take CPU cost into account We do not include cost to writing output to disk in our cost formulae MDA104, Vlastislav Dohnal, FI MUNI, 2024 14 Measures of Query Cost (Cont.) Several algorithms can reduce disk I/O by using extra buffer space Amount of real memory available to buffer depends on other concurrent queries and OS processes, known only during execution We often use worst case estimates, assuming only the minimum amount of memory needed for the operation is available Required data may be buffer resident already, avoiding disk I/O But hard to take into account for cost estimation MDA104, Vlastislav Dohnal, FI MUNI, 2024 15 Selection Operation File scan (table / sequential scan) – no index structure is necessary 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 matching 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 MDA104, Vlastislav Dohnal, FI MUNI, 2024 16 Selections Using Indices Index scan – search algorithms that use an index selection condition must be on search-key of index Now, assume the sequential file is ordered by this key: Algorithm for primary index & equality on primary key Retrieve a single record that satisfies the corresponding equality condition Cost = (hi + 1) * (tS + tT) hi – height of index i (for hashing hi =1) +1 – for reading the actual record Algorithm for primary index & equality on non-primary key Retrieve multiple records. Records will be on consecutive blocks Let b = number of blocks containing all n matching records Cost = hi * (tS + tT) + tS + tT * b MDA104, Vlastislav Dohnal, FI MUNI, 2024 17 Selections Using Indices Algorithm for secondary index & equality on non-primary key Sequential file is not ordered by this search key! Retrieve a single record if the search-key is a candidate key Cost = (hi + 1) * (tS + tT) 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) * (tS + tT) Can be very expensive! MDA104, Vlastislav Dohnal, FI MUNI, 2024 18 Sorting Relations We may build an index on the relation, and then use the index to read the relation in the sorted order. May lead to one disk block access for each tuple. Use a sorting algorithm For relations that fit in memory, techniques like quick-sort can be used. For relations that don’t fit in memory, external sort-merge is a good choice. MDA104, Vlastislav Dohnal, FI MUNI, 2024 19 External Sort-Merge Let M denote memory size (in pages/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) MDA104, Vlastislav Dohnal, FI MUNI, 2024 20 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. 2. Read the first block of each run into its buffer page 3. 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 next block (if any) of the run into the buffer. 4. until all input buffer pages are empty. MDA104, Vlastislav Dohnal, FI MUNI, 2024 21 External Sort-Merge (Cont.) If N  M, several merge passes are required. In each pass, continuous 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. MDA104, Vlastislav Dohnal, FI MUNI, 2024 22 Example: External Sorting Using Sort-Merge Available memory M=4 blocks. One record per block g 24 a 19 d 31 c 33 b 14 e 16 r 16 d 21 m 3 p 2 d 7 a 14 initial relation a 19 c 33 d 31 g 24 b 14 d 21 e 16 r 16 a 14 d 7 m 3 p 2 runscreate runs (m-1)-way merging a 14 a 19 b 14 c 33 d 7 d 21 d 31 e 16 g 24 m 3 p 2 r 16 sorted output MDA104, Vlastislav Dohnal, FI MUNI, 2024 24 External Sort-Merge (Cont.) Cost analysis: Total number of merge passes required: logM–1(br /M). Block transfers for initial run creation as well as in each pass is 2br 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 block transfers for external sorting: br (2 logM–1(br / M) + 1) Seeks: next slide MDA104, Vlastislav Dohnal, FI MUNI, 2024 26 Join Operation Several different algorithms to implement joins Nested-loop join Block nested-loop join Improved nested-loop join by reading records in blocks Indexed nested-loop join Improved by using an index to look up equal records Merge-join Hash-join Choice based on cost estimate For each of the variants a cost estimation can be stated. MDA104, Vlastislav Dohnal, FI MUNI, 2024 27 Nested-Loop Join To compute the 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 equality on shared attributes if they do, add tr • ts to the result. end 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. Cost = nr * (tS + tT) * (ns * (tS + tT) ) where nr = number of tuples in r 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 Example on student and takes student (the smaller one) as the outer relation: 5000  400 + 100 = 2,000,100 block transfers, 5000 + 100 = 5,100 seeks takes (the larger one) as the outer relation 10000  100 + 400 = 1,000,400 block transfers and 10,400 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 Example: student fits entirely in memory the cost estimate is 500 block transfers. Block nested-loops algorithm (next slide) is preferable. nstudent=5,000 bstudent=100 ntakes=10,000 btakes= 400 MDA104, Vlastislav Dohnal, FI MUNI, 2024 28 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 Cost: br * (1+bs) blocks; br * (1+1) seeks For student (outer) and takes (inner): 100 + 100 * 400 = 40,100 block transfers 100 + 100 seeks MDA104, Vlastislav Dohnal, FI MUNI, 2024 29 nstudent=5,000 bstudent=100 ntakes=10,000 btakes= 400 MDA104, Vlastislav Dohnal, FI MUNI, 2024 30 Merge-Join 1. Sort both relations on their join attributes If not already sorted. 2. Merge the sorted relations to join them Join step is similar to the merge stage of the sort-merge algorithm. Main difference is handling of duplicate values in join attribute Every pair with same value on join attribute must be matched Merge-Join (Cont.) Can be used only for equi-joins 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, and max. 2*br / bb + 1 seeks Assuming we read r in runs of bb blocks + the cost of sorting if relations are unsorted. MDA104, Vlastislav Dohnal, FI MUNI, 2024 31 MDA104, Vlastislav Dohnal, FI MUNI, 2024 32 Hash-Join A hash function h is used to partition tuples of both relations JoinAttrs are the common attributes of r and s used in r  s h maps JoinAttrs values to {0, 1, ..., n} r0 , r1 , . . . , rn denote buckets of r Each tuple tr  r is put in bucket ri where i = h(tr [JoinAttrs]). s0 , s1 , . . . , sn denotes buckets of s Each tuple ts  s is put in bucket si, where i = h(ts [JoinAttrs]). MDA104, Vlastislav Dohnal, FI MUNI, 2024 33 Hash-Join (Cont.) buckets ri of r buckets si of s MDA104, Vlastislav Dohnal, FI MUNI, 2024 34 Hash-Join (Cont.) Tuples in ri need only to be compared with tuples in si Need not be compared with s tuples in any other bucket, since: a tuple of r and a tuple of s that satisfy the join condition will have the same value for the join attributes. If that value is hashed to some value i, the tuple of r has to be in ri and the tuple of s in si. Cost of hash join is 3(br + bs) block transfers 3*(100+400) for student  takes nstudent=5,000 bstudent=100 ntakes=10,000 btakes= 400 Summary – Takeaways Steps in query processing Idea of query optimization expression transformations (in parse tree) selection of algorithm to evaluate an operator index vs table scan Algorithms Sorting large relations (exceeding RAM allocation) Joining relations nested loops, merge join, hash join MDA104, Vlastislav Dohnal, FI MUNI, 2024 35