50
Lecture #8 November 16 th , 2000 Query Optimization The Next-to-last Frontier

Lecture #8 November 16 th , 2000

  • Upload
    rowa

  • View
    12

  • Download
    0

Embed Size (px)

DESCRIPTION

Lecture #8 November 16 th , 2000. Query Optimization The Next-to-last Frontier. Administration. Last homework handed out by the weekend. Projects? Project demos: Dec. 4-6. Project reports due Dec. 4 th . The (short) Toronto story. Outer joins. Query Optimization. Goal:. - PowerPoint PPT Presentation

Citation preview

Page 1: Lecture #8 November 16 th , 2000

Lecture #8November 16th, 2000

Query Optimization

The Next-to-last Frontier

Page 2: Lecture #8 November 16 th , 2000

Administration

• Last homework handed out by the weekend.

• Projects?

• Project demos: Dec. 4-6.

• Project reports due Dec. 4th.

• The (short) Toronto story.

• Outer joins.

Page 3: Lecture #8 November 16 th , 2000

Query Optimization

Imperative query execution plan:Declarative SQL query

Ideally: Want to find best plan. Practically: Avoid worst plans!

Goal:

Purchase Person

Buyer=name

City=‘seattle’ phone>’5430000’

buyer

(Simple Nested Loops)

(Table scan) (Index scan)

SELECT S.buyerFROM Purchase P, Person QWHERE P.buyer=Q.name AND Q.city=‘seattle’ AND Q.phone > ‘5430000’

Inputs:• the query• statistics about the data (indexes, cardinalities, selectivity factors)• available memory

Page 4: Lecture #8 November 16 th , 2000

How are we going to build one?

• What kind of optimizations can we do?

• What are the issues?

• How would we architect a query optimizer?

Page 5: Lecture #8 November 16 th , 2000

Schema for Some Examples

• Reserves:– Each tuple is 40 bytes long, 100 tuples per page, 1000

pages (4000 tuples)

• Sailors:– Each tuple is 50 bytes long, 80 tuples per page, 500

pages (4000 tuples).

Sailors (sid: integer, sname: string, rating: integer, age: real)Reserves (sid: integer, bid: integer, day: dates, rname: string)

Page 6: Lecture #8 November 16 th , 2000

Motivating Example

• Cost: 500+500*1000 I/Os

• By no means the worst plan!

• 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.

SELECT S.snameFROM Reserves R, Sailors SWHERE R.sid=S.sid AND R.bid=100 AND S.rating>5

Reserves Sailors

sid=sid

bid=100 rating > 5

sname

Reserves Sailors

sid=sid

bid=100 rating > 5

sname

(Simple Nested Loops)

(On-the-fly)

(On-the-fly)

RA Tree:

Plan:

Page 7: Lecture #8 November 16 th , 2000

Alternative Plans 1

• 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=1800 – Total: 3560 page I/Os.

