- Introduced by
- IBM San Jose Research Laboratory
- Year
- 1979
- Type
- Database optimization technique
- Family
- Query Processing & Execution
What does it do?
Query optimization is the stage of a database system that turns a declarative SQL statement into an execution plan, meaning a choice of access paths, join orders and join methods.
The approach is associated with the System R project at the IBM San Jose Research Laboratory, where access path selection for single-relation and join queries was described in 1979 (Selinger et al., 1979). The aim is to lower execution cost, measured in terms such as time, disk input/output and resource use.
The intuition behind the method
A declarative SQL query states which rows are wanted but not how to find them, so the same result can usually be produced by several plans. These differ in whether a table is scanned or an index is used, and in the order in which relations are joined. Plans can differ considerably in cost. The optimizer estimates the cost of each candidate from information about the data, such as table sizes, index availability and predicate selectivity, and chooses the candidate with the lowest estimated cost, so the quality of the choice depends on the quality of those estimates.
History
The System R project at the IBM San Jose Research Laboratory addressed how a relational system should choose access paths for SQL queries, including queries that join several relations (Selinger et al., 1979). Jarke and Koch (1984) later surveyed query optimization in centralized database systems, covering logic-based and semantic transformations and combinatorial or heuristic methods for generating and choosing among alternative access plans.
When to use it
Rely on cost-based optimization whenever a relational database receives declarative SQL, because the engine rather than the application decides how each query is executed. The choice matters most for queries that join several relations, combine multiple predicates, or can be answered either by an index or by a full scan, since these have many candidate plans with different costs. Do not expect much benefit for a simple lookup on an indexed key, where there is essentially one sensible plan. The method also depends on statistics that describe the current data; when they are missing or out of date, plan selection is only as reliable as that outdated picture. It does not apply where the access strategy is written procedurally by the application.
Limitations and considerations
- Plan quality is bounded by the cost model and the statistics it uses; errors in estimated table sizes or predicate selectivity carry directly into the chosen plan.
- The number of candidate plans grows quickly with the number of joined relations, so exhaustive enumeration becomes costly and practical optimizers must restrict the search space.
- The plans considered depend on the access paths that exist; without a suitable index, the optimizer is limited to scan-based plans and cannot use an index to exploit a selective predicate.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Users state the required result in declarative SQL, and the optimizer chooses access paths, so a better plan can be obtained without rewriting application code.
- Plan choice is driven by estimated costs derived from statistics, so the selected plan can change as the data changes, without manual intervention.
- The System R design covered both single-relation queries and join queries with boolean combinations of predicates within one selection framework.
Applications
- Multi-table joins in relational reporting, where the join order and join method can substantially change the cost of a query.
- Queries that combine several predicates, where the optimizer decides whether an index on one predicate column is worth using or whether a full scan is cheaper.
- Ad hoc queries written by analysts or applications, whose execution plans are not written by hand in advance and therefore depend on the optimizer.
- Routine queries on tables whose contents change over time, where refreshed statistics are needed to keep plan choices appropriate.
How it works
How it works
Obtain the SQL statement and collect the metadata the optimizer needs: the tables and columns referenced, the indexes that exist, and the data statistics kept for them.
Parse the statement into an internal tree representation and rewrite it into a normalised form, so that equivalent formulations are handled consistently before plans are considered.
Enumerate candidate execution plans, varying the access method for each relation, the order in which relations are joined, and the join algorithm used.
Apply a cost estimation function to each candidate. The function combines the estimated resource use of the plan, chiefly disk input/output and CPU work, derived from statistics such as table size and predicate selectivity (the fraction of rows a predicate is expected to keep). Each candidate receives one estimated cost, so the candidates can be compared directly. Practical optimizers do not evaluate every conceivable plan; they generate and cost a bounded set of candidates.
Select the candidate with the minimum estimated cost and pass it to the database engine as the plan to execute. The chosen plan can be inspected with EXPLAIN, which shows the access method for each table, the join order and join algorithm, and the estimated row counts and costs. Estimated cost is a model value and does not equal measured run time, so the plan should be checked against the measured time and I/O of the actual query.
Common pitfalls
- Assuming manual query hints are better than optimizer decisions without first profiling the query and comparing the plans actually produced.
- Ignoring stale or missing table statistics, which can lead the optimizer to choose a plan that was appropriate for a different state of the data.
- Adding indexes in order to force a particular plan, without checking the plan the optimizer chooses with EXPLAIN.
- Judging a plan change from a single timing run. Capture the plan and timing before and after the change, repeat the runs at a representative data volume, and compare the results, because caching affects the first execution.
Frequently asked questions
Why does the same query sometimes run fast and sometimes slow?
Table statistics change as data is modified, which can cause the optimizer to select different plans. Refresh the statistics after substantial changes to the data, for example with ANALYZE or UPDATE STATISTICS. The exact command differs between database products, so consult the documentation of the system in use.
How can I see what plan the optimizer chose?
Use EXPLAIN or EXPLAIN PLAN commands to display the optimizer's chosen execution plan in a tree format showing access methods, join algorithms, and estimated costs. Estimated costs are model values, so confirm the plan with measured execution time and I/O.
When should I create an index to help optimization?
Consider indexes on columns in selective WHERE predicates or join conditions of frequent queries, and on ORDER BY columns where sorting is costly. Low-selectivity predicates often gain little from an index. Each index adds write and storage cost, so check the benefit with EXPLAIN and timing before keeping it.
Can I force the optimizer to use a specific plan?
Yes, most databases support optimizer hints (e.g., /*+ INDEX() */ in Oracle) to override automatic plan selection, but this should be a last resort after confirming the hint improves performance.
Related methods
Sources
Jarke, M., & Koch, J. (1984). Query optimization in database systems. ACM Computing Surveys, 16(2), 111-152.
Open DOI referenceSelinger, P. G., Astrahan, M. M., Chamberlin, D. D., Lorie, R. A., & Price, T. G. (1979). Access path selection in a relational database management system. Proceedings of the 1979 ACM SIGMOD International Conference on Management of Data, 23-34.
Open DOI referenceGarcia-Molina, H., Ullman, J. D., & Widom, J. (2009). Database Systems: The Complete Book (2nd ed.). Pearson Education.
Open publication reference