0% found this document useful (0 votes)
7 views

Module - 4

dbms

Uploaded by

suresh m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module - 4

dbms

Uploaded by

suresh m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

DBMS

DATA BASE MANAGEMENT SYSTYEMS

Module -- 4
Query Processing and
Query Optimization

Contents to be covered:
Steps in Query Processing,
Transforming SQL queries to Relational Algebra,
Heuristic Query Optimization
Query Optimization
• Query Optimization in DBMS is the process of
selecting the most efficient way to execute a
SQL statement, so that the correct rows are
returned.
• Because SQL is a nonprocedural language, the
optimizer can merge, restructure, and process
data in any sequence.
• Another important role of the optimizer is to produce an
“Execution plan” that is efficient.
Query Processing
• It refers to the range of activities
involved in extracting data from a
database.
• Query Processing is a translation of
“high-level queries” into “low-
level expression”.
• It is a step wise process.
• It can be used at the physical level of
the file system.
• It requires the basic concepts of
The basic steps involved in processing a
query are

1. Parsing and translation.


2. Optimization.
3. Evaluation.
Scanning , Parsing , Validating
• Scanner: The scanner identifies the language tokens such as
SQL Keywords, attribute names, and relation names in the text
of the query.

• Parser: The parser checks the query syntax to determine


whether it is formulated according to the syntax rules of the
query language.

• Validation: The query must be validated by checking that all


attributes and relation names are valid and semantically
meaningful names in the schema of the particular database
being queried.
Definitions
• Query Processing: The process by which the
query results are retrieved from a high-level query
such as SQL.

• Query Optimization: The process of choosing a


suitable execution strategy for retrieving results of
query from database files for processing a query is
known as Query Optimization.
Checks the syntax and It converts query into
It is in high level verify the relation. relational algebra
language query expression Best
query
selected
by
optimizer
Input from the
user as a query

It is the form
Low-level of query tree.
language query
1.Best evaluation
of query.
2. Consists of
dbms catalog.
Steps In Processing
High-Level Query
S. No. Category Selection Projection
The selection operation is The Project operation is also
1. Other Names also known as horizontal known as vertical
partitioning. partitioning.

It is used to choose the


subset of tuples from the It is used to select certain
2. Use relation that satisfies the required attributes, while
given condition mentioned discarding other attributes.
in the syntax of selection.

It partitions the table It partitions the table


3. Partitioning
horizontally. vertically.

The selection operation is The projection operation is


performed before projection performed after selection (if
4. Which used first
(if they are to be used they are to be used
together). together).

Select operator is used in Project operator is used in


5. Operator Used
Selection Operation. Projection Operation.

Select operator is denoted Project operator is denoted


6. Operator Symbol
by Sigma symbol. by Pi symbol.
Projection is not
7. Commutative Selection is commutative.
commutative.

Select is used to select all Project is used to select


8. Column Selection
columns of a specific tuple. specific columns.

9. SQL Statements used SELECT, FROM, WHERE SELECT, FROM


Example
Evaluation plan
Query Tree:- It can be used to represent relational algebraic expression. It
is the form of
1.Tree data structure.
2.Input as leaf nodes.
3.Opeartors as internal nodes

R.A Expr.
converted
into query
tree
Two main Techniques for Query
Optimization
 Heuristic Rules
Rules for ordering the operations in
query optimization.
 Systematical estimation
It estimates cost of different execution
strategies and chooses the execution plan
with lowest execution cost
QUERY DATA STRUCTURE
• Before optimizing the query it is represented in an internal or
intermediate form.

It is created using two data structures

• Query tree: A tree data structure that corresponds to a


relational algebra expression. It represents the input relations
of the query as leaf nodes of the tree, and represents the
relational algebra operations as internal nodes.

• Query graph: A graph data structure that corresponds to a


relational calculus expression. It does not indicate an order on
which operations to perform first. There is only a single graph
corresponding to each query.
QUERY PROCESSING

• Query Optimization: The process of choosing a suitable


execution strategy for processing a query. This module has the
task of producing an execution plan.

• Query Code Generator: It generates the code to execute the


plan.

• Runtime Database Processor: It has the task of running the


query code whether in compiled or interpreted mode. If a
runtime error results an error message is generated by the
runtime database processor.
Translating SQL Queries into
Relational Algebra
• Query block: The basic unit that can be translated
into the algebraic operators and optimized.
• A query block contains a single SELECT-FROM-WHERE
expression, as well as GROUP BY and HAVING clause
if these are part of the block.
• Nested queries within a query are identified as
separate query blocks.

• Aggregate operators in SQL must be included in the


