0% found this document useful (0 votes)
15 views47 pages

Chapter 2

Chapter Two discusses query processing and optimization in relational databases, covering topics such as relational algebra, SQL query translation, and various algorithms for executing query operations like SELECT and JOIN. It outlines the basic steps in query processing, including parsing, optimization, and evaluation, and introduces concepts like query trees and graphs. Additionally, it details different types of JOIN operations and algorithms for external sorting, emphasizing the importance of efficient query execution strategies.

Uploaded by

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

Chapter 2

Chapter Two discusses query processing and optimization in relational databases, covering topics such as relational algebra, SQL query translation, and various algorithms for executing query operations like SELECT and JOIN. It outlines the basic steps in query processing, including parsing, optimization, and evaluation, and introduces concepts like query trees and graphs. Additionally, it details different types of JOIN operations and algorithms for external sorting, emphasizing the importance of efficient query execution strategies.

Uploaded by

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

Chapter Two

Query Processing and


Optimization
2021

By Tadesse B.
Chapter Outline

Overview of relational algebra


Introduction to Query Processing
Translating SQL Queries into Relational Algebra
Algorithms for External Sorting
Algorithms for SELECT and JOIN Operations
Algorithms for PROJECT and SET Operations
Implementing Aggregate Operations and Outer
Joins
Using Heuristics in Query Optimization
Using Selectivity and Cost Estimates in Query
Optimization
Semantic Query Optimization
05/14/25 By Tadesse B. Slide 15- 2
Relational Algebra

A sequence of relational algebra operations forms a relational


algebra expression.
 It provides a formal foundation for relational model operations.
 It is used as a basis for implementing and optimizing queries in
relational database management system.
 Its operations can be divided into two:
1.Include set operations, UNION,INTERSECTION, SET
DIFFERENCE, and CARTESIAN PRODUCT.
• Developed for relational database specifically. (SELECT,
PROJECT, and JOIN)
05/14/25 By Tadesse B. Slide 15- 3
SELECT operation
• A SELECT operation can be visualized as a horizontal partitioning
of the relation into two sets of tuples.
• Example, σ Dno=4 (Employee) – to select employees whose
department is 4

• The general form is σ<Selection condition>(R)


•σ - sigma is used to denote the select operator, and the selection
operation is Boolean expression.
• Select operation is commutative

•σ<cond1>( σ<cond2>(R)) = σ<cond2>( σ<cond1>(R))


05/14/25 By Tadesse B. Slide 15- 4
Project operation

• Allows users of the relational model to retrieve attributes specific


data from a table
• Example, to list each employee’s first and last name and salary,
we can use project operation
• The general form of the project operation is π<Attribute list> (R)

• πLname,Fname,Salary (Employee)
• Where π (Pi) is used to represent the project operation.
• If the attribute list includes only nonkey attributes or R, duplicate
tuples are likely to occur.
• But project operation removes any duplicate tuples.
• Project operation is not commutative.
05/14/25 By Tadesse B. Slide 15- 5
JOIN

• The JOIN operation denoted by , is used to combine related tuples


from two relations into a single tuple.
• It allows as processing relationships among relations.
• example, to get the names of the managers of each department (i.e.
to get the managers name, we need to combine each department
tuple with the employee tuple whose SSN value matches the
mgrSSN value in the department tuple.)

• general form R <join condition>S - it can be combined with other


operations

• πDname,Lname,Fname(R<mgrSSN=SSN>S (Employee))
05/14/25 By Tadesse B. Slide 15- 6
Types of join operations

INNER JOIN
•Used to combine data from multiple relations so that related information can be
presented in a single table, only matching records are kept in the result.
LEFT OUTER JOIN
All rows from left side table are display
Matching value rows from right side table
Null values in place of non matching rows in other table

05/14/25 By Tadesse B. Slide 15- 7


Types of join operations

RIGHT OUTER JOIN


All rows from right side table are display
Matching value rows from left side table
Null values in place of non matching rows in other table
FULL OUTER JOIN
Union operation of an inner, left and right join
It returns all matched records
It returns all rows from right side table
It returns all rows from left side table

05/14/25 By Tadesse B. Slide 15- 8


