SlideShare a Scribd company logo
Chapter 15
Algorithms for Query Processing
and Optimization

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe
Chapter Outline (1)
0. Introduction to Query Processing
1. Translating SQL Queries into Relational Algebra
2. Algorithms for External Sorting
3. Algorithms for SELECT and JOIN Operations
4. Algorithms for PROJECT and SET Operations
5. Implementing Aggregate Operations and Outer Joins

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 2
0. Introduction to Query Processing (1)


Query processing:




Query optimization:




Is the list of activities that are perform to obtain the
required tuples that satisfy a given query.
The process of choosing a suitable execution
strategy for processing a query.

Two internal representations of a query:



Query Tree
Query Graph

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 3
Introduction to Query Processing (2)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 4
Introduction to Query Processing (2)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 5
1. Translating SQL Queries into Relational
Algebra






Parser & Translator:
 Syntax
 Schema element
 Converts the query into R.A expression.
Optimizer
 Find all equivalent R.A expressions
 Find the R.A expression with least cost
 Cost(CPU, Block access, time spent)
 Will create query evaluation plan which tell what R.A
and what algorithm is used.
Query evaluation plan:
 Evaluate the above plan and get the result
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 6
1. 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-FROMWHERE 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.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 7
Translating SQL Queries into Relational
Algebra
SELECT
FROM
WHERE

SELECT
FROM
WHERE

LNAME, FNAME
EMPLOYEE
SALARY > (
SELECT
FROM
WHERE

LNAME, FNAME
EMPLOYEE
SALARY > C

πLNAME, FNAME (σSALARY>C(EMPLOYEE))
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

SELECT
FROM
WHERE

MAX (SALARY)
EMPLOYEE
DNO = 5);

MAX (SALARY)
EMPLOYEE
DNO = 5

ℱMAX SALARY (σDNO=5 (EMPLOYEE))
Slide 15- 8
2. Algorithms for External Sorting (1)


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.
Sorting phase: nR = (b/nB)
Merging phase: dM = Min (nB-1, nR); nP = (logdM(nR))
nR: number of initial runs; b: number of file blocks;
nB: available buffer space; dM: degree of merging;
nP: number of passes.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 9
Algorithms for External Sorting (2)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 10
3. Algorithms for SELECT and JOIN
Operations (1)


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)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 11
Algorithms for SELECT and JOIN
Operations (2)



Implementing the SELECT Operation (contd.):
Search Methods for Simple Selection:


S1 Linear search (brute force):




S2 Binary search:




Retrieve every record in the file, and test whether its attribute
values satisfy the selection condition.
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.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 12
Algorithms for SELECT and JOIN
Operations (3)



Implementing the SELECT Operation (contd.):
Search Methods for Simple Selection:
 S4 Using a primary index to retrieve multiple records:




S5 Using a clustering 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.
If the selection condition involves an equality comparison on a nonkey attribute with a clustering index, use the clustering index to
retrieve all the records satisfying the selection condition.

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)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 13
Algorithms for SELECT and JOIN
Operations (4)



Implementing the SELECT Operation (contd.):
Search Methods for Simple Selection:


S7 Conjunctive selection using a individual index :




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. E.g index has been created on the composite key
(Essn, Pno) of the relational R( Works_on)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 14
Algorithms for SELECT and JOIN
Operations (5)



Implementing the SELECT Operation (contd.):
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.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 15
Algorithms for SELECT and JOIN
Operations (7)


Implementing the SELECT Operation (contd.):


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

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 16
Algorithms for SELECT and JOIN
Operations (8)


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

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 17
Algorithms for SELECT and JOIN
Operations (9)



Implementing the JOIN Operation (contd.):
Methods for implementing joins:


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].

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 18
Algorithms for SELECT and JOIN
Operations (10)



Implementing the JOIN Operation (contd.):
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.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 19
Algorithms for SELECT and JOIN
Operations (11)



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.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 20
Algorithms for SELECT and JOIN
Operations (14)



