Chapter 2 Short Note
Chapter 2 Short Note
When the relational model was first launched commercially, one of the main aims of query processing was to determine the
most cost-effective way to perform a complex query.
Because disk access is slow compared with memory access, disk access tends to be the dominant cost in query processing for a
centralized DBMS.
Query processing transforms a high-level query into a relational algebra query and checks that it is syntactically and
semantically correct.
The goal is to reduce the total execution time of the query. However, resource usage may also be viewed as the response time,
in which case, we concentrate on maximizing the number of parallel operations. Due to the computational complexity with a
large number of relations, the strategy is generally reduced to finding a near-optimum solution.
Both methods of query optimization depend on database statistics to properly assess the different options that are available.
The accuracy and currency of these statistics significantly affect the efficiency of the execution strategy. The statistics cover
information about relations, attributes, and indexes.
Page 1
Created by Turbolearn AI
For example, the system catalog may store statistics giving the cardinality of relations, the number of distinct values for each
attribute, and the number of levels in a multilevel index. Keeping the statistics current can be problematic, so an alternative
approach is to update the statistics periodically or whenever the system is idle, or to make it the users’ responsibility to indicate
when the statistics should be updated.
SELECT *
FROM Staff s,
Branch b
WHERE [Link] = [Link]
AND [Link] = 'Manager'
AND [Link] = 'London';
This query can be expressed in relational algebra in different ways. Here are two of them:
1. Calculate the Cartesian product of Staff and Branch, then apply the selection:
2. Join Staff and Branch on the branch number, then apply the selection:
Assume there are 1000 tuples in Staff, 50 in Branch, 50 Managers onef oreachbranch, and 5 London branches. Also, assume
there are no indexes or sort keys, and intermediate operations are stored on disk.
The first query would perform significantly more disk accesses because of the Cartesian product. A better strategy is to perform
the unary operations Selection and Projection as early as possible, thereby reducing the operands of any subsequent binary
operations.
Optimization Timing
A hybrid approach could be used to overcome the disadvantage of static query optimization, where the query is reoptimized if
the system detects that the database statistics have changed significantly across the entire DBMS session.
Query Decomposition
The aims of query decomposition are to transform a high-level query into one that is easier to process and to check whether the
query is syntactically and semantically correct. Typical stages of query decomposition are:
Page 2
Created by Turbolearn AI
1. Analysis
2. Normalization
3. Semantic Analysis
4. Simplification
5. Query Restructuring
1. Analysis
In this stage, the query is lexically and syntactically analyzed using techniques based on the grammar of the query language
defined in the system catalog. It also verifies that any operations applied to database objects are appropriate for the object type.
2. Normalization
The normalization stage of query processing converts the query into a normalized form to facilitate further processing. Common
normal forms include Conjunctive Normal Form and Disjunctive Normal Form.
Conjunctive normal form: a sequence of conjuncts connectedbyAN Doperator, where each conjunct contains one or more
terms connected by OR operator.
Disjunctive normal form: a sequence of disjuncts connectedbyORoperator, where each disjunct contains one or more terms
connected by AND operator.
(position = 'Manager' AND branchNo = 'B003') OR (salary > 20000 AND branchNo = 'B003')
3. Semantic Analysis
The objective of semantic analysis is to reject normalized queries that are incorrectly formulated or contradictory. A query is
contradictory if its predicate cannot be satisfied by any tuple.
4. Simplification
In this stage, the query is simplified by applying idempotency rules of boolean algebra, such as:
p AND (p) ≡ p
p OR (p) ≡ p
p AND false ≡ false
p OR false ≡ p
p AND true ≡ p
p OR true ≡ true
p AND (~p) ≡ false
p OR (~p) ≡ true
p AND (p OR q) ≡ p
p OR (p AND q) ≡ p
5. Query Restructuring
In the final stage of query decomposition, the query is restructured to provide a more efficient execution strategy.
Page 3
Created by Turbolearn AI
By applying transformation rules, the optimizer can transform a relational algebra expression into an equivalent expression that
is known to use less resources.
1. Conjunctive Selection Operations can cascade into individual Selection operations andviceversa:
σp∧q∧r(R) ≡ σp(σq(σr(R)))
σp(σq(R)) ≡ σq(σp(R))
R ⋈p S ≡ S ⋈p R
R × S ≡ S × R
R ∪ S ≡ S ∪ R
R ∩ S ≡ S ∩ R
(R ⋈ S) ⋈ T ≡ R ⋈ (S ⋈ T )
(R × S) × T ≡ R × (S × T )
(R ∪ S) ∪ T ≡ S ∪ (R ∪ T )
(R ∩ S) ∩ T ≡ S ∩ (R ∩ T )
Page 4
Created by Turbolearn AI
Database Statistics
The success of estimating the size and cost of intermediate relations depends on the amount of information the DBMS holds.
SCA(R) ∗ SCB(R) f or (A ∧ B)
SCA(R)∗SCB(R)
f or (A ∨ B)
1
Keeping these statistics current can be problematic because updating statistics every time a tuple is inserted or updated can
significantly impact performance. A common approach is for the DBMS to update the statistics periodically or whenever the
system is idle. Another approach is to make it the users’ responsibility to indicate that the statistics should be updated.
Page 5
Created by Turbolearn AI
Here are the main strategies for implementing the Selection operation:
Linear Search
With this approach, it may be necessary to scan each tuple in each block to determine whether it satisfies the
selection predicate.
As shown in the pseudocode above, a linear search involves checking each entry until you find the one you're looking for.
Cost Estimate:
[nBlocks(R)/2] for equality condition on a key attribute, assuming tuples are uniformly distributed.
nBlocks(R) otherwise.
Binary Search
If the file is ordered on the attribute involved in the equality comparison, a binary search can be used.
Cost Estimate:
[log2(nBlocks(R))] for equality condition on ordered attribute.
[log2(nBlocks(R))] + [SCA(R)/bF actor(R)] otherwise.
Other Strategies
Here are some additional strategies, with a brief overview of when each should be applied:
Cardinality Estimation
Estimating the cardinality of the result relation S obtained from the Selection operation can be quite difficult. However, if we
assume that attribute values are uniformly distributed within the domain and that attributes are independent, we can use the
following estimates:
Page 6
Created by Turbolearn AI
nT uples(S) = SCA(R)
It is possible to derive more accurate estimates when we relax the assumption of uniform distribution, but this requires the use of
more detailed statistical information, such as histograms and distribution.
Composite Predicates
We can express a composite predicate in two forms: conjunctive normal form and disjunctive normal form.
Conjunctive selection: Contains only those tuples that satisfy all conjuncts.
Disjunctive selection: Contains tuples formed by the union of all tuples that satisfy the disjuncts.
Recall that the Theta join operation defines a relation containing tuples that satisfy a specified predicate F from the
Cartesian product of two relations.
Here are the main strategies for implementing the Join operation:
Page 7
Created by Turbolearn AI
The simplest join algorithm is a nested loop that joins the two relations together. Because the basic unit of reading/writing is a
disk block, we can improve on the algorithm by having two additional loops that process blocks.
Cost Estimate:
An improvement to this strategy is to read as many blocks as possible from the smaller relation, say R, into the database buffer,
saving one block for the inner relation and one for the result relation. If the buffer can hold nBuffer blocks, then we read
(nBuf f er − 2) blocks from R into the buffer at a time, and one block from S at a time.
If there is an index orhashf unction on the join attributes of the inner relation, say S, the indexed nested loop join can be used.
For each tuple in R, we use the index to retrieve the matching tuples in S.
Cost Estimate:
Sort-Merge Join
Page 8
Created by Turbolearn AI
With the sort-merge join, the relations are first sorted on the join attributes and then merged. Because the relations are in sorted
order, tuples with the same join attribute value are guaranteed to be in consecutive order.
Cost Estimate:
nBlocks(R) + nBlocks(S)
If a relation, R, has to be sorted, we would have to add the cost of the sort. We can approximate this as
nBlocks(R) ∗ [log2(nBlocks(R))]
Hash Join
With a hash join, the relations are partitioned using a hash function. The hash function should provide uniformity and
randomness. The algorithm has to check equivalent partitions for the value.
Cost Estimate:
3 ∗ (nBlocks(R) + nBlocks(S))
Page 9
Created by Turbolearn AI
There are two main approaches to eliminating duplicates: sorting and hashing.
Cardinality Estimation
When the Projection contains a key attribute, then because no elimination of duplicates is required:
nT uples(S) = nT uples(R)
nT uples(S) = SCA(R)
To remove the unwanted attributes, we need to read all tuples of R and copy the required attributes to a temporary relation. The
estimated cost of sorting is nBlocks(R) ∗ [log (nBlocks(R))], and so the combined cost is:
2
Union: We place in the result any tuple that appears in either of the original relations, eliminating duplicates where
necessary.
Intersection: We place in the result only tuples that appear in both relations.
Set difference: We examine each tuple of R and place it in the result if it has no match in S.
For all these operations, we could develop an algorithm using the sort–merge join algorithm as a basis.
Page 10
Created by Turbolearn AI
Cardinality Estimation
Union:
Set difference:
0 ≤ nT uples(T ) ≤ nT uples(R)
R⋈S ⋈ T
R⋈T ⋈ S
S ⋈ T ⋈R
T ⋈ S ⋈ R
S⋈R⋈T
S⋈T ⋈R
R ⋈ T ⋈ S
T ⋈ R ⋈ S
T⋈R⋈S
T⋈S⋈R
R ⋈ S ⋈ T
S ⋈ R ⋈ T
In general, with n relations, there are (2(n − 1))!/(n − 1)! different join orderings. While manageable for small n, the number
grows rapidly. For n=4, there are 120; for n=5, the number exceeds 17 million; and for n=10, it surpasses 176 billion.
Pipelining
Pipelining enhances performance by processing data on-the-fly, avoiding the need to write intermediate relational algebra
operation results to disk temporarily.
Pipelining is an optimization technique where the results of one operation are immediately passed to another
operation without materialization.
Materialization involves storing the output of one operation in a temporary relation for subsequent processing.
σposition=‵M anager′∧salary<20000(Staf f )
σposition=‵M anager′(σsalary<20000(Staf f ))
Instead of creating a temporary relation, pipelining applies the second selection to each tuple resulting from the first selection.
Pipelining is typically implemented as a separate process or thread within a DBMS. It utilizes buffers for each pair of adjacent
operations to hold tuples being passed. However, pipelining may restrict algorithm choices, as inputs to operations might not be
immediately available. For instance, the standard sort-merge join algorithm cannot be used if pipelined input tuples are not
sorted on the join attributes.
Linear Trees
Linear trees are a specific tree structure used in query optimization.
Page 11
Created by Turbolearn AI
This image illustrates various tree structures: a and b show left-deep and right-deep trees respectively; c shows another linear
tree; d presents a bushy nonlinear tree.
Left-deep trees are appealing because inner relations are always base relations and thus materialized. With linear trees, one
side of each operator is always a base relation.
Left-deep trees reduce the search space for the optimum strategy and allow the query optimizer to be based on dynamic
processing techniques. A disadvantage of left-deep trees is that many alternative execution strategies are not considered,
which may be of lower cost than the one found using the linear tree.
Left-deep trees allow the generation of all fully pipelined strategies, where joins are all evaluated using pipelining.
The image illustrates two alternative execution strategies. Strategy a involves a hash join between 'Staff' and 'Branch' followed
by another hash join with 'PropertyForRent', utilizing a B+-tree index on 'city'. Strategy b uses an indexed nested loop join with
pipelining from 'Staff' to 'Branch', then a merge join with 'PropertyForRent', also with a B+-tree index on 'city'.
Some abstract operators used to implement functions at the leaves of relational algebra trees include:
3. IndexScan(R, p): Accesses tuples of R through an index on attribute A, where p is a predicate of the form A θ c
θisacomparisonoperator, cisaconstantvalue .
4. IndexScan(R, A): Retrieves the entire relation R using the index on attribute A.
DBMSs typically support a uniform iterator interface, hiding internal implementation details of each operator. The iterator
interface consists of three functions:
Page 12
Created by Turbolearn AI
1. Open: Initializes the state of the iterator to retrieve the first tuple and allocates buffers for inputs and the output.
2. GetNext: Returns the next tuple in the result and puts it in the output buffer. It calls GetNext on each child node and
performs operator-specific code to generate the output.
Restriction 1: Unary operations are processed on-the-fly: selections are processed as relations are accessed for the first
time; projections are processed as the results of other operations are generated.
This implies that all operations are dealt with as part of join execution.
Restriction 2: Cartesian products are never formed unless the query specifies one.
Restriction 3: The inner operand of each join is a base relation, never an intermediate result.
This third restriction is more heuristic and excludes many alternative strategies, but it significantly reduces the number of
alternative join strategies to be considered to O2n for queries with n relations and has a corresponding complexity of O3n.
To obtain the optimal strategy for a query consisting of n joins, consider only the optimal strategies for subexpressions that
consist of n − 1 joins and extend those strategies with an additional join. Suboptimal strategies can be discarded.
The algorithm recognizes that some potentially useful strategies could be discarded. To ensure that such possibilities are not
discarded, the algorithm introduces the concept of interesting orders: an intermediate result has an interesting order if it is
sorted by a final ORDER BY attribute, GROUP BY attribute, or any attributes that participate in subsequent joins.
The dynamic programming algorithm proceeds from the bottom up and constructs all alternative join trees that satisfy the
restrictions defined in the section:
Pass 1: Enumerate strategies for each base relation using a linear scan and all available indexes on the relation. Partition
these partial single − relation strategies into equivalence classes based on any interesting orders.
Pass k: Generate all k-relation strategies by considering each strategy retained after Pass k − 1 as the outer relation, again
discarding any Cartesian products generated and processing any selection and projections on-the-fly.
Pass n: Generate all n-relation strategies by considering each strategy retained after Pass n − 1 as the outer relation,
discarding any Cartesian products generated.
For example, consider the constraint that prevents a member of staff from managing more than 100 properties at the same time:
Page 13
Created by Turbolearn AI
Simulated Annealing: Searches a graph of alternative execution strategies, modeling the annealing process used in crystal
growth.
Iterative Improvement: Performs a number of local optimizations, each starting at a random node and repeatedly accepting
random downhill moves until a local minimum is reached.
Genetic Algorithms: Simulate a biological phenomenon. The algorithms start with an initial population, consisting of a
random set of strategies, each with its own cost.
A Heuristic Algorithm*: Expands one execution strategy at a time, based on its proximity to the optimal strategy.
One capability required is that the ORDBMS query processor flattens queries whenever possible.
The CPU cost of a function invocation is then given by the algorithm A + C ∗ expectedsizeof argument, and the I/O cost is
B ∗ expectedsizeof argument.
Page 14
Created by Turbolearn AI
The problem with this approach is that it can be for a user to provide these figures.
Example: Find all detached properties in Glasgow that are within two miles of a primary school and are managed
SELECT *
FROM PropertyForRent p, Staff s
The image includes four flowcharts that demonstrate different scenarios related to primary school networks and their internet
connectivity.
In this case, if the UDF causes a fatal runtime error, the only process affected of the UDF.
The rule-based optimizer assigns a score to each execution strategy using these rankings and then selects the execution strategy
with lowest score.
Page 15
Created by Turbolearn AI
SELECT propertyNo
FROM PropertyForRent
WHERE rooms > 7 AND city = ‘London’;
A single-column access path using the condition (city = ‘London’). This has a rank of 9.
An unbounded range scan using the index on the rooms column from the condition (rooms > 7). This has a rank of 11.
A full table scan, which has a rank of 15.
Even with an index on the propertyNo column, it's not considered because it isn't used in the WHERE clause. The optimizer would
choose the index on the city column based on these paths.
Cost-Based Optimization
Cost-based optimization has deprecated rule-based optimization. It minimizes resource usage based on either:
The OPTIMIZER_MODE initialization parameter determines which approach is used. The cost-based optimizer also considers user-
provided hints.
Statistics
The cost-based optimizer depends on statistics for tables, clusters, and indexes. Oracle can automatically gather statistics using
the automated maintenance tasks infrastructure (AutoTask). The DBMS_STATS PL/SQL package can generate statistics on various
objects. For instance, to gather schema statistics for a 'Manager' schema:
Page 16
Created by Turbolearn AI
Oracle uses parallel methods to gather statistics where possible, except for index statistics which are collected serially.
Sampling Methods
When gathering statistics, you can specify whether to calculate them on the entire data structure or just a sample. Options
include:
Row Sampling: Reads rows ignoring physical placement on disk, which may require a full table or index scan in the worst
case.
Block Sampling: Reads a random sample of blocks and gathers statistics using rows in these blocks.
Sampling uses fewer resources than computing exact figures for the entire structure.
Statistics can also be gathered while creating or rebuilding indexes using the COMPUTE STATISTICS option with CREATE INDEX or
ALTER INDEX commands. Statistics are stored in the Oracle data dictionary and can be inspected through various views.
ALL_TABLES All objects in the database that the user has access to.
USER_TABLES Objects in the user’s schema.
TAB_HISTOGRAMS Statistics about the use of histograms on tables.
TAB_COLUMNS Information about the columns in tables, views, and clusters.
TAB_COL_STATISTICS Column statistics and histogram information from TAB_COLUMNS.
TAB_PARTITIONS Information about the partitions in a partitioned table.
CLUSTERS Information about clusters.
INDEXES Information about indexes.
IND_STATISTICS Statistics about all indexes.
IND_COLUMNS Information about the columns in each index on tables/clusters.
TAB_SUBPARTITIONS Information on each table subpartition.
IND_PARTITIONS Information for each index partition.
IND_SUBPARTITIONS Information on each index subpartition.
PART_COL_STATISTICS Column statistics and histogram information for table partitions.
PART_HISTOGRAMS Histogram data for the histograms on the table partitions.
SUBPART_COL_STATISTICS Column statistics and histogram information for subpartitions of partitioned objects.
SUBPART_HISTOGRAMS Histogram data for histograms on table subpartitions.
These views can be prefixed with ALL_, USER_, or emptypref ix depending on the scope.
Hints
The cost-based optimizer considers hints to influence decisions, such as:
For example:
Page 17
Created by Turbolearn AI
If there are as many male as female staff members, a full table scan might be more efficient. If there are far fewer male staff
members, an index scan would be better. This hint forces the optimizer to use the index on the sex column.
Histograms
Histograms improve estimates when data values within a column are not uniformly distributed.
Figure a shows a uniform distribution while Figure b illustrates a non-uniform distribution. Storing a uniform distribution is
straightforward with a low value, a high value, and a total count.
A histogram is a data structure that improves estimation accuracy. There are two types:
Width-Balanced Histogram: Divides data into fixed equal-width ranges buckets, each containing a count of the number of
values.
Height-Balanced Histogram: Places approximately the same number of values in each bucket.
Histograms can be used to improve estimates with non uniform distributions. Here is an example of two types of histograms that
can be used:
Histogram
Description Characteristics
Type
Height- Places approximately the same number of End-points determined by data distribution, height of each
Balanced values per bucket. column approximately even.
For the predicate rooms > 9, a width-balanced histogram provides a better estimate than assuming uniform distribution. Oracle
uses height-balanced histograms.
Histograms are persistent objects, so creating and maintaining them involves overhead.
Page 18
Created by Turbolearn AI
Each line represents a step in the execution plan, with indentation showing the hierarchy of operations.
Query optimization aims to choose the most efficient strategy to minimize resource usage.
Query Decomposition
Query decomposition transforms a high-level query into a relational algebra query and checks its syntax and semantics. The
stages are:
1. Analysis
2. Normalization
3. Semantic Analysis
4. Simplification
5. Query Restructuring
Page 19
Created by Turbolearn AI
Cascade of selection.
Commutativity of unary operations.
Commutativity of Theta join andCartesianproduct.
Associativity of Theta join andCartesianproduct.
Cost Estimation
Cost estimation relies on statistical information from the system catalog, such as:
Pipelining saves the cost of creating temporary relations and reading results back.
Page 20
Created by Turbolearn AI
Left-Deep Trees
A relational algebra tree where the right-hand relation is always a base relation is known as a left-deep tree.
Left-deep trees:
Generic B-trees.
R-trees regiontrees for two- and three-dimensional data.
Indexes on the output of a function.
Page 21