Oracle SQL Tuning Steps
Oracle SQL Tuning Steps
Oracle SQL Tuning Steps
htm
The acronym SQL stands for Structured Query Language. SQL is an industry
Remote DBA standard database query language that was adopted in the mid-1980s. It should
Oracle Tuning not be confused with commercial products such as Microsoft SQL Server or open
Emergency 911 source products such as MySQL, both of which use the acronym as part of the
RAC Support title of their products.
Apps Support
Analysis Do this before you start individual SQL statement tuning
Design
Implementation This broad-brush approach can save thousands of hours of tedious SQL tuning
Oracle Support because you can hundreds of queries at once. Remember, you MUST do this
first, else later changes to the optimizer parameters or statistics may un-tune your
SQL.
SQL Tuning
Security
Oracle UNIX
Oracle Linux
Monitoring
Remote support
Remote plans
Remote services
Application Server
Applications
Oracle Forms
Oracle Portal
App Upgrades
SQL Server
Oracle Concepts
Software Support
Remote Support
Development
Implementation
Remember, you must ALWAYS start with system-level SQL tuning, else later
changes might undo your tuned execution plans:
Consulting Staff Optimize the server kernel - You must always tune your disk and
Consulting Prices network I/O subsystem (RAID, DASD bandwidth, network) to optimize
Help Wanted! the I/O time, network packet size and dispatching frequency.
Adjusting your optimizer statistics - You must always collect and store
optimizer statistics to allow the optimizer to learn more about the
Oracle Posters distribution of your data to take more intelligent execution plans. Also,
Oracle Books histograms can hypercharge SQL in cases of determining optimal table join
Oracle Scripts order, and when making access decisions on skewed WHERE clause
Ion predicates.
Excel-DB
Adjust optimizer parameters - Optimizer optimizer_mode,
optimizer_index_caching, optimizer_index_cost_adj.
Once the environment, instance, and objects have been tuned, the Oracle
administrator can focus on what is probably the single most important aspect of
tuning an Oracle database: tuning the individual SQL statements. In this final
article in my series on Oracle tuning, I will share some general guidelines for
tuning individual SQL statements to improve Oracle performance.
Oracle SQL tuning is a phenomenally complex subject. Entire books have been
written about the nuances of Oracle SQL tuning; however, there are some general
guidelines that every Oracle DBA follows in order to improve the performance of
their systems. Again, see the book "Oracle Tuning: The Definitive Reference",
for complete details.
The goals of SQL tuning focus on improving the execution plan to fetch the rows
with the smallest number of database "touches" (LIO buffer gets and PIO
physical reads).
These are the goals of SQL tuning in a nutshell. However, they are deceptively
simple, and to effectively meet them, we need to have a through understanding of
the internals of Oracle SQL. Let's begin with an overview of the Oracle SQL
optimizers.
One of the first things the Oracle DBA looks at is the default optimizer mode for
the database. The Oracle initialization parameters offer many cost-based
optimizer modes as well as the deprecated yet useful rule-based hint:
The cost-based optimizer uses statistics that are collected from the table using
the analyze table command. Oracle uses these metrics about the tables in order
to intelligently determine the most efficient way of servicing the SQL query. It is
important to recognize that in many cases, the cost-based optimizer may not
make the proper decision in terms of the speed of the query. The cost-based
optimizer is constantly being improved, but there are still many cases in which
the rule-based optimizer will result in faster Oracle queries.
Prior to Oracle 10g, Oracle's default optimizer mode was called choose. In the
choose optimizer mode, Oracle will execute the rule-based optimizer if there are
no statistics present for the table; it will execute the cost-based optimizer if
statistics are present. The danger with using the choose optimizer mode is that
problems can occur in cases where one Oracle table in a complex query has
statistics and the other tables do not.
Starting in Oracle 10g, the default optimizer mode is all_rows, favoring full-table
scans over index access. The all_rows optimizer mode is designed to minimize
computing resources and it favors full-table scans. Index access (first_rows_n)
adds additional I/O overhead, but they return rows faster, back to the originating
query:
Note: Staring in Oracle9i release 2, the Oracle performance tuning guide says
that the first_rows optimizer mode has been deprecated and to use first_rows_n
instead.
When only some tables contain CBO statistics, Oracle will use the cost-based
optimization and estimate statistics for the other tables in the query at runtime.
This can cause significant slowdown in the performance of the individual query.
In sum, the Oracle database administrator will always try changing the optimizer
mode for queries as the very first step in Oracle tuning. The foremost tenet of
Oracle SQL tuning is avoiding the dreaded full-table scan. One of the hallmarks
of an inefficient SQL statement is the failure of the SQL statement to use all of
the indexes that are present within the Oracle database in order to speed up the
query.
Of course, there are times when a full-table scan is appropriate for a query, such
as when you are doing aggregate operations such as a sum or an average, and the
majority of the rows within the Oracle table must be read to get the query results.
The task of the SQL tuning expert is to evaluate each full-table scan and see if
the performance can be improved by adding an index.
In most Oracle systems, a SQL statement will be retrieving only a small subset of
the rows within the table. The Oracle optimizers are programmed to check for
indexes and to use them whenever possible to avoid excessive I/O. However, if
the formulation of a query is inefficient, the cost-based optimizer becomes
confused about the best access path to the data, and the cost-based optimizer will
sometimes choose to do a full-table scan against the table. Again, the general rule
is for the Oracle database administrator to interrogate the SQL and always look
for full-table scans.
For the full story, see my book "Oracle Tuning: The Definitive Reference" for
details on choosing the right optimizer mode.
Many people ask where they should start when tuning Oracle SQL. Tuning
Oracle SQL is like fishing. You must first fish in the Oracle library cache to
extract SQL statements and rank the statements by their amount of activity.
The SQL statements will be ranked according the number of executions and will
be tuned in this order. The executions column of the v$sqlarea view and the
stats$sql_summary or the dba_hist_sql_summary table can be used to locate the
most frequently used SQL. Note that we can display SQL statements by:
CPU secsThis identifies the SQL statements that use the most processor
resources.
To see the output of an explain plan, you must first create a plan table. Oracle
Most relational databases use an explain utility that takes the SQL statement as
input, runs the SQL optimizer, and outputs the access path information into a
plan_table, which can then be interrogated to see the access methods. Listing 1
runs a complex query against a database.
This syntax is piped into the SQL optimizer, which will analyze the query and
store the plan information in a row in the plan table identified by RUN1. Please
note that the query will not execute; it will only create the internal access
information in the plan table. The plan tables contains the following fields:
Now that the plan_table has been created and populated, you may interrogate it to
see your output by running the following query in Listing 2.
plan.sql - displays contents of the explain plan table
SET PAGES 9999;
SELECT lpad(' ',2*(level-1))||operation operation,
options,
object_name,
position
FROM plan_table
START WITH id=0
AND
statement_id = 'RUN1'
CONNECT BY prior id = parent_id
AND
statement_id = 'RUN1';
Listing 3 shows the output from the plan table shown in Listing 1. This is the
execution plan for the statement and shows the steps and the order in which they
will be executed.
SQL> @list_explain_plan
OPERATION
-------------------------------------------------------------------------------------
OPTIONS OBJECT_NAME POSITION
------------------------------ -------------------------------------------------------
SELECT STATEMENT
SORT
GROUP BY 1
CONCATENATION 1
NESTED LOOPS 1
TABLE ACCESS FULL PLANSNET 1
TABLE ACCESS BY ROWID DETPLAN 2
INDEX RANGE SCAN DETPLAN_INDEX5 1
NESTED LOOPS
From this output, we can see the dreaded TABLE ACCESS FULL on the
PLANSNET table. To diagnose the reason for this full-table scan, we return to
the SQL and look for any plansnet columns in the WHERE clause. There, we see
that the plansnet column called mgc is being used as a join column in the
query, indicating that an index is necessary on plansnet.mgc to alleviate the
full-table scan.
While the plan table is useful for determining the access path to the data, it does
not tell the entire story. The configuration of the data is also a consideration. The
SQL optimizer is aware of the number of rows in each table (the cardinality) and
the presence of indexes on fields, but it is not aware of data distribution factors
such as the number of expected rows returned from each query component.
For those SQL statements that possess a sub-optimal execution plan, the SQL
will be tuned by one of the following methods:
Rewriting the SQL in PL/SQL. For certain queries this can result in more
than a 20x performance improvement. The SQL would be replaced with a
call to a PL/SQL package that contained a stored procedure to perform the
query.
Among the most common tools for tuning SQL statements are hints. A hint is a
directive that is added to the SQL statement to modify the access path for a SQL
query.
Troubleshooting tip! For testing, you can quickly test the effect of another optimizer parameter value at the
query level without using an alter session command, using the new opt_param SQL hint:
Oracle publishes many dozens of SQL hints, and hints become increasingly more
complicated through the various releases of Oracle and on into Oracle.
Note: Hints are only used for de-bugging and you should adjust your optimizer
statistics to make the CBO replicate the hinted SQL. Lets look at the most
common hints to improve tuning:
Self-order the table joins - If you find that Oracle is joining the tables together
in a sub-optimal order, you can use the ORDERED hint to force the tables to be
joined in the order that they appear in the FROM clause. See
One of the historic problems with SQL involves formulating SQL queries.
Simple queries can be written in many different ways, each variant of the query
producing the same resultbut with widely different access methods and query
speeds.
A standard join:
SELECT *
FROM STUDENT, REGISTRATION
WHERE
STUDENT.student_id = REGISTRATION.student_id
AND
REGISTRATION.grade = 'A';
A nested query:
SELECT *
FROM STUDENT
WHERE
student_id =
(SELECT student_id
FROM REGISTRATION
WHERE
grade = 'A'
);
A correlated subquery:
SELECT *
FROM STUDENT
WHERE
0 <
(SELECT count(*)
FROM REGISTRATION
WHERE
grade = 'A'
AND
student_id = STUDENT.student_id
);
Lets wind up with a review of the basic components of a SQL query and see
how to optimize a query for remote execution.
Space doesnt permit me to discuss every detail of Oracle tuning, but I can share
some general rules for writing efficient SQL in Oracle regardless of the optimizer
that is chosen. These rules may seem simplistic but following them in a diligent
manner will generally relieve more than half of the SQL tuning problems that are
experienced:
Use minus instead of EXISTS subqueries - Some say that using the
minus operator instead of NOT IN and NOT Exists will result in a faster
execution plan.
Below we combine the outer join with a NULL test in the WHERE
clause without using a sub-query, giving a faster execution plan.
select b.book_key from book b, sales s
where
b.book_key = s.book_key(+)
and
s.book_key IS NULL;
Index your NULL values - If you have SQL that frequently tests for
NULL, consider creating an index on NULL values. To get around the
optimization of SQL queries that choose NULL column values (i.e. where
emp_name IS NULL), we can create a function-based index using the null
value built-in SQL function to index only on the NULL columns.
Don't fear full-table scans - Not all OLTP queries are optimal when they
uses indexes. If your query will return a large percentage of the table rows,
a full-table scan may be faster than an index scan. This depends on many
factors, including your configuration (values for
db_file_multiblock_read_count, db_block_size), query parallelism and the
number of table/index blocks in the buffer cache.
Use those aliases - Always use table aliases when referencing columns.
Conclusion
This article should provide you with a good overall background in Oracle SQL
tuning, although there are many details that are too involved to discuss in one
article.
Note: This Oracle documentation was created as a support and Oracle training
reference for use by our DBA performance tuning consulting professionals. Feel
free to ask questions on our Oracle forum.
Burleson Consulting
The Oracle of Database Support