Wednesday, August 31, 2005

Essential performance forecasting, part 1

Craig Shallahamer
16 Aug 2005

SearchOracle: Oracle tips, scripts, and expert advice

Craig's Corner
Insights on Oracle technologies and trends by Craig Shallahamer

At a basic level, forecasting Oracle performance is absolutely essential for every DBA to understand and perform. When performance begins to degrade, it's the DBA who hears about it, and it's the DBA who's supposed to fix it. It's the DBA who has the most intimate knowledge of the database server, so shouldn't they be able to forecast performance? When a bunch of new users are going be added to a system, it's the DBA who is quickly asked, "That's not going to be a problem, is it?" Therefore, DBAs need the ability to quickly forecast performance. Low precision forecasting can be done very quickly and it is a great way to get started forecasting Oracle performance.

The key metrics we want to forecast are utilization, queue length, and response time. With only these three metrics, as a DBA you can perform all sorts of low precision what-if scenarios. To derive the values, you essentially need 3 things:

- a few simple formulas
- some basic operating system statistics
- some basic Oracle statistics


Before you are inundated with the formulas, it's important to understand some definitions and recognize their symbols.

S : Time to service one workload unit. This is known as the service time or service demand. It is how long it takes the CPU to service a single transaction. For example, 1.5 seconds per transaction or 1.5 sec/trx. The best way to get the value for Oracle systems is to simply derive it.

U : Utilization or CPU busyness. It's commonly displayed as a percentage and that's how it works in this formula. For example, in the formula it should be something like 75% or 0.75, but not 75. A simple way to gather CPU utilization is simply running sar -u 60 1. This will give you the average CPU utilization over a 60 second period.

λ : Workload arrival rate. This is how many transactions enter the system per unit of time. For example, 150 transactions each second or 150 trx/sec. When working with Oracle, there are many possible statistics that can be used for the "transaction" arrival rate. Common statistics gathered from v$sysstat are logical reads, block changes, physical writes, user calls, logons, executes, user commits, and user rollbacks. You can also mix and match as your experience increases. For this paper, we will simply use user calls.

Q : Queue length. This is the number of transactions waiting to be serviced. This excludes the number of transactions currently being serviced. We will derive this value.

M : Number of CPUs. You can get this from the instance parameter cpu_count.

The CPU formulas for calculating averages are as follows:

U = ( S λ ) / M [Formula 1]

R = S / (1 - U^M) [Formula 2]

Q = ( MU / (1 - U^M) ) - M [Formula 3]


Before we dive into real-life examples, let's check these formulas out by doing some thought experiments.

Thought experiment 1. Using formula (1), if the utilization was 50% with 1 CPU, it should be 25% with 2 CPUs. And that's what the formula says. As you probably already figured out, scalability is not taken into consideration.

Thought experiment 2. Using formula (1), if we increased the arrival rate, CPU utilization would also increase.

Thought experiment 3. Using formula (1), if we used faster CPUs, the service time would decrease, then the utilization would also decrease.

Thought experiment 4. Using formula (2), if the utilization increased, the denominator would decrease, which would cause the response time to increase!

Thought experiment 5. This one's tricky, so take your time. Using formula (2), if the number of CPUs increased, the denominator would increase, which would cause the response time to decrease.

Thought experiment 6. Using formula (3), if the utilization increased, the denominator would decrease and the numerator would increase, which would cause the queue length to increase.

Now that you have a feel and some trust in the formulas, let's take a look at a real life example.

Example 1. Let's say for the last 60 seconds you gathered the average CPU utilization and the number of user calls from a two CPU Linux box. You found the average utilization was 65% and Oracle processed 750 user calls. The number of user calls each second is then 12.5 (i.e., 750/60 = 12.5).

Therefore,

S = 0.104 sec/call ; U = ( S λ ) / M ; 0.650 = ( S * 12.500 ) / 2

R = 0.180 sec/call ; R = S / (1 - U^M); R = 0.104 / ( 1 - 0.65^2 )

Q = 0.251 calls ; Q = ( MU / (1 - U^M) ) - M ; Q = ( 2*0.65/(1-0.65^2) ) - 2

The only number that is immediately useful to us is the queue length. There is, on average, less than one process waiting for CPU cycles. That's OK for performance and for our users. But there is some queuing occurring, so now would be a good idea to plan for the future!

The response time and service time calculations will become more useful when we recalculate them using a different configuration or workload scenario. For example, let's say your workload is expected to increase 15% each quarter. How many quarters do we have until response time significantly increases? For Example 2, we will see this demonstrated.

Example 2. Let's suppose performance is currently acceptable, but the DBA has no idea how long the situation is going to last. Assuming the worst case, workload will increase each quarter by 15%. Using the system configuration described in Example 1 and using our three basic formulas, here's the situation quarter by quarter.