• If we used BNL join, join cost = 10+4*250, total cost = 2770.• If we `push’ projections, T1 has only sid, T2 only sid and sname:

– T1 fits in 3 pages, cost of BNL drops to under 250 pages, total < 2000.

Reserves Sailors

sid=sid

bid=100

sname(On-the-fly)

rating > 5(Scan;write to temp T1)

(Scan;write totemp T2)

(Sort-Merge Join)

Page 8: Lecture #8 November 16 th , 2000

Alternative Plans 2With Indexes

• With clustered index on bid of Reserves, we get 100,000/100 = 1000 tuples on 1000/100 = 10 pages.

• INL with pipelining (outer is not materialized).

Decision not to push rating>5 before the join is based on availability of sid index on Sailors. Cost: Selection of Reserves tuples (10 I/Os); for each, must get matching Sailors tuple (1000*1.2); total 1210 I/Os.

Join column sid is a key for Sailors.–At most one matching tuple, unclustered index on sid OK.

Reserves

Sailors

sid=sid

bid=100

sname(On-the-fly)

rating > 5

(Use hashindex; donot writeresult to temp)

(Index Nested Loops,with pipelining )

(On-the-fly)

Page 9: Lecture #8 November 16 th , 2000

Building Blocks

• Algebraic transformations (many and wacky).

• Statistical model: estimating costs and sizes.• Finding the best join trees:

– Bottom-up (dynamic programming): System-R

• Newer architectures:– Starburst: rewrite and then tree find– Volcano: all at once, top-down.

Page 10: Lecture #8 November 16 th , 2000

Query Optimization Process(simplified a bit)

• Parse the SQL query into a logical tree:– identify distinct blocks (corresponding to nested sub-

queries or views).

• Query rewrite phase:– apply algebraic transformations to yield a cheaper plan.

– Merge blocks and move predicates between blocks.

• Optimize each block: join ordering.• Complete the optimization: select scheduling

(pipelining strategy).

Page 11: Lecture #8 November 16 th , 2000

Key Lessons in Optimization

• There are many approaches and many details to consider in query optimization– Classic search/optimization problem!– Not completely solved yet!

• Main points to take away are:– Algebraic rules and their use in transformations

of queries.– Deciding on join ordering: System-R style

(Selinger style) optimization.– Estimating cost of plans and sizes of

intermediate results.

Page 12: Lecture #8 November 16 th , 2000

Operations (revisited)

• Scan ([index], table, predicate):– Either index scan or table scan.– Try to push down sargable predicates.

• Selection (filter)• Projection (always need to go to the data?)• Joins: nested loop (indexed), sort-merge,

hash, outer join.• Grouping and aggregation (usually the last).

Page 13: Lecture #8 November 16 th , 2000

Relational Algebra Equivalences

• Allow us to choose different join orders and to ‘push’ selections and projections ahead of joins.

• Selections: (Cascade)

c cn c cnR R1 1 ... . . .

c c c cR R1 2 2 1 (Commute)

Projections: RR anaa ...11 (Cascade)

Joins: R (S T) (R S) T (Associative)

(R S) (S R) (Commute)

R (S T) (T R) S Show that:

Page 14: Lecture #8 November 16 th , 2000

More Equivalences• A projection commutes with a selection that only

uses attributes retained by the projection.

• A selection on just attributes of R commutes with join R S. (i.e., (R S) (R) S )

• Similarly, if a projection follows a join R S, we can ‘push’ it by retaining only attributes of R (and S) that are needed for the join or are kept by the projection.

Page 15: Lecture #8 November 16 th , 2000

Query Rewrites: Sub-queries

SELECT Emp.Name

FROM Emp

WHERE Emp.Age < 30

AND Emp.Dept# IN

(SELECT Dept.Dept#

FROM Dept

WHERE Dept.Loc = “Seattle”

AND Emp.Emp#=Dept.Mgr)

Page 16: Lecture #8 November 16 th , 2000

The Un-Nested Query

SELECT Emp.Name

FROM Emp, Dept

WHERE Emp.Age < 30

AND Emp.Dept#=Dept.Dept#

AND Dept.Loc = “Seattle”

AND Emp.Emp#=Dept.Mgr

Page 17: Lecture #8 November 16 th , 2000

Semi-Joins, Magic Sets

• You can’t always un-nest sub-queries (it’s tricky).• But you can often use a semi-join to reduce the

computation cost of the inner query.• A magic set is a superset of the possible bindings

in the result of the sub-query.• Also called “sideways information passing”.• Great idea; reinvented every few years on a

regular basis.

Page 18: Lecture #8 November 16 th , 2000

Rewrites: Magic SetsCreate View DepAvgSal AS (Select E.did, Avg(E.sal) as avgsal From Emp E Group By E.did)

Select E.eid, E.salFrom Emp E, Dept D, DepAvgSal VWhere E.did=D.did AND D.did=V.did And E.age < 30 and D.budget > 100k And E.sal > V.avgsal

Page 19: Lecture #8 November 16 th , 2000

Rewrites: SIPsSelect E.eid, E.salFrom Emp E, Dept D, DepAvgSal VWhere E.did=D.did AND D.did=V.did And E.age < 30 and D.budget > 100k And E.sal > V.avgsal• DepAvgsal needs to be evaluated only for

departments where V.did IN Select E.did From Emp E, Dept D Where E.did=D.did And E.age < 30 and D.budget > 100K

Page 20: Lecture #8 November 16 th , 2000

Supporting Views1. Create View PartialResult as (Select E.eid, E.sal, E.did From Emp E, Dept D Where E.did=D.did And E.age < 30 and D.budget > 100K)2. Create View Filter AS Select DISTINCT P.did FROM PartialResult P.2. Create View LimitedAvgSal as (Select F.did Avg(E.Sal) as avgSal From Emp E, Filter F Where E.did=F.did Group By F.did)

Page 21: Lecture #8 November 16 th , 2000

And Finally…

Transformed query:

Select P.eid, P.sal

From PartialResult P, LimitedAvgSal V

Where P.did=V.did

And P.sal > V.avgsal

Page 22: Lecture #8 November 16 th , 2000

Rewrites: Group By and Join• Schema:

– Product (pid, unitprice,…)– Sales(tid, date, store, pid, units)

• Trees:

Join

groupBy(pid)Sum(units)

Scan(Sales)Filter(date in Q2,2000)

ProductsFilter (in NW)

Join

groupBy(pid)Sum(units)

Scan(Sales)Filter(date in Q2,2000)

ProductsFilter (in NW)

Page 23: Lecture #8 November 16 th , 2000

Rewrites:Operation Introduction• Schema: (pid determines cid)

– Category (pid, cid, details)– Sales(tid, date, store, pid, amount)

• Trees:

Join

groupBy(cid)Sum(amount)

Scan(Sales)Filter(store IN {CA,WA})

CategoryFilter (…)

Join

groupBy(cid)Sum(amount)

Scan(Sales)Filter(store IN {CA,WA})

CategoryFilter (…)

groupBy(pid)Sum(amount)

Page 24: Lecture #8 November 16 th , 2000

Query Rewriting: Predicate Pushdown

Reserves Sailors

sid=sid

bid=100 rating > 5

sname

Reserves Sailors

sid=sid

bid=100

sname

rating > 5(Scan;write to temp T1)

(Scan;write totemp T2)

The earlier we process selections, less tuples we need to manipulatehigher up in the tree.Disadvantages?

Page 25: Lecture #8 November 16 th , 2000

Query Rewrites: Predicate Pushdown (through grouping)

Select bid, Max(age)From Reserves R, Sailors SWhere R.sid=S.sid GroupBy bidHaving Max(age) > 40

Select bid, Max(age)From Reserves R, Sailors SWhere R.sid=S.sid and S.age > 40GroupBy bid

• For each boat, find the maximal age of sailors who’ve reserved it.•Advantage: the size of the join will be smaller.• Requires transformation rules specific to the grouping/aggregation operators.• Won’t work if we replace Max by Min.

Page 26: Lecture #8 November 16 th , 2000

Query Rewrite:Predicate Movearound

Create View V1 ASSelect rating, Min(age)From Sailors SWhere S.age < 20Group By rating

Create View V2 ASSelect sid, rating, age, dateFrom Sailors S, Reserves RWhere R.sid=S.sid

Select sid, dateFrom V1, V2Where V1.rating = V2.rating and V1.age = V2.age

Sailing wiz dates: when did the youngest of each sailor level rent boats?

Page 27: Lecture #8 November 16 th , 2000

Query Rewrite: Predicate Movearound

Create View V1 ASSelect rating, Min(age)From Sailors SWhere S.age < 20Group By rating

Create View V2 ASSelect sid, rating, age, dateFrom Sailors S, Reserves RWhere R.sid=S.sid

Select sid, dateFrom V1, V2Where V1.rating = V2.rating and V1.age = V2.age, age < 20

Sailing wiz dates: when did the youngest of each sailor level rent boats?

First, move predicates up the tree.

Page 28: Lecture #8 November 16 th , 2000

Query Rewrite: Predicate Movearound

Create View V1 ASSelect rating, Min(age)From Sailors SWhere S.age < 20Group By rating

Create View V2 ASSelect sid, rating, age, dateFrom Sailors S, Reserves RWhere R.sid=S.sid, and S.age < 20.

Select sid, dateFrom V1, V2Where V1.rating = V2.rating and V1.age = V2.age, and age < 20

Sailing wiz dates: when did the youngest of each sailor level rent boats?

First, move predicates up the tree.

Then, move themdown.

Page 29: Lecture #8 November 16 th , 2000

Query Rewrite Summary• The optimizer can use any semantically correct

rule to transform one query to another.• Rules try to:

– move constraints between blocks (because each will be optimized separately)

– Unnest blocks

• Especially important in decision support applications where queries are very complex.

• In a few minutes of thought, you’ll come up with your own rewrite. Some query, somewhere, will benefit from it.

• Theorems?

Page 30: Lecture #8 November 16 th , 2000

Cost Estimation

• For each plan considered, must estimate cost:– Must estimate cost of each operation in plan tree.

• Depends on input cardinalities.

– Must estimate size of result for each operation in tree!• Use information about the input relations.• For selections and joins, assume independence of predicates.

• We’ll discuss the System R cost estimation approach.– Very inexact, but works ok in practice.– More sophisticated techniques known now.

Page 31: Lecture #8 November 16 th , 2000

Statistics and Catalogs• Need information about the relations and indexes

involved. Catalogs typically contain at least:– # tuples (NTuples) and # pages (NPages) for each relation.– # distinct key values (NKeys) and NPages for each index.– Index height, low/high key values (Low/High) for each tree

index.

• Catalogs updated periodically.– Updating whenever data changes is too expensive; lots of

approximation anyway, so slight inconsistency ok.

• More detailed information (e.g., histograms of the values in some field) are sometimes stored.

Page 32: Lecture #8 November 16 th , 2000

Cost Model for Our Analysis

As a good approximation, we ignore CPU costs:– B: The number of data pages– P: Number of tuples per page– D: (Average) time to read or write disk page– Measuring number of page I/O’s ignores gains of

pre-fetching blocks of pages; thus, even I/O cost is only approximated.

Page 33: Lecture #8 November 16 th , 2000

General External Merge Sort

• To sort a file with N pages using B buffer pages:– Pass 0: use B buffer pages. Produce sorted runs

of B pages each. – Pass 2, …, etc.: merge B-1 runs.

N B/

B Main memory buffers

INPUT 1

INPUT B-1

OUTPUT

DiskDisk

INPUT 2

. . . . . .

. . .

More than 3 buffer pages. How can we utilize them?

Page 34: Lecture #8 November 16 th , 2000

Cost of External Merge Sort• Number of passes:• Cost = 2N * (# of passes)• E.g., with 5 buffer pages, to sort 108 page file:

– Pass 0: = 22 sorted runs of 5 pages each (last run is only 3 pages)

– Pass 1: = 6 sorted runs of 20 pages each (last run is only 8 pages)

– Pass 2: 2 sorted runs, 80 pages and 28 pages

– Pass 3: Sorted file of 108 pages

1 1 log /B N B

108 5/

22 4/

Page 35: Lecture #8 November 16 th , 2000

Number of Passes of External Sort

N B=3 B=5 B=9 B=17 B=129 B=257100 7 4 3 2 1 11,000 10 5 4 3 2 210,000 13 7 5 4 2 2100,000 17 9 6 5 3 31,000,000 20 10 7 5 3 310,000,000 23 12 8 6 4 3100,000,000 26 14 9 7 4 41,000,000,000 30 15 10 8 5 4

Page 36: Lecture #8 November 16 th , 2000

Simple Nested Loops Join

• For each tuple in the outer relation R, we scan the entire inner relation S. – Cost: M + (PR * M) * N.

• 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.

For each tuple r in R dofor each tuple s in S do

if ri == sj then add <r, s> to result

Page 37: Lecture #8 November 16 th , 2000

Index Nested Loops Join

• If there is an index on the join column of one relation (say S), can make it the inner. – Cost: M + ( (M*PR) * cost of finding matching S tuples)

• 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 depends on clustering.– Clustered index: 1 I/O (typical), unclustered: up to 1 I/O per

matching S tuple.

foreach tuple r in R doforeach tuple s in S where ri == sj do

add <r, s> to result

Page 38: Lecture #8 November 16 th , 2000

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 “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 & SHash table for block of R

(k < B-1 pages)

Input buffer for S Output buffer

. . .

Join Result

Page 39: Lecture #8 November 16 th , 2000

Sort-Merge Join (R S)• Sort R and S on the join column, then scan them to

do a ``merge’’ on the join column.– 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 and all S tuples with same value match; output <r, s> for all pairs of such tuples.

– Then resume scanning R and S.

i=j

Page 40: Lecture #8 November 16 th , 2000

Cost of Sort-Merge Join

• R is scanned once; each S group is scanned once per matching R tuple.

• Cost: M log M + N log N + (M+N)– The cost of scanning, M+N, could be M*N

(unlikely!)

Page 41: Lecture #8 November 16 th , 2000

Hash-Join• Partition both relations

using hash fn h: R tuples in partition i will only match S tuples in partition i.

Read in a partition of R, hash it using h2 (<> h!). Scan matching partition of S, search for matches.

Partitionsof R & S

Input bufferfor Si

Hash table for partitionRi (k < B-1 pages)

B main memory buffersDisk

Output buffer

Disk

Join Result

hashfnh2

h2

B main memory buffers DiskDisk

Original Relation OUTPUT

2INPUT

1

hashfunction

h B-1

Partitions

1

2

B-1

. . .

Page 42: Lecture #8 November 16 th , 2000

Cost of Hash-Join

• In partitioning phase, read+write both relations; 2(M+N). In matching phase, read both relations; M+N 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. Also, Hash Join shown to be highly parallelizable.

– Sort-Merge less sensitive to data skew; result is sorted.

Page 43: Lecture #8 November 16 th , 2000

Size Estimation and Reduction Factors

• Consider a query block:• Maximum # tuples in result is the product of the

cardinalities of relations in the FROM clause.• Reduction factor (RF) associated with each term reflects

the impact of the term in reducing result size. Result cardinality = Max # tuples * product of all RF’s.– Implicit assumption that terms are independent!

– Term col=value has RF 1/NKeys(I), given index I on col

– Term col1=col2 has RF 1/MAX(NKeys(I1), NKeys(I2))

– Term col>value has RF (High(I)-value)/(High(I)-Low(I))

SELECT attribute listFROM relation listWHERE term1 AND ... AND termk

Page 44: Lecture #8 November 16 th , 2000

Histograms

• Key to obtaining good cost and size estimates.

• Come in several flavors:– Equi-depth– Equi-width

• Which is better?• Compressed histograms: special treatment

of frequent values.

Page 45: Lecture #8 November 16 th , 2000

Plans for Single-Relation Queries(Prep for Join ordering)

• Task: create a query execution plan for a single Select-project-group-by block.

• Key idea: consider each possible access path to the relevant tuples of the relation. Choose the cheapest one.

• The different operations are essentially carried out together (e.g., if an index is used for a selection, projection is done for each retrieved tuple, and the resulting tuples are pipelined into the aggregate computation).

Page 46: Lecture #8 November 16 th , 2000

Example• If we have an Index on rating:

– (1/NKeys(I)) * NTuples(R) = (1/10) * 40000 tuples retrieved.

– Clustered index: (1/NKeys(I)) * (NPages(I)+NPages(R)) = (1/10) * (50+500) pages are retrieved (= 55).

– Unclustered index: (1/NKeys(I)) * (NPages(I)+NTuples(R)) = (1/10) * (50+40000) pages are retrieved.

• If we have an index on sid:– Would have to retrieve all tuples/pages. With a clustered index,

the cost is 50+500.

• Doing a file scan: we retrieve all file pages (500).

SELECT S.sidFROM Sailors SWHERE S.rating=8

Page 47: Lecture #8 November 16 th , 2000

Determining Join Order• In principle, we need to consider all possible join orderings:

• As the number of joins increases, the number of alternative plans grows rapidly; we need to restrict the search space.

• System-R: consider only left-deep join trees.– Left-deep trees allow us to generate all fully pipelined plans:Intermediate results not

written to temporary files.• Not all left-deep trees are fully pipelined (e.g., SM join).

BA

C

D

BA

C

D

C DBA

Page 48: Lecture #8 November 16 th , 2000

Enumeration of Left-Deep Plans• Naïve approach: n! combinations.• Principle of optimality: the best plan for the join of R1,…Rn-1 will be

part of the best plan for the join of R1,…,Rn

• Enumerated using N passes (if N relations joined):– Pass 1: Find best 1-relation plan for each relation.– Pass 2: Find best way to join result of each 1-relation plan (as

outer) to another relation. (All 2-relation plans.) – Pass N: Find best way to join result of a (N-1)-relation plan (as

outer) to the N’th relation. (All N-relation plans.)• For each subset of relations, retain only:

– Cheapest plan overall, plus– Cheapest plan for each interesting order of the tuples.

Page 49: Lecture #8 November 16 th , 2000

Enumeration of Plans (Contd.)

• ORDER BY, GROUP BY, aggregates etc. handled as a final step, using either an `interestingly ordered’ plan or an additional sorting operator.

• An N-1 way plan is not combined with an additional relation unless there is a join condition between them, unless all predicates in WHERE have been used up.– i.e., avoid Cartesian products if possible.

• In spite of pruning plan space, this approach is still exponential in the # of tables.

• If we want to consider all (bushy) trees, we need only a slight modification to the algorithm.

Page 50: Lecture #8 November 16 th , 2000

Example

• Pass 1: (essentially, access-path selection)– Sailors: B+ tree matches rating>5, and is probably

cheapest. However, if this selection is expected to retrieve a lot of tuples, and index is unclustered, file scan may be cheaper.

• Still, B+ tree plan kept (tuples are in rating order).

– Reserves: B+ tree on bid matches bid=100; cheapest.

• Pass 2: We consider each plan retained from Pass 1 as the outer, and consider how to join it with the (only) other relation.

e.g., Reserves as outer: Hash index can be used to get Sailors tuples that satisfy sid = outer tuple’s sid value.

Sailors: B+ tree on rating Hash on sidReserves: B+ tree on bid

Reserves Sailors

sid=sid

bid=100 rating > 5

sname