Unit 4 - SQL & Query Optimization
Unit 4 - SQL & Query Optimization
Jagdish Bhatta
Jagdish Bhatta 1
Unit – 4
SQL & Query Optimization
Jagdish Bhatta 2
SQL Standards ,Data types
Jagdish Bhatta 3
Database Objects- DDL-DML-DCL-TCL
Jagdish Bhatta 4
Embedded SQL
Embedded SQL is a method of combining the computing power of
a programming language and the database manipulation capabilities
of SQL. Embedded SQL statements are SQL statements written inline
with the program source code, of the host language. The embedded
SQL statements are parsed by an embedded SQL preprocessor and
replaced by host-language calls to a code library. The output from the
preprocessor is then compiled by the host compiler. This allows
programmers to embed SQL statements in programs written in any
number of languages such as C/C++. E.g.: Proc*C is Oracle’s
embedded SQL environment.
Jagdish Bhatta 5
Embedded SQL
E.g: Embedding SQL into C.
{
int a;
/* ... */
EXEC SQL SELECT salary INTO :a
FROM Employee
WHERE SSN=876543210;
/* ... */
printf("The salary is %d\n", a);
/* ... */
}
All SQL statements need to start with EXEC SQL and end with a semicolon ";". You can place the SQL
statements anywhere within a C/C++ block, with the restriction that the declarative statements do not come
after the executable statements.
Jagdish Bhatta 6
Static Vs Dynamic SQL
Jagdish Bhatta 7
Query Processing
Jagdish Bhatta 8
Query Processing
Jagdish Bhatta 9
Query Processing
Jagdish Bhatta 11
Query Processing
Jagdish Bhatta 12
Query Processing
Jagdish Bhatta 13
Query Processing
Further, we can execute each relational-algebra operation by one of
several different algorithms.
To specify fully how to evaluate a query, we need not only to provide
the relational-algebra expression, but also to annotate it with
instructions specifying how to evaluate each operation. Annotations
may state the algorithm to be used for a specific operation, or the
particular index or indices to use.
A relational algebra operation annotated with instructions on how to
evaluate it is called an evaluation primitive. A sequence of
primitive operations that can be used to evaluate a query is a
query-execution plan or query-evaluation plan.
The query-execution engine takes a query-evaluation plan,
executes that plan, and returns the answers to the query.
Jagdish Bhatta 14
Query Processing
Jagdish Bhatta 15
Query Processing
The different evaluation plans for a given query can have different
costs. We do not expect users to write their queries in a way that
suggests the most efficient evaluation plan. Rather, it is the
responsibility of the system to construct a query evaluation plan that
minimizes the cost of query evaluation; this task is called query
optimization.
Once the query plan is chosen, the query is evaluated with that plan,
and the result of the query is output.
The sequence of steps already described for processing a query is
representative; not all databases exactly follow those steps. For
instance, instead of using the relational-algebra representation,
several databases use an annotated parse tree representation based on
the structure of the given SQL query
Jagdish Bhatta 16
Query Processing
Jagdish Bhatta 17
Query Tree
Jagdish Bhatta 18
Query Tree
Jagdish Bhatta 19
Query Tree
Jagdish Bhatta 20
Measures of Query Cost
Jagdish Bhatta 21
Measures of Query Cost
The number of block transfers from disk and the number of disk seeks
can be used to estimate the cost of a query-evaluation plan. If the disk
subsystem takes an average of tT seconds to transfer a block of data,
and has an average block-access time (disk seek time plus rotational
latency) of tS seconds, then an operation that transfers b blocks and
performs S seeks would take b ∗ tT + S ∗ tS seconds.
The values of tT and tS must be calibrated for the disk system used,
but typical values for high-end disks today would be tS = 4
milliseconds and tT = 0.1 milliseconds, assuming a 4-kilobyte block
size and a transfer rate of 40 megabytes per second.
One can refine the cost estimates further by distinguishing block
reads from block writes, since block writes are typically about twice
as expensive as reads (this is because disk systems read sectors back
after they are written to verify that the write was successful).
Jagdish Bhatta 22
Measures of Query Cost
The response time for a query-evaluation plan (that is, the wall-
clock time required to execute the plan), assuming no other activity is
going on in the computer, would account for all these costs, and could
be used as a measure of the cost of the plan.
Unfortunately, the response time of a plan is very hard to estimate
without actually executing the plan, for the following reasons:
– The response time depends on the contents of the buffer when
the query begins execution; this information is not available
when the query is optimized, and is hard to account for even if it
were available.
– In a system with multiple disks, the response time depends on
how accesses are distributed among disks, which is hard to
estimate without detailed knowledge of data layout on disk.
Jagdish Bhatta 23
Measures of Query Cost
Jagdish Bhatta 24
Evaluation of Expressions
Jagdish Bhatta 25
Evaluation of Expressions
Materialization:
Consider the expression;
Jagdish Bhatta 26
Evaluation of Expressions
Materialization:
Jagdish Bhatta 29
Evaluation of Expressions
Pipelining:
Creating a pipeline of operations can provide two benefits:
– It eliminates the cost of reading and writing temporary
relations, reducing the cost of query evaluation.
– It can start generating query results quickly, if the root
operator of a query evaluation plan is combined in a pipeline
with its inputs. This can be quite useful if the results are displayed
to a user as they are generated, since otherwise there may be a
long delay before the user sees any query results.
Jagdish Bhatta 30
Query Optimization
Jagdish Bhatta 31
Query Optimization
Jagdish Bhatta 32
Query Optimization
Jagdish Bhatta 33
Query Optimization
Jagdish Bhatta 34
Query Optimization
Jagdish Bhatta 35
Query Optimization
Jagdish Bhatta 36
Query Optimization
Jagdish Bhatta 37
Query Optimization
Jagdish Bhatta 38
Heuristic Optimization of Query Trees
The query parser will typically generate a standard initial query tree
to correspond to an SQL query, without doing any optimization. For
example, for a SELECTPROJECT-JOIN query, in next slide, the
initial tree is shown in Figure (b). The CARTESIAN PRODUCT of
the relations specified in the FROM clause is first applied; then the
selection and join conditions of the WHERE clause are applied,
followed by the projection on the SELECT clause attributes. Such a
canonical query tree represents a relational algebra expression that is
very inefficient if executed directly, because of the CARTESIAN
PRODUCT (×) operations.
Jagdish Bhatta 39
Heuristic Optimization of Query Trees
Jagdish Bhatta 40
Heuristic Optimization of Query Trees
Jagdish Bhatta 41
Heuristic Optimization of Query Trees
Q: SELECT [Link]
FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE [Link]=‘Aquarius’ AND [Link] = [Link]
AND [Link]=[Link] AND [Link] > ‘1957-12-31’;
Jagdish Bhatta 42
Heuristic Optimization of Query Trees
The initial query tree for Q is shown in Figure 19.2(a). Executing this
tree directly first creates a very large file containing the CARTESIAN
PRODUCT of the entire EMPLOYEE, WORKS_ON, and PROJECT
files. That is why the initial query tree is never executed, but is
transformed into another equivalent tree that is efficient to execute.
This particular query needs only one record from the PROJECT
relation— for the ‘Aquarius’ project—and only the EMPLOYEE
records for those whose date of birth is after ‘1957-12-31’.
Figure 19.2(b) shows an improved query tree that first applies the
SELECT operations to reduce the number of tuples that appear in the
CARTESIAN PRODUCT.
Jagdish Bhatta 43
Heuristic Optimization of Query Trees
Jagdish Bhatta 45
Heuristic Optimization of Query Trees
Jagdish Bhatta 46
Heuristic Optimization of Query Trees
Jagdish Bhatta 47
Heuristic Optimization of Query Trees
Jagdish Bhatta 48
Heuristic Optimization of Query Trees
Jagdish Bhatta 49
Heuristic Optimization of Query Trees
Jagdish Bhatta 50
General Transformation Rules for Relational Algebra
Operations
Jagdish Bhatta 51
General Transformation Rules for Relational Algebra
Operations
Jagdish Bhatta 52
General Transformation Rules for Relational Algebra
Operations
Jagdish Bhatta 53
General Transformation Rules for Relational Algebra
Operations
Jagdish Bhatta 54
General Transformation Rules for Relational Algebra
Operations
Jagdish Bhatta 55
General Transformation Rules for Relational Algebra
Operations
Jagdish Bhatta 56
Outline of a Heuristic Algebraic Optimization Algorithm
We can now outline the steps of an algorithm that utilizes some of the
above rules to transform an initial query tree into a final tree that is
more efficient to execute (in most cases).
– Step 1: Using Rule 1, break up any SELECT operations with conjunctive
conditions into a cascade of SELECT operations. This permits a greater degree
of freedom in moving SELECT operations down different branches of the tree.
– Step 2: Using Rules 2, 4, 6, and 10, 13, 14 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. If
the condition involves attributes from only one table, which means that it
represents a selection condition, the operation is moved all the way to the leaf
node that represents this table. If the condition involves attributes from two
tables, which means that it represents a join condition, the condition is moved
to a location down the tree after the two tables are combined
Jagdish Bhatta 57
Outline of a Heuristic Algebraic Optimization Algorithm
We can now outline the steps of an algorithm that utilizes some of the
above rules to transform an initial query tree into a final tree that is
more efficient to execute (in most cases).
– Step 3: Using Rules 5 and 9 concerning commutativity and associativity of
binary operations, rearrange the leaf nodes of the tree using the following
criteria. First, position the leaf node relations with the most restrictive SELECT
operations so they are executed first in the query tree representation. The
definition of most restrictive SELECT can mean either the ones that produce a
relation with the fewest tuples or with the smallest absolute size.
– Step 4: Another possibility is to define the most restrictive SELECT as the one
with the smallest selectivity; this is more practical because estimates of
selectivities are often available in the DBMS catalog. Second, make sure that
the ordering of leaf nodes does not cause CARTESIAN PRODUCT operations;
for example, if the two relations with the most restrictive SELECT do not have
a direct join condition between them, it may be desirable to change the order of
leaf nodes to avoid Cartesian products.
Jagdish Bhatta 58
Outline of a Heuristic Algebraic Optimization Algorithm
We can now outline the steps of an algorithm that utilizes some of the
above rules to transform an initial query tree into a final tree that is
more efficient to execute (in most cases).
– Step 5: Using Rule 12, combine a CARTESIAN PRODUCT operation with a
subsequent SELECT operation in the tree into a JOIN operation, if the
condition represents a join condition.
– Step 6: 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. Only those attributes needed in the query
result and in subsequent operations in the query tree should be kept after each
PROJECT operation.
Jagdish Bhatta 59
Outline of a Heuristic Algebraic Optimization Algorithm
We can now outline the steps of an algorithm that utilizes some of the
above rules to transform an initial query tree into a final tree that is
more efficient to execute (in most cases).
– Identify subtrees that represent groups of operations that can be executed by a
single algorithm.
Jagdish Bhatta 60
Outline of a Heuristic Algebraic Optimization Algorithm
In the example, Figure 19.2(b) shows the tree in Figure 19.2(a) after
applying steps 1 and 2 of the algorithm;
Figure 19.2(c) shows the tree after step 3; Figure 19.2(d) after step 4;
and
Figure 19.2(e) after step 5.
In step 6, we may group together the operations in the subtree whose
root is the operation πEssn into a single algorithm. We may also group
the remaining operations into another subtree, where the tuples
resulting from the first algorithm replace the subtree whose root is the
operation πEssn , because the first grouping means that this subtree is
executed first.
Jagdish Bhatta 61
Outline of a Heuristic Algebraic Optimization Algorithm
SELECT [Link]
FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE [Link]=‘Aquarius’ AND [Link] = [Link] AND
[Link]=[Link] AND [Link] > ‘1957-12-31’;
Jagdish Bhatta 62
Outline of a Heuristic Algebraic Optimization Algorithm
In the example, Figure 19.2(b) shows the tree in Figure 19.2(a) after
applying steps 1 and 2 of the algorithm;
Jagdish Bhatta 63
Outline of a Heuristic Algebraic Optimization Algorithm
Jagdish Bhatta 64
Outline of a Heuristic Algebraic Optimization Algorithm
Jagdish Bhatta 65
Outline of a Heuristic Algebraic Optimization Algorithm
Jagdish Bhatta 66
Outline of a Heuristic Algebraic Optimization Algorithm
Jagdish Bhatta 67
Outline of a Heuristic Algebraic Optimization Algorithm
The main heuristic is to apply first the operations that reduce the size
of intermediate results.
This includes performing as early as possible SELECT operations to
reduce the number of tuples and PROJECT operations to reduce the
number of attributes—by moving SELECT and PROJECT operations
as far down the tree as possible.
Additionally, the SELECT and JOIN operations that are most
restrictive—that is, result in relations with the fewest tuples or with
the smallest absolute size—should be executed before other similar
operations. The latter rule is accomplished through reordering the leaf
nodes of the tree among themselves while avoiding Cartesian
products, and adjusting the rest of the tree appropriately
Jagdish Bhatta 68
Cost-Based Optimization
Jagdish Bhatta 69
Cost-Based Optimization
Jagdish Bhatta 70
Cost Components for Query Execution
Jagdish Bhatta 71
Cost Components for Query Execution
Disk storage cost. This is the cost of storing on disk any intermediate
files that are generated by an execution strategy for the query.
Computation cost. This is the cost of performing in-memory
operations on the records within the data buffers during query
execution. Such operations include searching for and sorting records,
merging records for a join or a sort operation, and performing
computations on field values. This is also known as CPU (central
processing unit) cost.
Jagdish Bhatta 72
Cost Components for Query Execution
Jagdish Bhatta 73
Cost Components for Query Execution
Jagdish Bhatta 75
Cost Based Optimization
Jagdish Bhatta 76
Cost Based Optimization
Jagdish Bhatta 77
Cost Based Optimization
Jagdish Bhatta 78
Cost Based Optimization
Jagdish Bhatta 79
Cost Based Optimization
Jagdish Bhatta 80
Cost Based Optimization
Jagdish Bhatta 81
Cost Based Optimization
The query 2 joins Employee and Branch which again requires (2000
+ 20) disk accesses to read each of the relations. The Join of these
two relations has 2000 tuples, one for each member of Employee.
Consequently, the Selection operation requires 2000 disk accesses to
read the result of the join, giving a total cost of (2000 + 20) + 2 ×
(2000) = 6020 disk accesses.
Jagdish Bhatta 82
Cost Based Optimization
Jagdish Bhatta 83
Cost Based Optimization
Jagdish Bhatta 84