Right away we can see that utilization is over 100% by the fourth quarter (i.e., 114%). This results in an unstable system because the queue length will always increase. The response time and queue length calculations also both go negative, indicating an unstable system.

The answer to the question, "When will the system run out of gas?" is something like, "Sometime between the first and second quarter." The answer is not the third quarter and probably not even the second quarter! While the system is technically stable in the second and third quarters, the response time has massively increased and by the third quarter there are typically 85 processes waiting for CPU power! Let's dig a little deeper.

Performance degradation occurs way before utilization reaches 100%. Our simple example shows that at 75% utilization, response time has increased by 33% and there is usually over one process waiting for CPU power. So while the system will technically function into the 3rd quarter, practically speaking it will not come close to meeting users expectations.

Based upon the above table, users are probably OK with the current performance. If you have done a good job setting expectations, they may be OK with performance into the first quarter. But once you get into the second quarter, with the utilization at 86%, the response time more than doubling, and over four processes waiting for CPU power, not matter what you do, your uses will be very, very unhappy.

So what are the options? There are many options at this point, but we'll save that for another article…sorry.

The forecast precision using the method described above is very low. This is because of a few reasons, some of which are; only one data sample was gathered, the forecasts were not validated, the workload was not carefully characterized, and our model only considered the CPU subsystem. When a more precise forecast is required, a product like HoriZone (horizone.orapub.com) is required. But many times a quick and low precision forecast is all that is necessary. When this is the case, you can get a general idea of the sizing situation using the formulas outlined above.

As you can see, with only a few basic formulas and some performance data, an amazing amount of useful forecasting can occur. Performance forecasting is an fascinating area that can expand a DBAs area of expertise, help answer those nagging questions we all get asked at 4:30pm on Fridays, and help anticipate poor performance.


About the Author
Craig Shallahamer has 18-plus years experience in IT. As the president of OraPub, Inc., his objective is to empower Oracle performance managers by "doing" and teaching others to "do" whole system performance optimization (reactive and proactive) for Oracle-based systems.

In addition to course development and delivery, Craig is a consultant who was previously involved with developing a landmark performance management product, technically reviews Oracle books and articles, and keynotes at various Oracle conferences.

To view more of Craig's work, visit www.orapub.com.

Wednesday, August 10, 2005

Script to show problem tablespaces

SearchOracle.com Brett Ogletree
02 Aug 2005


[Ed. note: This script is now corrected and has been tested on 8.1.7.4 and 9.2.0.6.0.]

I've seen a lot of scripts that tell you about all the tablespaces in a database, but very few show only the ones that are going to give you problems.

I've been using this script for a few years now and it has really saved me from dialing in at nights and on the weekends. I use it as a cursor for a procedure and have it build an e-mail and/or page notification that is sent to myself and others.

This script is useful because it drills down to what is going to give you a problem. I don't have a lot of time to wade through a reports to find out which tablespace is running out of space, this is short and sweet and lets me get on with my day. I've run the script on 8, 8i, and 9i. Just make sure you are using system or another user that can read the data dictionary.


SELECT space.tablespace_name, space.total_space, free.total_free,
ROUND(free.total_free/space.total_space*100) as pct_free,
ROUND((space.total_space-free.total_free),2) as total_used,
ROUND((space.total_space-free.total_free)/space.total_space*100) as pct_used,
free.max_free, next.max_next_extent
FROM
(SELECT tablespace_name, SUM(bytes)/1024/1024 total_space
FROM dba_data_files
GROUP BY tablespace_name) space,
(SELECT tablespace_name, ROUND(SUM(bytes)/1024/1024,2) total_free, ROUND(MAX(bytes)/1024/1024,2) max_free
FROM dba_free_space
GROUP BY tablespace_name) free,
(SELECT tablespace_name, ROUND(MAX(next_extent)/1024/1024,2) max_next_extent
FROM dba_segments
GROUP BY tablespace_name) NEXT
WHERE space.tablespace_name = free.tablespace_name (+)
AND space.tablespace_name = next.tablespace_name (+)
AND (ROUND(free.total_free/space.total_space*100) /*pct_free*/ < 10 OR next.max_next_extent > free.max_free)
/

Reader feedback

Perry W. writes: "This script is based on an Oracle7 mentality. It does not provide valid data if autoextend is used for datafiles. The column max_bytes must be used to identify how large a datafile can *potentially* grow. He must also account for the fact some datafiles may have autoextend on and some may not. Also, a monitor for disk space available must also be included in the monitoring infrastructure. This is a rookie script in my opinion and can provide misleading results with autoextend turned on.

Tuning: People, processes and technology

SearchOracle.com Jeremy Kadlec
31 May 2005


