CS222: Principles of Data Management Notes #12 Joins!

Slides:



Advertisements
Similar presentations
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Evaluation of Relational Operations Chapter 12, Part A.
Advertisements

Equality Join R X R.A=S.B S : : Relation R M PagesN Pages Relation S Pr records per page Ps records per page.
Implementation of relational operations
Lecture 13: Query Execution. Where are we? File organizations: sorted, hashed, heaps. Indexes: hash index, B+-tree Indexes can be clustered or not. Data.
1 Overview of Query Evaluation Chapter Outline  Query Optimization Overview  Algorithm for Relational Operations.
Database Management Systems, R. Ramakrishnan and Johannes Gehrke1 Evaluation of Relational Operations: Other Techniques Chapter 12, Part B.
Implementation of Relational Operations CS186, Fall 2005 R&G - Chapter 14 First comes thought; then organization of that thought, into ideas and plans;
1 Implementation of Relational Operations Module 5, Lecture 1.
Evaluation of Relational Operators 198:541. Relational Operations  We will consider how to implement: Selection ( ) Selects a subset of rows from relation.
1  Simple Nested Loops Join:  Block Nested Loops Join  Index Nested Loops Join  Sort Merge Join  Hash Join  Hybrid Hash Join Evaluation of Relational.
SPRING 2004CENG 3521 Join Algorithms Chapter 14. SPRING 2004CENG 3522 Schema for Examples Similar to old schema; rname added for variations. Reserves:
Implementation of Relational Operations CS 186, Spring 2006, Lecture 14&15 R&G Chapters 12/14 First comes thought; then organization of that thought, into.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Query Evaluation Chapter 12.
Query Processing 1: Joins and Sorting R&G, Chapters 12, 13, 14 Lecture 8 One of the advantages of being disorderly is that one is constantly making exciting.
Query Optimization 3 Cost Estimation R&G, Chapters 12, 13, 14 Lecture 15.
Introduction to Database Systems 1 Join Algorithms Query Processing: Lecture 1.
1 Evaluation of Relational Operations: Other Techniques Chapter 12, Part B.
1 Evaluation of Relational Operations Yanlei Diao UMass Amherst March 01, 2007 Slides Courtesy of R. Ramakrishnan and J. Gehrke.
Evaluation of Relational Operations. Relational Operations v We will consider how to implement: – Selection ( ) Selects a subset of rows from relation.
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications C. Faloutsos – A. Pavlo Lecture#14: Implementation of Relational Operations.
1 Implementation of Relational Operations: Joins.
Query Processing 2: Sorting & Joins
Relational Operator Evaluation. Overview Index Nested Loops Join If there is an index on the join column of one relation (say S), can make it the inner.
Lec3/Database Systems/COMP4910/031 Evaluation of Relational Operations Chapter 14.
RELATIONAL JOIN Advanced Data Structures. Equality Joins With One Join Column External Sorting 2 SELECT * FROM Reserves R1, Sailors S1 WHERE R1.sid=S1.sid.
Implementing Natural Joins, R. Ramakrishnan and J. Gehrke with corrections by Christoph F. Eick 1 Implementing Natural Joins.
1 Database Systems ( 資料庫系統 ) December 7, 2011 Lecture #11.
1 Database Systems ( 資料庫系統 ) December 19, 2004 Lecture #12 By Hao-hua Chu ( 朱浩華 )
CPSC 404, Laks V.S. Lakshmanan1 Evaluation of Relational Operations – Join Chapter 14 Ramakrishnan and Gehrke (Section 14.4)
Query Execution. Where are we? File organizations: sorted, hashed, heaps. Indexes: hash index, B+-tree Indexes can be clustered or not. Data can be stored.
CS 440 Database Management Systems Lecture 5: Query Processing 1.
Implementation of Relational Operations R&G - Chapter 14 First comes thought; then organization of that thought, into ideas and plans; then transformation.
Database Management Systems 1 Raghu Ramakrishnan Evaluation of Relational Operations Chpt 14.
Hash Tables and Query Execution March 1st, Hash Tables Secondary storage hash tables are much like main memory ones Recall basics: –There are n.
Relational Operator Evaluation. overview Projection Two steps –Remove unwanted attributes –Eliminate any duplicate tuples The expensive part is removing.
Implementation of Database Systems, Jarek Gryz1 Evaluation of Relational Operations Chapter 12, Part A.
Query Execution Query compiler Execution engine Index/record mgr. Buffer manager Storage manager storage User/ Application Query update Query execution.
Alon Levy 1 Relational Operations v We will consider how to implement: – Selection ( ) Selects a subset of rows from relation. – Projection ( ) Deletes.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Evaluation of Relational Operations Chapter 14, Part A (Joins)
Relational Operator Evaluation. Application Programmer (e.g., business analyst, Data architect) Sophisticated Application Programmer (e.g., SAP admin)
Implementation of Relational Operations Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein, Mike Franklin, and etc for.
Database Applications (15-415) DBMS Internals- Part VIII Lecture 17, Oct 30, 2016 Mohammad Hammoud.
CS 540 Database Management Systems
CS 440 Database Management Systems
Database Systems (資料庫系統)
Database Applications (15-415) DBMS Internals- Part VII Lecture 16, October 25, 2016 Mohammad Hammoud.
Evaluation of Relational Operations
Evaluation of Relational Operations: Other Operations
Relational Operations
CS222P: Principles of Data Management Notes #11 Selection, Projection
Database Applications (15-415) DBMS Internals- Part VII Lecture 19, March 27, 2018 Mohammad Hammoud.
CS222P: Principles of Data Management Notes #12 Joins!
Introduction to Database Systems
Implementation of Relational Operations
Selected Topics: External Sorting, Join Algorithms, …
Overview of Query Evaluation
Overview of Query Evaluation
Implementation of Relational Operations
Lecture 13: Query Execution
CS222: Principles of Data Management Notes #11 Selection, Projection
Evaluation of Relational Operations: Other Techniques
Overview of Query Evaluation: JOINS
Implementation of Relational Operations
Evaluation of Relational Operations: Other Techniques
CS222/CS122C: Principles of Data Management UCI, Fall 2018 Notes #10 Selection, Projection Instructor: Chen Li.
CS222/CS122C: Principles of Data Management UCI, Fall Notes #11 Join!
CS222P: Principles of Data Management UCI, Fall 2018 Notes #11 Join!
Presentation transcript:

