Download presentation
Presentation is loading. Please wait.
Published byIda Messner Modified over 6 years ago
1
Implementing Relational Operators Query Evaluation
Take a look at right-click, estimated query evaluation plan, in SQL Server. Can export to XML. Chapter 1: Introduction to Database Systems Chapter 2: The Entity-Relationship Model Chapter 3: The Relational Model Chapter 4 (Part A): Relational Algebra Chapter 4 (Part B): Relational Calculus Chapter 5: SQL: Queries, Progrg, Triggers Chapter 6: Query-by-Example (QBE) Chapter 7: Storing Data: Disks and Files Chapter 8: File Organizations and Indexing Chapter 9: Tree-Structured Indexing Chapter 10: Hash-Based Indexing Chapter 11: External Sorting Chapter 12 (Part A): Evaluation of Relational Operators Chapter 12 (Part B): Evaluation of Relational Operators: Other Techniques Chapter 13: Introduction to Query Optimization Chapter 14: A Typical Relational Optimizer Chapter 15: Schema Refinement and Normal Forms Chapter 16 (Part A): Physical Database Design Chapter 16 (Part B): Database Tuning Chapter 17: Security Chapter 18: Transaction Management Overview Chapter 19: Concurrency Control Chapter 20: Crash Recovery Chapter 21: Parallel and Distributed Databases Chapter 22: Internet Databases Chapter 23: Decision Support Chapter 24: Data Mining Chapter 25: Object-Database Systems Chapter 26: Spatial Data Management Chapter 27: Deductive Databases Chapter 28: Additional Topics 1
2
Motivation: Evaluating Queries
The same query can be evaluated in different ways. The evaluation strategy (plan) can make orders of magnitude of difference. Query efficiency is one of the main areas where DBMS systems compete with each other. Person-decades of development, secret details.
3
Computing Relational Operators
Make optional topic
4
Selection and Projection
5
Projection R.sid, R.bid The expensive part is removing duplicates.
SELECT DISTINCT R.sid, R.bid FROM Reserves R The expensive part is removing duplicates. SQL systems don’t remove duplicates unless the keyword DISTINCT is specified in a query. Sorting Approach: Sort on <sid, bid> and remove duplicates. Hashing Approach: Hash on <sid, bid> to create partitions. Load partitions into memory one at a time. Build in-memory hash structure, and eliminate duplicates. If there is an index with both R.sid and R.bid in the search key, may be cheaper to sort data entries! Compare duplicate elimination to contacts on gmail, tunes in itunes (Can optimize sorting by dropping unwanted information while sorting.) 16
6
One Approach to Selections
Estimate 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 requires the fewest page I/Os. Terms that match this index reduce the number of tuples retrieved. Other terms affect the query result, but not the number of tuples/pages fetched. Other terms are used to discard some retrieved tuples, but do not affect number of tuples/pages fetched. 14
7
Selectivity 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. A hash index on <bid, sid> could be used; day<8/9/94 must then be checked.
8
Using an Index for Selections
Cost depends on #qualifying tuples, and clustering. Cost of finding qualifying data entries (typically small) plus cost of retrieving records (could be large w/o clustering). In example, assume that about 10% of tuples qualify (100 pages, tuples). With a clustered tree index, cost is little more than 100 I/Os. if unclustered, up to 10,000 I/Os! % = 0 or more characters Add estimation cost from Chaper 12. Hash index typically 1.2 for data entry, 1 for record. SELECT * FROM Reserves R WHERE R.rname < ‘C%’ 12
9
Access Paths: Hash Index
An access path is a method of retrieving tuples: File scan, or index that matches a selection (in the query) A hash index matches (a conjunction of) terms that has a term attribute = value for every attribute in the search key of the index. Each matching term attribute = value is a primary conjunct. Example: consider Hash index on <a, b, c> Matches a=5 AND b=3 AND c=5. (3 primary conjuncts) Does not match b=3. Does not match a=5 AND b=3. Does not match a>5 AND b=3 AND c=5. General idea: use indexes if we have a match. Primary conjuncts = a =5 and b=3 and c=5. 13
10
Multiple Choice Question
Which of the following is a prefix of abc? a ac b ab Check all that apply. Nice question: Does Tree index a =x, c =d match? What are the primary conjuncts?
11
Access Paths: Tree Index
A tree index matches (a conjunction of) terms that involve only attributes in a prefix of the search key. Example: consider tree index on <a, b, c> Matches a=5 AND b=3. (2 primary conjuncts) Matches a=5 AND b>6. (2 primary conjuncts) Matches a=5 (1 primary conjunct) Does not match b=3. General idea: use indexes if we have a match. 13
12
Exercise Consider the following schema with the Sailors relation:
Sailors(sid: integer, sname: string, rating: integer, age: real) For each of the following indexes, list whether the index matches the given selection conditions. A hash index on the search key <Sailors.sid> sid<50,000 (Sailors) sid=50,000 (Sailors) A B+-tree on the search key <Sailors.sid> Get solutions. Match 1.b, not 1.a. Match both.
13
Nested Loops: Scan and Match Sort and Merge
The Biggie: Join Nested Loops: Scan and Match Sort and Merge This is the S&M part of the course. probably do query plan example first to cover assignment 4.
14
Join: Sort-Merge (R S) i=j Sort R and S on the join column, then scan them to do a ``merge’’ (on join col.), and output result tuples. Advance scan of R until current R-tuple >= current S tuple. Advance scan of S until current S-tuple >= current R tuple. Repeat until match: 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 is scanned once; each S group is scanned once per matching R tuple. (Multiple scans of an S group are likely to find needed pages in buffer.) 11
15
Example of Sort-Merge Join
M = Sailors = 500 pages N = Reserves = 1000 pages total sort cost: 2 * 2 * * 2 * 1000 = = 6000 scan cost = M + N = 1500 Total = = 7500 Cost: sort + scan = sort cost + (M+N) [sid is key] The cost of scanning, M+N, could be M*N (very unlikely!) 12
16
Sorting Sorting is strongly optimized in DBMS.
Common method: merge-sort. I/O Cost for merge sort using B buffer pages is O(N * logB-1 N/B) See textbook. Example: With enough buffer pages, both Reserves and Sailors can be sorted in 2 passes. total join cost: 7500. basic intuition: instead of merging 2 runs at a time, we merge B-1. It’s -1 because we need an output buffer.
17
Example of Sort-Merge Join
M = Sailors = 500 pages N = Reserves = 1000 pages total sort cost: 2 * 2 * * 2 * 1000 = = 6000 scan cost = M + N = 1500 Total = = 7500 Cost: sort + scan = 4* ( ) + ( ) = 7,500 I/Os 12
18
Exercise Consider the join R.A with S.b given the following information. The cost measure is the number of page i/Os, ignoring the cost of writing out the result. Relation R contains 10,000 tuples and has 10 tuples per page. Relation S contains 2000 tuples, also 10 tuples per page. Attribute b is the primary key for S. Both relations are stored as heap files. No indexes are available. What is the cost of joining R and S using a sort-merge join? Assume that the number of I/Os for sorting a table T is 4 *pages_in_T . Sort: 4* (M + N) = 4 * ( ) = 4800 Scan of R = 1000 Scan of S = 200 Total = = 6,000
19
Nested Loops: Flowchart
From
20
Join: Nested Loops 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 relation and exploit the index. Cost: Pages_in_r + Tuples_in_r* cost of finding matching S tuples if index on S is unique: Pages_in_r + Tuples_in_r* cost of equality search in S For each R tuple, cost of probing S index is about 1.2 for hash index, 2-4 for B+ tree. Cost of then finding S tuples (assuming alt. (2) or (3) for data entries) depends on clustering. Clustered index on S: 1 I/O (typical) for each R tuple, unclustered: up to 1 I/O per matching S tuple. Demonstrate with example using lego blocks. Also uses cards. Nice discussion of estimation error.
21
Examples: Index Nested Loops
Hash-index (Alt. 2) on sid of Sailors (as inner): Scan Reserves: page I/Os, 10*1000 tuples. For each Reserves tuple, find matches: 1.2 I/Os to get data entry in index. 1 I/O to get (the exactly one) matching Sailors tuple. Total: 22,000 I/Os for finding matches. Hash-index (Alt. 2) on sid of Reserves (as inner): Scan Sailors: 500 page I/Os, 10*500 tuples. For each Sailors tuple: plus cost of retrieving matching Reserves tuples. Assuming uniform distribution, 2.5 reservations per sailor (100,000 R/ 40,000 S). Cost of retrieving them is 1 or 2.5 I/Os depending on whether the index is clustered. First scenario: for scanning reserves, grand total 22,100. for second scenario: Total: 10*500*( ) = 10*500*3.7 = 18,500 for finding matches. Plus scan = 500. Grand total = 19,000. It’s important to take advantage of the key constraint, compare with doing n^2 match. 8
22
Exercise Consider the join R.A with S.b given the following information. The cost measure is the number of page I/Os, ignoring the cost of writing out the result. Relation R contains 10,000 tuples and has 10 tuples per page. Relation S contains 2000 tuples, also 10 tuples per page. Attribute b is the primary key for S. Both relations are stored as heap files. No indexes are available. What is the cost of joining R and S using nested loop join? R is the outer relation. 1,000 pages scanned in R 10,000 (tuples in R) * 200/2 (scans to find single matching tuple in S) = 10,000*100 = 1,000,000 altogether 1,001,000 huge! Solution key is buggy.
23
Query Planning Make optional topic
24
Overview of Query Evaluation
Plan: Tree of R.A. ops, with choice of alg for each op. Each operator typically implemented using a `pull’ interface: when an operator is `pulled’ for the next output tuples, it `pulls’ on its inputs and computes them. Much like cursor/iterator. Two main issues in query optimization: For a given query, what plans are considered? Algorithm to search for cheapest (estimated) plan. How is the cost of a plan estimated? Ideally: Want to find best plan. Practically: Avoid worst plans! We will study the System R approach (IBM). “pull” – iterator interface. Show access plan in SQL server. See --- Relative to batch refers to having several queries (like a script, begin end) can export to XML Examples: SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.colour='green’ do without where clause (omits Boats table) ------ SELECT MIN (S.age) FROM Sailors S GROUP BY S.rating 2
25
Examples
26
Example Relations Reservations Sailors
27
Query Plans Make optional topic
28
Query Plan Example RA Tree: R.bid=100 AND S.rating>5 Plan:
Reserves Sailors sid=sid bid=100 rating > 5 sname Query Plan Example SELECT S.sname FROM Reserves R, Sailors S WHERE R.sid=S.sid AND R.bid=100 AND S.rating>5 RA Tree: expression tree. Each leaf is a schema table. Internal nodes: relational algebra operator applied to children. Full plan labels each internal node with implementation strategy. Reserves Sailors sid=sid bid=100 rating > 5 sname (Simple Nested Loops) (On-the-fly) Plan: By convention, Outer table is left child Sailors: 500 pages, * 10 tuples/page = 5,000 records Reserves: 1,000 pages * 10 tuples/page = 10,000 records --- show in SQL server 4
29
Alternative Plan Goal of optimization: To find efficient plans that compute the same answer. Reserves Sailors sid=sid bid=100 sname (On-the-fly) rating > 5 (Scan; write to temp T1) temp T2) (Sort-Merge Join) 5
30
Highlights of System R Optimizer
Impact: Most widely used currently; works well for < 10 joins. Cost estimation: NP-hard, approximate art at best. Statistics, maintained in system catalogs, used to estimate cost of operations and result sizes. Considers combination of CPU and I/O costs. Plan Space: Too large, must be pruned. Only the space of left-deep plans is considered. (see text) Cartesian products avoided. Combines probability, logic, AI. 2
31
Cost Estimation For each plan considered, must estimate cost:
Must estimate cost of each operation in plan tree. Depends on input cardinalities. We’ve already discussed how to estimate the cost of operations (sequential scan, index scan, joins, etc.) Must also estimate size of result for each operation in tree! Use information about the input relations. For selections and joins, assume independence of predicates. 8
32
Schema for Examples Similar to old schema; rname added for variations.
Sailors (sid: integer, sname: string, rating: integer, age: real) Reserves (sid: integer, bid: integer, day: dates, rname: string) Similar to old schema; rname added for variations. Reserves: 10 tuples per page, 1000 pages. Sailors: 10 tuples per page, 500 pages. 3
33
Motivating Example RA Tree: R.bid=100 AND S.rating>5
Reserves Sailors sid=sid bid=100 rating > 5 sname Motivating Example SELECT S.sname FROM Reserves R, Sailors S WHERE R.sid=S.sid AND R.bid=100 AND S.rating>5 Cost: 1,001,000 I/Os (see above) Misses several opportunities: selections could have been `pushed’ earlier, no use is made of any available indexes, etc. Goal of optimization: To find more efficient plans that compute the same answer. Reserves Sailors sid=sid bid=100 rating > 5 sname (Simple Nested Loops) (On-the-fly) Plan: By convention, Outer table is left child Sailors: 500 pages, * 10 tuples/page = 5,000 records Reserves: 1,000 pages * 10 tuples/page = 10,000 records Join Cost: scan reserves, read Sailors pages ,000*500/2 = Total = 1,001,000 page I/Os. 4
34
Alternative Plans 1 (No Indexes)
Reserves Sailors sid=sid bid=100 sname (On-the-fly) rating > 5 (Scan; write to temp T1) temp T2) (Sort-Merge Join) Alternative Plans 1 (No Indexes) Main difference: push selects. With 5 buffers, cost of plan: Scan Reserves (1000) + write temp T1 (10 pages, if we have 100 boats, uniform distribution). Scan Sailors (500) + write temp T2 (250 pages, if we have 10 ratings). Sort T1 (2*2*10), sort T2 (2*3*250), merge (10+250) Total: page I/Os. Big win from pushing selections! T2 is too big to sort in 2 passes, need 3 passes. 5
35
Alternative Plan 2 With Indexes
(On-the-fly) Alternative Plan 2 With Indexes sname (On-the-fly) rating > 5 With clustered index on bid of Reserves, we get 10,000/100 = 100 tuples on 100/10 = 10 pages for selection. INL with pipelining (outer is not materialized). (Index Nested Loops, sid=sid with pipelining ) (Use clustered index. do not write result to temp) bid=100 Sailors Reserves Join column sid is a key for Sailors. At most one matching tuple, unclustered index on sid OK. Decision not to push rating>5 before the join: there is an index on sid of Sailors, don’t want to compute selection Cost: Selection of Reserves tuples (10 I/Os). For each, must get matching Sailors tuple (100*(1.2+1)). Total = 230 page I/Os. Assume that there are 100 uniformly distributed BoatIDs. And that Reserves is clustered. Book assumes Alternative 1 for Sailors, hence only 1210 page IOs. Projecting out unnecessary fields doesn’t help. By convention, left relation is outer relation 6
36
Index Selection Guidelines
Attributes in WHERE clause are candidates for index keys. Exact match condition suggests hash index. Range query suggests tree index. Clustering is especially useful for range queries. Multi-attribute search keys should be considered when a WHERE clause contains several conditions. Order of attributes is important for range queries. Try to choose indexes that benefit as many queries as possible. MS Index Tuning Wizard Relate exact match and range query performance back to performance table. Index-only strategy: answer question using data entries only. Often works for aggregation, e.g. count* (see below). Give example of product color from assignment, retrieve all colors. . Since only one index can be clustered per relation, choose it based on important queries that would benefit the most from clustering 14
37
Summary There are several alternative evaluation algorithms for each relational operator. A query is evaluated by converting it to a tree of operators and evaluating the operators in the tree. Must understand query optimization in order to fully understand the performance impact of a given database design (relations, indexes) on a workload (set of queries). Two parts to optimizing a query: Consider a set of alternative plans. Must prune search space; typically, left-deep plans only. Must estimate cost of each plan that is considered. Must estimate size of result and cost for each plan node. Key issues: Statistics, indexes, operator implementations. Left-deep plan: right child is base table. 19
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.