All too often, organizations attempt to resolve performance issues with a quick fix or magic bullet to keep the business moving ahead of the competition. The perception is that there is no time for planning, designing or testing a solution; you have to move from problem identification to immediately implementing the solution. Unfortunately, the reality is that accurate solutions derived in this manner are few and far between.

Quick fixes typically become long-term nightmares that no one wants to work on. It's only a matter of time before the IT team knows how fragile the system is and what is really required. To top it off, the quick fix is typically some other piece of software that "can just be integrated" and forgotten. In most cases, this is simply not possible.

It has been common knowledge for years that every IT solution consists of people, processes and technology. But when it comes to building a solution, those first two components are left in the dust by the idea that a single piece of technology is the solution. However, what is really necessary is to have your team and management support all three components and avoid shooting from the hip.

In this article, we will explore the components for properly leveraging people, processes and technology for performance tuning.

People: Trained, motivated and performance-tuned

In my opinion, people are the most important aspect of the triad because with good people, the correct processes and technology can be developed, tested and implemented. Without knowledgeable professionals focused on the issues, performance will continue to suffer. As such, I recommend focusing on the following:


Team -- Motivate a strong team to address performance-tuning needs. At a minimum, it should consist of developers, database administrators, network administrators, desktop technicians, testers and users.


Training -- Make sure the team is properly trained on the technology required to support the application from the front-end application all the way to the storage subsystems. Training in team building and knowledge sharing yields high-performance team members who are well aware of the challenges faced by other team members.


Time -- Our scarcest resource is time, but with proper time management we can achieve momentous results. Without the ability to manage your time well, you face insufficient time leading to pressure and stress. Vigilant time management gives you ample time to manage your workload. You do not want to be so busy that at the eleventh hour you realize an issue that was brought up two months earlier had been ignored because you only have brain cycles for the work that is right in front of you, thanks to ever-mounting demands.

Processes include well-known and lesser-known components

Building a process that meets your team's skill set and comfort level with performance-tuning needs is easier said then done. That's why I believe most "solutions" lack processes that address things like implementation, maintenance and support, upgrades, testing and troubleshooting. Do not make processes too complex. Break the work down into small manageable steps that can be distributed among team members.


Project management -- Address performance-tuning needs as a project, with a set of goals, start and end dates and, most importantly, managerial support for the project in terms of time and the members of the team. Most of the time, performance tuning is considered a side project to be worked on as time permits. Break this habit! Legitimize these needs.


Communication -- First and foremost, communicate your needs for completing the project. Identify, document and test the processes, implement them and learn from the experience and share the knowledge so the same performance-tuning issues are not re-created in the future.


Simplicity -- Build accurate and efficient processes and reuse them with the goal of distributing the work load among the team members. Don't risk having all of the knowledge in one person's head. This, too, is easier said then done. But after building a few processes, you will recognize opportunities to reuse processes and streamline the overall project.

Technology, remember, is one of three components

Do not pass by the first two components and proceed directly to a tool to solve your performance problems. A tool may help identify a performance bottleneck but will typically not be able to correct and validate the technical issue in your environment.


Components -- Keep in mind that the tool is a third component of the equation, not the overall solution. Once you find the right tool for the issue, the team may have to learn something new and processes may change.


Evaluation -- Make sure the technology meets your needs conceptually and practically. Bring the technology in-house and validate that it will meet user and IT expectations. Discuss the short- and long-term potential for the technology to be sure the plans and your expectations align and that support will be available when you need it.

Once you allocate the proper time for evaluation, training, and planning, then you can implement the solution in a timely manner -- while the information is fresh and the team can focus on the issues at hand. Then begin to reap the benefits of your team's efforts in terms of high-performing systems.



--------------------------------------------------------------------------------

Jeremy Kadlec is the principal database engineer at Edgewood Solutions, a technology services company delivering professional services and product solutions for Microsoft SQL Server. He has authored numerous articles and delivers frequent presentations at regional SQL Server users groups and nationally at SQL PASS. Kadlec is the SearchSQLServer.com Performance Tuning expert. Ask him a question here.

Tuesday, August 02, 2005

A script showing explain plan for currently running queries

Pachot Franck http://www.dba-village.com/village/dvp_scripts.ScriptDetails?ScriptIdA=2182

Script:
SET linesize 1000 pagesize 0 feedback OFF

