0% found this document useful (0 votes)
5 views29 pages

Oracle SQL Optimization

The document provides a comprehensive overview of the Oracle SQL optimizer, detailing its architecture, operations, and types of optimization methods, including Rule-Based and Cost-Based optimization. It explains the execution plan process, various optimizer operations, and techniques for optimizing SQL statements, such as expression evaluation and transformation of queries. Additionally, it covers specific optimization strategies for star schemas and how to specify the type of optimization in Oracle SQL.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

Oracle SQL Optimization

The document provides a comprehensive overview of the Oracle SQL optimizer, detailing its architecture, operations, and types of optimization methods, including Rule-Based and Cost-Based optimization. It explains the execution plan process, various optimizer operations, and techniques for optimizing SQL statements, such as expression evaluation and transformation of queries. Additionally, it covers specific optimization strategies for star schemas and how to specify the type of optimization in Oracle SQL.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Introduction to the optimizer ............................................................................................ ...

2
What is the Optimizer? .............................................................................. ................2
Execution plans ............................................................................................... .......3
Stages of the Execution Plan
The EXPLAIN PLAN command.......................................................... ...............................3
Types of Optimization
Optimizer operations................................................................................... ..........4
Evaluation of Expressions, Conditions, and Constants ...............................4
Transformation of sentences
Table merging methods .......................................................... ....6
Optimization of Sentences in 'Star' ........................................... ...........................7
How to specify the type of optimization ............................................................ 7
Cost-based optimization
Objective of cost-based estimation...
Statistics for cost-based estimation .......................................................... .9
Features available with Cost-Based Optimization................................10
Collection of statistics..................................................................... ...........................10
ANALYZE command .............................................................................................. ......11
DBMS_STATS Package ................................. .............................11
Histograms
Access roads to the data.................................................................13
Execution plan
Definition of the PLAN_TABLE.................................................. ..........................15
Operations and Options of the PLAN_TABLE table.................................... .................15
EXPLAIN PLAN Command .............................................................................. ............17
Rule-based Optimization
Introduction to Rules Optimization..................................................... ...............18
Access paths to the data............................................................... ....................18
SQL Statement Adjustment. SQL Trace and TKPROF Utility ............................................ .19
Activate the Initialization Parameters............................................................... ........19
Activate the trace............................................................................................. ................20
Formatting the trace with TKPROF...............................................................................20
Interpret the output file..................................................................................... .21
Tabular Statistics................................................................................ .................21
Store statistics in the Database.................................................... ...........22
The AUTOTRACE feature of SQL*PLUS ........................................................ .......23
Manual adjustment of sentences: The HINTS ............................................ ..........................23
Purpose of the Hints............................................................. ..............23
Comments to decide the Optimization method........................................ ..........24
Comments to decide the Access method............................................... ............24
Comments to decide the order of combination.....................................................24
Comments to decide the combination method..................................................25
Comments for parallel execution.............................................................. ........25
Additional comments.......................................................................................... ....25
Materialized Views .................................................................................................... ..25
Introduction............................................................................................. ....................25
Creation of materialized views.................................................. .............................26
Refreshing materialized views.................................................. .............................26
Rewriting of Queries......................................................................................... ....26
Stability of Plans.......................................................................................... ............28
Creation of Outlines for Plan Stability.................................... ....................28
Use of Outlines with Cost-Based Optimization........................................ ......29

Optimization of Oracle SQL Javier Navarro Grau Page 1 of 29


Introduction to the optimizer

What is the Optimizer?

The Oracle database uses the following architecture for processing


the SQL statements received from the users.

Figure 1. Oracle SQL Processing Architecture

Its main components are:

• The parser, or interpreter, that translates SQL statements, performing the Analysis
Syntactic (checks the syntactic correctness of SQL instructions) and
Semantic (checks that the used objects and their attributes exist and are
correct), to the internal representation used by Oracle.
• The optimizer, which uses internal rules and cost statistics to
determine the most efficient way to produce the results of the sentence. The
The output of the optimizer is an optimal execution plan.
• The record sources generator, which receives the optimal plan developed
by the optimizer, and generates the execution plan: a sequence of sources of
structured records in the form of a tree.
• The SQL execution engine, which receives the execution plan and executes it,
extracting records from each of the indicated sources, and combining these
records, until obtaining the result of the sentence.

For each SQL instruction executed by Oracle, the optimizer can perform
various of the following tasks :

1. Evaluation of expressions and conditions: Expressions and conditions are evaluated.


conditions that contain constants in the broadest possible form

Optimization of Oracle SQL Javier Navarro Grau Page 2 of 29


2. Transformation of Instructions: For complex instructions that
contain, for example, related queries or subqueries, the optimizer
could you transform the original statement into a statement with a join
equivalent.

3. Access path selection: For each table accessed by the instruction,


the optimizer chooses one or more of the available access paths to
obtain the data from the table.

4. Choice of order for combinations (joins): For each instruction of


combination of more than two tables, the optimizer chooses which pair of tables to
first combine, and what table is combined with the result, and so on.

5. Choice of join methods: For each combination, the


Optimizer chooses the ideal method to use.

Execution plans

To execute an SQL statement, Oracle may require many steps. In each


one of these steps either retrieves data records from the database, or
prepare it in some way so that the user gets the output of their
instruction. The combination of steps that Oracle uses to execute an instruction is what
what is called Execution Plan. An Execution Plan includes:

• An access path for each table that the instruction accesses.


• The order of the combination of the tables, with the appropriate method of
combination.

Stages of the Execution Plan

Each stage of the execution plan returns a set of records that are either
Used by the next step, or in the last step, are returned to the user or application.
releasing the SQL instruction. The group of records returned by a step is known
comorow set, the set of records. The origin of these records can be either
recovery from a specific object in the database, or the combination of
the row sets obtained from the previous steps in the execution plan.

The execution plan forms a tree. To process it, the database manager
first execute the steps corresponding to the leaves of the tree. The records
obtained become sources of the steps father of these. Then Oracle carries out
these steps father, and so on until reaching the root of the tree.

The EXPLAIN PLAN command

The EXPLAIN PLAN command allows obtaining, in tabular form, the plan of
execution chosen by the Oracle optimizer for the SELECT, UPDATE instruction
INSERT and DELETE as indicated.

Types of Optimization

Oracle SQL Optimization Javier Navarro Grau Page 3 of 29


The Oracle database manager, in its current versions, has two methods of
optimization: the Rule Based Optimizer (RBO) and the
Cost-Based Optimizer (CBO)

• The rule-based optimizer, which has been the main method of


