BKM_DATS: Databázové systémy 9. Query Processing and Relational Algebra Vlastislav Dohnal BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 2 Query Processing Overview Evaluation of Expressions Measures of Query Cost Evaluation algorithms Sorting Join Operation BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 3 Basic Steps in Query Processing 1. Parsing and translation 2. Optimization 3. Evaluation BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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)) BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 5 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 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 Relational Algebra Procedural language Six basic operations Select:  Project:  Union:  Set difference: – Cartesian product: × Rename:  Principle: An operation takes one or two relations as input and produce a new relation as a result. So, another operation can be applied to this result. Note: SQL is a declarative language. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 15 A=B  D > 5 (r) A,C (r) PB168, Vlastislav Dohnal, FI MUNI, 2023 16 Select and Project Operations: Example Relation r A B C D         1 5 12 23 7 7 3 10 A B C D     1 23 7 10 A C     1 5 12 23 PB168, Vlastislav Dohnal, FI MUNI, 2023 17 Select Operation Select operation is defined as: p(r) = {t | t  r  p(t)} where p is a formula in propositional calculus: formula := term formula formula  formula (not) ( formula ) term := expr expr expr := attribute_name constant is one of:  (and),  (or) is one of: =, , >, , <,  Project operation is defined as: ∏ 𝐴1,…,𝐴 𝑘 𝑟 = 𝑡 ∃𝑞 ∈ 𝑟 ∶ 𝑡 𝐴1 = 𝑞 𝐴1 ∧ ⋯ ∧ 𝑡 𝐴 𝑘 = 𝑞 𝐴 𝑘 where Ai are attribute names and r is a relation name. PB168, Vlastislav Dohnal, FI MUNI, 2023 18 Union, Set Difference, Intersect Operations Relations r, s: r  s A B    1 2 1 A B   2 3 r s A B     1 2 1 3 r – s A B   1 1 r ∩ s A B  2 PB168, Vlastislav Dohnal, FI MUNI, 2023 19 Can build complex expressions using multiple operations Example: A=C(r × s) Relations: Cartesian product and Operation Composition A B         1 1 1 1 2 2 2 2 C D         10 10 20 10 10 10 20 10 E a a b b a a b b A B C D E    1 2 2    10 10 20 a a b A B   1 2 r C D     10 10 20 10 E a a b b s r × s : A=C(r × s) PB168, Vlastislav Dohnal, FI MUNI, 2023 20 Example Queries Relations customer (customer_name, customer_street, customer_city) loan (loan_number, branch_name, amount) borrower (customer_name, loan_number) Find the names of all customers who have a loan at the Perryridge branch. customer_name(loan.loan_number = borrower.loan_number ( (branch_name = 'Perryridge' (loan)) × borrower)) Alternatively, as: customer_name (branch_name = 'Perryridge' ( borrower.loan_number = loan.loan_number (borrower × loan))) PB168, Vlastislav Dohnal, FI MUNI, 2023 21 Natural-Join Operation: Example Relations r, s: r  s A B      1 2 4 1 2 C D      a a b a b r A B C D E      1 1 1 1 2      a a a a b      B 1 3 1 2 3 D a a a b b E      s r  s is defined as: r.A, r.B, r.C, r.D, s.E (r.B = s.B  r.D = s.D (r  s)) PB168, Vlastislav Dohnal, FI MUNI, 2023 22 Bank Example Queries Relations: loan (loan_number, branch_name, amount) depositor (customer_name, account_number) borrower (customer_name, loan_number) Find the names of all customers who have a loan and an account at the bank. customer_name (borrower)  customer_name (depositor) Find the names of all customers who have a loan at the Perryridge branch. customer_name(branch_name = 'Perryridge' (loan  borrower)) Find all customers who have a loan at the bank and return his/her name, loan number and the loan amount. customer_name, loan_number, amount (borrower  loan) PB168, Vlastislav Dohnal, FI MUNI, 2023 23 Aggregate Operation: Example Relation account G sum(balance) (account) sum 3500 branch_name account_number balance Perryridge Perryridge Brighton Brighton Redwood A-102 A-201 A-217 A-215 A-222 400 900 750 750 700 branch_name G sum(balance) (account) branch_name sum Perryridge Brighton Redwood 1300 1500 700 PB168, Vlastislav Dohnal, FI MUNI, 2023 24 Left Outer Join: Example Left Outer Join loan  borrower Right Outer Join loan  borrower Full Outer Join loan  borrower Jones Smith null loan_number amount L-170 L-230 L-260 3000 4000 1700 customer_namebranch_name Downtown Redwood Perryridge 3000 4000 1700 loan_number amount L-170 L-230 L-260 branch_name Downtown Redwood Perryridge loan customer_name loan_number Jones Smith Hayes L-170 L-230 L-155 borrower loan_number amount L-170 L-230 L-155 3000 4000 null customer_name Jones Smith Hayes branch_name Downtown Redwood null loan_number amount L-170 L-230 L-260 L-155 3000 4000 1700 null customer_name Jones Smith null Hayes branch_name Downtown Redwood Perryridge null Query Processing Operators Selection or projection Table scan vs Index scan Sorting for ORDER BY or table joins In-memory → quick sort, … On-disk → external merge sort Joining tables Nested-loop join Merge-join Hash-join BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 25 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 26 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 27 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 28 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! BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 29 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. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 30 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) BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 31 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. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 32 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. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 33 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 34 Example: External Sorting Using Sort-Merge (2) Available memory M=3 blocks. One record per block BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 35 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 36 External Sort-Merge (Cont.) Cost in seeks During run generation: one seek to read each run and one seek to write each run 2 br / M During the merge phase Buffer size: bb (read/write bb blocks at a time) cannot be larger than (M-1) / “number of runs” 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 logM–1(br / M) -1) BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 37 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. BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 38 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 39 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 40 nstudent=5,000 bstudent=100 ntakes=10,000 btakes= 400 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 41 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 BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 43 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]). BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 44 Hash-Join (Cont.) buckets ri of r buckets si of s BKM_DATS, Vlastislav Dohnal, FI MUNI, 2022 45 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