Implementing the JOIN Operation (contd.):
Factors affecting JOIN performance




Available buffer space
Join selection factor
Choice of inner VS outer relation

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 21
Algorithms for SELECT and JOIN
Operations (15)




Implementing the JOIN Operation (contd.):
Other types of JOIN algorithms
Partition hash join


Partitioning phase:


Each file (R and S) is first partitioned into M partitions using a
partitioning hash function on the join attributes:








R1 , R2 , R3 , ...... Rm and S1 , S2 , S3 , ...... Sm

Minimum number of in-memory buffers needed for the
partitioning phase: M+1.
A disk sub-file is created per partition to store the tuples
for that partition.

Joining or probing phase:



Involves M iterations, one per partitioned file.
Iteration i involves joining partitions Ri and Si.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 22
Algorithms for SELECT and JOIN
Operations (16)



Implementing the JOIN Operation (contd.):
Partitioned Hash Join Procedure:


Assume Ri is smaller than Si.
1. Copy records from Ri into memory buffers.
2. Read all blocks from Si, one at a time and each
record from Si is used to probe for a matching
record(s) from partition Si.
3. Write matching record from Ri after joining to the
record from Si into the result file.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 23
Algorithms for SELECT and JOIN
Operations (17)



Implementing the JOIN Operation (contd.):
Cost analysis of partition hash join:
1. Reading and writing each record from R and S during the
partitioning phase:
(bR + bS), (bR + bS)
2. Reading each record during the joining phase:
(bR + bS)
3. Writing the result of join:
bRES



Total Cost:


3* (bR + bS) + bRES

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 24
Algorithms for SELECT and JOIN
Operations (18)



Implementing the JOIN Operation (contd.):
Hybrid hash join:


Same as partitioned hash join except:




Partitioning phase:






Joining phase of one of the partitions is included during the
partitioning phase.
Allocate buffers for smaller relation- one block for each of the
M-1 partitions, remaining blocks to partition 1.
Repeat for the larger relation in the pass through S.)

Joining phase:


M-1 iterations are needed for the partitions R2 , R3 , R4 ,
......Rm and S2 , S3 , S4 , ......Sm. R1 and S1 are joined
during the partitioning of S1, and results of joining R1 and S1
are already written to the disk by the end of partitioning phase.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 25
4. Algorithms for PROJECT and SET
Operations (1)


Algorithm for PROJECT operations (Figure 15.3b)

 <attribute list>(R)

1. If <attribute list> has a key of relation R, extract all tuples
from R with only the values for the attributes in <attribute
list>.
2. If <attribute list> does NOT include a key of relation R,
duplicated tuples must be removed from the results.


Methods to remove duplicate tuples
1. Sorting
2. Hashing

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 26
Algorithms for PROJECT and SET
Operations (2)



Algorithm for SET operations
Set operations:






CARTESIAN PRODUCT of relations R and S include all
possible combinations of records from R and S. The
attribute of the result include all attributes of R and S.
Cost analysis of CARTESIAN PRODUCT




UNION, INTERSECTION, SET DIFFERENCE and
CARTESIAN PRODUCT

If R has n records and j attributes and S has m records and
k attributes, the result relation will have n*m records and j+k
attributes.

CARTESIAN PRODUCT operation is very expensive
and should be avoided if possible.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 27
Algorithms for PROJECT and SET
Operations (3)



Algorithm for SET operations (contd.)
UNION (See Figure 15.3c)





INTERSECTION (See Figure 15.3d)





Sort the two relations on the same attributes.
Scan and merge both sorted files concurrently, whenever
the same tuple exists in both relations, only one is kept in
the merged results.
Sort the two relations on the same attributes.
Scan and merge both sorted files concurrently, keep in the
merged results only those tuples that appear in both
relations.

SET DIFFERENCE R-S (See Figure 15.3e)


Keep in the merged results only those tuples that appear in
relation R but not in relation S.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 28
5. Implementing Aggregate Operations
and Outer Joins (1)