CS222: Principles of Data Management Notes #12 Joins! Instructor: Chen Li ICS, UC Irvine

Schema for Examples Reserves: Sailors: Sailors (sid: integer, sname: string, rating: integer, age: real) Reserves (sid: integer, bid: integer, day: dates, rname: string) Reserves: Each tuple is 40 bytes long, 100 tuples per page, 1000 pages. (Total cardinality is thus 100,000 reservations) Sailors: Each tuple is 50 bytes long, 80 tuples per page, 500 pages. (Total cardinality is thus 40,000 sailing club members) 4

Equality Joins With One Join Column SELECT * FROM Reserves R1, Sailors S1 WHERE R1.sid=S1.sid In algebra: R S. Incredibly common! Must thus be carefully optimized. R S is large; so, doing R S followed by a selection would be highly inefficient. Assume: M pages in R, pR tuples per page, N pages in S, pS tuples per page. 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.) 5

Simple Nested Loops Join(s) foreach tuple r in R do foreach tuple s in S do if ri == sj then add <r, s> to result For each tuple in the outer relation R, we scan the entire inner relation S. Cost: M + (pR * M) * N = 1000 + (100*1000)*500 I/Os Page-oriented Nested Loops join: For each page of R, get each page of S, and write out matching pairs of tuples <r, s>, where r is in R-page and S is in S-page. Cost: M + M*N = 1000 + 1000*500 If smaller relation (S) is outer, cost = 500 + 500*1000 (Notice that we were essentially wasting an opportunity!) 6

Block Nested Loops Join Use one page as an input buffer for scanning the inner S, one page as the output buffer, and use all remaining pages to hold a “block” of outer R. For each matching tuple r in R-block, s in S-page, add <r, s> to result. Then read next R-block, scan S, etc. R & S Join Result Hash table for block of R (k < B-1 pages) . . . . . . . . . Input buffer for S Output buffer 9