SELECT /* tag F354R334A56N47C687K645P6A628C7638H608O658758T8 */
DECODE(id,0,'
=== SID,SERIAL: ('||sid||','||serial#||') USER: '||username||' , ROWS_PROCESSED: '||rows_processed||' , BUFFER_GETS: '||buffer_gets||'
=== PROGRAM: '||program ||' , MODULE: ' || s.MODULE||'
'||'
'||sql_text|| '
'||'
EXPLAIN PLAN: ',LPAD(''||depth||'.'||position||') ',6+2*depth,' '))||
INITCAP(operation||DECODE(options,NULL,'',' '||options||'')) ||
DECODE(object_name,NULL,'',' '||object_owner||'.'||object_name)||
DECODE(OBJECT#,NULL,'',DECODE(optimizer,'ANALYZED','',' not analyzed'))||
DECODE(partition_start,NULL,'',' partition '||partition_start||'->'||partition_stop||' ')||
DECODE(cardinality,NULL,'',' card='||DECODE(SIGN(cardinality-1000), -1, cardinality||'',DECODE(SIGN(cardinality-1000000), -1, ROUND(cardinality/1000)||'K',DECODE(SIGN(cardinality-1000000000), -1, ROUND(cardinality/1000000)||'M',ROUND(cardinality/1000000000)||'G')))) ||
DECODE(cost,NULL,' ',' cost='||DECODE(SIGN(cost-10000000), -1, cost||'',DECODE(SIGN(cost-1000000000), -1, ROUND(cost/1000000)||'M',ROUND(cost/1000000000)||'G'))) ||
DECODE(bytes,NULL,' ',' bytes='||DECODE(SIGN(bytes-1024), -1, bytes||'',DECODE(SIGN(bytes-1048576), -1, ROUND(bytes/1024)||'K',DECODE(SIGN(bytes-1073741824), -1, ROUND(bytes/1048576)||'M',ROUND(bytes/1073741824)||'G'))))||
DECODE(cpu_cost,NULL,' ',' cpu_cost='||DECODE(SIGN(cpu_cost-10000000), -1, cpu_cost||'',DECODE(SIGN(cpu_cost-1000000000), -1, ROUND(cpu_cost/1000000)||'M',ROUND(cpu_cost/1000000000)||'G'))) ||
DECODE(io_cost,NULL,' ',' io_cost='||DECODE(SIGN(io_cost-10000000), -1, io_cost||'',DECODE(SIGN(io_cost-1000000000), -1, ROUND(io_cost/1000000)||'M',ROUND(io_cost/1000000000)||'G'))) ||
DECODE(temp_space,NULL,' ',' temp='||DECODE(SIGN(temp_space-1024), -1, temp_space||'',DECODE(SIGN(temp_space-1048576), -1, ROUND(temp_space/1024)||'K',DECODE(SIGN(temp_space-1073741824), -1, ROUND(temp_space/1048576)||'M',ROUND(temp_space/1073741824)||'G'))))||
'' text
FROM v$session s,v$sql q,v$sql_plan p
WHERE s.sql_hash_value=q.hash_value AND q.users_executing>0 AND q.hash_value=p.hash_value AND q.child_number=p.child_number
AND sql_text NOT LIKE '%F354R334A56N47C687K645P6A628C7638H608O658758T8%'
ORDER BY buffer_gets,s.sid,s.serial#,p.hash_value,p.child_number,p.id;

Sample Output:
=== SID,SERIAL: (90,33387) USER: APP , ROWS_PROCESSED: 0 , BUFFER_GETS: 152
=== PROGRAM: sqlplus.exe , MODULE: test.sql

INSERT /*+ append nologging */ INTO FACTS subpartition (DWH_P_333_NLGROC) (dwh_tpr_id, dwh_sho_id, ...

EXPLAIN PLAN: Insert Statement cost=267970

1.1) Load As Select
2.1) View card=22M cost=267970 bytes=18G
3.1) Window Sort card=22M cost=267970 bytes=18G io_cost=267970 temp=42G
4.1) View card=22M cost=3693 bytes=18G
5.1) Union-All
6.1) Table Access Full APP.FACTS partition 1179->1179 card=14M cost=1895 bytes=1G io_cost=1895
6.2) Table Access Full APP.FACTS partition 1173->1173 card=8M cost=1798 bytes=321M io_cost=1798

Friday, March 11, 2005

Autotrace in SQLPLUS

http://asktom.oracle.com/~tkyte/article1/autotrace.html

