Introduction We’ve covered the basic underlying storage, buffering, and indexing technology. – Now we can move on to query processing. Some database operations.

Slides:



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

Evaluation of Relational Operators CS634 Lecture 11, Mar Slides based on “Database Management Systems” 3 rd ed, Ramakrishnan and Gehrke.
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 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.
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;
Midterm Review Spring Overview Sorting Hashing Selections Joins.
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!
Implementation of Relational Operations R&G - Chapters 12 and 14.
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.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Implementing Relational Operators and Query Evaluation Chapter 12.
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.
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)
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.
Unary Query Processing Operators
Evaluation of Relational Operations
Evaluation of Relational Operations: Other Operations
Introduction to Database Systems
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
Lecture 13: Query Execution
CS222: Principles of Data Management Notes #11 Selection, Projection
Evaluation of Relational Operations: Other Techniques
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:

Introduction We’ve covered the basic underlying storage, buffering, and indexing technology. – Now we can move on to 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 “equivalencies” of relational operators 3.using statistics and cost models to choose among these. Query Optimization and Execution Relational Operators Files and Access Methods Buffer Management Disk Space Management DB SQL Query

A Really Bad Query Optimizer For each Select-From-Where query block – Create a plan that: Forms the cartesian product of the FROM clause Applies the WHERE clause Applies the projection of the SELECT Incredibly inefficient – Huge intermediate results! 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 Plan Evaluator Query Optimizer Plan Generator Plan Cost Estimator Usually there is a heuristics-based rewriting step before the cost-based steps. Statistics Catalog Manager Schema Select * From Blah B Where B.blah = blah Queries Query Parser

The Query Optimization Game “Optimizer” is a bit of a misnomer… Goal is to pick a “good” (i.e., low expected cost) plan. – Involves choosing access methods, physical operators, operator orders, … – Notion of cost is based on an abstract “cost model” Roadmap for this topic: – Query plan structure – Then: unary (single relation) operators – Then: joins – After that: optimizing multiple operators

Query Processing Overview The query optimizer translates SQL to a special internal “language” – Query Plans The query executor is an interpreter for query plans Think of query plans as “box-and-arrow” dataflow diagrams – Each box implements a relational operator – Edges represent a flow of tuples (columns as specified) – For single-table queries, these diagrams are straight-line graphs Scan Sort Distinct name, gpa Optimizer SELECT DISTINCT name, gpa FROM Students

Query Optimization A deep subject, focuses on multi-table queries – We will only need a cookbook version for now. Build the dataflow bottom up: – Choose an Access Method (HeapScan or IndexScan) Non-trivial, we’ll learn about this later! – Next apply any WHERE clause filters – Next apply GROUP BY and aggregation Can choose between sorting and hashing! – Next apply any HAVING clause filters – Next Sort to help with ORDER BY and DISTINCT In absence of ORDER BY, can do DISTINCT via hashing! Distinct Scan FilterHashAggFilterSort

Iterators The 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) – Encapsulation: any iterator can be input to any other! – When subclassing, different iterators will keep different kinds of state information iterator

Example: Scan init() : – Set up internal state – call init() on child – often a file open next(): – call next() on child until qualifying tuple found or EOF – keep only those fields in “proj_list” – return tuple (or EOF -- “End of File” -- if no tuples remain) close() : – call close() on child – clean up internal state Note: Scan also applies “selection” filters and “projections” (without duplicate elimination) class Scan extends iterator { void init(); tuple next(); void close(); iterator inputs[1]; bool_expr filter_expr; proj_attr_list proj_list; }

Example: Sort init() : – generate the sorted runs on disk – Allocate runs[] array and fill in with disk pointers. – Initialize numberOfRuns – Allocate nextRID array and initialize to NULLs 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 File” -- 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[]; }

Relational Operations We will consider how to implement: – Selection (  ) Selects a subset of rows from relation. – Projection (  ) Deletes unwanted columns from relation. – Join (  ) Allows us to combine two relations. – Set-difference ( - ) Tuples in reln. 1, but not in reln. 2. – Union (  ) Tuples in reln. 1 and in reln. 2. – Aggregation ( SUM, MIN, etc.) and GROUP BY Since each op returns a relation, ops can be composed! After we cover the operations, we will discuss how to optimize queries formed by composing them.

Selection (filter) Operators

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