extended algebra.
Translating SQL Queries
into Relational Algebra
SAMPLE RELATIONAL ALGEBRA QUERIES
Algorithms for SELECT and JOIN
Operations

Implementing the SELECT Operation:


Examples:
(OP1): s SSN='123456789' (EMPLOYEE)
(OP2): s DNUMBER>5 (DEPARTMENT)
(OP3): s DNO=5 (EMPLOYEE)
(OP4): s DNO=5 AND SALARY>30000 AND GENDER=F (EMPLOYEE)
(OP5): s ESSN=123456789 AND PNO=10 (WORKS_ON)
Algorithms for SELECT and JOIN Operations

Implementing the SELECT Operation (cont.):


Search Methods for Simple Selection:
S1.Linear search (brute force): Retrieve every record in the file,
and test whether its attribute values satisfy the selection condition.
S2.Binary search: If the selection condition involves an equality
comparison on a key attribute on which the file is ordered, binary
search (which is more efficient than linear search) can be used.
(See OP1).
S3.Using a primary index or hash key to retrieve
a single record: If the selection condition involves an
equality comparison on a key attribute with a
primary index (or a hash key), use the primary index
(or the hash key) to retrieve the record.
Implementing the SELECT Operation (cont.):
Search Methods for Simple Selection:
S4.Using a primary index to retrieve multiple
records: If the comparison condition is >, ≥, <, or ≤
on a key field with a primary index, use the index to
find the record satisfying the corresponding equality
condition, then retrieve all subsequent records in
the (ordered) file.
S5.Using a clustering index to retrieve multiple
records: If the selection condition involves an
equality comparison on a non-key attribute with a
clustering index, use the clustering index to
retrieve all the records satisfying the selection
condition.
Implementing the SELECT Operation (cont.):
Search Methods for Simple Selection:
S6.Using a secondary (B+-tree) index: On an equality
comparison, this search method can be used to retrieve a single
record if the indexing field has unique values (is a key) or to
retrieve multiple records if the indexing field is not a key. In
addition, it can be used to retrieve records on conditions involving
>,>=, <, or <=. (FOR RANGE QUERIES)
Implementing the SELECT Operation (cont.):
Search Methods for Complex Selection:
S7.Conjunctive selection: If an attribute involved in any single
simple condition in the conjunctive condition has an access path
that permits the use of one of the methods S2 to S6, use that
condition to retrieve the records and then check whether each
retrieved record satisfies the remaining simple conditions in the
conjunctive condition.
S8.Conjunctive selection using a composite index: If two or
more attributes are involved in equality conditions in the
conjunctive condition and a composite index (or hash structure)
exists on the combined field, we can use the index directly.
Implementing the SELECT Operation (cont.):
Search Methods for Complex Selection:
S9.Conjunctive selection by intersection of record pointers:
This method is possible if secondary indexes are available on all
(or some of) the fields involved in equality comparison conditions
in the conjunctive condition and if the indexes include record
pointers (rather than block pointers). Each index can be used to
retrieve the record pointers that satisfy the individual condition.
The intersection of these sets of record pointers gives the record
pointers that satisfy the conjunctive condition, which are then
used to retrieve those records directly. If only some of the
conditions have secondary indexes, each retrieved record is
further tested to determine whether it satisfies the remaining
conditions.
Implementing the SELECT Operation (cont.):
Whenever a single condition specifies the selection, we can
only check whether an access path exists on the attribute
involved in that condition. If an access path exists, the method
corresponding to that access path is used; otherwise, the “brute
force” linear search approach of method S1 is used. (See
OP1, OP2 and OP3)
For conjunctive selection conditions, whenever
more than one of the attributes involved in the
conditions have an access path, query
optimization should be done to choose the access
path that retrieves the fewest records in the most
efficient way .
Disjunctive selection conditions
Implementing the JOIN Operation:
Join (EQUIJOIN, NATURAL JOIN)
two–way join: a join on two files
e.g. R A=B S
multi-way joins: joins involving more than two files.
e.g. R A=B S C=D T
Examples
(OP6): EMPLOYEE DNO=DNUMBER DEPARTMENT
(OP7): DEPARTMENT MGRSSN=SSN EMPLOYEE
Implementing the JOIN Operation (cont.):
Methods for implementing joins:
J1Nested-loop join (brute force): For each record t in R (outer
loop), retrieve every record s from S (inner loop) and test
whether the two records satisfy the join condition t[A] = s[B].
J2.Single-loop join (Using an access structure to retrieve the
matching records): If an index (or hash key) exists for one of
the two join attributes — say, B of S — retrieve each record t
in R, one at a time, and then use the access structure to retrieve
directly all matching records s from S that satisfy s[B] = t[A].
Implementing the JOIN Operation (cont.):
Methods for implementing joins:
J3.Sort-merge join: If the records of R and S are physically
sorted (ordered) by value of the join attributes A and B,
respectively, we can implement the join in the most efficient
way possible. Both files are scanned in order of the join
attributes, matching the records that have the same values for
A and B. In this method, the records of each file are scanned
only once each for matching with the other file—unless both
A and B are non-key attributes, in which case the method
needs to be modified slightly
Implementing the JOIN Operation (cont.):
Methods for implementing joins:
J4.Hash-join: The records of files R and S are both hashed to
the same hash file, using the same hashing function on the join
attributes A of R and B of S as hash keys. A single pass through
the file with fewer records (say, R) hashes its records to the hash
file buckets. A single pass through the other file (S) then hashes
each of its records to the appropriate bucket, where the record is
combined with all matching records from R.
General Transformation Rules for Relational
Algebra Operations:

