Cost-based Query Sub-System. Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Last Class.

Similar documents
Faloutsos 1. Carnegie Mellon Univ. Dept. of Computer Science Database Applications. Outline

CS 4604: Introduction to Database Management Systems. B. Aditya Prakash Lecture #10: Query Processing

15-415/615 Faloutsos 1

Implementation of Relational Operations. Introduction. CS 186, Fall 2002, Lecture 19 R&G - Chapter 12

CAS CS 460/660 Introduction to Database Systems. Query Evaluation II 1.1

Evaluation of Relational Operations

Announcement. Reading Material. Overview of Query Evaluation. Overview of Query Evaluation. Overview of Query Evaluation 9/26/17

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Administrivia. Administrivia. Faloutsos/Pavlo CMU /615

Evaluation of relational operations

Database Applications (15-415)

Implementing Relational Operators: Selection, Projection, Join. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

Implementation of Relational Operations

Evaluation of Relational Operations: Other Techniques. Chapter 14 Sayyed Nezhadi

Evaluation of Relational Operations

Evaluation of Relational Operations. Relational Operations

Database Management System

Database Applications (15-415)

Implementation of Relational Operations: Other Operations

Overview of Query Evaluation. Chapter 12

Overview of Implementing Relational Operators and Query Evaluation

Administriva. CS 133: Databases. General Themes. Goals for Today. Fall 2018 Lec 11 10/11 Query Evaluation Prof. Beth Trushkowsky

Database Applications (15-415)

External Sorting Implementing Relational Operators

Evaluation of Relational Operations

Overview of Query Processing. Evaluation of Relational Operations. Why Sort? Outline. Two-Way External Merge Sort. 2-Way Sort: Requires 3 Buffer Pages

Evaluation of Relational Operations: Other Techniques

CS330. Query Processing

Implementing Joins 1

CompSci 516 Data Intensive Computing Systems

Overview of Query Evaluation. Overview of Query Evaluation

Database Applications (15-415)

Evaluation of Relational Operations: Other Techniques

Overview of Query Evaluation

Principles of Data Management. Lecture #9 (Query Processing Overview)

ECS 165B: Database System Implementa6on Lecture 7

Evaluation of Relational Operations: Other Techniques

Database Systems. Announcement. December 13/14, 2006 Lecture #10. Assignment #4 is due next week.

Join Algorithms. Lecture #12. Andy Pavlo Computer Science Carnegie Mellon Univ. Database Systems / Fall 2018

Query Evaluation Overview, cont.

Evaluation of Relational Operations. SS Chung

R & G Chapter 13. Implementation of single Relational Operations Choices depend on indexes, memory, stats, Joins Blocked nested loops:

Dtb Database Systems. Announcement

Midterm Review CS634. Slides based on Database Management Systems 3 rd ed, Ramakrishnan and Gehrke

Query Evaluation Overview, cont.

QUERY EXECUTION: How to Implement Relational Operations?

Today's Class. Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Example Database. Query Plan Example

CompSci 516 Data Intensive Computing Systems. Lecture 11. Query Optimization. Instructor: Sudeepa Roy

Review. Relational Query Optimization. Query Optimization Overview (cont) Query Optimization Overview. Cost-based Query Sub-System

Last Class Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications

CSE 444: Database Internals. Sec2on 4: Query Op2mizer

Query Optimization. Schema for Examples. Motivating Example. Similar to old schema; rname added for variations. Reserves: Sailors:

CSE 444: Database Internals. Section 4: Query Optimizer

Overview of Query Processing

Relational Query Optimization

Relational Query Optimization. Highlights of System R Optimizer

RELATIONAL OPERATORS #1

Query Processing. Debapriyo Majumdar Indian Sta4s4cal Ins4tute Kolkata DBMS PGDBA 2016

Presenter: Eunice Tan Lam Ziyuan Yan Ming fei. Join Algorithm

Chapter 12: Query Processing. Chapter 12: Query Processing

Chapter 12: Query Processing

Query Optimization. Schema for Examples. Motivating Example. Similar to old schema; rname added for variations. Reserves: Sailors:

Chapter 13: Query Processing

TotalCost = 3 (1, , 000) = 6, 000

Schema for Examples. Query Optimization. Alternative Plans 1 (No Indexes) Motivating Example. Alternative Plans 2 With Indexes