Implementing Aggregate Operations:
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.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 29
Implementing Aggregate Operations and
Outer Joins (2)










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.
What if we have Clustering index on the grouping attributes?

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 30
Implementing Aggregate Operations and
Outer Joins (3)



Implementing Outer Join:
Outer Join Operators:







LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN.

The full outer join produces a result which is equivalent to the union of the
results of the left and right outer joins.
Example:
SELECT
FROM



FNAME, DNAME
(EMPLOYEE LEFT OUTER JOIN DEPARTMENT
ON DNO = DNUMBER);

Note: The result of this query is a table of employee names and their
associated departments. It is similar to a regular join result, with the exception
that if an employee does not have an associated department, the employee's
name will still appear in the resulting table, although the department name
would be indicated as null.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 31
Implementing Aggregate Operations and
Outer Joins (4)



Implementing Outer Join (contd.):
Modifying Join Algorithms:


Nested Loop or Sort-Merge joins can be modified to
implement outer join. E.g.,






For left outer join, use the left relation as outer relation and
construct result from every tuple in the left relation.
If there is a match, the concatenated tuple is saved in the
result.
However, if an outer tuple does not match, then the tuple is
still included in the result but is padded with a null value(s).

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 32
Implementing Aggregate Operations and
Outer Joins (5)




Implementing Outer Join (contd.):
Executing a combination of relational algebra operators.
Implement the previous left outer join example
 {Compute the JOIN of the EMPLOYEE and DEPARTMENT
tables}
 TEMP1FNAME,DNAME(EMPLOYEE
DNO=DNUMBER DEPARTMENT)
 {Find the EMPLOYEEs that do not appear in the JOIN}
 TEMP2   FNAME (EMPLOYEE) - FNAME (Temp1)
 {Pad each tuple in TEMP2 with a null DNAME field}




{UNION the temporary tables to produce the LEFT OUTER JOIN}




TEMP2  TEMP2 x 'null'
RESULT  TEMP1 υ TEMP2

The cost of the outer join, as computed above, would include the cost
of the associated steps (i.e., join, projections and union).

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Slide 15- 33

More Related Content

What's hot (20)

PPTX
Distributed database management system
Pooja Dixit
 
PPTX
Lec 7 query processing
Md. Mashiur Rahman
 
PPTX
Concurrency Control in Distributed Database.
Meghaj Mallick
 
PPTX
Distributed DBMS - Unit 6 - Query Processing
Gyanmanjari Institute Of Technology
 
PDF
DDBMS Paper with Solution
Gyanmanjari Institute Of Technology
 
PPTX
Distributed Database Management System
AAKANKSHA JAIN
 
PPTX
Query processing and optimization (updated)
Ravinder Kamboj
 
PPT
Distributed objects & components of corba
Mayuresh Wadekar
 
PPTX
Integrity Constraints
madhav bansal
 
PPTX
Distributed DBMS - Unit 5 - Semantic Data Control
Gyanmanjari Institute Of Technology
 
PPTX
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
PPT
17. Recovery System in DBMS
koolkampus
 
PPTX
Transaction management DBMS
Megha Patel
 
PPTX
Data mining primitives
lavanya marichamy
 
PPT
Database Relationships
wmassie
 
PPTX
Transaction management in DBMS
Megha Sharma
 
PPTX
Deadlock dbms
Vardhil Patel
 
PPT
Query optimization and processing for advanced database systems
meharikiros2
 
PPTX
Major issues in data mining
Slideshare
 
PPTX
Deductive databases
Dabbal Singh Mahara
 
Distributed database management system
Pooja Dixit
 
Lec 7 query processing
Md. Mashiur Rahman
 
Concurrency Control in Distributed Database.
Meghaj Mallick
 
Distributed DBMS - Unit 6 - Query Processing
Gyanmanjari Institute Of Technology
 
DDBMS Paper with Solution
Gyanmanjari Institute Of Technology
 
Distributed Database Management System
AAKANKSHA JAIN
 