1. Cascade of s:

A conjunctive selection condition can be broken


up into a cascade (sequence) of individual s
operations:

s c1 AND c2 AND ... AND cn (R) = sc1 (sc2 (...(scn(R))...) )


General Transformation Rules for Relational
Algebra Operations:

2. Commutativity of s:

The s operation is commutative:

sc1 (sc2(R)) = sc2 (sc1(R))


General Transformation Rules for Relational
Algebra Operations:

3. Cascade of p:
In a cascade (sequence) of p operations, all but
the last one can be ignored:
pList1 (pList2 (...(pListn(R))...) ) = pList1, List2,…, Listn(R)
General Transformation Rules for Relational
Algebra Operations:

4. Commuting s with p:

If the selection condition c involves only the attributes


A1, ..., An in the projection list, the two operations
can be commuted:
pA1, A2, ..., An (sc (R)) = sc (pA1, A2, ..., An (R))
Equivalence Rules
θ, θ1, θ2 … : Used for denoting the predicates.

L1, L2, L3 … : Used for denoting the list of attributes.

E, E1, E2 …. : Represents the relational-algebra expressions.

Let's discuss a number of equivalence rules:

Rule 1: Cascade of σ

This rule states the deconstruction of the conjunctive selection operations into a sequence of
individual selections. Such a transformation is known as a cascade of σ.

σθ1 ᴧ θ 2 (E) = σθ1 (σθ2 (E))

Rule 2: Commutative Rule

a) This rule states that selections operations are commutative.

σθ1 (σθ2 (E)) = σ θ2 (σθ1 (E))

b) Theta Join (θ) is commutative.

E1 ⋈ θ E 2 = E 2 ⋈ θ E 1 (θ is in subscript with the join symbol)

However, in the case of theta join, the equivalence rule does not work if the order of attributes is
considered. Natural join is a special case of Theta join, and natural join is also commutative.
However, in the case of theta join, the equivalence rule does not work if the order of attributes is considered.
Natural join is a special case of Theta join, and natural join is also commutative.

Rule 3: Cascade of ∏

This rule states that we only need the final operations in the sequence of the projection operations, and other
operations are omitted. Such a transformation is referred to as a cascade of ∏.

∏L1 (∏L2 (. . . (∏Ln (E)) . . . )) = ∏L1 (E)

Rule 4: We can combine the selections with Cartesian products as well as theta joins

Rule 4: We can combine the selections with Cartesian products as well as theta joins

σθ (E1 x E2) = E1θ ⋈ E2


σθ1 (E1 ⋈ θ2 E2) = E1 ⋈ θ1ᴧθ2 E2
Rule 5: Associative Rule

a) This rule states that natural join operations are associative.

(E1 ⋈ E2) ⋈ E3 = E1 ⋈ (E2 ⋈ E3)

b) Theta joins are associative for the following expression:

(E1 ⋈ θ1 E2) ⋈ θ2ᴧθ3 E3 = E1 ⋈ θ1ᴧθ3 (E2 ⋈ θ2 E3)

In the theta associativity, θ2 involves the attributes from E2 and E3 only. There may be chances of empty
conditions, and thereby it concludes that Cartesian Product is also associative.
Rule 6: Distribution of the Selection operation over the Theta join.

Under two following conditions, the selection operation gets distributed over the theta-join operation:

a) When all attributes in the selection condition θ0 include only attributes of one of the expressions which
are being joined.

σθ0 (E1 ⋈ θ E2) = (σθ0 (E1)) ⋈ θ E2

b) When the selection condition θ1 involves the attributes of E1 only, and θ2 includes the attributes of E2
only.