Here is what I like to do to get autotrace working:
cd $oracle_home/rdbms/admin
log into sqlplus as system
run SQL> @utlxplan
run SQL> create public synonym plan_table for plan_table
run SQL> grant all on plan_table to public
exit sqlplus and cd $oracle_home/sqlplus/admin
log into sqlplus as SYS
run SQL> @plustrce
run SQL> grant plustrace to public You can replace public with some user if you want. by making it public, you let anyone trace using sqlplus (not a bad thing in my opinion).
About AutotraceYou can automatically get a report on the execution path used by the SQL optimizer and the statement execution statistics. The report is generated after successful SQL DML (that is, SELECT, DELETE, UPDATE and INSERT) statements. It is useful for monitoring and tuning the performance of these statements.
Controlling the ReportYou can control the report by setting the AUTOTRACE system variable. SET AUTOTRACE OFF - No AUTOTRACE report is generated. This is the
default.
SET AUTOTRACE ON EXPLAIN - The AUTOTRACE report shows only the optimizer
execution path.
SET AUTOTRACE ON STATISTICS - The AUTOTRACE report shows only the SQL
statement execution statistics.
SET AUTOTRACE ON - The AUTOTRACE report includes both the
optimizer execution path and the SQL
statement execution statistics.
SET AUTOTRACE TRACEONLY - Like SET AUTOTRACE ON, but suppresses the
printing of the user's query output, if any.
To use this feature, you must have the PLUSTRACE role granted to you and a PLAN_TABLE table created in your schema. For more information on the PLUSTRACE role and PLAN_TABLE table, see the AUTOTRACE variable of the SET command in Chapter 6 of the SQL*Plus Guide.
Execution PlanThe Execution Plan shows the SQL optimizer's query execution path.
Each line of the Execution Plan has a sequential line number. SQL*Plus also displays the line number of the parent operation.
The Execution Plan consists of four columns displayed in the following order: Column Name Description
------------------------------------------------------------------------

ID_PLUS_EXP Shows the line number of each execution step.
PARENT_ID_PLUS_EXP Shows the relationship between each step and its
parent. This column is useful for large reports.
PLAN_PLUS_EXP Shows each step of the report.
OBJECT_NODE_PLUS_EXP Shows the database links or parallel query servers
used.The format of the columns may be altered with the COLUMN command. For example, to stop the PARENT_ID_PLUS_EXP column being displayed, enter:
SQL> COLUMN PARENT_ID_PLUS_EXP NOPRINT
The default formats can be found in the site profile (for example, glogin.sql).
The Execution Plan output is generated using the EXPLAIN PLAN command. For information about interpreting the output of EXPLAIN PLAN, see the Oracle7 Server Tuning guide.
The following is an example of tracing statements for performance statistics and query execution path.
If the SQL buffer contains the following statement:
SQL> SELECT D.DNAME, E.ENAME, E.SAL, E.JOB
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO = D.DEPTNOThe statement can be automatically traced when it is run:
SQL> SET AUTOTRACE ON
SQL> /

DNAME ENAME SAL JOB
-------------- ---------- ---------- ---------
ACCOUNTING CLARK 2450 MANAGER
ACCOUNTING KING 5000 PRESIDENT
ACCOUNTING MILLER 1300 CLERK
RESEARCH SMITH 800 CLERK
RESEARCH ADAMS 1100 CLERK
RESEARCH FORD 3000 ANALYST
RESEARCH SCOTT 3000 ANALYST
RESEARCH JONES 2975 MANAGER
SALES ALLEN 1600 SALESMAN
SALES BLAKE 2850 MANAGER
SALES MARTIN 1250 SALESMAN
SALES JAMES 950 CLERK
SALES TURNER 1500 SALESMAN
SALES WARD 1250 SALESMAN

14 rows selected.
Execution Plan
-----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 MERGE JOIN
2 1 SORT (JOIN)
3 2 TABLE ACCESS (FULL) OF 'DEPT'
4 1 SORT (JOIN)
5 4 TABLE ACCESS (FULL) OF 'EMP'

Statistics
----------------------------------------------------------
148 recursive calls
4 db block gets
24 consistent gets
6 physical reads
43 redo size
591 bytes sent via SQL*Net to client
256 bytes received via SQL*Net from client
33 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
14 rows processed
Note: The output may vary depending on the version of the server to which you are connected and the configuration of the server.

Saturday, November 20, 2004

Analyze table revisite/Gather Statistics

DBMS_STATS Package
Description
The PL/SQL package DBMS_STATS lets you generate and manage statistics for cost-based optimisation. You can use this package to gather, modify, view, export, import, and delete statistics.
The DBMS_STATS package can gather statistics on indexes, tables, columns, and partitions, as well as statistics on all schema objects in a schema or database. The statistics-gathering operations can run either serially or in parallel (DATABASE/SCHEMA/TABLE only)
Procedure Name
Description
GATHER_TABLE_STATS
Collects table, column, and index statistics.
GATHER_INDEX_STATS
Collects index statistics.
GATHER_SCHEMA_STATS
Collects statistics for all objects in a schema.
GATHER_DATABASE_STATS
Collects statistics for all objects in a database.
GATHER_SYSTEM_STATS
Collects CPU and I/O statistics for the system.
Previous to 8i, you would be using the ANALYZE ... methods. However 8i onwards, using ANALYZE for this purpose is not recommended because of various restrictions; for example:
1. ANALYZE always runs serially.
2. ANALYZE calculates global statistics for partitioned tables and indexes instead of gathering them directly. This can lead to inaccuracies for some statistics, such as the number of distinct values.
3. ANALYZE cannot overwrite or delete some of the values of statistics that were gathered by DBMS_STATS.
4. Most importantly, in the future, ANALYZE will not collect statistics needed by the cost-based optimiser.