Query processing and optimization (updated)
Ravinder Kamboj
 
Distributed objects & components of corba
Mayuresh Wadekar
 
Integrity Constraints
madhav bansal
 
Distributed DBMS - Unit 5 - Semantic Data Control
Gyanmanjari Institute Of Technology
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
17. Recovery System in DBMS
koolkampus
 
Transaction management DBMS
Megha Patel
 
Data mining primitives
lavanya marichamy
 
Database Relationships
wmassie
 
Transaction management in DBMS
Megha Sharma
 
Deadlock dbms
Vardhil Patel
 
Query optimization and processing for advanced database systems
meharikiros2
 
Major issues in data mining
Slideshare
 
Deductive databases
Dabbal Singh Mahara
 

Similar to 8 query processing and optimization (20)

PPT
Chapter2.ppt Algorithms Query processing and Optimization
KeenboonAsaffaa
 
PPTX
Advanced Database Management System in Mtech
okmanjunatha23cse
 
PPT
query processing and optimization chapter 2.ppt
eliasaraya142
 
PPTX
Adbms 38 algorithms for select and join operations
Vaibhav Khanna
 
PPTX
Chapter 4 - Query Processing and Optimization.pptx
ahmed518927
 
PDF
Chapter 2.pdf WND FWKJFW KSD;KFLWHFB ASNK
alemunuruhak9
 
PPT
Chapter15
gourab87
 
PPTX
SQL Performance Tuning
Luay Sakr
 
PPTX
Query-porcessing-& Query optimization
Saranya Natarajan
 
PPTX
Adbms 37 query optimisation
Vaibhav Khanna
 
PPT
QPOfutyfurfugfuyttruft7rfu65rfuyt PPT - Copy.ppt
ahmed518927
 
PPT
ch02-240507064009-ac337bf1 .ppt
iamayesha2526
 
PPTX
Query evaluation and optimization
lavanya marichamy
 
PPTX
unit-2 Query processing and optimization,Query equivalence, Join strategies.pptx
RiteshSingh171777
 
PPTX
Adbms 39 algorithms for project and set operations
Vaibhav Khanna
 
PPTX
Lecture 5.pptx
Shafii8
 
PPT
13. Query Processing in DBMS
koolkampus
 
PDF
01Query Processing and Optimization-SUM25.pdf
sfsmj710f
 
PPTX
Relational Algebra Operator With Example
exitjogja
 
Chapter2.ppt Algorithms Query processing and Optimization
KeenboonAsaffaa
 
Advanced Database Management System in Mtech
okmanjunatha23cse
 
query processing and optimization chapter 2.ppt
eliasaraya142
 
Adbms 38 algorithms for select and join operations
Vaibhav Khanna
 
Chapter 4 - Query Processing and Optimization.pptx
ahmed518927
 
Chapter 2.pdf WND FWKJFW KSD;KFLWHFB ASNK
alemunuruhak9
 
Chapter15
gourab87
 
SQL Performance Tuning
Luay Sakr
 
Query-porcessing-& Query optimization
Saranya Natarajan
 
Adbms 37 query optimisation
Vaibhav Khanna
 
QPOfutyfurfugfuyttruft7rfu65rfuyt PPT - Copy.ppt
ahmed518927
 
ch02-240507064009-ac337bf1 .ppt
iamayesha2526
 
Query evaluation and optimization
lavanya marichamy
 
unit-2 Query processing and optimization,Query equivalence, Join strategies.pptx
RiteshSingh171777
 
Adbms 39 algorithms for project and set operations
Vaibhav Khanna
 
Lecture 5.pptx
Shafii8
 
13. Query Processing in DBMS
koolkampus
 
01Query Processing and Optimization-SUM25.pdf
sfsmj710f
 
Relational Algebra Operator With Example
exitjogja
 
Ad

More from Kumar (20)

PPT
Graphics devices
Kumar
 
PPT
Fill area algorithms
Kumar
 
PDF
region-filling
Kumar
 