Examples of Block Nested Loops Cost: Scan of outer + #outer blocks * scan of inner #outer blocks = M + M/B * N With Reserves (R) as outer, and 100-page blocks of R: Cost of scanning R is 1000 I/Os; there’ll be 10 blocks total. Per R block, we scan Sailors (S); 10*500 (=5000) I/Os for S. With (100-page blocks of) Sailors as outer: Cost of scanning S is 500 I/Os; a total of 5 blocks. Per block of S, we scan Reserves; 5*1000 I/Os for R. (With sequential reads considered, analysis changes: may want to divide buffers evenly between R and S.)

Index Nested Loops Join foreach tuple r in R do foreach tuple s in S where ri == sj do add <r, s> to result If there is an index on the join column of one relation (say S), can make it the inner and exploit the index. Cost: M + ( (pR * M) * cost of finding matching S tuples) For each R tuple, cost of probing S’s index is about 1.2 for hash index, and say 2-4 for B+ tree. Cost of fetching actual S tuples (assuming Alt. (2) or (3) for index data entries) depends on clustering. Clustered (sj) index: 1 I/O per R tuple (typical); unclustered: 1 I/O per matching S tuple per R tuple.

Examples of Index Nested Loops Hash-index (Alt. 2) on sid of Sailors (as inner): Scan Reserves: 1000 page I/Os, 100*1000 (=100,000) tuples. For each Reserves tuple: 1.2 I/Os to get data entry in index, plus 1 I/O to get (the exactly one) matching Sailors tuple. Total: 220,000 I/Os. (Plus 1000 in Reserves “noise”.) Formula: 1000 + 100 * 1000 * (1.2 + 1) 8

Examples of Index Nested Loops Hash-index (Alt. 2) on sid of Reserves (as inner): Scan Sailors: 500 page I/Os, 80*500 (=40,000) tuples. For each Sailors tuple: 1.2 I/Os to find index page with data entries, plus cost of retrieving matching Reserves tuples. Assuming uniform distribution, 2.5 reservations per sailor (100,000 / 40,000). Cost of retrieving them is 1 or 2.5 I/Os depending on the index’s clustering setup. Formula: 500 + 500 * 80 * (1.2 + 100,000/40,000) 8

Sort-Merge Join (R S) i=j Sort R and S on the join column, then scan them to do a “merge” (on join column), and output result tuples. Advance scan of R until current R-tuple >= current S tuple, then advance scan of S until current S-tuple >= current R tuple; do this until current R tuple = current S tuple. At this point, all R tuples with same value in Ri (current R group) and all S tuples with same value in Sj (current S group) match; output <r, s> for all pairs of such tuples. Then resume scanning R and S. R scanned once; each S group scanned once per matching R tuple. (Multiple scans of an S group very likely to find all needed pages in buffer pool.) 11

Example of Sort-Merge Join Cost: Sort R (roughly M log M) + sort S (roughly N log N) + (M+N) 12

Cost of Sort-Merge Join The cost of scanning M+N could be M*N in the worst case When there are many records with the same join value Very unlikely With 35 buffer pages, both Reserves and Sailors can be sorted in 2 passes; total join cost: 7500 = 5 * (1000 + 500). Versus BNL cost: 2500 to 15000 I/O range 12

