3 Query Processing And Optimization

Advanced Database · Unit 3 · 7 hrs

Query Processing and Optimization

Exam-focused notes for Query Processing and Optimization (Advanced Database, CSC475): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Query Processing and Optimization in short

This unit covers how a DBMS turns a high-level SQL query into an efficient execution plan: the stages of query processing, relational-algebra equivalence rules, heuristic and cost-based optimization, join algorithms and their I/O costs, and how an optimizer chooses among competing plans.

Query Processing and Optimization: notes

Concept of Query Processing

Query processing is the sequence of steps that transforms a high-level query, typically SQL, into instructions the DBMS can execute against the stored data. Parsing and validation checks the query's syntax against the language grammar and its structural correctness. Semantic analysis checks the query against the schema itself: do the named tables and columns exist, and are the data types compatible. The parsed query is then translated into an internal form, a relational algebra expression or an equivalent query tree, distinct from any one query execution plan: the expression is a logical plan (what to compute), while an execution plan choosing specific algorithms and access paths for each operation is a physical plan (how to compute it), and it is exactly this logical-to-physical gap that query optimization searches to close efficiently. Plan generation produces one or more candidate sequences of operations (table access, filters, joins); plan execution carries out the chosen plan using disk I/O, memory and CPU; and result retrieval returns the final rows to the caller.

Query Trees and Heuristics for Query Optimization

A query tree is a tree-structured representation of a relational algebra expression: leaf nodes are the base relations, internal nodes are operators (SELECT/$\sigma$, PROJECT/$\pi$, JOIN/$\Join$), and the root is the final result. Representing a query this way lets the optimizer visualize the plan, systematically transform it into equivalent but cheaper trees, and cache and reuse trees for structurally similar queries.

Heuristic optimization rewrites the query tree using equivalence transformation rules that are always safe (they never change the result) and usually, though not provably always, cheaper:

What this unit covers

  • Concept of Query Processing
  • Query Trees and Heuristics for Query Optimization
  • Choice of Query Execution Plans
  • Cost-Based Optimization

Query Trees and Heuristics for Query Optimization

2081 · 10 marks

Why do we need query optimization in databases? Explain heuristic query optimization with examples.[10]

Show solved answer

Query Optimization in Databases

Why Do We Need Query Optimization?

Query optimization is essential in database systems for the following reasons:

ReasonExplanation
Improved PerformanceReduces execution time of queries, making data retrieval faster
Resource UtilizationMinimizes CPU usage, disk I/O, and network traffic
Cost ReductionMinimizes resource usage and improves overall efficiency of query execution
ScalabilityTechniques like indexing, caching, and parallel processing help handle growing workloads
Complex Query SupportConsiders query rewriting, join ordering, and index selection for complex queries
Application ResponsivenessProvides faster responses, leading to better user experiences

Heuristic Query Optimization

Definition

Heuristic query optimization transforms an initial query tree into a final (optimized) query tree using a set of equivalence transformation rules (heuristic rules). These rules typically improve execution performance without computing the actual cost of each alternative plan.

The internal representation of the query is usually a query tree or query graph data structure, and heuristic rules are applied to modify this structure to improve performance.


Key Heuristic Rules

The following are the most commonly applied heuristic rules:

  1. Perform SELECT (selection) operations as early as possible

    • Selection reduces the number of tuples in intermediate results.
    • Applying it before JOIN or other binary operations reduces the size of files being joined.
  2. Perform PROJECT (projection) operations as early as possible

    • Projection reduces the number of attributes (columns) in intermediate results.
    • This reduces the size of tuples flowing through the query tree.
  3. Perform the most restrictive selection and join operations first

    • Operations that eliminate the most data should be applied before less restrictive ones.
  4. Apply SELECT before JOIN or other binary operations

    • This is the main heuristic rule: since SELECT and PROJECT reduce file size, they should always precede JOIN operations.

How Heuristic Query Optimizer Works

Initial Query Tree
       |
       v
Apply Equivalence Transformation Rules (Heuristics)
       |
       v
Final Optimized Query Tree

The optimizer:

  1. Parses the SQL query into an initial query tree (usually based on relational algebra).
  2. Applies heuristic rules to push selections and projections down the tree (closer to the leaf nodes/base relations).
  3. Produces a final query tree that is expected to execute more efficiently.

Example

Consider the following query:

SELECT e.ename, d.dname
FROM EMPLOYEE e, DEPARTMENT d
WHERE e.dno = d.dnumber
  AND e.salary > 50000;

Step 1: Initial Query Tree (Naive Plan)

The naive approach applies operations in the order they appear:

         PROJECT (e.ename, d.dname)
                  |
              SELECT (e.salary > 50000)
                  |
              JOIN (e.dno = d.dnumber)
               /        \
        EMPLOYEE       DEPARTMENT

In the naive plan, the JOIN is performed first on the full EMPLOYEE and DEPARTMENT tables, producing a large intermediate result. Then the SELECT filter is applied.