PDF
Bresenham derivation
Kumar
 
PPT
Bresenham circles and polygons derication
Kumar
 
PPTX
Introductionto xslt
Kumar
 
PPTX
Extracting data from xml
Kumar
 
PPTX
Xml basics
Kumar
 
PPTX
XML Schema
Kumar
 
PPTX
Publishing xml
Kumar
 
PPTX
DTD
Kumar
 
PPTX
Applying xml
Kumar
 
PPTX
Introduction to XML
Kumar
 
PDF
How to deploy a j2ee application
Kumar
 
PDF
JNDI, JMS, JPA, XML
Kumar
 
PDF
EJB Fundmentals
Kumar
 
PDF
JSP and struts programming
Kumar
 
PDF
java servlet and servlet programming
Kumar
 
PDF
Introduction to JDBC and JDBC Drivers
Kumar
 
PDF
Introduction to J2EE
Kumar
 
Graphics devices
Kumar
 
Fill area algorithms
Kumar
 
region-filling
Kumar
 
Bresenham derivation
Kumar
 
Bresenham circles and polygons derication
Kumar
 
Introductionto xslt
Kumar
 
Extracting data from xml
Kumar
 
Xml basics
Kumar
 
XML Schema
Kumar
 
Publishing xml
Kumar
 
DTD
Kumar
 
Applying xml
Kumar
 
Introduction to XML
Kumar
 
How to deploy a j2ee application
Kumar
 
JNDI, JMS, JPA, XML
Kumar
 
EJB Fundmentals
Kumar
 
JSP and struts programming
Kumar
 
java servlet and servlet programming
Kumar
 
Introduction to JDBC and JDBC Drivers
Kumar
 
Introduction to J2EE
Kumar
 
Ad

Recently uploaded (20)

PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Dimensions of Societal Planning in Commonism
StefanMz
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Horarios de distribución de agua en julio
pegazohn1978
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Controller Request and Response in Odoo18
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 

