Chapter5 Query Processing
Chapter5 Query Processing
Query Optimization
It is the process in which multiple query execution plans for satisfying a query are examined and
a most efficient query plan is identified for execution.
3. Shared Pool check – Every query possess a hash code during its execution. So, this
check determines existence of written hash code in shared pool if code exists in shared
pool then database will not take additional steps for optimization and execution.
Translation involves conversion of high level query to low level instruction in relational algebra.
Example : Select book_title, price From Book
Where price > 400
This query can be translated into either of the following relational-algebra expressions:
π book_title, price ( σ price > 400 ( Book ) )
σ price > 400 ( π book_title, price ( Book ) )
2. Optimization
It is a process in which multiple query execution plan for satisfying a query are examined and
most efficient query plan is satisfied for execution. Optimizer uses the statistical data stored as
part of data dictionary. The statistical data are information about the size of the table, the length
of records, the indexes created on the table, etc. Optimizer also checks for the conditions and
conditional attributes which are parts of the query.
Execution Plan : The query processor module, at this stage, using the information collected in
query optimization to find different relational algebra expressions that are equivalent and return
the result of the one which we have written already. For our example, the query written in
Relational algebra can also be written as the one given below;
3. Evaluation
It takes a physical query plan i.e. evaluation plan, executes that plan and return the result. It is
used to fully specify how to evaluate a query, each operation in the query tree is annotated with
instruction which specify the algorithm or the index to be used to evaluate that operation.
σprice>400
Book
Fig : Query Tree
(Note : Different evaluation plans for a given query can have different cost. It is the
responsibility of query optimizer to generate a least costly plan.)
(Best query evaluation plan is finally submitted to the query evaluation engine for actual
execution.)
Query Tree : It is used to represent relational algebra expression.
It has - Tree data structure
- I/P relations are represented as leaf node
- Relational algebra operations as internal node
σprice>400
Book
Query Blocks : Query submitted to the database system is first decomposed into query blocks. A
query block from a basic unit that can be translated into relational algebra expression and
optimized.
Example : Select book_title From Book Query Blok One
Where price > (Select Min(price) From Book Query Block Two
Where category = 'nobel')
A. Simple select operation (No logical operators such as AND, OR, NOT)
A1. Linear search
All records are scanned to see whether they satisfy the selection condition. This algorithm is
simple and slower than other algorithm for implementing selection. It can be applied to any file
regardless of the ordering of file, availability of indices or the nature of selection operation.
There can be 2 cases :
Whether the record is at 1st position or at the last position in relation.
If there are br number of blocks , then
Avg. Cost = (br/2)
Worst case
Cost = br
A2 Binary search
It is used if file is ordered on some attributes and select condition involves an equality
comparison on that attributes. Book
BID BPrice
A01 100
A02 200
A03 300
There can be one publisher that publish more than one book.
Cost = height of tree + B
Where B - no of blocks satisfying the condition.
A5 Use of secondary index, equality on key or non-key attributes
In this case, when search key is candidate key, single record can be retrieved.
Here,
Cost = (H+1)*(tT + tS)
And when search key is not candidate key, multiple records can be retrieved.
Here,
Cost = (H+B)* (tT + tS)
A6 Use of primary index
If selection condition involves comparison like A>V, A>=V, A<V or A<=V.
A is the attribute with primary index.
V is the attribute value.
Avg. Cost = (bR/2)+H
r1 r1
r2 r3
r3
R1 R2
From above example, the relation created by the selection on Book relation will be
temporary relation and then join will be evaluated between temporary relation and
Publisher relation, which further gives another temporary relation.
By repeating the process, we evaluate the operation at root of the tree that gives the final
result.
A disadvantages to this approaches is the need to construct the temporary relations,
which( unless they are small) must be written to disk.
Cost : Generally the cost of evaluating an expression is the addition of cost of all
operation and cost of writing intermediate result to disk.
We assume that records of the result accumulate in a buffer and when the buffer is full,
they are written to disk. The number of block written out 'br' can be estimated as nr/fr,
where nr is the estimated number of tuples in result relation r and fr is the blocking factor
i.e., number of records r that fit in a block. In addition to transfer time, some disk seeks
may be required, since the disk head may have moved between successive writes. The
number of seeks can be estimated as (br/bb) where bb is the size of output
buffer(measured in blocks).
Double Buffering : (Using two buffers, with one continuing execution of the algorithm
while the other is being written out) allows the algorithm to execute more quickly by
performing CPU activity in parallel with I/O activity. The number of seeks can be
reduced by allocating extra blocks to the output buffer and writing out multiple blocks at
once.
Query Optimization
The process of selecting the most efficient query evaluation plan from among the many strategies
usually possible for processing a given query especially if the query is complex.
Example : Relation schema
instructor (ID , name , dept_name , salary)
teaches (ID , curse_id , sec_id , semester , year)
course (course_id , title , dept_name , credits)
Q. Find the names of all instructors in the music department together with the course title of all
the courses that the instructor teaches?
πname , title (σdept_name = 'Music'(instructor |X| (teaches |X| πcourse_id , title (course))))
It's expression tree is :
Implement First Step, the query optimizer must generate expressions equivalent to a given
expression. It does so by means of equivalence rules that specify how to transform an expression
in to a logically equivalent one.
Transformation of relational expression
A query van be expressed in several different ways with different cost of [Link], two
relational algebra expressions are said to be equivalent if, on every legal database instance, the
two expressions generate the same set of tuples.
Equivalence Rules
It says that expressions of two forms are equivalent.
1. Conjunctive selection operations can be deconstructed into a sequence of individual
selections. It is referred to as cascade of σ.
σ Θ1 Ʌ Θ2 (E) = σ Θ1(σ Θ2(E))
7. The selection operation distributes over the theta join operation under the following
conditions :
a. It distributes when all the attributes in selection condition Θ0 involve only the
attributes of one of the expressions (say E1) being joined.
σ Θ0 (E1 |X|Θ E2) = (σ Θ1 (E1)) |X|Θ E2
b. It distributes when selection condition Θ1 involves only the attributes of E1 and Θ2
involves only the attributes of E2.
σ Θ1 Ʌ Θ2 (E1 |X|Θ E2) = (σ Θ1(E1)) |X|Θ (σ Θ2(E2))
8. The projection operation distributes over the theta join operation under the following
condition :
a) Let L1 and L2 be set of attributes of E1 and E2 respectively. Suppose that the join
condition Θ involves only attributes in L1 ⋃ L2 . Then
πL1 ⋃ L2 (E1 |X|Θ E2) = (πL1(E1)) |X|Θ (πL2(E2))
b) Consider a join E1 |X|Θ E2. Let L1 and L2 be sets of attributes from E1 and E2,
respectively. Let L3 be the attributes of E1 that are involved in join condition Θ,
but are not in L1⋃L2 and let L4 be attributes E2 that are involved in join condition
Θ but are not in L1⋃L2. Then ,
πL1 ⋃ L2 (E1 |X|Θ E2) = πL1 ⋃ L2 ((πL1 ⋃ L3 (E1)) |X|Θ (πL2 ⋃ L4 (E2)))
11. The selection operation distributes over the union, intersection and set difference
operation.
σp(E1 - E2) = σp (E1) - σp (E2)
Similarly, the preceding equivalence with - replaced with either ⋃ or ⋂, also holds.
Further,
σp(E1 - E2) = σp (E1) - E2
The preceding equivalence, with - replaced by ⋂ also holds, but does not hold if - replaced
by ⋃.
12. The projection operation distributes over union operation.
πL (E1 ⋂ E2) = (πL(E1)) ⋃ (πL(E2))
Example : Relation schema
instructor (ID , name , dept_name , salary)
teaches (ID , curse_id , sec_id , semester , year)
course (course_id , title , dept_name , credits)
Q. Find the names of all instructors in the music department together with the course title of all
the courses that the instructor teaches in 2009?
πname , title (σdept_name = 'Music'Ʌyear=2009(instructor |X| (teaches |X| πcourse_id , title (course))))
Now we can't apply the selection predicate directly to instructor relation, since the predicate
involves attibutes of both the instructor and teaches relation.
By applying rule 6 (a) to transform the join
instructor |X| (teaches |X| πcourse_id , title (course)) in to
(instructor |X| teaches) |X| πcourse_id , title (course)
We get
πname , title (σdept_name = 'Music'Ʌyear=2009((instructor |X| teaches) |X| πcourse_id , title (course))
Using rule 7 (a)
πname , title ((σdept_name = 'Music'Ʌyear=2009(instructor |X| teaches)) |X| πcourse_id , title (course))
Using rule 1, we get
πname , title ((σdept_name = 'Music' (σ year=2009(instructor |X| teaches)) |X| πcourse_id , title (course))
Using rule 7(b), we get
πname , title ((σdept_name = 'Music' (instructor) |X| σyear=2009(teaches)) |X| πcourse_id , title (course))
T1 ∞ T2 ∞ T3 ∞ T4∞ T5 ∞ T6
For above query we can have any order of evaluation. We can start taking any two tables
in any order and start evaluating the query. Ideally, we can have join combinations in
(2(n-1))! / (n-1)! ways. For example, suppose we have 5 tables involved in join, then we
can have 8! / 4! = 1680 combinations. But when query optimizer runs, it does not
evaluate in all these ways always. It uses dynamic programming where it generates the
costs for join orders of any combination of tables. It is calculated and generated only
once. This least cost for all the table combination is then stored in the database and is
used for future use. i.e.; say we have a set of tables, T = { T1 , T2 , T3 .. Tn}, then it
generates least cost combination for all the tables and stores it.
Dynamic Programming
As we learnt above, the least cost for the joins of any combination of table is generated
here. These values are stored in the database and when those tables are used in the query,
this combination is selected for evaluating the query.
While generating the cost, it follows below steps :
Suppose we have set of tables, T = {T1 , T2 , T3 .. Tn}, in a DB. It picks the first table,
and computes cost for joining with rest of the tables in set T. It calculates cost for each of
the tables and then chooses the best cost. It continues doing the same with rest of the
tables in set T. It will generate 2n – 1 cases and it selects the lowest cost and stores it.
When a query uses those tables, it checks for the costs here and that combination is used
to evaluate the query. This is called dynamic programming.
In this method, time required to find optimized query is in the order of 3n, where n is the
number of tables. Suppose we have 5 tables, then time required in 35 = 243, which is
lesser than finding all the combination of tables and then deciding the best combination
(1680). Also, the space required for computing and storing the cost is also less and is in
the order of 2n. In above example, it is 25 = 32.
Here instead of calculating the best join cost for set of tables, best join cost for joining
with each table is calculated. In this method, time required to find optimized query is in
the order of n2n, where n is the number of tables. Suppose we have 5 tables, then time
required in 5*25 =160, which is lesser than dynamic programming. Also, the space
required for computing storing the cost is also less and is in the order of 2n. In above
example, it is 25 = 32, same as dynamic programming.
(T1 ∞T2)∞ T3 ∞… ∞ Tn
This method uses hash join or merge join method to calculate the cost. Hash Join will
simply join the tables. We get sorted output in merge join method, but it is costlier than
hash join. Even though merge join is costlier at this stage, when it moves to join with
third table, the join will have less effort to sort the tables. This is because first table is the
sorted result of first two tables. Hence it will reduce the total cost of the query.
But the number of tables involved in the join would be relatively less and this cost/space
difference will be hardly noticeable.
All these cost based optimizations are expensive and are suitable for large number of
data. There is another method of optimization called heuristic optimization, which is
better compared to cost based optimization.
Suppose we have a query to retrieve the students with age 18 and studying in class
DESIGN_01. We can get all the student details from STUDENT table, and class details
from CLASS table. We can write this query in two different ways.
Here both the queries will return same result. But when we observe them closely we can
see that first query will join the two tables first and then applies the filters. That means, it
traverses whole table to join, hence the number of records involved is more. But he
second query, applies the filters on each table first. This reduces the number of records on
each table (in class table, the number of record reduces to one in this case!). Then it joins
these intermediary tables. Hence the cost in this case is comparatively less.
Instead of writing query the optimizer creates relational algebra and tree for above case.
σAge = 18 Ʌ CLASS_NAME = 'DESIGN_01' (STUDENT |X|CLASS_ID CLASS) Not so efficient
Here again, both the queries look alike, results alike. But when we compare the number
of records and attributes involved at each stage, second query uses less records and hence
more efficient.
o Next step is to perform most restrictive joins and selection operations. When we
say most restrictive joins and selection means, select those set of tables and views
which will result in comparatively less number of records. Any query will have
better performance when tables with few records are joined. Hence throughout
heuristic method of optimization, the rules are formed to get less number of
records at each stage, so that query performance is better. So is the case here too.
Suppose we have STUDENT, CLASS and TEACHER tables. Any student can attend
only one class in an academic year and only one teacher takes a class. But a class can
have more than 50 students. Now we have to retrieve STUDENT_NAME, ADDRESS,
AGE, CLASS_NAME and TEACHER_NAME of each student in a school.
In the first query, it tries to select the records of students from each class. This will result
in a very huge intermediary table. This table is then joined with another small table.
Hence the traversing of number of records is also more. But in the second query, CLASS
and TEACHER are joined first, which has one to one relation here. Hence the number of
resulting record is STUDENT table give the final result. Hence this second method is
more efficient.
o Sometimes we can combine above heuristic steps with cost based optimization
technique to get better results.
All these methods need not be always true. It also depends on the table size, column size,
type of selection, projection, join sort, constraints, indexes, statistics etc. Above
optimization describes the best way of optimizing the queries.
Query Decomposition
Process of minimizing the resource usage.
Aims of query decomposition
To transform a high level query in to a relational algebra query
To check the query is syntactically and semantically correct.
It is efficient way to retrieve data from database.
Example : Select * From staff as s , branch as b
Where [Link] = [Link] And
([Link]='Manager' And
[Link] ='London')
3 equivalent Relational Algebra
σ(position ='Manager' Ʌ [Link] = [Link] Ʌ [Link] ='London')(staff |X| branch)
Let we have 1000 records in staff & 50 records in branch. This query calculates the
Cartesian product of staff and branch, (100 + 50) disk accesses to read and creates
relation with (1000 * 50) tuples. We then have to read each of these tuples again to test
them against the selection predicates so it gives total cost of
(1000 + 50) + 2 * (1000 * 50) = 101050 disk access.
σ(position ='Manager') Ʌ ([Link] ='London')(staff |X| [Link] = [Link] branch)
2*1000 + (1000+50) = 3050 disk access
Stages
1. Analysis
2. Normalization
3. Semantic Analysis
4. Simplification or redundancy eliminator
5. Query restructuring
Analysis
Query is syntactically analyzed
verifies that the relation and attributes specified in the query are defined in the system
catalog.
verifies that any operation applied to database objects are appropriate for the object type.
Example : Select staffNumber
From staff
Where position > 10 ;
This query would be rejected on 2 grounds.
o In select list the attributes staffNumber is not defended for staff relation (should
be staffNo)
o In where clause comparison '>10' is incompatible with the datatype position
which is a variable character string.
After completion of this stage, high level query has been transformed to relational algebra.
Query Tree
Semantic Analysis
Rejects normalized query that are incorrectly formulated of contradictory.
Example : the predicate (position ='manager' Ʌ position = 'assistant') or staff relation is
contracting because a person can't be both manager and assistant.
Elimination of redundancy
Simplifying the qualification of user query to eliminate redundancy. Transform query to a
semantically equivalent but more easily and efficiently computed form. Queries on relation that
satisfy certain integrity and security constraints(access restriction).
o Before elimination of redundancy
Select position From staff as s, branch as b
Where (not ([Link]='manager')
AND ([Link] ='manager' OR [Link] ='assistant')AND
NOT([Link] ='assistant'))
OR([Link]=[Link] AND [Link] ='ABC')
o After elimination of redundancy
Select [Link] From staff as s , branch as b Where [Link] =[Link] AND [Link]='ABC'
Query Restructuring
It is the final stage where query is restructured to provide a more efficient implementation.
o Code Optimization
It includes improving the code so that not many loops are involved and the code is
executed outside the loop wherever possible
o Configuration Optimization
Configuration tuning includes improving the performance of the application finding the
best configuration for complex applications like Big Data.
o Caching Strategy
It is used to remove the performance bottleneck. It improves performance by retaining
frequently used information in high-speed memory, reducing access time and avoiding
repeated computation.
o Load Balancing
This arrangement results in the utilization of systems equally for addressing those many
service requests, resulting in proper utilization of resources without any system remaining
idle.
Our Approach
Indentify the Problem Component
This stage includes understanding the nature of the problem. In-depth analysis and system audits
are conducted to identify and the problem and performance obstacle. A detailed report with
current system health, insights and recommendations are mentioned.
Performance Goals
Thorough System