ANALYZE can gather additional information that is not used by the optimiser, such as information about chained rows and the structural integrity of indexes, tables, and clusters. DBMS_STATS does not gather this information.

SQL Sourceset echo on
set feed on
set timing on
execute dbms_stats.gather_table_stats (ownname => 'SCOTT'
, tabname => 'DEPT'
, partname=> null
, estimate_percent => 20
, degree => 5
, cascade => true);
execute dbms_stats.gather_schema_stats (ownname => 'SCOTT'
, estimate_percent => 20
, degree => 5
, cascade => true);
execute dbms_stats.gather_database_stats (estimate_percent => 20
, degree => 5
, cascade => true);
SQL Source - Dynamic MethodDECLARE
sql_stmt VARCHAR2(1024);
BEGIN
FOR tab_rec IN (SELECT owner,table_name
FROM all_tables WHERE owner like UPPER('&1')
) LOOP
sql_stmt := 'BEGIN dbms_stats.gather_table_stats (ownname => :1, tabname
=> :2,partname=> null, estimate_percent => 20, degree => 5 ,cascade => true); END;'
;
EXECUTE IMMEDIATE sql_stmt USING tab_rec.owner, tab_rec.table_name ;
END LOOP;
END;
/

DBMS_STATS in 9i

http://www.oracledba.co.uk/tips/9i_dbms_stats.htm

Oracle Optimizer: Moving to and working with CBO and other articles from Amar Kumar Padhi

http://www.databasejournal.com/article.php/1558281

http://www.databasejournal.com/features/oracle/article.php/10893_3098241_1

Monday, November 15, 2004

SQL Tuning Troubleshooting Suggestions

This document contains a number of potentially useful pointers for use when attempting to tune an individual SQL statement. This is a vast topic and this is just a drop in the ocean.


Contents: Possible Causes of Poor SQL Performance
=================================================

1. Poorly tuned SQL
2. Poor disk performance/disk contention
3. Unnecessary sorting
4. Late row elimination
5. Over parsing
6. Missing indexes/use of 'wrong' indexes
7. Wrong plan or join order selected
8. Import estimating statistics on tables
9. Insufficiently high sample rate for CBO
10. Skewed data
11. New features forcing use of CBO
12. ITL contention


Diagnostics/Remedies
====================

1. Poorly tuned SQL

Often, part of the problem is finding the SQL that is causing the problems.
If you are seeing problems on a system, it is usually a good idea to start
by eliminating database setup issues by using the statspack (or older
UTLBSTAT & UTLESTAT) reports. See:

[NOTE:61998.1] Introduction to Tuning
[NOTE:94224.1] FAQ- STATSPACK COMPLETE REFERENCE
Tuning using BSTAT/ESTAT

for much more on this.

Once the database has been tuned to a reasonable level then the most
resource hungry selects can be determined as follows
(a very similar report can be found in the Enterprise Manager Tuning Pack):

SELECT address, SUBSTR(sql_text,1,20) Text, buffer_gets, executions,
buffer_gets/executions AVG
FROM v$sqlarea
WHERE executions > 0
AND buffer_gets > 100000
ORDER BY 5;

Remember that the 'buffer_gets' value of > 100000 needs to be varied for the
individual system being tuned. On some systems no queries will read more than
100000 buffers, while on others most of them will. This value allows you to
control how many rows you see returned from the select.

The ADDRESS value retrieved above can then be used to lookup the whole
statement in the v$sqltext view:

SELECT sql_text FROM v$sqltext WHERE address = '...' ORDER BY piece;

Once the whole statement has been identified it can be tuned to reduce
resource usage.

If the problem relates to CPU bound applications then CPU information
for each session can be examined to determine the culprits. The v$sesstat
view can be queried to find high cpu using sessions and then SQL can be
listed as before. Steps:

1. Verify the reference number for the 'CPU used by this session'
statistic:

SELECT name ,statistic#
FROM v$statname
WHERE name LIKE '%CPU%session';

NAME STATISTIC#
----------------------------------- ----------
CPU used by this session 12

2. Then determine which session is using most of the cpu:

SELECT * FROM v$sesstat WHERE statistic# = 12;

SID STATISTIC# VALUE
---------- ---------- ----------
1 12 0
2 12 0
3 12 0
4 12 0
5 12 0
6 12 0
7 12 0
8 12 0
9 12 0
10 12 0
11 12 0
12 12 0
16 12 1930

3. Lookup details for this session:

