Implementation of Relational Operations R&G - Chapters 12 and 14.

Slides:



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

Implementation of relational operations
1 Overview of Query Evaluation Chapter Outline  Query Optimization Overview  Algorithm for Relational Operations.
Database Management Systems 3ed, R. Ramakrishnan and Johannes Gehrke1 Evaluation of Relational Operations: Other Techniques Chapter 14, Part B.
Implementation of Other Relational Algebra Operators, R. Ramakrishnan and J. Gehrke1 Implementation of other Relational Algebra Operators Chapter 12.
Database Management Systems, R. Ramakrishnan and Johannes Gehrke1 Evaluation of Relational Operations: Other Techniques Chapter 12, Part B.
Database Management Systems, R. Ramakrishnan and Johannes Gehrke1 Evaluation of Relational Operations: Other Techniques Chapter 12, Part B.
1 Overview of Query Evaluation Chapter Objectives  Preliminaries:  Core query processing techniques  Catalog  Access paths to data  Index matching.
Query Evaluation. An SQL query and its RA equiv. Employees (sin INT, ename VARCHAR(20), rating INT, age REAL) Maintenances (sin INT, planeId INT, day.
SPRING 2004CENG 3521 Query Evaluation Chapters 12, 14.
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.
Unary Query Processing Operators CS 186, Spring 2006 Background for Homework 2.
Unary Query Processing Operators Not in the Textbook!
Query Optimization II R&G, Chapters 12, 13, 14 Lecture 9.
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.
Overview of Implementing Relational Operators and Query Evaluation
1 Overview of Query Evaluation Chapter Overview of Query Evaluation  Plan : Tree of R.A. ops, with choice of alg for each op.  Each operator typically.
CPSC 404, Laks V.S. Lakshmanan1 Evaluation of Relational Operations: Other Operations Chapter 14 Ramakrishnan & Gehrke (Sections ; )
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.
Database Systems/comp4910/spring20031 Evaluation of Relational Operations Why does a DBMS implements several algorithms for each algebra operation? What.
Implementing Natural Joins, R. Ramakrishnan and J. Gehrke with corrections by Christoph F. Eick 1 Implementing Natural Joins.
Introduction We’ve covered the basic underlying storage, buffering, and indexing technology. – Now we can move on to query processing. Some database operations.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Implementing Relational Operators and Query Evaluation Chapter 12.
Introduction to Query Optimization, R. Ramakrishnan and J. Gehrke 1 Introduction to Query Optimization Chapter 13.
Relational Operator Evaluation. Overview Application Programmer (e.g., business analyst, Data architect) Sophisticated Application Programmer (e.g.,
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.
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.
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)
1 Overview of Query Evaluation Chapter Outline  Query Optimization Overview  Algorithm for Relational Operations.
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.
Introduction to Query Optimization
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 VI Lecture 15, Oct 23, 2016 Mohammad Hammoud.
Introduction to Database Systems
Implementation of Relational Operations
Overview of Query Evaluation
Overview of Query Evaluation
Implementation of Relational Operations
Relational Query Optimization
CS222: Principles of Data Management Notes #11 Selection, Projection
Evaluation of Relational Operations: Other Techniques
Overview of Query Evaluation: JOINS
Implementation of Relational Operations
Overview of Query Evaluation
Evaluation of Relational Operations: Other Techniques
CS222/CS122C: Principles of Data Management UCI, Fall 2018 Notes #10 Selection, Projection Instructor: Chen Li.
Presentation transcript:

Implementation of Relational Operations R&G - Chapters 12 and 14

Introduction Today’s topic: QUERY PROCESSING Some database operations are EXPENSIVE Can greatly improve performance by being “smart” –e.g., can speed up 1,000,000x over naïve approach Main weapons are: 1.clever implementation techniques for operators 2.exploiting relational algebra “equivalences” 3.using statistics and cost models to choose among these.

A Really Bad Query Optimizer For each Select-From-Where query block –Create a plan that: Forms the cross product of the FROM clause Applies the WHERE clause Then, as needed: –Apply the GROUP BY clause –Apply the HAVING clause –Apply any projections and output expressions –Apply duplicate elimination and/or ORDER BY   predicates tables …

Cost-based Query Sub-System Query Parser Query Optimizer Plan Generator Plan Cost Estimator Query Plan Evaluator Catalog Manager Schema Statistics Select * From Blah B Where B.blah = blah Queries

The Query Optimization Game Goal is to pick a “good” plan –Good = low expected cost, under cost model –Degrees of freedom: access methods physical operators operator orders Roadmap for this topic: –First: implementing individual operators –Then: optimizing multiple operators

Relational Operations We will consider how to implement: –Selection (  ) Select a subset of rows. –Projection (  ) Remove unwanted columns. –Join ( ) Combine two relations. –Set-difference ( - ) Tuples in reln. 1, but not in reln. 2. –Union (  ) Tuples in reln. 1 and in reln. 2. Q: What about Intersection?

Schema for Examples Similar to old schema; rname added for variations. Sailors: –Each tuple is 50 bytes long, 80 tuples per page, 500 pages. –|S|=500, p S =80. Reserves: –Each tuple is 40 bytes, 100 tuples per page, 1000 pages. –|R|=1000, p R =100. Sailors ( sid : integer, sname : string, rating : integer, age : real) Reserves ( sid : integer, bid : integer, day : dates, rname : string)

Simple Selections How best to perform? Depends on: –what indexes are available –expected size of result Size of result approximated as (size of R) * selectivity –selectivity estimated via statistics – we will discuss shortly. SELECT * FROM Reserves R WHERE R.rname < ‘C%’

Our options … If no appropriate index exists: Must scan the whole relation cost = |R|. For “reserves” = 1000 I/Os.

With index on selection attribute: 1. Use index to find qualifying data entries 2. Retrieve corresponding data records Total cost = cost of step 1 + cost of step 2 –For “reserves”, if selectivity = 10% (100 pages, tuples): If clustered index, cost is a little over 100 I/Os; If unclustered, could be up to I/Os! … unless … Our options … Index entries Data entries direct search for (Index File) (Data file) Data Records data entries Data entries Data Records CLUSTERED UNCLUSTERED

Refinement for unclustered indexes 1. Find qualifying data entries. 2. Sort the rid’s of the data records to be retrieved. 3. Fetch rids in order. Each data page is looked at just once (though # of such pages likely to be higher than with clustering). (Index File) (Data file) Data entries Data Records UNCLUSTERED

General Selection Conditions First, convert to conjunctive normal form (CNF): –(day<8/9/94 OR bid=5 OR sid=3 ) AND (rname=‘Paul’ OR bid=5 OR sid=3) We only discuss the case with no OR s Terminology: –A B-tree index matches terms that involve only attributes in a prefix of the search key. e.g.: –Index on matches a=5 AND b= 3, but not b=3.  (day<8/9/94 AND rname=‘Paul’) OR bid=5 OR sid=3

2 Approaches to General Selections Approach I: 1.Find the cheapest access path 2.retrieve tuples using it 3.Apply any remaining terms that don’t match the index –Cheapest access path: An index or file scan that we estimate will require the fewest page I/Os.

Cheapest Access Path - Example query: day < 8/9/94 AND bid=5 AND sid=3 some options: B+tree index on day; check bid=5 and sid=3 afterward. hash index on ; check day<8/9/94 afterward. How about a B+tree on ? How about a Hash index on ?

Approach II: use 2 or more matching indexes. 1. From each index, get set of rids 2. Compute intersection of rid sets 3. Retrieve records for rids in intersection 4. Apply any remaining terms EXAMPLE: day<8/9/94 AND bid=5 AND sid=3 Suppose we have an index on day, and another index on sid. –Get rids of records satisfying day<8/9/94. –Also get rids of records satisfying sid=3. –Find intersection, then retrieve records, then check bid=5. 2 Approaches to General Selections

Projection Issue is removing duplicates. Use sorting!! 1. Scan R, extract only the needed attributes 2. Sort the resulting set 3. Remove adjacent duplicates Cost: Reserves with size ratio 0.25 = 250 pages. With 20 buffer pages can sort in 2 passes, so: * 2 * = 2500 I/Os SELECT DISTINCT R.sid, R.bid FROM Reserves R

Projection -- improved Modify the external sort algorithm: –Modify Pass 0 to eliminate unwanted fields. –Modify Passes 1+ to eliminate duplicates. Cost: Reserves with size ratio 0.25 = 250 pages. With 20 buffer pages can sort in 2 passes, so: 1.Read 1000 pages 2.Write 250 (in runs of 40 pages each) 3.Read and merge runs Total cost = = 1500.

Other Projection Tricks If an index search key contains all wanted attrs: Do index-only scan –Apply projection techniques to data entries (much smaller!) If a B+Tree index search key prefix has all wanted attrs: Do in-order index-only scan –Compare adjacent tuples on the fly (no sorting required!)

Query Execution Framework SELECT DISTINCT name, gpa FROM Students One possible query execution plan: HeapScan Sort Distinct name, gpa

iterator Iterators Relational operators are all subclasses of the class iterator : class iterator { void init(); tuple next(); void close(); iterator &inputs[]; // additional state goes here } Note: –Edges in the graph are specified by inputs (max 2, usually) –Any iterator can be input to any other!

Example: Sort init() : –generate the sorted runs on disk (passes 0 to n-1) –Allocate runs[] array and fill in with disk pointers. –Initialize numberOfRuns –Allocate nextRID array and initialize to first RID of each run next(): –nextRID array tells us where we’re “up to” in each run –find the next tuple to return based on nextRID array –advance the corresponding nextRID entry –return tuple (or EOF -- “End of Fun” -- if no tuples remain) close() : –deallocate the runs and nextRID arrays class Sort extends iterator { void init(); tuple next(); void close(); iterator &inputs[1]; int numberOfRuns; DiskBlock runs[]; RID nextRID[]; }

Postgres Version src/backend/executor/nodeSort.c –ExecInitSort (init) –ExecSort (next) –ExecEndSort (close) The encapsulation stuff is hardwired into the Postgres C code –Postgres predates even C++! –See src/backend/execProcNode.c for the code that “dispatches the methods” explicitly!

Joins Joins are very common. R  S is large; so, R  S followed by a selection is inefficient. Many approaches to reduce join cost. Join techniques we will cover today: 1.Nested-loops join 2.Index-nested loops join 3.Sort-merge join SELECT * FROM Reserves R1, Sailors S1 WHERE R1.sid=S1.sid

foreach tuple r in R do foreach tuple s in S do if r i == s j then add to result Simple Nested Loops Join Cost = (p R *|R|)*|S| + |R| = 100*1000* IOs –At 10ms/IO, Total time: ??? What if smaller relation (S) was “outer”? What assumptions are being made here? What is cost if one relation can fit entirely in memory? R S:

Page-Oriented Nested Loops Join Cost = |R|*|S| + |R| = 1000* If smaller relation (S) is outer, cost = 500* Much better than naïve per-tuple approach! foreach page b R in R do foreach page b S in S do foreach tuple r in b R do foreach tuple s in b S do if r i == s j then add to result R S:

Block Nested Loops Join Page-oriented NL doesn’t exploit extra buffers :( Idea to use memory efficiently:... R & S block of R tuples (B-2 pages) Input buffer for S Output buffer... Join Result Cost: Scan outer + (#outer blocks * scan inner) #outer blocks =

Examples of Block Nested Loops Join Say we have B = memory buffers Join cost = |outer| + (#outer blocks * |inner|) #outer blocks = |outer| / 100 With R as outer (|R| = 1000): –Scanning R costs 1000 IO’s (done in 10 blocks) –Per block of R, we scan S; costs 10*500 I/Os –Total = *500. With S as outer (|S| = 500): –Scanning S costs 500 IO’s (done in 5 blocks) –Per block of S, we can R; costs 5*1000 IO’s –Total = *1000.

Index Nested Loops Join foreach tuple r in R do foreach tuple s in S where r i == s j do add to result R S: Data entries Data Records INDEX on S lookup(r i ) sjsj S: R: riri

Cost = |R| + (|R|*p R ) * cost to find matching S tuples If index uses Alt. 1, cost = cost to traverse tree from root to leaf. For Alt. 2 or 3: 1.Cost to lookup RID(s); typically 2-4 IO’s for B+Tree. 2.Cost to retrieve records from RID(s); depends on clustering. –Clustered index: 1 I/O per page of matching S tuples. –Unclustered: up to 1 I/O per matching S tuple. Index Nested Loops Join foreach tuple r in R do foreach tuple s in S where r i == s j do add to result R S:

Sort-Merge Join Example: SELECT * FROM Reserves R1, Sailors S1 WHERE R1.sid=S1.sid 1.Sort R on join attr(s) 2.Sort S on join attr(s) 3.Scan sorted-R and sorted-S in tandem, to find matches

Cost of Sort-Merge Join Cost: Sort R + Sort S + (|R|+|S|) –But in worst case, last term could be |R|*|S| (very unlikely!) –Q: what is worst case? Suppose B = 35 buffer pages: Both R and S can be sorted in 2 passes Total join cost = 4* *500 + ( ) = 7500 Suppose B = 300 buffer pages: Again, both R and S sorted in 2 passes Total join cost = 7500 Block-Nested-Loop cost = 2500 … 15,000

Other Considerations … 1. An important refinement: Do the join during the final merging pass of sort ! If have enough memory, can do: 1. Read R and write out sorted runs 2. Read S and write out sorted runs 3. Merge R-runs and S-runs, and find R S matches Cost = 3*|R| + 3*|S| Q: how much memory is “enough” (will answer next time …)  2. Sort-merge join an especially good choice if: –one or both inputs are already sorted on join attribute(s) –output is required to be sorted on join attributes(s) Q: how to take these savings into account? (stay tuned …)

Summary A virtue of relational DBMSs: queries are composed of a few basic operators –The implementation of these operators can be carefully tuned Many alternative implementation techniques for each operator –No universally superior technique for most operators. Must consider available alternatives –Called “Query optimization” -- we will study this topic soon!