8 query processing and optimization

  • 1. Chapter 15 Algorithms for Query Processing and Optimization Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe
  • 2. Chapter Outline (1) 0. Introduction to Query Processing 1. Translating SQL Queries into Relational Algebra 2. Algorithms for External Sorting 3. Algorithms for SELECT and JOIN Operations 4. Algorithms for PROJECT and SET Operations 5. Implementing Aggregate Operations and Outer Joins Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 2
  • 3. 0. Introduction to Query Processing (1)  Query processing:   Query optimization:   Is the list of activities that are perform to obtain the required tuples that satisfy a given query. The process of choosing a suitable execution strategy for processing a query. Two internal representations of a query:   Query Tree Query Graph Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 3
  • 4. Introduction to Query Processing (2) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 4
  • 5. Introduction to Query Processing (2) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 5
  • 6. 1. Translating SQL Queries into Relational Algebra    Parser & Translator:  Syntax  Schema element  Converts the query into R.A expression. Optimizer  Find all equivalent R.A expressions  Find the R.A expression with least cost  Cost(CPU, Block access, time spent)  Will create query evaluation plan which tell what R.A and what algorithm is used. Query evaluation plan:  Evaluate the above plan and get the result Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 6
  • 7. 1. 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-FROMWHERE 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. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 7
  • 8. Translating SQL Queries into Relational Algebra SELECT FROM WHERE SELECT FROM WHERE LNAME, FNAME EMPLOYEE SALARY > ( SELECT FROM WHERE LNAME, FNAME EMPLOYEE SALARY > C πLNAME, FNAME (σSALARY>C(EMPLOYEE)) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe SELECT FROM WHERE MAX (SALARY) EMPLOYEE DNO = 5); MAX (SALARY) EMPLOYEE DNO = 5 ℱMAX SALARY (σDNO=5 (EMPLOYEE)) Slide 15- 8
  • 9. 2. Algorithms for External Sorting (1)  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. Sorting phase: nR = (b/nB) Merging phase: dM = Min (nB-1, nR); nP = (logdM(nR)) nR: number of initial runs; b: number of file blocks; nB: available buffer space; dM: degree of merging; nP: number of passes. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 9
  • 10. Algorithms for External Sorting (2) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 10
  • 11. 3. Algorithms for SELECT and JOIN Operations (1)  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) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 11
  • 12. Algorithms for SELECT and JOIN Operations (2)   Implementing the SELECT Operation (contd.): Search Methods for Simple Selection:  S1 Linear search (brute force):   S2 Binary search:   Retrieve every record in the file, and test whether its attribute values satisfy the selection condition. 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. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 12
  • 13. Algorithms for SELECT and JOIN Operations (3)   Implementing the SELECT Operation (contd.): Search Methods for Simple Selection:  S4 Using a primary index to retrieve multiple records:   S5 Using a clustering 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. If the selection condition involves an equality comparison on a nonkey attribute with a clustering index, use the clustering index to retrieve all the records satisfying the selection condition. 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) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 13
  • 14. Algorithms for SELECT and JOIN Operations (4)   Implementing the SELECT Operation (contd.): Search Methods for Simple Selection:  S7 Conjunctive selection using a individual index :   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. E.g index has been created on the composite key (Essn, Pno) of the relational R( Works_on) Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 14
  • 15. Algorithms for SELECT and JOIN Operations (5)   Implementing the SELECT Operation (contd.): 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. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 15
  • 16. Algorithms for SELECT and JOIN Operations (7)  Implementing the SELECT Operation (contd.):  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 Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 16
  • 17. Algorithms for SELECT and JOIN Operations (8)  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 Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 17
  • 18. Algorithms for SELECT and JOIN Operations (9)   Implementing the JOIN Operation (contd.): Methods for implementing joins:  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]. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 18
  • 19. Algorithms for SELECT and JOIN Operations (10)   Implementing the JOIN Operation (contd.): 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. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 19
  • 20. Algorithms for SELECT and JOIN Operations (11)   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. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 20
  • 21. Algorithms for SELECT and JOIN Operations (14)   Implementing the JOIN Operation (contd.): Factors affecting JOIN performance    Available buffer space Join selection factor Choice of inner VS outer relation Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 21
  • 22. Algorithms for SELECT and JOIN Operations (15)    Implementing the JOIN Operation (contd.): Other types of JOIN algorithms Partition hash join  Partitioning phase:  Each file (R and S) is first partitioned into M partitions using a partitioning hash function on the join attributes:     R1 , R2 , R3 , ...... Rm and S1 , S2 , S3 , ...... Sm Minimum number of in-memory buffers needed for the partitioning phase: M+1. A disk sub-file is created per partition to store the tuples for that partition. Joining or probing phase:   Involves M iterations, one per partitioned file. Iteration i involves joining partitions Ri and Si. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 22
  • 23. Algorithms for SELECT and JOIN Operations (16)   Implementing the JOIN Operation (contd.): Partitioned Hash Join Procedure:  Assume Ri is smaller than Si. 1. Copy records from Ri into memory buffers. 2. Read all blocks from Si, one at a time and each record from Si is used to probe for a matching record(s) from partition Si. 3. Write matching record from Ri after joining to the record from Si into the result file. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 23
  • 24. Algorithms for SELECT and JOIN Operations (17)   Implementing the JOIN Operation (contd.): Cost analysis of partition hash join: 1. Reading and writing each record from R and S during the partitioning phase: (bR + bS), (bR + bS) 2. Reading each record during the joining phase: (bR + bS) 3. Writing the result of join: bRES  Total Cost:  3* (bR + bS) + bRES Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 24
  • 25. Algorithms for SELECT and JOIN Operations (18)   Implementing the JOIN Operation (contd.): Hybrid hash join:  Same as partitioned hash join except:   Partitioning phase:    Joining phase of one of the partitions is included during the partitioning phase. Allocate buffers for smaller relation- one block for each of the M-1 partitions, remaining blocks to partition 1. Repeat for the larger relation in the pass through S.) Joining phase:  M-1 iterations are needed for the partitions R2 , R3 , R4 , ......Rm and S2 , S3 , S4 , ......Sm. R1 and S1 are joined during the partitioning of S1, and results of joining R1 and S1 are already written to the disk by the end of partitioning phase. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 25
  • 26. 4. Algorithms for PROJECT and SET Operations (1)  Algorithm for PROJECT operations (Figure 15.3b)  <attribute list>(R) 1. If <attribute list> has a key of relation R, extract all tuples from R with only the values for the attributes in <attribute list>. 2. If <attribute list> does NOT include a key of relation R, duplicated tuples must be removed from the results.  Methods to remove duplicate tuples 1. Sorting 2. Hashing Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 26
  • 27. Algorithms for PROJECT and SET Operations (2)   Algorithm for SET operations Set operations:    CARTESIAN PRODUCT of relations R and S include all possible combinations of records from R and S. The attribute of the result include all attributes of R and S. Cost analysis of CARTESIAN PRODUCT   UNION, INTERSECTION, SET DIFFERENCE and CARTESIAN PRODUCT If R has n records and j attributes and S has m records and k attributes, the result relation will have n*m records and j+k attributes. CARTESIAN PRODUCT operation is very expensive and should be avoided if possible. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 27
  • 28. Algorithms for PROJECT and SET Operations (3)   Algorithm for SET operations (contd.) UNION (See Figure 15.3c)    INTERSECTION (See Figure 15.3d)    Sort the two relations on the same attributes. Scan and merge both sorted files concurrently, whenever the same tuple exists in both relations, only one is kept in the merged results. Sort the two relations on the same attributes. Scan and merge both sorted files concurrently, keep in the merged results only those tuples that appear in both relations. SET DIFFERENCE R-S (See Figure 15.3e)  Keep in the merged results only those tuples that appear in relation R but not in relation S. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 28
  • 29. 5. Implementing Aggregate Operations and Outer Joins (1)      Implementing Aggregate Operations: 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. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 29
  • 30. Implementing Aggregate Operations and Outer Joins (2)       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. What if we have Clustering index on the grouping attributes? Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 30
  • 31. Implementing Aggregate Operations and Outer Joins (3)   Implementing Outer Join: Outer Join Operators:      LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN. The full outer join produces a result which is equivalent to the union of the results of the left and right outer joins. Example: SELECT FROM  FNAME, DNAME (EMPLOYEE LEFT OUTER JOIN DEPARTMENT ON DNO = DNUMBER); Note: The result of this query is a table of employee names and their associated departments. It is similar to a regular join result, with the exception that if an employee does not have an associated department, the employee's name will still appear in the resulting table, although the department name would be indicated as null. Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 31
  • 32. Implementing Aggregate Operations and Outer Joins (4)   Implementing Outer Join (contd.): Modifying Join Algorithms:  Nested Loop or Sort-Merge joins can be modified to implement outer join. E.g.,    For left outer join, use the left relation as outer relation and construct result from every tuple in the left relation. If there is a match, the concatenated tuple is saved in the result. However, if an outer tuple does not match, then the tuple is still included in the result but is padded with a null value(s). Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 32
  • 33. Implementing Aggregate Operations and Outer Joins (5)    Implementing Outer Join (contd.): Executing a combination of relational algebra operators. Implement the previous left outer join example  {Compute the JOIN of the EMPLOYEE and DEPARTMENT tables}  TEMP1FNAME,DNAME(EMPLOYEE DNO=DNUMBER DEPARTMENT)  {Find the EMPLOYEEs that do not appear in the JOIN}  TEMP2   FNAME (EMPLOYEE) - FNAME (Temp1)  {Pad each tuple in TEMP2 with a null DNAME field}   {UNION the temporary tables to produce the LEFT OUTER JOIN}   TEMP2  TEMP2 x 'null' RESULT  TEMP1 υ TEMP2 The cost of the outer join, as computed above, would include the cost of the associated steps (i.e., join, projections and union). Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15- 33