Introduction

• What is Query?
• to ask questions, especially in order to check if something is
true(dictionary definition)
• Retrievals of records(db definition)
• Example SELECT LName, Fname FROM
EMPLOYEE
WHERE Salary > 4500
• What is Query Processing?
• The range of activities involved in extracting data from a
database.
• Includes: translation of queries, query-optimizing
transformations, evaluation of queries.
05/14/25 By Tadesse B. Slide 15- 9
Basic Steps in Query
Processing
1. Parsing and translation
2. Optimization
3. Evaluation

Parser & Relational Algebra


Query Expression
Translator

Optimizer

Query
Evaluation Engine Execution Plan
Output

Statistics
Data
About Data

05/14/25 By Tadesse B. Slide 15- 10


Basic Steps in Query
Processing(cont..)
Step 1. Parsing and translation
• System checks the syntax of the query.
• Creates a parse-tree representation of the query.
• Translates the query into a relational-algebra expression.
• Parser checks syntax, verifies relations
Step 2:Optimization
• Optimization – finding the cheapest evaluation plan for a
query.
• Each relational-algebra operation can be executed by one
of several different algorithms.
• A query optimizer must know the cost of each operation.
Step 3:Evaluation
• The query-execution engine takes a query-evaluation plan,
executes that plan, and returns the answers to the query.
05/14/25 By Tadesse B. Slide 15- 11
Introduction to Query
Processing
• Query optimization:
• The process of choosing a suitable execution strategy for
processing a query.
• Two internal representations of a query:
• Query Tree
• Query Graph

05/14/25 By Tadesse B. Slide 15- 12


Introduction to Query Processing
Cont. …

• 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.
• An execution of the query tree consists of executing an internal node
operation whenever its operands are available and then replacing that
internal node by the relation that results from executing the operation.
• 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.

05/14/25 By Tadesse B. Slide 15- 13


Introduction to Query Processing
Cont. …

05/14/25 By Tadesse B. Slide 15- 14


Introduction to Query Processing
Cont. …

05/14/25 By Tadesse B. Slide 15- 15


Translating SQL queries to
Relational Algebra
• Relational data model is based on concepts derived from the
mathematical theory of sets.
• Set theory defines a table as a relation.
• Operations:
• select: σ
• project: π
• union: 
• difference: -
• product: x
• join

05/14/25 By Tadesse B. Slide 15- 16


Introduction to Query Processing
Cont.…

• Since relational algebra is somewhat low level than SQL queries


it will give us a mathematical foundation for analyzing and
optimizing SQL queries.

1.For example, translate the following query to relational algebra


notation that can retrieve the name and address of all employees
who work for the research department.
• SELECT Fname,Lname,Address
• FROM Employee,Department
• WHERE DName=’research’ AND Dnumber=Dno
05/14/25 By Tadesse B. Slide 15- 17
Introduction to Query
Processing Cont.…
• Now to translate this SQL query to relational algebra we can
use temporary variables that can store the intermediate results.
• Research_Dept σDname=‘research’(Department)
• Research_Emps  (Research_Dept
<Dnumber=Dno>Employee)

• Result πFname,Lname,Address (Research_Emps)

05/14/25 By Tadesse B. Slide 15- 18


Introduction to Query
Processing Cont.…
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE SALARY > ( SELECT MAX (SALARY)
FROM EMPLOYEE
WHERE DNO = 5);

SELECT LNAME, FNAME SELECT MAX (SALARY)


FROM EMPLOYEE FROM EMPLOYEE
WHERE SALARY > C WHERE DNO = 5

πLNAME, FNAME (σSALARY>C(EMPLOYEE)) ℱMAX SALARY (σDNO=5 (EMPLOYEE))

05/14/25 By Tadesse B. Slide 15- 19


Basic Algorithms for Executing
Query Operations
• There are several algorithms are used during query processing.
• Sorting(External Sorting)
• One of the primary algorithms used in query processing.
• For Example ,during order by
Join, Union, Intersection, Distinct operations
• External sorting refers to sorting algorithms that are suitable
for large files of records stored on disk that do not fit entirely
in main memory, such as most database files.
• Sorting large files of records that do not fit entirely in main
memory