Principles of Data Management. Lecture #12 (Query Optimization I)

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #11: Query Processing and Midterm Review

Last Class. Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Why do we need to sort? Today's Class

Relational Query Optimization. Overview of Query Evaluation. SQL Refresher. Yanlei Diao UMass Amherst October 23 & 25, 2007

! A relational algebra expression may have many equivalent. ! Cost is generally measured as total elapsed time for

Chapter 13: Query Processing Basic Steps in Query Processing

Chapter 12: Query Processing

Administrivia. Relational Query Optimization (this time we really mean it) Review: Query Optimization. Overview: Query Optimization

192 Chapter 14. TotalCost=3 (1, , 000) = 6, 000

Relational Query Optimization

ATYPICAL RELATIONAL QUERY OPTIMIZER

Examples of Physical Query Plan Alternatives. Selected Material from Chapters 12, 14 and 15

Operator Implementation Wrap-Up Query Optimization

Final Exam Review. Kathleen Durant CS 3200 Northeastern University Lecture 22

CSE 544 Principles of Database Management Systems

Overview of DB & IR. ICS 624 Spring Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

EECS 647: Introduction to Database Systems

An SQL query is parsed into a collection of query blocks optimize one block at a time. Nested blocks are usually treated as calls to a subroutine

Final Exam Review. Kathleen Durant PhD CS 3200 Northeastern University

Query Processing: The Basics. External Sorting

Query Evaluation! References:! q [RG-3ed] Chapter 12, 13, 14, 15! q [SKS-6ed] Chapter 12, 13!

Query Processing. Introduction to Databases CompSci 316 Fall 2017

CSIT5300: Advanced Database Systems

CSE 444: Database Internals. Lectures 5-6 Indexing

IMPORTANT: Circle the last two letters of your class account:

Announcements. Two typical kinds of queries. Choosing Index is Not Enough. Cost Parameters. Cost of Reading Data From Disk

Database System Concepts

Sorting & Aggregations

Administrivia. CS 133: Databases. Cost-based Query Sub-System. Goals for Today. Midterm on Thursday 10/18. Assignments

Data Storage. Query Performance. Index. Data File Types. Introduction to Data Management CSE 414. Introduction to Database Systems CSE 414

Query Evaluation (i)

Sorting a file in RAM. External Sorting. Why Sort? 2-Way Sort of N pages Requires Minimum of 3 Buffers Pass 0: Read a page, sort it, write it.

Query Processing. Lecture #10. Andy Pavlo Computer Science Carnegie Mellon Univ. Database Systems / Fall 2018

Overview of Query Evaluation

Spring 2017 QUERY PROCESSING [JOINS, SET OPERATIONS, AND AGGREGATES] 2/19/17 CS 564: Database Management Systems; (c) Jignesh M.

Advances in Data Management Query Processing and Query Optimisation A.Poulovassilis

Transcription:

Cost-based Query Sub-System Carnegie Mellon Univ. Dept. of Computer Science 15-415/615 - DB Applications Queries Select * From Blah B Where B.blah = blah Query Parser Query Optimizer C. Faloutsos A. Pavlo Lecture#14: Implementation of Relational Operations Plan Generator Plan Cost Estimator Query Plan Evaluator Catalog Manager Schema Statistics 3 Last Class Query Processing Sorting: External Merge Sort Projection: External Merge Sort Two-Phase Hashing These are for when the data is larger than the amount of memory available. Some database operations are expensive. The DBMS can greatly improve performance by being smart e.g., can speed up 1,000,000x over naïve approach Faloutsos/Pavlo 15-415/615 4 Faloutsos/Pavlo 15-415/615 5

Query Processing Today s Class There are clever implementation techniques for operators. We can exploit equivalencies of relational operators to do less work. Use statistics and cost models to choose among these. Introduction Selection Joins Explain Work smarter, not harder. Faloutsos/Pavlo 15-415/615 6 Faloutsos/Pavlo 15-415/615 7 Sample Database Sample Database SAILORS sid sname rating age 1 Trump 999 45.0 3 Obama 50 52.0 2 Tupac 32 26.0 6 Bieber 10 19.0 RESERVES sid bid day rname 6 103 2014-02-01 matlock 1 102 2014-02-02 macgyver 2 101 2014-02-02 a-team 1 101 2014-02-01 dallas Sailors(sid: int, sname: varchar, rating: int, age: real) Reserves(sid: int, bid: int, day: date, rname: varchar) SAILORS sid sname rating age 1 Trump 999 45.0 3 Obama 50 52.0 2 Tupac 32 26.0 6 Bieber 10 19.0 Each tuple is 50 bytes 80 tuples per page 500 pages total N=500, p S =80 RESERVES sid bid day rname 6 103 2014-02-01 matlock 1 102 2014-02-02 macgyver 2 101 2014-02-02 a-team 1 101 2014-02-01 dallas Each tuple is 40 bytes 100 tuples per page 1000 pages total M=1000, p R =100 Faloutsos/Pavlo 15-415/615 8 Faloutsos/Pavlo 15-415/615 9

