CPS216: Advanced Database Systems Query Rewrite Rules for Subqueries Shivnath Babu
More Query Rewrite Rules Transform one logical plan into another –Do not use statistics Equivalences in relational algebra Push-down predicates Do projects early Avoid cross-products if possible Use left-deep trees Use of constraints, e.g., uniqueness Subqueries Joins (we will study this rewrite rule after we do physical plan selection)
SQL Query with an Uncorrelated Subquery Find the movies with stars born in 1960 MovieStar(name, address, gender, birthdate) StarsIn(title, year, starName) SELECT title FROM StarsIn WHERE starName IN ( SELECT name FROM MovieStar WHERE birthdate LIKE ‘%1960’ );
Parse Tree SELECT FROM WHERE IN title StarsIn ( ) starName SELECT FROM WHERE LIKE name MovieStar birthDate ‘%1960’
Generating Relational Algebra title StarsIn IN name birthdate LIKE ‘%1960’ starName MovieStar Two-argument selection
Rewrite Rule for Two-argument Selection with Conditions Involving IN Lexp IN Rexp Two-argument selection Lexp Rexp δ X
Applying the Rewrite Rule title StarsIn IN name birthdate LIKE ‘%1960’ starName MovieStar title starName=name StarsIn δ birthdate LIKE ‘%1960’ MovieStar name
Improving the Logical Query Plan title starName=name StarsIn name birthdate LIKE ‘%1960’ MovieStar title starName=name StarsIn δ birthdate LIKE ‘%1960’ MovieStar name
SQL Query with an Correlated Subquery MovieStar(name, address, gender, birthdate) StarsIn(title, year, starName) SELECT title FROM StarsIn WHERE starName IN ( SELECT name FROM MovieStar WHERE name LIKE ‘Tom%’ and year = birthdate + 30 ); Can we rewrite this query as a single-block join query?