SELECT address ,SUBSTR(sql_text,1,20) Text, buffer_gets, executions,
buffer_gets/executions AVG
FROM v$sqlarea a, v$session s
WHERE sid = 16
AND s.sql_address = a.address
AND executions > 0
ORDER BY 5;

4. Use v$sqltext to extract the whole SQL text.

5. Explain the queries and examine their access paths. Autotrace is
a useful tool for examining access paths. See [NOTE:43214.1]


2. Poor disk performance/disk contention

Use of statspack (or BSTAT/ESTAT) and/or operating system i/o reports can
help in this area. Remember that you may be able to capture the activity of
a single statement by running the report around the run of your statement with
no other activity.

Another good way of monitoring IO is to run a 10046 Level 8 trace to
capture all the waits for a particular session. 10046 can be turned on at
the session level using:

alter session set events '10046 trace name context forever, level 8';

Excessing i/o can be found by examining the resultant trace file and
looking for i/o related waits such as:

'db file sequential read' (Single-Block i/o - Index, Rollback Segment or Sort)
'db file scattered read' (Multi-Block i/o - Full table Scan).

Remember to set TIMED_STATISTICS = TRUE to capture timing information
otherwise comparisons will be meaningless. See:

[NOTE:39817.1] SQL_TRACE interpretation

If you are also interested in viewing bind variable values then a level 12
trace an be used.


3. Unnecessary sorting

The first question to ask is 'Does the data REALLY need to be sorted?'
If sorting does need to be done then try to allocate enough memory to
prevent the sorts from spilling to disk an causing i/o problems.

Sorting is a very expensive operation:

- High CPU usage
- Potentially large disk usage

Try to make the query sort the data as late in the access path as possible.
The idea behind this is to make sure that the smallest number of rows
possible are sorted.

Remember that:

- Indexes may be used to provided presorted data.

- Sort merge joins inherently need to do a sort.

- Some sorts don't actually need a sort to be performed. In this case the
explain plan should show NOSORT for this operation.

In summary:

- Increase sort area size to promote in memory sorts.

- Modify the query to process less rows -> Less to sort

- Use an index to retrieve the rows in order and avoid the sort.

- use sort_direct_writes to avoid flooding the buffer cache with sort
blocks.

- If Pro*C use release_cursor=yes as this will free up any temporary
segments held open.



4. Late row elimination

Queries are more likely to be performant if the bulk of the rows can be
eliminated early in the plan. If this does happen then unnecessary
comparisons may be made on rows that are simply eliminated later.
This tends to increase CPU usage with no performance benefits.

If these rows can be eliminated early in the access path using a selective
predicate then this may significantly enhance the query performance.


5. Over parsing

Over parsing implies that cursors are not being shared.

If statements are referenced multiple times then it makes sense to share
then rather than fill up the shared pool with multiple copies of
essentially the same statement. See:

[NOTE:62143.1] Main issues affecting the Shared Pool on Oracle 7 and 8
[NOTE:70075.1] Use of bind variables with CBO


6. Missing indexes/use of 'wrong' indexes

If indexes are missing on key columns then queries will have to use Full
Table Scans to retrieve data. Usually indexes for performance should be
added to support selective predicates included in queries.

If an unselective index is chosen in preference to a selective one then
potential solutions are:

RBO
- indexes have an equal ranking so row cache order is used. See [NOTE:73167.1]

CBO
- reanalyze with a higher sample size
- add histograms if column data has an uneven distribution of values
- add hints to force use of the index you require

Remember that index usage on join can be compromised by the join type and
join order chosen. For more information on the use of indexes see
[NOTE:67522.1].



7. Wrong plan or join order selected

If the wrong plan has been selected then you may want to force the correct
one.

If the problem relates to an incorrect join order, then it ofter helps to
draw out the tables linking them together to show how they join e.g.:

A-B-C-D

E-F

This can help with visualisation of the join order and identifications of
missing joins. When tuning a plan, try different join orders
examining number of rows returned to get an idea of how good they may be.


8. Import estimating statistics on tables

Pre 8i, import performs an analyze estimate statistics on all tables
that were analyzed when the tables were exported. This can result in
different performance after an export/import.

Introduced in 8i, more sampling functionality has been introduced including
the facility to extract statistics on export.


9. Insufficiently high sample rate for CBO

If the CBO does not have the correct statistical information then it
cannot be expected to produce accurate results. Usually a sample size of
5% will be sufficient, however in some cases it may be necessary to have
more accurate statistics at its' disposal. Please see
[NOTE:44961.1] for Analysis recommendations.


10. Skewed data

If column data distribution is non uniform, then the use of column statistics
in the form of histograms should be considered. Histogram statistics do not
help with uniformly distributed data or where no information about the
column predicate is available such as with bind variables.
11. New features forcing use of CBO