Single-Table Selection Single-Table Selection SELECT * FROM Reserves AS R WHERE R.rname < C% SELECT * FROM Reserves AS R WHERE R.rname < C% σ rname< C% (Reserves) σ rname< C% RESERVES What s the best way to execute this query? A: It depends on What indexes and access paths are available. What is the expected size of the result (in terms of number of tuples and/or number of pages) Faloutsos/Pavlo 15-415/615 10 Faloutsos/Pavlo 15-415/615 11 Access Paths Simple Selections How the DBMS retrieves tuples from a table for a query plan. File Scan (aka Sequential Scan) Index Scan (Tree, Hash, List, ) Selectivity of an access path: % of pages we retrieve e.g., Selectivity of a hash index, on range query: 100% (no reduction!) Size of result approximated as: (size of R) (selectivity) Selectivity is also called Reduction Factor. The estimate of reduction factors is based on statistics we will discuss shortly. Faloutsos/Pavlo 15-415/615 12 Faloutsos/Pavlo 15-415/615 13

Selection Options Selection: No Index, Unsorted Data No Index, Unsorted Data No Index, Sorted Data B+Tree Index Hash Index, Equality Selection SELECT * FROM Reserves AS R WHERE R.rname < C% Must scan the whole relation. Cost: M For Reserves = 1000 I/Os. Faloutsos/Pavlo 15-415/615 14 Faloutsos/Pavlo 15-415/615 15 Selection: No Index, Sorted Data Selection: B+Tree Index SELECT * FROM Reserves AS R WHERE R.rname < C% SELECT * FROM Reserves AS R WHERE R.rname < C% Cost of binary search + number of pages containing results. Cost: log 2 M + selectivity #pages With an index on selection attribute: Use index to find qualifying data entries, then retrieve corresponding data records. Note: Hash indexes are only useful for equality selections. Faloutsos/Pavlo 15-415/615 16 Faloutsos/Pavlo 15-415/615 17

Selection: B+Tree Index B+Tree Indexes Cost depends on #qualifying tuples, and clustering. Finding qualifying data entries (typically small) Plus cost of retrieving records (could be large w/o clustering). CLUSTERED Index entries direct search for data entries Data entries UNCLUSTERED Data entries (Index File) (Data file) Data Records Data Records Faloutsos/Pavlo 15-415/615 18 Faloutsos/Pavlo 15-415/615 19 B+Tree Indexes Selection: B+Tree Index CLUSTERED <key,rid> rid data Index entries direct search for data entries Data entries Data Records UNCLUSTERED Data entries (Index File) (Data file) Data Records SELECT * FROM Reserves AS R WHERE R.rname < C% In example Reserves relation, if 10% of tuples qualify (100 pages, 10,000 tuples): With a clustered index, cost is little more than 100 I/Os; If unclustered, could be up to 10,000 I/Os! unless Faloutsos/Pavlo 15-415/615 20 Faloutsos/Pavlo 15-415/615 21