Step 2: Apply Heuristic Rules

Rule Applied: Push the SELECT operation below the JOIN (apply it early, before the JOIN).

Step 3: Final Optimized Query Tree

         PROJECT (e.ename, d.dname)
                  |
              JOIN (e.dno = d.dnumber)
               /              \
    SELECT                  DEPARTMENT
  (e.salary > 50000)
         |
      EMPLOYEE

What changed:

  • The selection e.salary > 50000 is now applied directly on EMPLOYEE before the JOIN.
  • This filters out employees with salary <= 50000 first, producing a much smaller intermediate relation.
  • The JOIN is then performed on this smaller EMPLOYEE result and the DEPARTMENT table.
  • Finally, PROJECT reduces the attributes to only ename and dname.

Benefits of This Optimization

StepWithout HeuristicWith Heuristic
JOIN input sizeFull EMPLOYEE table (e.g., 10,000 rows)Filtered EMPLOYEE (e.g., 500 rows)
Intermediate resultVery largeMuch smaller
Execution timeSlowSignificantly faster

Summary

Heuristic query optimization is a rule-based approach that improves query performance by transforming the query tree. The core principle is:

"Apply SELECT and PROJECT early to reduce intermediate result sizes before performing expensive JOIN operations."

Unlike cost-based optimization (which uses statistics and computes actual costs), heuristic optimization applies general rules that are known to improve performance in most cases, making it simpler and faster to apply.

Open this answer on its own page →

2081 · 5 marks

What are the uses of query trees in query processing? Explain. [5]

Show solved answer

Uses of Query Trees in Query Processing

Definition

A query tree is a hierarchical (tree-based) representation of the steps and operations involved in executing a database query. It outlines the logical and physical operations required to retrieve the desired data from the database.


Uses of Query Trees in Query Processing

1. Visualization and Understanding

Query trees provide a visual representation of the query execution plan. This makes it easier for database administrators, developers, and optimizers to understand and analyze the sequence of steps involved in processing a query. Instead of reading complex procedural instructions, one can simply trace the tree from leaves (base relations) to the root (final result).


2. Query Optimization

By representing the query execution plan as a tree, the query optimizer can efficiently explore and evaluate various alternative plans. It can rearrange nodes, reorder operations (such as pushing selections down the tree), and compare costs of different plans to select the most efficient execution strategy. This directly helps in minimizing execution time and resource consumption.


3. Execution Order and Data Flow

Query trees define the order in which operations (such as selection, projection, join) are performed and how data flows between them. Each internal node represents an operation, and data flows upward from child nodes to parent nodes, making the execution sequence explicit and unambiguous.


4. Query Plan Caching and Reuse

Query trees can be cached and reused for similar queries that differ only in parameter values. When the same or a structurally similar query is submitted again, the stored query tree can be retrieved and reused, avoiding the overhead of re-parsing and re-optimizing. This significantly improves query performance.


5. Support for Complex Queries

Query trees help in managing and processing complex queries involving multiple joins, subqueries, and nested operations. By breaking down a complex query into a structured tree of simpler operations, the system can handle each operation systematically and efficiently.


Summary Table

UseBenefit
VisualizationEasier understanding of execution plan
Query OptimizationFinds the most efficient execution strategy
Execution Order & Data FlowDefines clear operation sequence
Plan Caching & ReuseAvoids redundant computation
Complex Query SupportManages multi-step queries systematically

In summary, query trees are a fundamental tool in query processing that bridge the gap between a high-level SQL query and its efficient execution by the DBMS.

Open this answer on its own page →

2080 · 5 marks

Why query optimization is essential in databases? What is heuristic optimization? [5]

Query Optimization refers to the process of improving the performance and efficiency of database queries by finding the most effective way to retrieve data. The primary goal is to minimize execution time and resource consumption (CPU usage, disk I/O, and network traffic). Query optimization is es...

Open this answer on its own page →

Concept of Query Processing

2080 · 5 marks

Explain different steps in query processing. [5]

Query Processing is the process of executing a database query or request for information. It involves several steps that transform a high-level query written in a programming language (such as SQL) into instructions that can be understood and executed by the DBMS. --- - The query written in a hig...

Open this answer on its own page →

2079 · 5 marks

What is query processing? Differentiate query processing with query optimization. [5]

Query Processing is the process of executing a database query or request for information. It involves several steps that transform a high-level query written in a programming language (such as SQL) into low-level instructions that can be understood and executed by the Database Management System (...

Open this answer on its own page →

Choice of Query Execution Plans

2079 · 5 marks

Why query optimization is necessary? Illustrate on the choices of query execution plans. [5]

Query optimization refers to the process of improving the performance and efficiency of database queries by finding the most effective way to retrieve data. The primary goal is to minimize execution time and resource consumption (CPU usage, disk I/O, and network traffic). The key reasons why quer...

Open this answer on its own page →