Simple Selections Of the form Question: how best to perform? Depends on: – what indexes/access paths are available – what is the expected size of the result (in terms of number of tuples and/or number of pages) Size of result approximated as size of R * reduction factor – “reduction factor” is usually called selectivity. – estimate of reduction factors is based on statistics – we will discuss shortly. SELECT * FROM Reserves R WHERE R.rname < ‘C%’

Alternatives for Simple Selections With no index, unsorted: – Must essentially scan the whole relation – cost is M (#pages in R). For “Reserves” = 1000 I/Os. With no index, sorted on rname: – cost of binary search + number of pages containing results. – For reserves = 10 I/Os +  selectivity*#pages  With an index on selection attribute: – Use index to find qualifying data entries, – then retrieve corresponding data records. – (Hash index useful only for equality selections.)

Using an Index for Selections Cost depends on #qualifying tuples, and clustering. – Cost: finding qualifying data entries (typically small) plus cost of retrieving records (could be large w/o clustering). – In example “reserves” relation, if 10% of tuples qualify (result size estimate: 100 pages, tuples). With a clustered index, cost is little more than 100 I/Os; if unclustered, could be more than I/Os! unless…

Selections using Index (cont) Important 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. This ensures that each data page is looked at just once (though # of such pages likely to be higher than with clustering). Index entries Data entries direct search for (Index File) (Data file) Data Records data entries Data entries Data Records CLUSTERED UNCLUSTERED

General Selection Conditions Such selection conditions are first converted 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 (a conjunction of terms of the form attr op value). A B-tree index matches (a conjunction of) terms that involve only attributes in a prefix of the search key. – Index on matches a=5 AND b= 3, but not b=3. For Hash index, must have all attributes in search key  (day<8/9/94 AND rname=‘Paul’) OR bid=5 OR sid=3

Composite Search Keys Search on a combination of fields. – Equality query: Every field value is equal to a constant value. E.g. wrt index: age=20 and sal =75 – Range query: Some field value is not a constant. E.g.: age > 20; age=12 and sal > 10 Data entries in index sorted by search key to support range queries. – Lexicographic order – Like the dictionary, but on fields, not letters! sue1320 bob cal joe nameagesal 12,20 12,10 11,80 13,20 20,12 10,12 20,13 80, Data records sorted by name Data entries in index sorted by Data entries sorted by Examples of composite key indexes using lexicographic order.

Two Approaches to General Selections First approach: Find the most selective access path, retrieve tuples using it, and apply any remaining terms that don’t match the index: – Most selective access path: An index or file scan that we estimate will require the fewest page I/Os. – Terms that match this index reduce the number of tuples retrieved; other terms are used to discard some retrieved tuples, but do not affect number of tuples/pages fetched.

Most Selective Index - Example Consider day < 8/9/94 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 could be used; – Then, day<8/9/94 must be checked. How about a B+tree on ? How about a Hash index on ?

Intersection of Rids Second approach: if we have 2 or more matching indexes (w/Alternatives (2) or (3) for data entries): – 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. Consider day<8/9/94 AND bid=5 AND sid=3. With a B+ tree index on day and an index on sid, we can retrieve rids of records satisfying day<8/9/94 using the first, rids of recs satisfying sid=3 using the second, intersect, retrieve records and check bid=5. – Note: commercial systems use various tricks to do this: bit maps, bloom filters, index joins

Join Operators

Joins are a very common query operation. Joins can be very expensive: Consider an inner join of R and S each with 1M records. Q: How many tuples in the answer? (cross product in worst case, 0 in the best(?)) Many join algorithms have been developed Can have very different join costs.

Equality Joins With One Join Column Assume: – M = 1000 pages in R, p R =100 tuples per page. – N = 500 pages in S, p S = 80 tuples per page. – In our examples, R is Reserves and S is Sailors. Cost metric : # of I/Os. We will ignore output costs. We will consider more complex join conditions later. SELECT * FROM Reserves R1, Sailors S1 WHERE R1.sid=S1.sid

Simple Nested Loops Join For each tuple in the outer relation R, we scan the entire inner relation S. How much does this Cost? (p R * M) * N + M = 100,000* I/Os. – At 10ms/IO, Total: ??? What if smaller relation (S) was outer? (p s * N) *M + N = 40,000* I/Os. What assumptions are being made here? foreach tuple r in R do foreach tuple s in S do if r i == s j then add to result

Page-Oriented Nested Loops Join For each page of R, get each page of S, and write out matching pairs of tuples, where r is in R-page and S is in S-page. What is the cost of this approach? M*N + M= 1000* – If smaller relation (S) is outer, cost = 500* 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