Selection: B+Tree Index Partial Indexes Refinement for unclustered indexes: Find qualifying data records by their rid. Sort rid s of the data records to be retrieved. Fetch rids in order. This ensures that each data page is looked at just once (though # of such pages likely to be higher than with clustering). Create an index on a subset of the entire table. This potentially reduces its size and the amount of overhead to maintain it. CREATE INDEX idx_foo ON foo (a, b) WHERE c = WuTang SELECT b FROM foo WHERE a = 123 AND c = WuTang Faloutsos/Pavlo 15-415/615 22 Faloutsos/Pavlo 15-415/615 23 Covering Indexes Index Include Columns If all of the fields needed to process the query are available in an index, then the DBMS does not need to retrieve the tuple. CREATE INDEX idx_foo ON foo (a, b) SELECT b FROM foo WHERE a = 123 Embed additional columns in indexes to support index-only queries. Not part of the search key. CREATE INDEX idx_foo ON foo (a, b) INCLUDE (c) SELECT b FROM foo WHERE a = 123 AND c = WuTang Faloutsos/Pavlo 15-415/615 24 Faloutsos/Pavlo 15-415/615 25

Selection Conditions B+Tree Prefix Search A B-tree index matches terms that involve only attributes in a prefix of the search key. Index on <a,b,c> matches (a=5 AND b=3), but not (b=3). For Hash index, we must have all attributes in search key. Key = xy Key = _y yz? xx xy zy zz Faloutsos/Pavlo 15-415/615 26 Faloutsos/Pavlo 15-415/615 27 Two Approaches to Selection Approach #1 Approach #1: Find the cheapest access path, retrieve tuples using it, and apply any remaining terms that don t match the index Approach #2: Use multiple indexes to find the intersection of matching tuples. Find the cheapest access path, retrieve tuples using it, and apply any remaining terms that don t match the index: Cheapest access path: An index or file scan with fewest I/Os. Terms that match this index reduce the number of tuples retrieved; other terms help discard some retrieved tuples, but do not affect number of tuples/pages fetched. Faloutsos/Pavlo 15-415/615 28 Faloutsos/Pavlo 15-415/615 29

Approach #1 Example Approach #1 Example (day< 10/13/2015 AND bid=5 AND sid=3) A B+ tree index on day can be used; then, bid=5 and sid=3 must be checked for each retrieved tuple. Similarly, a hash index on <bid,sid> could be used; Then, day< 10/13/2015 must be checked. (day< 10/13/2015 AND bid=5 AND sid=3) How about a B+tree on <rname,day>? How about a B+tree on <day,rname>? How about a Hash index on <day,rname>? What if we have multiple indexes? Faloutsos/Pavlo 15-415/615 30 Faloutsos/Pavlo 15-415/615 31 Approach #2 Approach #2 Example Get rids from first index; rids from second index; intersect and fetch. If we have 2 or more matching indexes: Get sets of rids of data records using each matching index. Then intersect these sets of rids. Retrieve the records and apply any remaining terms. (day< 10/13/2015 AND bid=5 AND sid=3) With an index on day and an index on sid, We can retrieve rids of records satisfying day< 10/13/2015 using the first, rids of recs satisfying sid=3 using the second, intersect, retrieve records and check bid=5. Faloutsos/Pavlo 15-415/615 32 Faloutsos/Pavlo 15-415/615 33

Approach #2 Example (day< 10/13/2015 AND bid=5 AND sid=3) Set intersection can be done with bitmaps, hash tables, or bloom filters. day< 10/13/2015 record ids sid=3 record ids Summary For selections, we always want an index. B+Trees are more versatile. almost! Hash indexes are faster, but only support equality predicates. Last resort is to just scan entire table. fetch records bid=5 Faloutsos/Pavlo 15-415/615 34 Faloutsos/Pavlo 15-415/615 35 Today s Class Joins Introduction Selection Joins Explain R S is very common and thus must be carefully optimized. R S followed by a selection is inefficient because cross-product is large. There are many approaches to reduce join cost, but no one works best for all cases. Remember, join is associative and commutative. Faloutsos/Pavlo 15-415/615 36 Faloutsos/Pavlo 15-415/615 37

Joins Joins Join techniques we will cover: Nested Loop Joins Index Nested Loop Joins Sort-Merge Joins Hash Joins Assume: M pages in R, pr tuples per page, m tuples total N pages in S, ps tuples per page, n tuples total In our examples, R is Reserves and S is Sailors. We will consider more complex join conditions later. Cost metric: # of I/Os We will ignore output costs Faloutsos/Pavlo 15-415/615 38 Faloutsos/Pavlo 15-415/615 39 First Example Simple Nested Loop Join SELECT * FROM Reserves R, Sailors S WHERE R.sid = S.sid Assume that we don t know anything about the tables and we don t have any indexes. Algorithm #0: Simple Nested Loop Join foreach tuple r of R foreach tuple s of S output, if they match Faloutsos/Pavlo 15-415/615 40 Faloutsos/Pavlo 15-415/615 41

Simple Nested Loop Join Simple Nested Loop Join Algorithm #0: Simple Nested Loop Join outer relation foreach tuple r of R foreach tuple s of S output, if they match inner relation Algorithm #0: Why is it bad? How many disk accesses ( M and N are the number of blocks for R and S )? Cost: M + (pr M) N M pages, m tuples N pages, n tuples Faloutsos/Pavlo 15-415/615 42 Faloutsos/Pavlo 15-415/615 43 Simple Nested Loop Join Simple Nested Loop Join Actual number: M + (pr M) N = 1000 + 100 1000 500 = 50,001,000 I/Os At 10ms/IO, Total time 5.7 days What if smaller relation (S) was outer? Slightly better What assumptions are being made here? 1 buffer for each table (and 1 for output) Actual number: M + (pr M) N = 1000 + 100 SSD 1000 1.3 500 hours = 50,001,000 I/Os at 0.1ms/IO At 10ms/IO, Total time 5.7 days What if smaller relation (S) was outer? Slightly better What assumptions are being made here? 1 buffer for each table (and 1 for output) Faloutsos/Pavlo 15-415/615 44 Faloutsos/Pavlo 15-415/615 45

Simple Nested Loop Join Simple Nested Loop Join Actual number: M + (pr M) N = 1000 + 100 SSD 1000 1.3 5000 hours = 50,001,000 I/Os at 0.1ms/IO At 10ms/IO, Total time 5.7 days What if smaller relation (S) was outer? Slightly better What assumptions are being made here? 1 buffer for each table (and 1 for output) Actual number: M + (pr M) N = 1000 + 100 SSD 1000 1.3 5000 hours = 50,001,000 I/Os at 0.1ms/IO At 10ms/IO, Total time 5.7 days What if smaller relation (S) was outer? Slightly better What assumptions are being made here? 1 buffer for each table (and 1 for output) Faloutsos/Pavlo 15-415/615 46 Faloutsos/Pavlo 15-415/615 47 Block Nested Loop Join Block Nested Loop Join Algorithm #1: Block Nested Loop Join read block from R read block from S output, if tuples match Algorithm #1: Things are better. How many disk accesses ( M and N are the number of blocks for R and S )? Cost: M + (M N) M pages, m tuples N pages, n tuples M pages, m tuples N pages, n tuples Faloutsos/Pavlo 15-415/615 48 Faloutsos/Pavlo 15-415/615 49

Block Nested Loop Join Block Nested Loop Join Actual number: SSD 50 seconds at 0.1ms/IO M + (M N) = 1000 + 1000 500 = 501,000 I/Os At 10ms/IO, Total time 1.4 hours Actual number: N + (M N) = 500 + 1000 500 = 500,500 I/Os At 10ms/IO, Total time 1.4 hours What if we use the smaller one as the outer relation? The smallest in terms of # of pages. What if we have B buffers available? Give B-2 buffers to outer relation, 1 to inner relation, 1 for output Faloutsos/Pavlo 15-415/615 50 Faloutsos/Pavlo 15-415/615 51 Block Nested Loop Join Block Nested Loop Join Algorithm #1: Using multiple buffers. read B-2 blocks from R read block from S output, if tuples match Algorithm #1: Using multiple buffers. How many disk accesses ( M and N are the number of blocks for R and S )? Cost: M+ ( M/(B-2) N ) M pages, m tuples N pages, n tuples M pages, m tuples N pages, n tuples Faloutsos/Pavlo 15-415/615 52 Faloutsos/Pavlo 15-415/615 53

Block Nested Loop Join Block Nested Loop Join Algorithm #1: Using multiple buffers. But if the outer relation fits in memory: Cost: M+N Actual number: M + N = 1000 + 500 = 1500 At 10ms/IO, Total time 15 seconds SSD 0.15 seconds at 0.1ms/IO M pages, m tuples N pages, n tuples Faloutsos/Pavlo 15-415/615 54 Faloutsos/Pavlo 15-415/615 55 Joins Index Nested Loop Join techniques we will cover: Nested Loop Joins Index Nested Loop Joins Sort-Merge Joins Hash Joins Why do basic nested loop joins suck? For each tuple in the outer table, we have to do a sequential scan to check for a match in the inner table. A better approach is to use an index to find inner table matches. We could use an existing index, or even build one on the fly. Faloutsos/Pavlo 15-415/615 56 Faloutsos/Pavlo 15-415/615 57

Index Nested Loop Join Index Nested Loop Join Algorithm #2: Index Nested Loop Join foreach tuple r of R foreach tuple s of S, where r i ==s j output Index Probe Algorithm #2: Index Nested Loop Join How many disk accesses ( M and N are the number of blocks for R and S )? Cost: M + m C Look-up Cost M pages, m tuples N pages, n tuples M pages, m tuples N pages, n tuples Faloutsos/Pavlo 15-415/615 58 Faloutsos/Pavlo 15-415/615 59 Nested Loop Joins Guideline Joins Pick the smallest table as the outer relation i.e., the one with the fewest pages Put as much of it in memory as possible Loop over the inner Join techniques we will cover: Nested Loop Joins Index Nested Loop Joins Sort-Merge Joins Hash Joins Faloutsos/Pavlo 15-415/615 60 Faloutsos/Pavlo 15-415/615 61

Sort-Merge Join Sort-Merge Join First sort both tables on joining attribute. Then step through each one in lock-step to find matches. This algorithm is useful if: One or both tables are already sorted on join attribute(s) Output is required to be sorted on join attributes The Merge phase can require some back tracking if duplicate values appear in join column. Faloutsos/Pavlo 15-415/615 62 Faloutsos/Pavlo 15-415/615 63 Sort-Merge Join Sort-Merge Join Algorithm #3: Sort-Merge Join How many disk accesses ( M and N are the number of blocks for R and S )? Cost: (2M logm/logb) + (2N logn/logb) + M + N Algorithm #3: Sort-Merge Join How many disk Sort accesses Cost ( M and Sort N Cost are the number of blocks for R and S )? Cost: (2M logm/logb) + (2N logn/logb) + M + N Merge Cost M pages, m tuples N pages, n tuples M pages, m tuples N pages, n tuples Faloutsos/Pavlo 15-415/615 64 Faloutsos/Pavlo 15-415/615 65

Sort-Merge Join Example Sort-Merge Join Example SELECT * FROM Reserves R, Sailors S WHERE R.sid = S.sid SELECT * FROM Reserves R, Sailors S WHERE R.sid = S.sid sid sname rating age 1 Trump 999 45.0 3 Obama 50 52.0 2 Tupac 32 26.0 6 Bieber 10 19.0 Sort! sid bid day rname 6 103 2014-02-01 matlock 1 102 2014-02-02 macgyver 2 101 2014-02-02 a-team 1 101 2014-02-01 dallas Sort! sid sname rating age 1 Trump 999 45.0 2 Tupac 32 26.0 3 Obama 50 52.0 6 Bieber 10 19.0 Merge! sid bid day rname 1 102 2014-02-02 macgyver 1 101 2014-02-01 dallas 2 101 2014-02-02 a-team 6 103 2014-02-01 matlock Merge! Faloutsos/Pavlo 15-415/615 66 Faloutsos/Pavlo 15-415/615 67 Sort-Merge Join Example Sort-Merge Join Example With 100 buffer pages, both Reserves and Sailors can be sorted in 2 passes: Cost: 7,500 I/Os At 10ms/IO, Total time 75 seconds Block Nested Loop: Cost: 2,500 to 15,000 I/Os With 100 buffer pages, both Reserves and Sailors can be sorted in 2 passes: SSD 0.75 seconds at 0.1ms/IO Cost: 7,500 I/Os At 10ms/IO, Total time 75 seconds Block Nested Loop: Cost: 2,500 to 15,000 I/Os Faloutsos/Pavlo 15-415/615 68 Faloutsos/Pavlo 15-415/615 69

Sort-Merge Join Sort-Merge Join Optimizations Worst case for merging phase? When all of the tuples in both relations contain the same value in the join attribute. Cost: (M N) + (sort cost) All the refinements from external sorting Plus overlapping of the merging of sorting with the merging of joining. Multi-threaded optimizations. Don t worry kids! This is unlikely! Faloutsos/Pavlo 15-415/615 70 Faloutsos/Pavlo 15-415/615 71 Joins In-Memory Hash Join Join techniques we will cover: Nested Loop Joins Index Nested Loop Joins Sort-Merge Joins Hash Joins This assumes H Algorithm #4: In-Memory Hash fits in Join memory! build hash table H for R foreach tuple s of S output, if h(s j ) H R(A,...) Hash Table Hash Probe h 1 h 1 Faloutsos/Pavlo 15-415/615 72 Faloutsos/Pavlo 15-415/615 73

Grace Hash Join Grace Hash Join Hash join when tables don t fit in memory. Partition Phase: Hash both tables on the join attribute into partitions. Probing Phase: Compares tuples in corresponding partitions for each table. Named after the GRACE database machine. Hash R into (0, 1,..., max ) buckets Hash S into buckets (same hash function) R(A,...) h 1 h 1 Faloutsos/Pavlo 15-415/615 74 Faloutsos/Pavlo 15-415/615 75 Grace Hash Join Grace Hash Join Join each pair of matching buckets: Build another hash table for H S(i), and probe it with each tuple of H R(i) Choose the (page-wise) smallest - if it fits in memory, do a nested loop join Build a hash table (with H 2!= H) And then probe it for each tuple of the other R(A,...) H R(i) 0 H S(i) 1 h 1 2 max h 1 Faloutsos/Pavlo 15-415/615 76 Faloutsos/Pavlo 15-415/615 77

Grace Hash Join Grace Hash Join What if H S(i) is too large to fit in memory? Recursive Partitioning! More details (overflows, hybrid hash joins) available in textbook (Ch 14.4.3) Cost of hash join? Assume that we have enough buffers. Cost: 3(M + N) Partitioning Phase: read+write both tables 2(M+N) I/Os Probing Phase: read both tables M+N I/Os Faloutsos/Pavlo 15-415/615 78 Faloutsos/Pavlo 15-415/615 79 Grace Hash Join Sort-Merge Join vs. Hash Join Actual number: SSD 0.45 seconds at 0.1ms/IO 3(M + N) = 3 (1000 + 500) = 4,500 I/Os At 10ms/IO, Total time 45 seconds Given a minimum amount of memory both have a cost of 3(M+N) I/Os. When do we want to choose one over the other? Faloutsos/Pavlo 15-415/615 80 Faloutsos/Pavlo 15-415/615 81

Sort-Merge Join vs. Hash Join Today s Class Sort-Merge: Less sensitive to data skew. Result is sorted (may help upstream operators). Goes faster if one or both inputs already sorted. Hash: Superior if relation sizes differ greatly. Shown to be highly parallelizable. Introduction Selection Joins Explain Faloutsos/Pavlo 15-415/615 82 Faloutsos/Pavlo 15-415/615 83 EXPLAIN EXPLAIN When you precede a SELECT statement with the keyword EXPLAIN, the DBMS displays information from the optimizer about the statement execution plan. The system explains how it would process the query, including how tables are joined and in which order. Faloutsos/Pavlo 15-415/615 84 SELECT bid, COUNT(*) AS cnt FROM Reserves GROUP BY bid ORDER BY cnt Pseudo Query Plan: SORT COUNT GROUP BY π bid RESERVES Faloutsos/Pavlo 15-415/615 85

EXPLAIN EXPLAIN EXPLAIN SELECT bid, COUNT(*) AS cnt FROM Reserves GROUP BY bid ORDER BY cnt EXPLAIN SELECT bid, COUNT(*) AS cnt FROM Reserves GROUP BY bid ORDER BY cnt Postgres v9.1 Faloutsos/Pavlo 15-415/615 86 MySQL v5.5 Faloutsos/Pavlo 15-415/615 87 EXPLAIN ANALYZE EXPLAIN ANALYZE ANALYZE option causes the statement to be actually executed. The actual runtime statistics are displayed. This is useful for seeing whether the planner's estimates are close to reality. Note that ANALYZE is a Postgres idiom. EXPLAIN ANALYZE SELECT bid, COUNT(*) AS cnt FROM Reserves GROUP BY bid ORDER BY cnt Postgres v9.1 Faloutsos/Pavlo 15-415/615 88 Faloutsos/Pavlo 15-415/615 89

EXPLAIN ANALYZE Summary Works on any type of query. Since ANALYZE actually executes a query, if you use it with a query that modifies the table, that modification will be made. There are multiple ways to do selections if you have different indexes. Joins are difficult to optimize. Index Nested Loop when selectivity is small. Sort-Merge/Hash when joining whole tables. Faloutsos/Pavlo 15-415/615 90 Faloutsos/Pavlo 15-415/615 91 Next Class Set & Aggregate Operations Query Optimizations Mid-Term Review Faloutsos/Pavlo 15-415/615 92