Lecture 14: Query Optimization. This Lecture Query rewriting Cost estimation –We have learned how atomic operations are implemented and their cost –We’ll.

Slides:



Advertisements
Similar presentations
Overview of Query Evaluation (contd.) Chapter 12 Ramakrishnan and Gehrke (Sections )
Advertisements

Query Optimization The Next-to-last Frontier
Query Optimization Reserves Sailors sid=sid bid=100 rating > 5 sname (Simple Nested Loops) Imperative query execution plan: SELECT S.sname FROM Reserves.
Query Optimization May 31st, Today A few last transformations Size estimation Join ordering Summary of optimization.
Query Optimization CS634 Lecture 12, Mar 12, 2014 Slides based on “Database Management Systems” 3 rd ed, Ramakrishnan and Gehrke.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Relational Query Optimization Chapters 14.
Query Optimization Goal: Declarative SQL query
1 Overview of Query Evaluation Chapter Objectives  Preliminaries:  Core query processing techniques  Catalog  Access paths to data  Index matching.
Query Optimization. Query Optimization Process (simplified a bit) Parse the SQL query into a logical tree: –identify distinct blocks (corresponding to.
1 Relational Query Optimization Module 5, Lecture 2.
Relational Query Optimization 198:541. Overview of Query Optimization  Plan: Tree of R.A. ops, with choice of alg for each op. Each operator typically.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Query Evaluation Chapter 12.
Query Rewrite: Predicate Pushdown (through grouping) Select bid, Max(age) From Reserves R, Sailors S Where R.sid=S.sid GroupBy bid Having Max(age) > 40.
Relational Query Optimization (this time we really mean it)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Query Evaluation Chapter 12.
Overview of Query Evaluation R&G Chapter 12 Lecture 13.
Query Optimization: Transformations May 29 th, 2002.
Query Optimization II R&G, Chapters 12, 13, 14 Lecture 9.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Relational Query Optimization Chapter 15.
Query Optimization Overview Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems December 2, 2004 Some slide content derived.
Overview of Query Optimization v Plan : Tree of R.A. ops, with choice of alg for each op. –Each operator typically implemented using a `pull’ interface:
Query Optimization, part 2 CS634 Lecture 13, Mar Slides based on “Database Management Systems” 3 rd ed, Ramakrishnan and Gehrke.
Overview of Implementing Relational Operators and Query Evaluation
Introduction to Database Systems1 Relational Query Optimization Query Processing: Topic 2.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Query Evaluation Chapter 12: Overview.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Implementing Relational Operators and Query Evaluation Chapter 12.
Query Optimization. overview Histograms A histogram is a data structure maintained by a DBMS to approximate a data distribution Equiwidth vs equidepth.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Query Evaluation Chapter 12.
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.
Database systems/COMP4910/Melikyan1 Relational Query Optimization How are SQL queries are translated into relational algebra? How does the optimizer estimates.
Query Optimization March 6 th, Query Optimization Process (simplified a bit) Parse the SQL query into a logical tree: –identify distinct blocks.
Query Optimization Imperative query execution plan: Declarative SQL query Ideally: Want to find best plan. Practically: Avoid worst plans! Goal: Purchase.
Query Optimization March 10 th, Very Big Picture A query execution plan is a program. There are many of them. The optimizer is trying to chose a.
1 Relational Query Optimization Chapter Query Blocks: Units of Optimization  An SQL query is parsed into a collection of query blocks :  An SQL.
1 Lecture 25 Friday, November 30, Outline Query execution –Two pass algorithms based on indexes (6.7) Query optimization –From SQL to logical.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Overview of Implementing Relational Operators and Query Evaluation Chapter 12.
CS411 Database Systems Kazuhiro Minami 12: Query Optimization.
Introduction to Query Optimization, R. Ramakrishnan and J. Gehrke 1 Introduction to Query Optimization Chapter 13.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Introduction to Query Optimization Chapter 13.
Implementation of Database Systems, Jarek Gryz1 Relational Query Optimization Chapters 12.
Lecture 15: Query Optimization. Very Big Picture Usually, there are many possible query execution plans. The optimizer is trying to chose a good one.
Cost Estimation For each plan considered, must estimate cost: –Must estimate cost of each operation in plan tree. Depends on input cardinalities. –Must.
CSE 544: Lecture 14 Wednesday, 5/15/2002 Optimization, Size Estimation.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Introduction To Query Optimization and Examples Chpt
Tallahassee, Florida, 2016 COP5725 Advanced Database Systems Query Optimization Spring 2016.
Query Optimization. overview Application Programmer (e.g., business analyst, Data architect) Sophisticated Application Programmer (e.g., SAP admin) DBA,
DBMS Internals Execution and Optimization May 10th, 2004.
CS222P: Principles of Data Management Lecture #15 Query Optimization (System-R) Instructor: Chen Li.
Indexing and Execution
Introduction to Query Optimization
Introduction to Database Systems
Examples of Physical Query Plan Alternatives
Database Applications (15-415) DBMS Internals- Part IX Lecture 21, April 1, 2018 Mohammad Hammoud.
Relational Query Optimization
Overview of Query Evaluation
Overview of Query Evaluation
Lecture 24: Query Execution
Lecture 25: Query Optimization
Relational Query Optimization
Query Optimization.
Monday, 5/13/2002 Hash table indexes, query optimization
Query Optimization March 7th, 2003.
Relational Query Optimization (this time we really mean it)
Overview of Query Evaluation
Query Optimization May 16th, 2002
CS222: Principles of Data Management Lecture #15 Query Optimization (System-R) Instructor: Chen Li.
Lecture 26 Monday, December 3, 2001.
Relational Query Optimization
Relational Query Optimization
Lecture 24: Wednesday, November 27, 2002.
Presentation transcript:

Lecture 14: Query Optimization

This Lecture Query rewriting Cost estimation –We have learned how atomic operations are implemented and their cost –We’ll complete the picture by estimating the cost query plans –Including computing the size of the output (reduction factors) Join ordering - optimization

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: SQL-to-SQL transforms –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).

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

Algebraic Laws Commutative and Associative Laws –R U S = S U R, R U (S U T) = (R U S) U T –R ∩ S = S ∩ R, R ∩ (S ∩ T) = (R ∩ S) ∩ T –R ⋈ S = S ⋈ R, R ⋈ (S ⋈ T) = (R ⋈ S) ⋈ T Distributive Laws –R ⋈ (S U T) = (R ⋈ S) U (R ⋈ T)

Algebraic Laws Laws involving selection: –  C AND C’ (R) =  C (  C’ (R)) =  C (R) ∩  C’ (R) –  C OR C’ (R) =  C (R) U  C’ (R) –  C (R ⋈ S) =  C (R) ⋈ S When C involves only attributes of R –  C (R – S) =  C (R) – S –  C (R U S) =  C (R) U  C (S) –  C (R ∩ S) =  C (R) ∩ S

Algebraic Laws Example: R(A, B, C, D), S(E, F, G) –  F=3 (R ⋈ S) = ? –  A=5 AND G=9 (R ⋈ S) = ? D=E

Algebraic Laws Laws involving projections –  M (R ⋈ S) =  N (  P (R) ⋈  Q (S)) Where N, P, Q are appropriate subsets of attributes of M –  M (  N (R)) =  M∩N (R) Example: R(A,B,C,D), S(E, F, G) –  A,B,G (R ⋈ S) =  ? (  ? (R) ⋈  ? (S)) D=E

Query Rewrites: Sub-queries SELECTEmp.Name FROMEmp WHEREEmp.Age < 30 AND Emp.Dept# IN (SELECTDept.Dept# FROMDept WHEREDept.Loc = “Seattle” ANDEmp.Emp#=Dept.Mgr)

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

Converting Nested Queries Select distinct x.name, x.maker From product x Where x.color= “blue” AND x.price >= ALL (Select y.price From product y Where x.maker = y.maker AND y.color=“blue”) Select distinct x.name, x.maker From product x Where x.color= “blue” AND x.price >= ALL (Select y.price From product y Where x.maker = y.maker AND y.color=“blue”)

Converting Nested Queries Select distinct x.name, x.maker From product x Where x.color= “blue” AND x.price < SOME (Select y.price From product y Where x.maker = y.maker AND y.color=“blue”) Select distinct x.name, x.maker From product x Where x.color= “blue” AND x.price < SOME (Select y.price From product y Where x.maker = y.maker AND y.color=“blue”) Let’s compute the complement first:

Converting Nested Queries Select distinct x.name, x.maker From product x, product y Where x.color= “blue” AND x.maker = y.maker AND y.color=“blue” AND x.price < y.price Select distinct x.name, x.maker From product x, product y Where x.color= “blue” AND x.maker = y.maker AND y.color=“blue” AND x.price < y.price This one becomes a SFW query: This returns exactly the products we DON’T want, so…

Converting Nested Queries (Select x.name, x.maker From product x Where x.color = “blue”) EXCEPT (Select x.name, x.maker From product x, product y Where x.color= “blue” AND x.maker = y.maker AND y.color=“blue” AND x.price < y.price) (Select x.name, x.maker From product x Where x.color = “blue”) EXCEPT (Select x.name, x.maker From product x, product y Where x.color= “blue” AND x.maker = y.maker AND y.color=“blue” AND x.price < y.price)

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.

Rewrites: Magic Sets Create View DepAvgSal AS (Select E.did, Avg(E.sal) as avgsal From Emp E Group By E.did) Select E.eid, E.sal From Emp E, Dept D, DepAvgSal V Where E.did=D.did AND D.did=V.did And E.age 100k And E.sal > V.avgsal

Rewrites: SIPs Select E.eid, E.sal From Emp E, Dept D, DepAvgSal V Where E.did=D.did AND D.did=V.did And E.age 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 100K

Supporting Views 1. Create View PartialResult as (Select E.eid, E.sal, E.did From Emp E, Dept D Where E.did=D.did And E.age 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)

And Finally… Transformed query: Select P.eid, P.sal From PartialResult P, LimitedAvgSal V Where P.did=V.did And P.sal > V.avgsal

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,2013) Products Filter (price>100) Join groupBy(pid) Sum(units) Scan(Sales) Filter(date in Q2,2013) Products Filter (price>100)

Schema for Some Examples 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)

Query Rewriting: Predicate Pushdown ReservesSailors sid=sid σ bid=100 AND rating >5  sname sid=sid  sname Reserves Sailors σ bid=100 σ rating > 5 (Scan; write to temp T1) The earlier we process selections, the less tuples we need to manipulate higher up in the tree. Disadvantages? (Scan; write to temp T2)

Query Rewrites: Predicate Pushdown (through grouping) Select bid, Max(age) From Reserves R, Sailors S Where R.sid=S.sid GroupBy bid Having Max(age) > 40 Select bid, Max(age) From Reserves R, Sailors S Where R.sid=S.sid and S.age > 40 GroupBy 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. Will it work work if we replace Max by Min?

Query Rewrite: Predicate Movearound Sailing dates: when did the youngest of each sailor level rent boats? Create View V1 AS Select rating, Min(age) From Sailors S Where S.age < 20 Group By rating Create View V2 AS Select sid, rating, age, date From Sailors S, Reserves R Where R.sid=S.sid Select sid, date From V1, V2 Where V1.rating = V2.rating and V1.age = V2.age

Query Rewrite: Predicate Movearound Create View V1 AS Select rating, Min(age) From Sailors S Where S.age < 20 Group By rating Create View V2 AS Select sid, rating, age, date From Sailors S, Reserves R Where R.sid=S.sid Select sid, date From V1, V2 Where V1.rating = V2.rating and V1.age = V2.age, age < 20 Sailing dates: when did the youngest of each sailor level rent boats? First, move predicates up the tree.

Query Rewrite: Predicate Movearound Create View V1 AS Select rating, Min(age) From Sailors S Where S.age < 20 Group By rating Create View V2 AS Select sid, rating, age, date From Sailors S, Reserves R Where R.sid=S.sid, and S.age < 20. Select sid, date From V1, V2 Where V1.rating = V2.rating and V1.age = V2.age, and age < 20 Sailing dates: when did the youngest of each sailor level rent boats? First, move predicates up the tree. Then, move them down.

Query Rewrite Summary The optimizer can use any semantically correct rule to transform one query to another. Rules are used for: –moving constraints between blocks (because each will be optimized separately) –Un-nesting blocks In a few minutes of thought, you’ll come up with your own rewrite. Some query, somewhere, will benefit from it. Theorems?

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.

Statistics and Catalogs Need information about the relations and indexes involved. Catalogs typically contain at least: –# tuples (T) and # pages (B) for each relation. –# distinct key values (K) and #pages for each index. –Index height, low/high key values (Low/High) for each tree index. –Alternatively V(R, F) – #distinct values in field F of relation R 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.

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/K(I), given index I on col –Term col1=col2 has RF 1/MAX(K(I1), K(I2)) –Term col>value has RF (High(I)-value)/(High(I)-Low(I)) SELECT attribute list FROM relation list WHERE term 1 AND... AND term k

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.

Histograms Statistics on data maintained by the RDBMS Makes size estimation much more accurate (hence, cost estimations are more accurate) V(R,F) – number of distinct values in field F of relation R

Histograms Employee(ssn, name, salary, phone) Maintain a histogram on salary: T(Employee) = 25000, but now we know the distribution Salary:0..20k20k..40k40k..60k60k..80k80k..100k> 100k Tuples

Histograms Ranks(rankName, salary) Estimate the size of Employee ⋈ Ranks Employee0..20k20k..40k40k..60k60k..80k80k..100k> 100k Ranks0..20k20k..40k40k..60k60k..80k80k..100k> 100k Salary

Histograms Assume: –V(Employee, Salary) = 200 –V(Ranks, Salary) = 250 Then T(Employee ⋈ Ranks) = = (  i=1,6 T i T’ i )/ 250 = (200x x x x x x2)/250 = …. Salary

Schema for Some Examples 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)

Pipelining Assume that we want to find all the boats ever reserved by sailors with rank 8. SELECTR.bid FROMSailors S, Reserves R WHERES.rating=8 AND S.sid=R.sid Consider a plan that performs selection, hash join, and projection in this order Writing the result of each operation to the disk is redundant! In the best case, there is enough memory to perform all the operations simultaneously in memory

Pipelining Sailors Reserves σ rating=8 h2 П bid Output 2 1 N h 2 1 h N Selection Hash join step 1 for Sailors Hash join step 1 for Reserves Hash join step 2 Projection

Pipelining We ignored output cost for single operations For operations that get their input in a pipeline, we reduce the first read cost –E.g., selection is for free! –In the previous example – we “saved” the full read in the first stage of hash join for sailor, and the full read for the projection Requires sufficient memory –To perform succeeding operations in parallel –We will usually assume that this is the case

Plan Optimimization Task: create a query execution plan Key idea: perform an estimation of the possible query plan costs and choose the cheapest one The query plan operations are carried out in some order, where the results of one operation are pipelined

Example If we have an Index on rating: –(1/K(I)) · T(R) = (1/10) · tuples retrieved. –Clustered index: (1/K(I)) · (B(I)+B(R)) = search cost + (1/10) · (500) pages are read (= ). –Unclustered index: (1/K(I)) · (B(I)+T(R)) = search cost + (1/10) · ( ) pages are read. Doing a file scan: we retrieve all the pages (500). SELECT S.sid FROM Sailors S WHERE S.rating=8

Determining Join Ordering R1 R2 …. Rn Join tree: A join tree represents a plan. An optimizer needs to inspect many (all ?) join trees R3R1R2R4

Types of Join Trees Left deep: R3 R1 R5 R2 R4

Types of Join Trees Bushy: R3 R1 R2R4 R5

Types of Join Trees Right deep: R3 R1 R5 R2R4

Problem Given: a query R 1 ⋈ R 2 ⋈ … ⋈ R n Assume we have a function cost() that gives us the cost of every join tree Find the best join tree for the query

Dynamic Programming Idea: for each subset of {R 1, …, R n }, compute the best plan for that subset In increasing order of set cardinality: –Step 1: for {R 1 }, {R 2 }, …, {R n } –Step 2: for {R 1,R 2 }, {R 1,R 3 }, …, {R n-1, R n } –… –Step n: for {R 1, …, R n } A subset of {R 1, …, R n } is also called a subquery

Dynamic Programming For each subquery Q ⊆ {R 1, …, R n } compute the following: –Size(Q) –A best plan for Q: Plan(Q) –The cost of that plan: Cost(Q)

Dynamic Programming Step 1: For each {R i } do: –Size({R i }) = B(R i ) –Plan({R i }) = R i –Cost({R i }) = (cost of scanning R i )

Dynamic Programming Step i: For each Q ⊆ {R 1, …, R n } of cardinality i do: –Compute Size(Q) –For every pair of subqueries Q’, Q’’ s.t. Q = Q’ U Q’’ compute cost(Plan(Q’) ⋈ Plan(Q’’)) –Cost(Q) = the smallest such cost –Plan(Q) = the corresponding plan

Dynamic Programming Return Plan({R 1, …, R n })

Dynamic Programming Summary: computes optimal plans for subqueries: –Step 1: {R 1 }, {R 2 }, …, {R n } –Step 2: {R 1, R 2 }, {R 1, R 3 }, …, {R n-1, R n } –… –Step n: {R 1, …, R n } We used naïve size/cost estimations In practice: –more realistic size/cost estimations (next) –heuristics for Reducing the Search Space Restrict to left linear trees Restrict to trees “without cartesian product” –need more than just one plan for each subquery: “interesting orders”

The Course in Perspective The relational data model, SQL –Views, updates, transactions Conceptual design –Expressing the constraints on the domain –Using them to get good schema designs Building a database system: –Storage and indexing –Query execution (join algorithms) –Query optimization