Query Execution and Optimization


Query Execution and Optimization

Anna
Today we’re looking at query execution and optimization: how a database turns an SQL request into work it can actually perform, and how it tries to do that work efficiently. The field is broad, so we’ll focus on the core ideas: rewriting a query, choosing algorithms, and estimating their costs.

Simon
The starting point is an SQL query. The database represents it as a relational algebra expression tree, with operations such as selection, projection, and join. It then needs to choose algorithms for those operations and execute them.

Anna
But before execution, the database can rewrite that initial expression into an equivalent one. The meaning must stay the same, but the form can change in ways that make the work cheaper. This stage uses algebraic transformation rules and heuristics.

Simon
And rewriting isn’t the last decision. Once there’s a suitable expression tree, cost-based optimization considers the possible algorithms for its operators. A join, for instance, might have several applicable evaluation methods, each with a different estimated cost.

Anna
Those choices can affect one another. The method chosen for one operator may change the size or form of its result, which can affect how a later operator should be performed. So the optimizer is trying to choose a good combination for the plan as a whole, not simply pick the cheapest-looking method at each step in isolation.

Simon
Exactly. It estimates costs using information such as the sizes of the input relations and whether indexes are available, along with measures such as the number of block accesses. It then compares possible execution plans and chooses one with a low estimated total cost. The search is intractable in general, so optimizers rely on heuristics and estimates—and those estimates can sometimes be wrong.

Anna
Let’s begin with a key heuristic: push selections down the tree as far as possible. A selection keeps only rows that satisfy a condition. If you can apply that condition while the data is still close to a base relation, fewer rows need to flow into later operations.

Simon
Projections are pushed down too. A projection keeps only specified attributes, or columns. Applying it early means intermediate results carry fewer fields. Together, early selections and projections can shrink intermediate results in both the number of rows and the width of each row.

Anna
The optimizer also uses algebraic laws to rearrange operations without changing the answer. For example, selections can be reordered when both are applied, and joins can be reordered or regrouped using commutativity and associativity. Those laws give the optimizer alternative expression trees to consider.

Simon
Let’s make that concrete. Imagine three relations: Professor, Teaching, and Enrollment. We want the employee ID, name, and phone details of a professor who taught a course taken by a particular student—roll number CS08B207—in the even semester of 2010.

Anna
The query connects the relations through two matching attributes: Enrollment’s course ID matches Teaching’s course ID, and the professor’s employee ID matches Teaching’s employee ID. It also checks that the relevant semester and year are even and 2010, respectively, in both Enrollment and Teaching. Finally, it asks for the professor’s employee ID, name, and phone.

Simon
A direct relational algebra translation would take the Cartesian product of all three relations, select rows satisfying the whole WHERE condition, and then project the requested professor attributes. That’s logically valid, but forming a huge product before filtering would be wasteful.

Anna
So first split the combined condition into smaller predicates. Put the student roll-number condition and Enrollment’s semester and year conditions together, because they refer only to Enrollment. Put the semester and year conditions on Teaching together, because they refer only to Teaching.

Simon
Then apply those selections directly to their own relations. The remaining predicates connect relations: Enrollment course ID equals Teaching course ID, and Professor employee ID equals Teaching employee ID. Those can’t be evaluated on just one relation, but they can be used when the appropriate relations are joined.

Anna
That leads to another important rewrite: a Cartesian product followed by a selection that matches attributes between the two inputs can be expressed as a join. Instead of making every possible pair and filtering afterward, the join directly combines rows that satisfy the matching condition.

Simon
So we can first join the filtered Enrollment and Teaching results on course ID, then join that result with Professor on employee ID. The order and grouping of joins can matter in other queries, and the algebraic laws let the optimizer explore alternatives.

Anna
Now push projections down as well. After filtering Enrollment, the only attribute needed for its join is course ID, so we can discard its other fields. From filtered Teaching, we need course ID for the first join and employee ID for the next one.

Simon
Professor needs a slightly different projection: employee ID must remain for the join, and name and phone must remain for the final answer. Once the joins are complete, project the requested professor employee ID, name, and phone. The general rule is not to carry an attribute upward unless a later operation needs it.

Anna
The result is a much more execution-friendly tree: filter and narrow the base relations, join only the information that is needed, and return just the requested fields. The example shows the spirit of heuristic optimization, rather than every possible algebraic rewrite.

Simon
After rewriting, cost-based optimization chooses how to implement each remaining operation. For the joins, the database considers applicable methods and estimates their costs using input sizes, indexes, and cost formulas such as block-access estimates. It uses the available catalog information to help make those estimates.

Anna
The optimizer also has to think about intermediate results. If an intermediate table fits in memory, keeping it there may be preferable; if necessary, it can be materialized. And when possible, operators can be pipelined: as records are read, the system filters them, keeps the needed attributes, and passes results onward instead of writing every intermediate result out and rereading it.

Simon
That’s why selection and projection can often be combined with reading the input. Rather than scan a relation, store a filtered copy, scan that copy again, and then project, the system can do the useful work as records arrive. Pipelining helps avoid unnecessary intermediate storage and repeated work.

Anna
There’s also a practical tradeoff in how much optimization to do. Some queries are compiled as part of transactions whose query patterns are known ahead of time. Because those queries may run hundreds of times, it can be worthwhile to spend extra time finding a strong plan, even doing that optimization offline.

Simon
Ad hoc queries are different: an analyst might submit a brand-new request and expect an answer quickly. Optimizing the query itself takes time, so a heavy search can add noticeable delay. The system may need to use a lighter optimization approach to balance planning time against execution time.

Anna
So the whole process is a balance: preserve the query’s meaning while rewriting it, reduce the data flowing through the tree, estimate the costs of alternative algorithms and plans, and account for the time and memory available during execution.

Simon
And because query optimization is central to database performance, it remains a substantial research area. The essential takeaway is that a query plan is not just the SQL translated into operations: it is the result of carefully choosing an equivalent expression, implementation methods, and a workable way to handle intermediate results.

Ask anything
We've read this whole study set, so questions about it get the best answers.