optimization of Oracle until the cost-based optimizer was introduced
In version 7, it has been gaining features. It is based on rules obtained
heuristically by Oracle, based on experience with successive versions.
• The cost-based optimizer, which takes into account the state of the database
data at the time of the execution of the sentence, to determine which of
The execution plans are more efficient. It also takes hints into account.
optimization suggestions placed as comments in the SQL instruction
by the programmer.

Optimizer operations

Evaluation of Expressions, Conditions, and Constants

The optimizer performs a series of operations with the statement, transforming it and
normalizing it, so that it is easier to obtain an optimal execution plan. Among
these operations include the evaluation of expressions, conditions, and
constants.

• Constant expressions are evaluated during optimization, in such a way


that do not have to be evaluated time and time again during execution. This
evaluation is limited to the terms of the conditions, not to the conditions themselves
conditions. Therefore, it is always preferable to pass all expressions
constants next to the condition, so that Oracle evaluates them together.

• The IN conditions can be translated into multiple equality conditions.


separated by OR operators.

• NOT operators can be eliminated by transforming the


condition that is denied. This transformation may involve the introduction of
new conditions with NOT operators, which could be optimized to its
time.

• The conditions that use the BETWEEN operator are replaced by


equivalent conditions that use the comparison operators >= and <=

• The ANY and SOME operators followed by a list of values are translated to
individual conditions, separated by OR operators. If they are followed by
a subquery translates to an EXISTS condition, with one more condition
in the subquery.

• The ALL operators followed by a list of values translate to conditions.


individuals separated by AND operators. If followed by a
subquery, translates to ANY operators, with a contrary condition in the
subquery. The obtained ANY operator can be transformed, in turn.

Oracle SQL Optimization Javier Navarro Grau Page 4 of 29


• Common subexpression optimization seeks common parts in
conditions separated by OR operators, so that they can be
removed from these conditions, and executed only once.

• The optimizer can take into account deterministic functions (functions


that always return the same result for the same parameters of
(input) to evaluate them in optimization time, or use results
stored at runtime. The programmer can use the keyword
DETERMINISTIC key to indicate that one of the functions it defines is
deterministic.

• The cost-based optimizer can also introduce new conditions.


obtained by transitivity, based on other existing conditions in the
sentence.

Transformation of sentences

SQL is a quite flexible language; different paths can be used to


achieve the same objective. Many times, the optimizer will transform one statement into another
that achieves the same result but is more efficient. Some of the transformations
what the optimizer applies is:

• Queries with OR operators, in multiple queries joined by UNION:


if the optimizer finds that separating the initial statement into multiple
sentences, each with one of the conditions separated by OR, and then
joining them using the UNION operator is more efficient than the first option.

• Subqueries, in combinations (joins): if the transformation of the


Subquery in combination with the main query ensures the same
result that the initial query, the optimizer can transform it and proceed
to the optimization of the new query obtained.

• Combinations with views, in combinations with statements: if it is possible


replace the reference to a view with the reference to its creation statement, and
try to optimize the new obtained statement. It cannot be done
this substitution if the view contains, in its creation statement, operators
UNION, INTERSECT, MINUS, CONNECT BY, the pseudo-column ROWNUM, or
the group functions AVG, COUNT, MAX, MIN, and SUM.

• Combinations with complex views: if the combination has been activated.


complex views, Oracle may attempt to transform views with functions
of group and GROUP BY clauses.

• Expansion of predicates: if a view is not combinable with the statement that


referring to her, her creation sentence can be transformed through
the introduction of the conditions of the initial sentence corresponding to the
view, within the creation sentence.

• Composite queries, in simple queries joined by operators: the


execution plan of a compound query, it transforms into plans of

Optimization of Oracle SQL Javier Navarro Grau Page 5 of 29


parallel execution for each of the subqueries, joined by the
corresponding operators (UNION, INTERSECT, MINUS).

Table combination methods

Joins are statements that return data from more than one table (or from a single one)
table referenced multiple times). A join is characterized by multiple tables in the
The FROM clause and the relationship between these tables is defined through the condition
WHERE. The optimizer has several methods to perform combinations between
tables, and must choose the most efficient one among them. Among the main join methods
they are

• Nested Loops: the optimizer uses this method with


small datasets, and in the case that the join condition is a
efficient access path for the "interior" table. The optimizer determines which
It is the 'conductor' table, and it executes a loop accessing the records of this.
table that meets the conditions of the query. For each record of the table
driver, a loop is executed accessing the inner table, through the
current values of the conductor table. Therefore, it is important that the path
access to the interior table is very efficient.

• External Nested Loops (Nested Loop Outer Joins): in case of