05/14/25 By Tadesse B. Slide 15- 20


Basic Algorithms for Executing
Query Operations cont. ...
 Sort-merge strategy
(a) Sort phase

1.Portions of the file that can fit in the available buffer space
are read into the main memory

2.sorted using an internal sorting algorithm, and written back


to disk as temporary sorted sub files (or runs).
(b) Merge phase
The sorted runs are merged during one or more passes.

05/14/25 By Tadesse B. Slide 15- 21


Algorithms for External
Sorting
• External sorting:
• Refers to sorting algorithms that are suitable for large files of
records stored on disk that do not fit entirely in main memory,
such as most database files.
• Sort-Merge strategy:
• Starts by sorting small subfiles (runs) of the main file and
then merges the sorted runs, creating larger sorted subfiles
that are merged in turn.

05/14/25 By Tadesse B. Slide 15- 22


Basic Algorithms for Executing Query
Operations (cont..)
Internal Sorting

05/14/25 By Tadesse B. Slide 15- 23


Basic Algorithms for Executing Query
Operations (cont..)
External Sorting

05/14/25 By Tadesse B. Slide 15- 24


Example: External Sorting Using
Sort-Merge
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 SEX=F(EMPLOYEE)
• (OP5): s ESSN=123456789 AND PNO=10(WORKS_ON)

05/14/25 By Tadesse B. Slide 15- 26


Algorithms for SELECT and JOIN
Operations Cont. …

• Search Methods for Simple Selection:


• S1 Linear search:
• 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.
05/14/25 By Tadesse B. Slide 15- 27
Algorithms for SELECT and JOIN
Operations 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.

05/14/25 By Tadesse B. Slide 15- 28


Algorithms for SELECT and JOIN
Operations Cont. …

• 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)

05/14/25 By Tadesse B. Slide 15- 29


Algorithms for SELECT and JOIN
Operations Cont. …

• Search Methods for Simple 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.

05/14/25 By Tadesse B. Slide 15- 30


Algorithms for SELECT and JOIN
Operations Cont. …

• 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

05/14/25 By Tadesse B. Slide 15- 31


Algorithms for SELECT and JOIN
Operations Cont. …
• Implementing the JOIN Operation (contd.):
• J1 Nested-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].

05/14/25 By Tadesse B. Slide 15- 32


Algorithms for SELECT and JOIN
Operations Cont. …
• Implementing the JOIN Operation (contd.):
• 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.

05/14/25 By Tadesse B. Slide 15- 33


Algorithms for SELECT and JOIN
Operations Cont. …
• Implementing the JOIN Operation (contd.):
• 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.

05/14/25 By Tadesse B. Slide 15- 34


Implementing Aggregate
Operations and Outer Joins
• Aggregate operators:
• MIN, MAX, SUM, COUNT and AVG
• Options to implement aggregate operators:
• Table Scan
• Index
• Example
• SELECT MAX (SALARY) FROM EMPLOYEE;
• If an (ascending) index on SALARY exists for the employee relation,
then the optimizer could decide on traversing the index for the largest
value, which would entail following the right most pointer in each
index node from the root to a leaf.

05/14/25 By Tadesse B. Slide 15- 35


Cont.…
• Implementing Aggregate Operations (contd.):
• SUM, COUNT and AVG
• For a dense index (each record has one index entry):
• Apply the associated computation to the values in the index.
• For a non-dense index:
• Actual number of records associated with each index entry must
be accounted for
• With GROUP BY: the aggregate operator must be applied
separately to each group of tuples.
• Use sorting or hashing on the group attributes to partition the file
into the appropriate groups;
• Computes the aggregate function for the tuples in each group.

05/14/25 By Tadesse B. Slide 15- 36


Using Heuristics in Query
Optimization
• 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.
05/14/25 By Tadesse B. Slide 15- 37
Cont. …

• Heuristic Optimization of Query Trees:


• The same query could correspond to many different relational
algebra expressions and hence many different query trees.
• The task of heuristic optimization of query trees is to find a final
query tree that is efficient to execute.
• Example:
Q: SELECT LNAME
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE PNAME = ‘AQUARIUS’ AND
PNMUBER=PNO AND ESSN=SSN AND BDATE >
‘1957-12-31’;

