Query Execution and Optimization
Query Execution and Optimization
From SQL to an Execution Plan
A database system does not usually execute an SQL query exactly as it is written. It first represents the query using relational algebra, then rewrites that representation and chooses algorithms for carrying out its operations.
The process has three broad stages:
Translate the query into a relational algebra expression, often represented as a tree. The base relations appear at the leaves, and operations such as selection, projection, and join appear above them.
Rewrite the expression using algebraic equivalences and heuristics. The aim is to preserve the query’s meaning while producing an expression that is likely to execute efficiently.
Choose an execution plan by selecting algorithms for the operations in the expression and estimating the cost of the resulting plan.
An execution plan specifies both the operations to perform and the methods used to perform them. For example, it identifies the algorithms used for joins and the order in which those joins are carried out.
Heuristic and Algebraic Optimization
Push selections toward the base relations
A central heuristic is to apply selection operations as early as possible—ideally directly to the base relations they filter.
A selection keeps only rows satisfying a condition. If rows can be removed before a join or another expensive operation, fewer rows need to be processed by that later operation. In a relational algebra tree, this means moving a selection down toward the leaves.
For example, filtering an enrollment relation for a particular student before joining it with teaching records can make the join inputs much smaller.
Push projections toward the base relations
A projection keeps only specified attributes (columns). Projections can also be moved down toward the leaves to reduce the width of intermediate records.
When pushing a projection down, the system must retain every attribute needed later for:
Join conditions
Selections that have not yet been applied
The final output
An attribute should be discarded only when it is no longer needed anywhere above that point in the tree.
Use relational algebra equivalences
Algebraic laws allow a query to be rewritten without changing its result. Important examples include:
Conjunctive selections can be reordered or combined. If several conditions must all hold, their order does not affect the result. This makes it possible to separate conditions according to which relation they apply to.
Joins can often be reordered or regrouped. Under the appropriate semantics, inner joins are commutative and associative. Different join orders can produce the same result while having very different execution costs.
A selection over a Cartesian product can be expressed as a join when the selection condition relates attributes from the two inputs. This avoids generating every possible pair of records before filtering them.
The relevant transformations must preserve the query’s meaning. In particular, a condition involving attributes from two relations cannot be applied to either relation alone; it must remain until both relations are available.
The purpose of heuristic rewriting is to reduce the amount of data processed, especially the size of intermediate results.
Cost-Based Query Optimization
After rewriting the relational algebra expression, the optimizer considers alternative execution methods for its operators. A join, for example, may have several applicable algorithms. Choosing among them requires estimating the cost of each alternative.
Estimating costs
A cost estimate can account for factors such as:
The sizes of the input relations
The number of blocks that must be read or written
The availability of indexes
The expected number of rows that pass a selection
The size of intermediate results
Estimates are commonly based on statistics maintained about the database. Formulas for the costs of individual operations can be used to compare alternative methods.
Evaluate whole plans, not just individual operations
The choices made for operations in one part of a plan can affect the choices available or desirable elsewhere. For example, the join order affects the sizes of intermediate results, which in turn affects the cost of later operations.
For this reason, optimization is a combined planning problem: the optimizer seeks a low-cost choice of algorithms and operation order for the plan as a whole, rather than choosing every operation independently.
Finding the globally best plan can be computationally intractable for complex queries. Optimizers therefore use search strategies and heuristics to explore a manageable number of alternatives. They select a plan with a low estimated cost, but the chosen plan is not guaranteed to be the fastest in practice. Estimates can be inaccurate when the optimizer’s statistics do not reflect the actual data.
Example: Finding a Professor’s Contact Details
Suppose a query asks for the employee ID, name, and phone number of professors who taught a course taken by a particular student in the even semester of a specified year.
The relations are:
Professor, abbreviated as P, containing professor details
Teaching, abbreviated as T, recording which professors taught which courses
Enrollment, abbreviated as E, recording students’ course enrollments
The query connects these relations through two conditions:
The professor’s employee ID matches the teaching record’s employee ID.
The teaching record’s course ID matches the enrollment record’s course ID.
It also filters enrollment records by the specified student, semester, and year, and teaching records by semester and year.
Initial relational algebra expression
A direct translation can use a Cartesian product followed by a selection containing all the conditions, then a projection containing the requested output attributes:
Here, θ represents the complete set of filtering and matching conditions. This expression describes the query correctly, but it suggests forming a large Cartesian product before filtering it. That would generally be inefficient.
Separate conditions by relation
Because the conditions are conjunctive, they can be grouped according to the relations they use:
Conditions involving only E—such as the student, semester, and year filters—can be applied directly to E.
Conditions involving only T—such as its semester and year filters—can be applied directly to T.
The course-ID match between E and T must be applied when those relations are joined.
The employee-ID match between P and T must be applied when those relations are joined.
This arrangement pushes single-relation selections down toward the base relations while keeping cross-relation conditions at the appropriate join.
Replace products and matching selections with joins
A condition matching attributes from two relations turns their Cartesian product into a join. Thus, instead of forming a product and filtering it afterward, the expression can use joins directly.
A suitable rewritten plan shape is:
The join labels above abbreviate the corresponding equality conditions: the first join matches professor and teaching employee IDs, and the second matches teaching and enrollment course IDs. The final projection returns only the professor details requested by the query.
Push projections down carefully
The example also demonstrates projection pushdown:
The filtered enrollment input needs only its course ID for the later join.
The filtered teaching input needs both its course ID and employee ID, because each is used in a different join.
The professor input needs its employee ID for the join and its name and phone number for the output.
Keeping only these attributes prevents unnecessary columns from being carried through the joins. All attributes required by later operations must remain available until those operations have been performed.
Pipelining and Intermediate Results
The internal nodes of a relational algebra tree produce intermediate results. These results may be stored temporarily, or operations may be combined so that records flow directly from one operation to the next.
Pipelining
With pipelining, records produced by one operation are passed directly to a subsequent operation without first writing the complete intermediate relation to storage. For example, while scanning a base relation, the system can filter records and retain only the necessary attributes before passing the results to a join.
Pipelining can avoid extra writes and reads. It is especially useful when one operation’s output can be consumed incrementally by the next.
Materialization
With materialization, an intermediate result is fully produced and stored before the next operation uses it. Materialization may be necessary when the result is too large to keep in memory, when a later operation needs repeated access to it, or when the plan’s structure prevents direct pipelining.
When possible, intermediate results can be kept in memory or pipelined. The choice depends on the result sizes and on the operations in the execution plan.
Compiled Queries and Ad Hoc Queries
Query optimization must also account for how a query will be used.
Compiled queries
A compiled query is known in advance as part of a database program or transaction. Because the query is expected to run repeatedly, it can be worthwhile to spend more time searching for a good execution plan. The cost of optimization is then spread across many executions.
Ad hoc queries
An ad hoc query is submitted as a new request, often for immediate analysis. Since the query may be run only once, lengthy optimization can delay the answer. The system may therefore use a faster, lighter optimization process, balancing the time spent finding a plan against the time the plan is expected to save during execution.
The best optimization strategy depends partly on this trade-off: more optimization effort can improve execution, but optimization itself has a cost.
Key Takeaways
SQL queries are translated into relational algebra and then organized into execution plans.
Heuristic and algebraic rewrites preserve query meaning while aiming to reduce the work required.
Selections should generally be pushed close to the relations they filter, and projections should retain only attributes needed later.
Cost-based optimization estimates the costs of algorithms and plan alternatives, accounting for the relationships between operations.
Intermediate results can be pipelined or materialized, depending on the plan and available resources.
Repeated compiled queries can justify more optimization effort than one-off ad hoc queries.

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