outer joins, if the selection conditions are met
From Nested Loops, the method of External Nested Loops can be used,
in which the conductor table is always the 'outer' table (while, in the
previous method, one can choose either table as the conductor table.

• Hash Joins: this method is used to link


large datasets, where the join condition is equality. The
optimizer uses the smaller of the two source tables to construct a
hash table on the join key, in memory. When the retrieved
records of the largest table, the hash table is examined to find the
linked rows in the other table. This situation is optimal when the smaller table
is small enough to fit in the available memory, since the
the cost is limited to a simple reading of the data from the smaller table. However, if
the hash table is too large, the optimizer splits it into several
partitions, which are written to different time segments of disk, that
They are read as needed, which decreases efficiency.

• Hash Combinations in Outer Joins (Hash Join Outer Joins): this


the method is very similar to the previous one, but in the case of external combinations.
The conductor table is always the external table, and the hash table is constructed.
about her. The inner table is traversed, checking the hash table the
existence of data in the outer table. The records of the table are preserved.
exterior that does not have an equivalent in the interior.

• Sort Merge Joins: consist of


a fusion of the two datasets, previously ordered by the
join condition columns. There is no concept of a driving table or
director. They are used to combine records from two independent sources,
especially if they are already sorted by the condition columns of
join, or if the join condition includes any operator other than equality. In

Optimization of Oracle SQL Javier Navarro Grau Page 6 of 29


In another case, it is better to use hash combinations. There is a similar method,
for the outer joins, called Sort Merge Outer Joins.

• Cartesian Combinations (Cartesian Joins): consist of the combination


from two sources of records, among which no condition is defined
join. Its cost is very high, depending on the volumes of the two sources.
of records.

• Full Outer Joins consist of


external combinations in which the records of both must be preserved
data sources (using the keywords FULL OUTER JOIN).

• Anti-Combinations (Anti-Joins): are combinations in which


they return the records from the first data source that do not meet the
conditions imposed on the second source (NOT IN operators with
subqueries or NOT EXISTS.

• Semi-Joins: these are combinations in which


they return the records from the first data source that meet the
conditions imposed on the second source (IN operators with subqueries or
EXISTS).

Optimization of Queries in 'Star'

Some data warehouses are designed as star schemas, which include


a large fact table and several small dimension tables. In the first one, it
stores basic information and in the others, it saves information about the attributes of the table
of facts.

A star query is a union between a fact table and a certain number of


of dimension tables, joined by primary key – foreign key relationships, and without relation
among the dimension tables. The Cost-Based Optimizer is able to identify
this type of relationship and to create an efficient execution plan. The Based Optimizer
Rules do not present specific optimizing activity in these cases.

A typical fact table contains keys and measures. For example, the measure
Sales amount and the keys Date, Product and Market (that connect with the
corresponding dimension tables). The fact table usually has a
concatenated index in the key columns to facilitate this type of join or else
independent indices for each column of the key.

How to specify the type of optimization

By modifying the INIT.ORA parameter called


OPTIMIZER_MODE allows for the determination of the type of optimization. If it is given the
value RULE, the optimizer works through Rules (RCO). If the value CHOOSE is given, the
the optimizer will choose Costs (CBO), as long as there are statistics on the tables, or
suggestions (hints) from the programmer. If you have noticed CHOOSE, but
There are no statistics or suggestions, the Optimizer will work by Rules (RCO).

Optimization of Oracle SQL Javier Navarro Grau Page 7 of 29


function of other values of the parameter, the CBO focused on a specific one will be used
objective.

Cost-based optimization
By default, the strong point of the Cost-Based Optimizer is the amount of
data processed per second, while dedicating the minimum resources to the solution of the
query. That is to say, it works in two directions: minimum applicable resources, to obtain
in the shortest time the first record accessed by the query used (minimum time
of response).

However, it is possible to enhance one service or another depending on the task to be performed.

For batch-type applications, such as Oracle Reports, it is preferable to optimize for


maximum productivity: total task time is reduced, regardless of
both the response time.

For interactive applications, such as Oracle Forms or queries in SQL*Plus,


optimize for the best response time.

The CBO determines which of the execution plans is the most efficient, taking into account
count the available access paths and factoring the information based on
statistics of the schema objects (tables or indexes) accessed by the statement
SQL, in addition to the optimization suggestions placed as comments in the
SQL instruction, and the objective set in OPTIMIZER_MODE.

When new features are designed for the database in Oracle, they are used
exclusively the CBO as a means of optimization. It generally consists of three stages:

Development of potential record recovery plans.


2. Cost estimation per plan taking into account the stored statistics
in the dictionary of data available for each object included in the query.
cost calculation is based on the estimated resources for the computer
including Input/Output, CPU, and memory.
3. Selection of the lowest cost plan.

Objective of cost-based estimation

The INIT.ORA parameter allows selecting and adapting the behavior of the
optimizer to our needs:

• CHOOSE: This is the default value for the parameter. The use of is decided
CBO, if there are statistics available, in which case the goal to be achieved is the
higher productivity (records per unit of time). If the statistics are
incomplete (only some of the objects have been analyzed) a
suboptimized execution plan: information can be taken as an alternative
internal as the number of data blocks set by the table. If there are none
statistics, the optimizer decides to use the Rules-Based approach (RBO).

Oracle SQL Optimization Javier Navarro Grau Page 8 of 29


• ALL_ROWS. The optimizer uses a CBO approach for all
consultation records. The goal is to achieve the highest productivity
(minimal resources used to complete all parts of the instruction).

• FIRST_ROWS_n: The optimization is CBO, but priority is given to the best


response time to obtain the first n records. N can be 1, 10,
100 or 1000.

• The optimizer uses a mix of CBO and heuristic rules,


to find the best plan that provides the initial records with the greatest speed.
Sometimes the heuristic part involves a higher cost. This value
(FIRST_ROWS) is available for backward compatibility and the
stability plan.

• RULE: Optimization is based on rules, regardless of presence.


of statistics.

The OPTIMIZER_GOAL parameter can override the shape and objectives of


optimization, globally set by OPTIMIZER_MODE, for an individual session,
through the ALTER SESSION statement. The value of this parameter affects optimization
of the SQL instructions used by the user including those corresponding to
stored procedures and functions, during the duration of the session. The values
what can be taken are the same as those of OPTIMIZER_MODE.

Statistics for cost-based estimation


The statistics about the Oracle database objects are stored in the
data dictionary, and they must be regularly maintained to be representative
from the data. They can be collected using the DBMS_STATS package or the command
ANALYZE.

• For versions 8i or later, use the DBMS_STATS package.


• For versions prior to 8i, use the ANALYZE statement.

By using updated statistics, the CBO can create the best


execution plan, with the lowest cost. The CBO uses statistics to calculate the
predicate selectivity (the fraction of records in a table that is selected)
predicate), and estimate the cost of a certain access path and the optimal order of
combination with other tables.

It is logical to capture statistics periodically and automatically.


it must be done punctually, every time the structure of an object is changed, or if there have been
updated many records in a table in a short time. The statistics generated, by
type of object or action, include:

• For tables: the number of records, number of blocks, and the average length of
registration.
• For columns: the number of distinct values (NDV) in the column, the number
of nulls in the column, and the data distribution (histogram).

Optimization of Oracle SQL Javier Navarro Grau Page 9 of 29


• For indexes: the number of leaf blocks, the levels, and the factor of
clustering.
• For the system: the performance and use of input/output, and the performance and use
of the CPU.

Oracle uses various techniques in order to obtain statistics for the CBO:

• Estimation based on random sampling of data.


• Exact calculation.
• User-defined statistics collection methods.

In the absence of statistics for a certain object used in


for a statement, the optimizer uses the following default values:

• For tables: 100 records, 100 blocks and an average length of 20 bytes per
registry.
• For remote tables: 2000 records and 100 bytes of average length per record.
• For indices: 25 leaf blocks, one level and 100 distinct keys.

Features available with Cost-Based Optimization

The following features are only available when using the Optimizer.
Cost-Based (CBO):

• Partitioned tables and index-organized tables

• Inverse key indices and function-based indices

• SAMPLE clauses in SELECT statements

• Parallel queries and parallel DML

• Star transformations and star queries

• Extensible optimizer

• Rewriting queries with materialized views

• Hash combinations

• Bitmap indices

• Index Skip Scans

Collection of statistics

Optimization of Oracle SQL Javier Navarro Grau Page 10 of 29


ANALYZE command

The ANALYZE command currently generates statistics for Optimization Based


in Costs. However, the use of ANALYZE for this purpose is not recommended because
various reasons :

• ANALYZE always runs serially, not in parallel.


• ANALYZE calculates global statistics for partitioned tables and indexes, in
place to collect them locally in each partition. This is causing problems
in some statistics, such as the number of different values in a column.
• ANALYZE cannot overwrite or delete some of the values of
statistics that have been collected by DBMS_STATS.
• In the future, ANALYZE will not collect statistics needed by the CBO.

ANALYZE, on the other hand, can gather another type of information (that is not used
by the optimizer), such as chained records and the structural integrity of indices,
tables and clusters (DBMS_STATS cannot collect this information).
To collect statistics from a table or index, the ANALYZE command could be:

ANALYZE TABLE table-name COMPUTE STATISTICS;

ANALYZE INDEX index-name COMPUTE STATISTICS;

ANALYZE TABLE table-name ESTIMATE STATISTICS SAMPLE 1000 ROWS;

ANALYZE TABLE table-name ESTIMATE STATISTICS SAMPLE 20 PERCENT;

ANALYZE TABLE table-name DELETE STATISTICS;

The COMPUTE method generates exact statistics, as it processes all the


table or index records. The ESTIMATE method is faster, as it is based on a
random sample of the records. On the contrary, its statistics are less reliable. The
The DELETE method is used to delete statistics that are considered unreliable, without generating
new statistics.

DBMS_STATS package

It can be used for the complete maintenance of statistics, from generation


until deletion including the identification (named) of the collected statistics. It
applies to tables, indexes, columns, and partitions. It does not work globally for clusters (there is
to analyze each component in isolation), nor for partitions (separate analysis
by partition). It allows collecting:

• Statistics about the system collected by means of


GATHER_SYSTEM_STATS and retrieved through GET_SYSTEM_STATS.
SET_SYSTEM_STATS allows arbitrary values to be given to statistics of the
system.
• Statistics about tables, retrieved using GATHER_TABLE_STATS.
through GET_TABLE_STATS.

Oracle SQL Optimization Javier Navarro Grau Page 11 of 29


• Statistics on indices, using GATHER_INDEX_STATS and
GET_INDEX_STATS.
• Statistics about all objects in a schema, using
GATHER_SCHEMA_STATS.
• Statistics about all objects in a database, through the use
of GATHER_DATABASE_STATS.

The generated statistics are stored in the data dictionary, unless


a statistics storage table is specified as a parameter of the
corresponding procedure. The views of the data dictionary that contain the
generated statistics are:

• DBA_TABLES
• DBA_TAB_COL_STATISTICS
• DBA_INDEXES
• DBA_CLUSTERS
• DBA_TAB_PARTITIONS
• DBA_TAB_SUBPARTITIONS
• DBA_IND_PARTITIONS
• DBA_IND_SUBPARTITIONS
• DBA_PART_COL_STATISTICS
• DBA_SUBPART_COL_STATISTICS

Histograms

The Cost-Based Optimizer can use data value histograms to


obtain a reliable estimate of the data distribution of a column. A
Histogram partitions the values of a column into bands, so that all the
Values of the column in a band fall within the same range. Thus the Histograms
they provide a superior selective estimation for biased data, resulting in optimal
execution plans with non-uniform data distributions.

One of the tasks of the CBO is to determine the selectivity of the predicates that
They appear in the queries. The selectivity estimates are used to decide whether to use or
no an index, and the order in which to combine tables. The problem arises when the values
from a column are not evenly distributed. In these cases, it is useful to save
histograms of the distribution of its values.

Care must be taken in the selection of those columns for which one
generate histograms, as they can affect performance. They should only be saved
when they significantly improve the efficiency of the queries. The space used
to store a histogram depends on the size of the chosen sample. In general, it
You should create histograms only for those columns that are frequently used in the
WHERE clause of the queries, and it should be known that they have a little distribution
uniform distribution of values. If the distribution of values in a column is uniform, it is not
it is necessary to use histograms. If the distribution of values in the column varies
constantly, it will be necessary to recalculate your histogram constantly, to reflect the
situation exactly, with the consequent use of resources.

To create histograms about a column of a table, the parameter is used


METHOD_OPT of the GATHER_TABLE_STATS procedure of the DBMS_STATS package:

Optimization of Oracle SQL Javier Navarro Grau Page 12 of 29


BEGIN
DBMS_STATS.GATHER_TABLE_STATS('SCOTT', 'EMP',
FOR COLUMNS SIZE 10 SAL
END;

This call generates a histogram of ten partitions for the SAL column of the
table EMP of the user SCOTT. In general, it is better for the database to determine the
number of histogram partitions, using the AUTO value.

Histograms can be:

• Based on heights: each partition contains approximately the same.


number of values, so the maximum value of the column is stored for
each partition.

• Based on values: there are fewer distinct values in the column in the table.
what partitions in the corresponding histogram, so each partition
reflects a value and the number of occurrences of it.

To visualize the histograms, the following views of the dictionary are available:

• DBA_HISTOGRAMS
• DBA_PART_HISTOGRAMS
• DBA_SUBPART_HISTOGRAMS
• DBA_TAB_COL_STATISTICS

Access paths to the data


Access paths are the ways in which data is retrieved from the
database. The most common ways to access a specific record of a
table referenced by an SQL statement are:

- Through a full table scan, which accesses all


Its records. A sequential reading of the blocks that make up the table is conducted.
(improving performance with the simultaneous reading of several blocks, as indicated by
the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT is being discarded
those who do not meet the selection criteria of the WHERE clause. This access
is used in those cases when:

- The optimizer is unable to use an index access path, or

- The optimizer assumes that the resulting subset of the query is a


important percentage of the total records in the table, or

- The table is very small and can be loaded into memory in a single
input/output operation, or

- In general, when the optimizer perceives that the number of operations


I/O will be less than with the access paths that use indexes.

Oracle SQL Optimization Javier Navarro Grau Page 13 of 29


- Through access by record identifier (ROWID scan): in which the
registration identifier, a unique value that specifies the exact physical position of the
registration in the database. This value can be retrieved by a statement
SELECT y used later in other statements that retrieve the record in
question (with limitations, since the ROWID of a record can vary to
consequence of updates in the value of its fields). More frequently, the
access by ROWID is used as a second step of index access (the indexes
they contain the identifier of the records they point to.

- Through an index scan, where specified values are used in


the SQL statement, for the columns of the table that are part of the index. If a
statement only uses columns that are part of one of its indexes, it
they use these values, without needing access to the table through ROWID. In case
on the contrary, access is performed using ROWID to retrieve the values of the rest of
the columns. An access by index can be:

- Unique index access (index unique scan): in which values are used from
all the columns of a UNIQUE index of the table, with conditions of
equality, so a single record is retrieved (or none).

- Index range access: in which values are used from


some or all columns of an index (UNIQUE or not) of the table, with
conditions of equality or not, therefore an indeterminate number is recovered
of records. Normally, this access is performed in ascending order of the
values of the index columns, unless requested through the clause
ORDER BY to be retrieved in descending order.

- Fast full index scan: it occurs when you are going to


only use index columns, even if the first ones are not used. It
perform a full scan on the index blocks, instead of on the blocks
what the table is made of. In the index, there must be some NOT NULL column
(to ensure that there is an entry in the index for each entry in the table), and
it is advisable to analyze the index from time to time, so that the optimizer can
costs take this possibility into account.

- Access through index joins: it occurs when all


the necessary columns for the query are present, in the set of
various indices, and cost optimization is available.

Execution plan
The execution plan is the sequence of database operations that is
created by the optimizer from a SQL statement, in order to execute it. It is
it is possible to obtain the execution plan of any SQL statement without having to
execute it, using the EXPLAIN PLAN statement. This statement produces its
result in the form of records inserted into a table called PLAN_TABLE.

The execution plan for the same SQL statement varies over time, in
function of the selected optimization mode, the indices that are added or
eliminate, the analyses carried out for the cost optimizer, the amount of
data from the tables, etc., which complicates the a priori analysis of the SQL statements. The

Oracle SQL Optimization Javier Navarro Grau Page 14 of 29


The EXPLAIN PLAN statement can help, at least, to verify that a
A certain sentence performs a sequence of 'recommended' operations.
There are other Oracle tools that are used for analyzing statements.
SQL, once it has finished its execution over a certain state of the database
data.

Definition of the PLAN_TABLE

The PLAN_TABLE is not usually created by default in the database.


Oracle. To create it, a file called UTLXPLAN.SQL is used, the location of which varies,
depending on the operating system on which Oracle is installed. This file must
execute in each database schema that needs to use the EXPLAIN statement
PLAN.

The records inserted into the PLAN_TABLE, using the EXPLAIN statement.
PLAN, for a given SQL statement, forms a tree of database operations
data. Each operation, within this tree, collects the result created by its
child operations perform their task and send the result to their parent operation.
The 'root' operation within the tree is what returns the final result of the execution of the
SQL statement.

Common fields within the PLAN_TABLE are (with possible variations


in the name) :

• statement identifier, used to distinguish the


different sentences analyzed, within the table.
• TIMESTAMP: indicates the date and time of execution plan creation.
• identifier of the operation, within the statement.
• identifier of the 'parent' operation of this one.
• POSITION: order of operation among its 'sisters'.
• OPERATION: database operation performed.
• OPTIONS: options that apply to the operation.
• owner of the object on which the operation is performed.
• name of the object on which the operation is performed.
• names of the search columns, if there are any.

Operations and Options of the PLAN_TABLE

Each record of PLAN_TABLE corresponds to a certain operation of


database. Each possible operation, within an execution plan, can be
modified through a series of options. The main operations, with their
respective options are:

• TABLE ACCESS: operation of accessing data from a table. Its main options
son

• ALL: access to all the records in the table.


• A sampling of records from the table is carried out.

Optimization of Oracle SQL Javier Navarro Grau Page 15 of 29


• BY ROWID RANGE: records are retrieved from a range of
ROWIDs.
• SAMPLE BY ROWID RANGE: a sample of the records is retrieved
from a range of ROWIDs.
• BY USER ROWID: records are retrieved using ROWIDs
explicitly provided in the SQL statement.
• BY INDEX ROWID: records are retrieved using ROWIDs
provided by an index access operation.
• BY GLOBAL INDEX ROWID: in the case of partitioned tables, it
They recover records using ROWIDs from global indexes of the table.
• BY LOCAL INDEX ROWID: for partitioned tables, they are retrieved
records via ROWID of local partition indexes.

• INDEX: data access operation using an index. Its main options:

• UNIQUE SCAN: recovery of a unique record identifier.


• RANGE SCAN: recovery of a series of record identifiers,
in ascending order of the index.
• RANGE SCAN DESCENDING: retrieving a series of ROWIDs,
in descending order of the index.

• VIEW: data recovery from a view.

• SEQUENCE: data recovery from a sequence.

• REMOTE: data recovery from a remote database.

• PARTITION: recovery of data from a table partition. Some of its


options are :

• SINGLE: access to a single partition


• ITERATOR: access to multiple partitions
• ALL: access to all the partitions of the table

• sorting and grouping operations of data. Some options:

• AGGREGATE: result of aggregations without GROUP BY clause.


• UNIQUE: sorting to eliminate duplicates.
• GROUP BY: result of groupings with the GROUP BY clause.
• JOIN: sorting prior to a MERGE JOIN.
• ORDER BY: sorting according to an ORDER BY clause.

• COUNT: returns the number of records in a table.

• FILTER: takes a set of records and returns the subset that meets a
series of restrictions.

• FIRST ROW: returns only the first record of a query

Oracle SQL Optimization Javier Navarro Grau Page 16 of 29


• FOR UPDATE: retrieves and locks a set of records, in case it is necessary
make some modification to them.

• AND-EQUAL: it combines several sets of ROWIDs and returns the intersection between
they, removing duplicates.

• HASH JOIN: operation of combining two sets of records.

• MERGE JOIN: operation of combining two sets of records, previously


sorted. It can have the OUTER option, among others.

• NESTED LOOPS: operation of combining two sets of records. It can


to have the OUTER option, among others.

• UNION: this operation takes two sets of records and returns their union,
removing duplicate records.

• CONCATENATION: this operation takes two sets of records and returns their
union, without eliminating duplicates.

• INTERSECTION: takes two sets of records and returns their intersection.

• MINUS: takes two sets of records and returns the records of the first that do not
be in the second, eliminating duplicates.

• CONNECT BY: retrieves a set of records in hierarchical order.

EXPLAIN PLAN command

The EXPLAIN PLAN command is the creator of the data in the PLAN_TABLE.
The easiest way to use it is:

EXPLAIN PLAN FOR statement;

This instruction calculates the execution plan for the statement and stores it in the
PLAN_TABLE. Since the statement identifier that may have been is not known.
could generate, it can be searched in PLAN_TABLE using the TIMESTAMP column,
approximately, by the date and time. To give a known sentencing identifier:

EXPLAIN PLAN SET STATEMENT_ID = 'identifier'


FORsentence;

In this way, the records from PLAN_TABLE can be retrieved through the
sentence identification column. Since the records of PLAN_TABLE, for a
determined sentence, they form a tree, the best way to visualize them is through a
SELECT with the CONNECT BY option:

SELECT LPAD(' ', LEVEL - 1) || ' ' || OPERATION || ' ' ||


OPTIONS || ' ' || OBJECT_NAME PLAN
FROM PLAN_TABLE
CONNECT BY PRIOR ID = PARENT_ID
AND PRIOR STATEMENT_ID = STATEMENT_ID

Oracle SQL Optimization Javier Navarro Grau Page 17 of 29


START WITH ID = 0
AND STATEMENT_ID = 'identifier';

This statement visualizes the database operations of a statement, in


hierarchical form, starting from the root and indenting the successive 'child' operations.

Rule-Based Optimization

Introduction to Rule Optimization

The rule-based optimizer has been the main optimization method of


Oracle until the cost-based optimizer, introduced in version 7, has been
gaining in performance. Currently, the use of the optimizer is not recommended.
based on rules, except for applications originally developed on Oracle 6 or
previous versions, or explicitly for this optimizer on versions 7 and
later.

The INIT.ORA parameter called OPTIMIZER_MODE determines the choice


from the optimizer. If it has the value RULE, the rule-based optimizer is always used.
If it has the value CHOOSE, the cost-based optimizer is used, unless there is none.
statistics about the tables, and no 'hints' have been indicated in the statements (then it
use the rule-based one).

The method used by the rule-based optimizer is as follows: it analyzes


the SQL statement in question, obtaining several possible execution plans. It
they classify these plans based on the ranking of their operations, and the plan with is chosen.
lower ranking. The operations ranking has been created by Oracle, based on data from
average CPU times, number of Input/Output operations, etc., for each type of
operation.

Access paths to the data

The ranking created by Oracle for data access pathways is,


from lowest to highest (the smaller the ranking, the better):

1. Unique record, by ROWID: it is obtained by explicitly searching.


by ROWID, or with the WHERE CURRENT OF clause.
2. Unique record, by cluster combination: achieved by combining tables
from the same cluster, to obtain a single record, using only
cluster key columns.
3. Unique record, by hash cluster key with unique or primary key: it
obtain using the columns of a hash cluster, to achieve a unique
registry.
4. Unique record, by unique or primary key: is achieved using in the
WHERE clause all columns of a unique index or primary key, in
conditions of equality, joining them with AND operators, so that it
retrieve a single record.
5. Cluster combination: it is achieved by combining tables stored in the
same cluster, through equality of the columns of the cluster key.

Optimization of Oracle SQL Javier Navarro Grau Page 18 of 29


6. Hash cluster key: it is obtained using the columns of the key of a
cluster hash created on the table.
7. Indexed cluster key: it is achieved by using all the columns of a
indexed cluster key.
8. Composite index: is obtained by using all the columns of an index
composed of more than one column, under conditions of equality.
9. Single column index: it is achieved by using, under equal conditions,
the columns of one or more single column indexes.
10. Restricted range of indexed columns: it is achieved when
they specify one or more columns of an index, in such a way that it restricts a
data range (e.g. with the BETWEEN operator).
11. Unrestricted range of indexed columns: it is achieved when
they specify one or more columns of an index, but it is not restricted to a range
data closed.
12. Combination of ordered sets: it is achieved when a join is performed.
between two tables that are not part of a cluster, through columns in
conditions of equality. Both tables are ordered by the columns of the join, and
then they merge to obtain the combination of both.
13.MAX or MIN of indexed columns: it is obtained by searching for the MAX or MIN of
the first column of an index, if there are no other conditions that limit it
dataset.
14.ORDER BY indexed columns: it is achieved using in a clause
ORDER BY the first columns of an index.
15. Full access to table: it is the last access path within the ranking.

SQL Statement Adjustment. SQL Trace and TKPROF Utility


The EXPLAIN PLAN statement allows for the a priori study of SQL statements,
showing the database operations that it breaks down into. This can give
indications of possible inefficiencies, but does not help in situations where a module or
reports a slow response, and it is not known which of the SQL statements being executed is the one.
responsible. For these situations, Oracle provides SQL tracing, a mechanism
for collecting information about the execution of sentences in the database, and the
TKPROF utility, a program that interprets the raw trace result and produces
execution plans and statistics.

The SQL trace can be activated for a specific Oracle session, or for the
complete Oracle instance. The load on the database server is minimal
for a single session with tracing enabled, but activate tracing for the entire instance
it may require up to 25% of CPU time, and a large amount of disk space for
collect the raw output of the trace.

Activate the Initialization Parameters

The first step to use the trace is to assign values to the corresponding parameters.
from INIT.ORA. The main parameters are:

• TIMED_STATISTICS: can have the values TRUE or FALSE. If it is TRUE, the trace of
SQL will collect information on the execution times of statements, as well as others.
information that it always collects. As a drawback, the trace will still have a weight.
greater in CPU time and input/output.

Oracle SQL Optimization Javier Navarro Grau Page 19 of 29


• MAX_DUMP_FILE_SIZE: sets the maximum possible size (in system blocks
operational) of the files generated by the SQL trace. If sessions are going to be analyzed
long-lasting, with a large number of SQL statements, it will be necessary to increase
this parameter, to prevent the produced files from being truncated.
• indicates the directory where the trace files will be created
corresponding to the analyzed sessions. It can be altered at the session level.
through ALTER SYSTEM.

Activate the trace

To activate tracing, it is necessary to set the SQL_TRACE parameter to TRUE.


This can be done in the INIT.ORA file, to enable tracing throughout the instance, or to
session level, with the possibilities:

ALTER SYSTEM SET SQL_TRACE = TRUE;

BEGIN
DBMS_SESSION.SET_SQL_TRACE( TRUE );
END;
/

From the moment the trace is activated for a session, it begins to be written.
in a file corresponding to this all the information about the sentences that are going
running, until the moment the session ends, or the trace is deactivated with the
sentences :

ALTER SYSTEM SET SQL_TRACE = FALSE;

BEGIN
DBMS_SESSION.SET_SQL_TRACE( FALSE );

Formatting the trace with TKPROF

Once the trace of a session has been made, it is necessary to identify the trace file.
corresponding, in the target trace directory. It is usually enough to look at the date and
time of the last created files, searching for one that matches the date and time of
completion of the session in question. Alternatively, in case of multiple users
simultaneously performing traces, the USER_DUMP_DEST directory can be changed to
session level.

The TKPROF utility takes a trace file as input and produces a report.
formatted, according to the additional options indicated. The syntax of
TKPROF is the following:

Oracle SQL Optimization Javier Navarro Grau Page 20 of 29


TKPROF input-file output-file options

Where:

• input-file is the file generated by the SQL trace


• output-file is the name of the file that TKPROF will create
• options can be one or several of the following:
• SORT=parameters, which indicates by which parameters to sort the
different SQL statements. The available parameters are the times
of the CPU, input/output operations, block reads, etc., in
each stage of execution (parse, execute & fetch).
• PRINT=n, which indicates how many SQL statements to display in the report. It is
useful when combined with the previous one.
• INSERT=file, to create a SQL file that would be used to save
in the database the generated statistics.
• SYS=YES or SYS=NO, indicating whether the statements should be interpreted or not.
from recursive SQL produced by the database itself.
• USER, indicates that an EXPLAIN PLAN will be performed for
each SQL statement, in the schema of the specified user, will be displayed
the corresponding execution plan in the file created by TKPROF.

Interpret the output file

For each SQL statement collected in the trace file, TKPROF emits a
report with:

• Full text of the SQL sentence;


• Execution plan corresponding to the number of records processed by
each operation;
• Statistics of each stage of SQL statement execution (interpretation,
execution and collection of records), as well as CPU times
elapsed, the input/output performed, and the number of times it has been
executed.

In addition, overall totals for all variables are shown. To interpret


correctly the result of TKPROF, it is advisable to order the result (by the
parameter SORT), based on CPU times or input/output operations, to highlight
the most costly operations. When optimizing a specific SQL statement that
It has been detected as costly, its cost should be put into perspective considering the
number of times it is executed. A small improvement in a statement that is executed a
a large number of times, or a variable number of times, may be more important to the
longer, that an important improvement in a more expensive sentence that executes a number
a little bit of times.

Tabular Statistics

TKPROF lists the statistics in the form of rows and columns. Each row is
corresponds to a stage of the SQL statement processing:

Optimization of Oracle SQL Javier Navarro Grau Page 21 of 29


• PARSE: at this stage, the statement is translated into an execution plan, and it
check the existence of the involved objects

• EXECUTE: at this stage, the database manager executes the statement. In


data manipulation statements, the update is performed. In statements
from the query (SELECT), the queried statements are identified.

• FETCH: in the case of query statements, in this stage the results are returned
records to the process that has sent the SQL statement to the database manager
data.

In addition, another row is included with the combined total of the three stages. The columns of
each row is:

• COUNT: Number of times the stage in question has been executed.

• CPU: Total CPU time for the stage (only if TIMED_STATISTICS is TRUE).

• ELAPSED: Total time elapsed for the stage (if TIMED_STATISTICS).

• DISK: Total number of physical blocks read in the stage.

• Total number of buffers retrieved in consistent mode for the stage. This
way is usually used for queries.

• CURRENT: Total number of buffers retrieved in current mode for the stage. This
mode is usually used for updates.

• ROWS: Total number of records processed in the stage. In statements of


manipulation, the updated records appear in the EXECUTE stage. In queries,
in the FETCH stage.

When interpreting the information about times, it must be taken into account that the resolution is of
a hundredth of a second, so it can be significant, especially in sentences of
very fast execution, that is executed many times. The information about used buffers is
more reliable.

Store statistics in the Database

It is possible, through a parameter of the TKPROF command, to generate a file of


SQL statements that, when executed in a database schema, create a table,
called TKPROF_TABLE, and insert the corresponding records for the trace data
processed. Some of the fields in this table are:

• the processed SQL statement.

• the date of insertion of the record in the database.

• the level of recursion of the execution of the statement. The value 0 indicates
a statement executed by the user. A higher value indicates a statement
executed by the database itself to obtain the result of a
lower court ruling.

Optimization of Oracle SQL Javier Navarro Grau Page 22 of 29


• PARSE_%: values corresponding to the PARSE phase.

• EXE_%: values corresponding to the EXECUTE phase.

• FETCH_%: values corresponding to the FETCH phase.

The AUTOTRACE feature of SQL*PLUS


The SQL*Plus tool provides the ability to easily obtain the plan of
execution and statistics on the execution of SQL statements, as they are
they are being introduced. With the command:

SET AUTOTRACE ON

the automatic trace feature is activated. After the execution of each


sentence, the execution plan is shown, and statistics about the execution. With the option
OFF, automatic tracing is disabled. Other options are:

SET AUTOTRACE ON EXPLAIN

SET AUTOTRACE ON STATISTICS

With the first one, only the display of the execution plan is activated. With the
second, only the visualization of the statistics. An example of the statistics
produced is :

Statistics
----------------------------------------------------------
0 recursive calls
0 db block gets
1055 consistent gets
0 physical reads
0 redo size
6971 bytes sent via SQL*Net to client
1416 bytes received via SQL*Net from client
11 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
143 rows processed

Manual adjustment of statements: The HINTS

Purpose of the Hints

The designer or programmer of an application can know information about the


data that is not available for the Oracle optimizer (About its current distribution
or future, about selectivity of indices, etc). Based on this information, you can choose a
more efficient execution plan than the optimizer. For this case, Oracle provides the
hints, a mechanism for the programmer to convey this

Oracle SQL Optimization Javier Navarro Grau Page 23 of 29


information to the Cost-Based Optimizer, to force it to use an execution plan
alternative.

Suggestions are provided as comments in SQL statements, so that


they do not affect the code that should be executed on databases without these
features. The comment-suggestion is included immediately after the
keyword INSERT, UPDATE, DELETE, and SELECT. If they are not entered correctly, or
they have no meaning, they are ignored, without the database returning an error.

In the same comment, multiple suggestions can be introduced, starting with


a plus sign, and separating successive suggestions with spaces.

Comments to decide on the Optimization method

To decide the optimization method of a specific statement, the used


following hints, equivalent to values of the parameter OPTIMIZER_MODE:

• /*+ ALL_ROWS */ : equivalent to the value ALL_ROWS


• /*+ FIRST_ROWS(n) */ : equivalent to the FIRST_ROWS_n value
• /*+ CHOOSE */ : equivalent to the CHOOSE value
• /*+ RULE */ : equivalent to the RULE value

Comments to decide on the Access method

To determine the access method for a table, the following are used
suggestions :

• FULL SCAN on the indicated table.


• /*+ ROWID(table) */ : access by ROWID on the indicated table.
• /*+ CLUSTER(table) */ : clustered access to the table.
• /*+ HASH(table) */ : hash access to the table.
• /*+ INDEX(index table) */ : access through a specific index to the table.
• /*+ INDEX_ASC(table index) */ : ascending access by a given index
to the table.
• /*+ INDEX_COMBINE(table indexes) */ : access through multiple indexes to the table.
• /*+ INDEX_DESC(table index) */ : descending access for a certain
index to the table.
• /*+ INDEX_FFS(index table) */ : FAST FULL INDEX access for the table.
• /*+ NO_INDEX(table index) */ : disables the use of the indicated indexes.
• /*+ AND_EQUAL(table indexes) */ : performs an AND-EQUAL access over several
table indices.

Comments to decide the order of combination

To vary the order of table combinations, Oracle provides the hints:

Optimization of Oracle SQL Javier Navarro Grau Page 24 of 29


• /*+ ORDERED */ : indicates that the order of joining the tables must be the
indicated in the FROM clause. If not specified, the optimizer will choose the order
what is best for you.
• /*+ STAR */ : indicates a star join, where the largest table
it is the last one on the list of tables to combine.

Comments to decide on the combination method

To decide the method of combining the tables, there are suggestions:

• /*+ USE_NL(table1 table2) */ : indicates a Nested Loop Join between the tables table1
and table2, with the inner table table1.
• /*+ USE_MERGE(table1 table2) */ : indicates a Sort Merge Join between the tables
table1 and table2.
• /*+ USE_HASH(table1 table2) */ : indicates a Hash Merge Join between the tables.

Comments for parallel execution

The following hints allow for the parallel execution of queries:

• /*+ PARALLEL(table, number) */ : indicates that up to a certain number of


parallel servers can work on accessing the table.
• /*+ NO_PARALLEL(table) */: indicates a table on which parallel execution should not be performed
parallel accesses.

Additional comments

• /*+ CACHE(table) */ : indicates that the blocks retrieved from the table in question
be stored in the cache with high priority, so that they are not
quickly discarded. Useful for small tables that are frequently used.
• /*+ NO_CACHE(table) */ : indicates that priority should not be given to the cache for the
blocks of the indicated table.
• /*+ UNNEST */ : indicates that transformations can be performed on
subqueries in combinations with the main tables.
• /*+ NO_UNNEST */ : indicates that transformations cannot be performed on
subqueries.
• /*+ ORDERED_PREDICATES */ : indicates that the conditions of the clause
WHERE they must be executed in the order in which they have been indicated.

Materialized Views

Introduction

Materialized views are database objects that contain the result


from a query, which may reference objects from the same database, or from
remote databases. They allow for greater efficiency, as they contain the result of

Optimization of Oracle SQL Javier Navarro Grau Page 25 of 29


complex queries, with the drawback of requiring space in the database, and
maintenance time, for the periodic refreshing of its content, so that it is
updated.

Creation of materialized views

To create a materialized view in a specific schema, the most


simple es :

CREATE MATERIALIZED VIEW view-name AS query;

This definition can include storage specifications, just like


in the definition of tables and indexes.

Refreshing materialized views

In the definition of a materialized view, the refresh frequency can be specified.


update of your content :

CREATE MATERIALIZED VIEW view-name


REFRESH type of refreshment
START WITH start-date NEXT next-date
AS inquiry;

The type of refresh can be FAST or COMPLETE. In order to


use a quick refresh, there must be a record of the materialized view, defined on
the source table of the materialized view. In complex queries, or if it is not defined
registration, a complete refresh may be mandatory.

The start date and next date are valid Oracle expressions that are evaluated
at the time of creation, and in successive refreshes, to calculate the next date in
the one that will take place.

The instruction to create a materialized view on a table is:

CREATE MATERIALIZED VIEW LOG ON table-name;

Storage specifications can be included for the record. In these


records store the changes that the indicated table undergoes, so that when
a materialized view that references it performs a quick refresh, it just has to
take into account the changes indicated in the record, since its last refresh date.

Rewriting Queries
When the optimizer analyzes a user query and finds that it is
compatible with the query associated with a materialized view, the user's query
it can be rewritten in terms of the materialized view, to take advantage of it. At
doing this, performance is improved, since part of the result has already been calculated with
previousness. Depending on the cost of the rewriting and the additional conditions that
It is necessary to apply to the materialized view, one can opt for rewriting.

Oracle SQL Optimization Javier Navarro Grau Page 26 of 29


In order for query rewriting to be enabled, it is necessary for the parameter
the INIT.ORA parameter QUERY_REWRITE_ENABLED should have the value TRUE.

Oracle SQL optimization Javier Navarro Grau Page 27 of 29


Stability of Plans
The stability of plans prevents changes in the database environment.
affect the performance in the execution of applications. The 'changes in the environment' can
make changes to the optimizer statistics, changes to the configuration of
optimizer, or in parameters that affect the size of memory structures of the database
of data, such as SORT_AREA_SIZE, or others. The utility of the stability of plans is in
applications where a change in performance cannot be risked.

The stability of plans preserves the execution plans of SQL statements.


the applications in stored outlines. When a ...
outline for a statement, and it is indicated to the optimizer to use it, it retrieves the
outline and generate an equivalent execution plan, disregarding the most information
current of the database. In this way, it becomes possible to immunize SQL statements
whatever is desired, regarding future changes in the state of the database.

The stability of plans is essentially contrary to the optimization method.


based on costs, since it tries to use the most recent information on the basis of
data, while stability requires the use of selected execution plans in a
past time, which may have lost efficiency. One should try to find a
balance between both extremes, in the development of applications.

Creation of Outlines for Stability of Plans

An Outline consists of a set of hints equivalent to the execution plan that


wants to store, for a certain statement. When executing a statement with a
outline created, the optimizer gathers its hints and uses them to create the execution plan,
which will be equivalent to the original.

To activate the creation of outlines for the statements executed in a session, you
use the CREATE_STORED_OUTLINES parameter of ALTER SESSION.

ALTER SESSION SET CREATE_STORED_OUTLINES = TRUE;

Until the end of the session, or until outline creation is disabled by giving the
a FALSE value for the parameter will generate an outline for each unique statement executed.
One alternative is to generate an outline for a single sentence, with the command:

CREATE OUTLINEname
FOR CATEGORY
ONsentence;

Oracle allows viewing the outlines stored by the user in the view
USER_OUTLINES, and the hints of each outline in the USER_OUTLINE_HINTS view. The
the main fields of USER_OUTLINES are:

• NAME : Assigned name to the outline


• CATEGORY : Outline Category
• Date and time of outline creation

Optimization of Oracle SQL Javier Navarro Grau Page 28 of 29


• VERSION: Database version for creating the outline
• SQL text of the original statement

The main fields of USER_OUTLINE_HINTS are:

• NAME : Assigned name to the outline


• Node
• STAGE : Stage
• Position in the join
• hint for the optimizer

Use of Outlines with Cost-Based Optimization

To use the stored outlines, it is necessary that the


cost-based optimization, and that the parameter USE_STORED_OUTLINES has the
value TRUE, in which case the DEFAULT category outlines are used, or the name of
a category of hints, in which case the outlines of that category will be used. For
use an outline, the optimizer requires that the SQL statement text is identical to the
from the original sentence, so it is advisable to use a consistent style.

Oracle SQL Optimization Javier Navarro Grau Page 29 of 29

You might also like