05/14/25 By Tadesse B. Slide 15- 38


Cont. …

Example:
Q: SELECT LNAME
FROM EMPLOYEE, WORKS_ON,
PROJECT
WHERE PNAME = ‘AQUARIUS’ AND
PNMUBER=PNO AND ESSN=SSN
AND BDATE > ‘1957-12-31’;
05/14/25 By Tadesse B. Slide 15- 39
Cont. …

05/14/25 By Tadesse B. Slide 15- 40


Cont. …

05/14/25 By Tadesse B. Slide 15- 41


Cont. …

05/14/25 By Tadesse B. Slide 15- 42


Cont.
Outline of a Heuristic Algebraic Optimization Algorithm:
1.Using rule 1, break up any select operations with conjunctive conditions into a
cascade of select operations.
2.Using rules 2, 4, 6, and 10 concerning the commutativity of select with other
operations, move each select operation as far down the query tree as is permitted
by the attributes involved in the select condition.
3.Using rule 9 concerning associativity of binary operations, rearrange the leaf
nodes of the tree so that the leaf node relations with the most restrictive select
operations are executed first in the query tree representation.
4.Using Rule 12, combine a Cartesian product operation with a subsequent select
operation in the tree into a join operation.
5.Using rules 3, 4, 7, and 11 concerning the cascading of project and the
commuting of project with other operations, break down and move lists of
projection attributes down the tree as far as possible by creating new project
operations as needed.
6.Identify subtrees that represent groups of operations that can be executed by a
single algorithm.
05/14/25 By Tadesse B. Slide 15- 43
Summary of Heuristics for
Algebraic Optimization:
1. The main heuristic is to apply first the operations that reduce
the size of intermediate results.
2. Perform select operations as early as possible to reduce the
number of tuples and perform project operations as early as
possible to reduce the number of attributes. (This is done by
moving select and project operations as far down the tree as
possible.)
3. The select and join operations that are most restrictive should
be executed before other similar operations. (This is done by
reordering the leaf nodes of the tree among themselves and
adjusting the rest of the tree appropriately.)

05/14/25 By Tadesse B. Slide 15- 44


Typical stages in query
decomposition are
• Analysis: lexical and syntactical analysis of the query(correctness)
based on attributes, data type.. ,.
• Query tree will be built for the query containing leaf node for base
relations, one or many non-leaf nodes for relations produced by
relational algebra operations and root node for the result of the
query.
• Sequence of operation is from the leaves to the root.(SELECT *
FROM Catalog c ,Author a Where a.authorid = c.authorid AND
c.price>200 AND a.country= ‘ USA’ )
• Normalization: convert the query into a normalized form. The
predicate WHERE will be converted to Conjunctive (∨) or
Disjunctive (∧) Normal form.

05/14/25 By Tadesse B. 45
Typical stages in query
decomposition …
• Semantic Analysis:
• to reject normalized queries that are not correctly formulated or
contradictory. Incorrect if components do not contribute to generate
result.
• Contradictory if the predicate can not be satisfied by any tuple.
• for example,(gender=“m”  gender= “f”) since a given book can
only be classified in either of the category at a time
• Simplification:
Detect redundant qualifications, eliminate common sub-expressions,
and transform the query to a semantically equivalent but more
easily and effectively computed form.
For example, If a user don’t have the necessary access to all of the
objects of the query , it should be rejected.
05/14/25 By Tadesse B. 46
Semantic Query Optimization
• Uses constraints specified on the database schema in order to modify
one query into another query that is more efficient to execute.

Consider the following SQL query,


SELECT E.LNAME, M.LNAME
FROM EMPLOYEE E M
WHERE E.SUPERSSN=M.SSN AND
E.SALARY>M.SALARY
•Explanation:
• Suppose that we had a constraint on the database schema that stated
that no employee can earn more than his or her direct supervisor.
• If the semantic query optimizer checks for the existence of this
constraint, it need not execute the query at all because it knows that
the result of the query will be empty.
• Techniques known as theorem proving can be used for this purpose.
05/14/25 By Tadesse B. Slide 15- 47

You might also like