A number of new features are not implemented in the RBO and their presence
in queries will force the use of the CBO. These include:

- Degree of parallelism set on any table in the query

- Index-only tables

- Partition Tables

- Materialised views

See [NOTE:66484.1] for a more extensive list.


12. ITL contention

ITL contention can occur when there is not enough Interested Transaction
Lists in each block to support the update volume required. This can often
occur after an export and import especially when no update space has been
left in the blocks and the ITLs have not been increased.

Wednesday, November 10, 2004

Sizing Extents for Performance

www.kevinloney.com/free/extperf.doc

This is an edited excerpt from ORACLE8 Advanced Tuning and Administration, by Eyal Aronoff, Kevin Loney, and Noorali Sonawalla, published under Osborne/McGraw-Hill's Oracle Press imprint. This edited version first appeared on http://www.kevinloney.com.

During a full table scan, Oracle uses its multiblock read capability to scan multiple blocks at a time. The number of blocks read at a time is determined by the database's DB_FILE_MULTIBLOCK_READ_COUNT setting in the init.ora file and by the limitations of the operating system's read buffers. For example, if you are limited to a 64KB buffer for the operating system, and the database block size is 4KB, you can read no more than 16 database blocks during a single read.
Consider the SALES table again, with an 8MB initial extent and a 4MB second extent. For this example, assume that the highwatermark of SALES is located at the end of the second extent. In the first extent, there are 2048 database blocks, 4KB each in size (8 MB/4 KB = 2048). During a full table scan, those blocks will be read 16 at a time, for a total of 128 reads (2048/16 = 128). In the second extent, there are 1024 database blocks. During a full table scan, those blocks will be read 16 at a time, for a total of 64 reads (1024/16=64). Thus, scanning the entire table will require 192 reads (128 for the first extent, plus 64 for the second extent).
What if the two extents were combined, with the table having the same highwatermark? The combined extent would be 12MB in size, consisting of 3072 database blocks. During a full table scan, those blocks will be read 16 at a time, for a total of 192 reads. Despite the fact that the extents have been compressed into a single extent, the exact same number of reads is required because of the way the extents were sized. As you will see in the next section, the location of the extents may influence the efficiency of the reads, but the number of reads is the same in both the single- and two-extent examples.
What if SALES had 192 extents, each one 16 blocks in length? A full table scan would read 16 blocks at a time, for a total of 192 reads. Thus, whether the SALES table had 1, 2, or 192 extents, the exact same number of reads was required to perform the full table scan. The size of the extents is critical—the size of each extent must be a multiple of the number of blocks read during each multiblock read (set via the DB_FILE_MULTIBLOCK_READ_COUNT init.ora parameter value).
In the 192-extent example, the extent size matched the setting of the DB_FILE_MULTIBLOCK_READ_COUNT value (16). If each extent had been 20 blocks (instead of 16 blocks), how many reads would be required?
The SALES table contains 3072 blocks of data (12MB total). If each extent is 20 blocks (80 KB) each, you'll need 154 extents to store the 3072 blocks of data. When reading the first extent during a full table scan, Oracle will read the first 16 blocks of the extent (as dictated by the DB_FILE_MULTIBLOCK_READ_COUNT). Because there are four blocks left in the extent, Oracle will issue a second read for that extent. Reads cannot span extents, so only four blocks are read by the second read. Therefore, the 20-block extent requires two reads. Since each extent is 20 blocks in length, each extent will require two reads. Because there are 154 extents, a full table scan of SALES will now require 308 reads—a 60 percent increase over the 192 reads previously required!

dbazine: Tuning and Performance

http://www.dbazine.com/foot3.shtml

Changing DB_FILE_MULTIBLOCK_READ_COUNT
This is a neat trick I learned from one of Rich Niemiec's articles. Rich has written numerous articles and given dozens of presentations on Oracle. If you don't have his latest book on tuning titled, Oracle Performance Tuning Tips & Techniques you need to buy it.
If you are thinking about changing the DB_BLOCK_SIZE parameter to increase database performance, consider increasing the DB_FILE_MULTIBLOCK_READ_COUNT parameter. More blocks will be read during sequential read operations. In some cases, it will provide benefits similar to a larger DB_BLOCK_SIZE parameter and you won't have to rebuild the entire database.
Increasing the DB_FILE_MULTIBLOCK_READ_COUNT may have an impact on access path selection. Full table scans use multiblock reads, so the cost of a full table scan depends on the number of multiblock reads required to read the entire table. The number of multiblock reads required to read the entire table depends on the number of blocks read by a single multiblock read which is specified by the DB_FILE_MULTIBLOCK_READ_COUNT parameter.
For this reason, the optimizer may be more likely to choose a full table scan when the value of this parameter is high.