Improving Sort-Merge Join We can combine the merging phases in the sorting of R and S with the merging required for the join. Allocate 1 page per run of each relation, and do a parallel `merge’ while checking the join condition. (Else wasteful!) Cost: read+write each relation in Pass 0 + read each relation in (only) merging pass (+ writing of result tuples). Cost: goes down from 7500 to 4500 I/Os (3 * (1000 + 500)). With large memory, the cost of sort-merge join, like the cost of external sorting, behaves like it’s linear. 13

Improving sort-merge join Join Result R run (sorted) R R sorted chunks In-memory merge join Sort B pages in memory to generate runs S Output buffer S sorted . . . S run (sorted) Memory requirement: M/B + N/B <= B – 1 So B >= sqrt (M + N) 9

Improving sort-merge join First create sorted runs for each table (S & R) ..... ..... then merge S & R runs at the same time as joining them...! 12

Hash table for partition Grace Hash-Join B main memory buffers Disk Original Relation OUTPUT 2 INPUT 1 hash function h B-1 Partitions . . . (First do R, then do S) Partition both of the relations using a hash function h: R tuples in R’s partition i will only match S tuples in S’s partition i. Partitions of R & S Input buffer for Si Hash table for partition Ri (k < B-1 pages) B main memory buffers Disk Output buffer Join Result hash fn h2 Read in one partition of R, hashing it using function h2 (<> h). Scan the matching partition of S, search for its R matches. 14

Observations on Grace Hash-Join #partitions k ≤ B-1 (why?), and B-2 ≥ size of largest partition to be held in memory. Assuming uniformly sized partitions, and maximizing k, we get: k= B-1, and M/(B-1) ≤ B-2, i.e., B must be ≥ sqrt(M) If we build an in-memory hash table to speed up the matching of tuples, a little more memory is needed. If the hash function does not partition uniformly, one or more R partitions may not fit in memory. Can try hash-join technique recursively to do the join of such an R-partition with its corresponding S-partition. 15

Cost of Grace Hash-Join In partitioning phase, read+write both relns; 2(M+N). In matching phase, read both relns; M+N I/Os. In our running example, this is a total of 4500 I/Os. Sort-Merge Join vs. Hash Join: Given a minimum amount of memory, both have a cost of 3(M+N) I/Os. Hash Join superior on this count if relation sizes differ greatly (as it wins by needing less memory). Also, Hash Join is neatly parallelizable, as we will see later. Sort-Merge less sensitive to data skew; result is sorted. 16

Simple Hash-Join (see Shapiro!) Grace Hash-Join: Partitioning (“build”) does read+write of R and S [2(M+N)] Matching (“probe”) does read of R and S; M+N [3(M+N)] Q: What if the smaller relation (R) is just slightly too big? Simple Hash-Join addresses this case: Scan R, using most of memory for a hash table; write overflow part of R to R’(R’s leftovers) on disk Scan S, probe R’s hash table with “most” of S; write overflow part of S to S’ (S’s leftovers) on disk Repeat (recursively!) to join R’ and S’ 16

Simple hash join Memory Step 1 Step 2 Build Step 1 In-memory Hash table Passed over R tuples R Store Output if match Probe Step 2 In-memory Hash table Passed over S tuples S Store Repeat steps 1 and 2 for passed over tuples 9

“Simple” Hash-Join (see Shapiro!) Cost when |R|≈ 2B?  half of the pages go to the disk Cost: (M+N) + (.5M+.5N) * 2 = 2(M+N) Reason: M + N: each relation needs to be read into memory 0.5M + 0.5N: half of the pages need to be written to disk and read from the disk again (round trip, thus “* 2”) 16

Hybrid Hash-Join (see Shapiro!!) Grace Hash-Join wins when both tables are very large compared to our memory allocation B. (Big Data? ) Simple Hash-Join wins when R almost fits in memory. Q: What do you do when you have two winners, each with a region of superiority?  “Hybrid” Algorithm! And thus Hybrid Hash-Join was born… Use a portion of B for an in-memory R hash table Use the rest of B for Grace-style partition buffering Result is that the leftovers are now partitioned! Like Grace HJ when B is small (if no room for a hash table) Like Simple HJ when B ≈|R|+ε (if only one partition is spilled) 16

Hybrid hash join Memory Step 1 Step 2 Remaining R partitions Step 1 h1(x) = 0 In-memory Hash table R Output page Output buffers Build h1(x) = i i Output if match Remaining S partitions In-memory Hash table Step 2 h1(x) = 0 Output page S Output buffers Probe h1(x) = i i Step 3: process remaining R/S partitions as in the Grace Join 9

Join with multiple attributes Equalities over several attributes (e.g., R.sid=S.sid AND R.rname=S.sname): For Index NL, build index on <sid, sname> (if S is inner); or use existing indexes on sid or sname. For Sort-Merge and Hash Join, sort or hash-partition on the combination of the two join columns.

More General (θ) Join Conditions? Inequality conditions (e.g., R.rname < S.sname): For Index NL, need (clustered!) B+ tree index. Range scans on inner; # matches likely much higher vs. equijoins Hash Join, Sort Merge Join simply not applicable. Block NL quite likely to be the best join method here (ditto for other predicates w/non-hashable functions)

So Many Joins, So Little Time...! Nested Loops Join: Simple NL-Join Index NL-Join Page NL-Join  Block NL-Join (also works for θ- joins!) Sort-Merge Join SM-Join can avoid sorting R and/or S if ordered; can read and merge run sets from R and S together during the join Hash-Join Grace Hash-Join Simple Hash-Join Hybrid Hash-Join 16