σθ1ꓥ θ2 (E1 ⋈ θ E2) = (σθ1 (E1)) ⋈ θ ((σθ2 (E2))

Rule 7: Distribution of the projection operation over the theta join.

Under two following conditions, the selection operation gets distributed over the theta-join operation:

a) Assume that the join condition θ includes only in L1 υ L2 attributes of E1 and E2 Then, we get the
following expression:

∏L1υL2 (E1 ⋈ θ E2) = (∏L1 (E1)) ⋈ θ (∏L2 (E2))

b) Assume a join as E1 ⋈ E2. Both expressions E1 and E2 have sets of attributes as L1 and L2. Assume
two attributes L3 and L4 where L3 be attributes of the expression E1, involved in the θ join condition but not
in L1 υ L2 Similarly, an L4 be attributes of the expression E2 involved only in the θ join condition and not in
L1 υ L2 attributes. Thus, we get the following expression:

∏L1υL2 (E1 ⋈ θ E2) = ∏L1υL2 ((∏L1υL3 (E1)) ⋈ θ ((∏L2υL4 (E2)))


Rule 8: The union and intersection set operations are commutative.

E1 υ E2 = E2 υ E1

E1 ꓵ E2 = E2 ꓵ E1

However, set difference operations are not commutative.

Rule 9: The union and intersection set operations are associative.

(E1 υ E2) υ E3 = E1 υ (E2 υ E3)

(E1 ꓵ E2) ꓵ E3 = E1 ꓵ (E2 ꓵ E3)

Rule 10: Distribution of selection operation on the intersection, union, and set difference operations.

The below expression shows the distribution performed over the set difference operation.

σp (E1 − E2) = σp(E1) − σp(E2)

We can similarly distribute the selection operation on υ and ꓵ by replacing with -. Further, we get:

σp (E1 − E2) = σp(E1) −E2

Rule 11: Distribution of the projection operation over the union operation.

This rule states that we can distribute the projection operation on the union operation for the given
expressions.

∏L (E1 υ E2) = (∏L (E1)) υ (∏L (E2))

Apart from these discussed equivalence rules, there are various other equivalence rules also.
Query Graph
• Nodes represents Relations.
• Ovals represents constant nodes.
• Edges represents Join & Selection conditions.
• Attributes to be retrieved from relations represented
in square brackets.
• Drawback :- Does not indicate an order on which
operations are performed.
There is only a single graph corresponding to each query.
Process for heuristics optimization

1. The parser of a high-level query generates an initial


internal representation;
2. Apply heuristics rules to optimize the internal
representation.
3. A query execution plan is generated to execute groups
of operations based on the access paths available on
the files involved in the query.

• The main heuristic is to apply first the operations


that reduce the size of intermediate results.
E.g., Apply SELECT and PROJECT operations
before applying the JOIN or other binary operations.
Heuristic Query Tree Optimization
Steps in converting a query tree during heuristic optimization:

• Initial (canonical) query tree for SQL query.


• Moving SELECT operations down the query tree.
• Applying the more restrictive SELECT operation first.
• Replacing CARTESIAN PRODUCT and SELECT with
JOIN operations.
• Moving PROJECT operations down the query tree.
For Example :

SELECT LNAME
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE PNAME= ‘AQUARIUS’ AND
PNUMBER=PNO AND
ESSN=SSN AND
BDATE > ‘1957-12-31’
a. Initial (canonical) query tree for SQL query.

b. Moving SELECT operations down the query tree.


c. Applying the more restrictive SELECT operation first.

d. Replacing CARTESIAN PRODUCT and SELECT with JOIN operations.


e. Moving PROJECT operations down the query tree.
Query Tree Optimization
• Summary:- The main idea behind this is to
reduce intermediate results. This includes
performing a SELECT operation to reduce the
number of tuples & PROJECT operation to
reduce the number of attributes.
• Example:
For every project located in ‘Stafford’, retrieve the project
number, the controlling department number and the
department manager’s last name, address and birthdate.

Relation algebra:
PNUMBER, DNUM, LNAME, ADDRESS, BDATE (((PLOCATION=‘STAFFORD’(PROJECT))
DNUM=DNUMBER (DEPARTMENT)) MGRSSN=SSN (EMPLOYEE))

SQL query:
Q2: SELECT P.NUMBER,P.DNUM,E.LNAME, E.ADDRESS, E.BDATE
FROM PROJECT AS P,DEPARTMENT AS D, EMPLOYEE AS
E
WHERE P.DNUM=D.DNUMBER AND D.MGRSSN=E.SSN AND
P.PLOCATION=‘STAFFORD’;
The same query could correspond to many different relational
algebra expressions — and hence many different query
trees.

You might also like