Showing posts with label Performance. Show all posts
Showing posts with label Performance. Show all posts

Saturday, August 18, 2018

Step by Step: How to troubleshoot a slow running query in Oracle


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

 # Step by Step: How to troubleshoot a slow running query in Oracle

 -  what are sessions doing

set lines 999
col osuser form a10
col username form a10
col spid form a10
select a.sid, a.serial#,
       spid ,
       sql_id,
       a.inst_id,
       a.osuser,
       a.username, status,
       substr(to_char(logon_time,'dd-mon-yy hh24:mi'),1,18) logon_time,
       substr(to_char(sql_exec_start,'dd-mon-yy hh24:mi'),1,18) sql_exec_start,
       substr(a.module,1,18) module ,
       substr(machine,1,17) machine,
       event
--       substr(a.program,1,16) program
from   gv$session a, gv$process b
where  a.username not in (' ','PATROL','SYS','DBSNMP')
and    b.addr=a.paddr
and    b.inst_id=a.inst_id
and    a.status='ACTIVE'
-- and    event='inactive transaction branch'
order by status desc, logon_time
/


--  blockers in standalone

select s1.username || '@' || s1.machine || ' ( SID=' || s1.sid || ') is blocking'
       || s2.username || '@' || s2.machine || '( SID=' || s2.sid || ')' from
       v$lock l1, v$session s1, v$lock l2, v$session s2
       where s1.sid=l1.sid and s2.sid=l2.sid
       and l1.block=1 and l2.request > 0
       and l1.id1=l2.id1
       and l2.id2=l2.id2;


--  blockers in rac
set pages 1000
select s1.username || '@' || s1.machine || ' ( SID=' || s1.sid || ' Serial#= '||s1.serial# ||' Inst=' ||s1.INST_ID ||' )  is blocking '
  || s2.username || '@' || s2.machine || ' ( SID=' || s2.sid || ' ) ' AS blocking_status
   from gv$lock l1, gv$session s1, gv$lock l2, gv$session s2
  where s1.sid=l1.sid and s2.sid=l2.sid
  and l1.BLOCK=1 and l2.request > 0
  and l1.id1 = l2.id1
  and l2.id2 = l2.id2 ;
 
 
-- top
get pid

-- get sid using pid
select sid
from v$session s, v$process p
where p.spid = &pid
and s.paddr = p.addr;

-- get sqlId using sid
select sql_id
from v$session
where sid = &sid;

- get sql using sid
select sql_fulltext
from v$sql l, v$session s
where s.sid = &sid
and l.sql_id = s.sql_id;


# Check for the wait events:

-- Check for the particular user and session.
col "Description" format a50
select sid,
        decode(state, 'WAITING','Waiting',
                'Working') state,
        decode(state,
                'WAITING',
                'So far '||seconds_in_wait,
                'Last waited '||
                wait_time/100)||
        ' secs for '||event
        "Description"
from v$session
where username = 'GOS_USER';

select SID, osuser, machine, terminal, service_name,
       logon_time, last_call_et
from v$session
where username = 'GOS_USER';

--  Session waits for a specific machine
col username format a5
col program format a10
col state format a10
col last_call_et head 'Called|secs ago' format 999999
col seconds_in_wait head 'Waiting|for secs' format 999999
col event format a50
select sid, username, program,
        decode(state, 'WAITING', 'Waiting',
                'Working') state,
last_call_et, seconds_in_wait, event
from v$session
where sid = &sid
/


History of wait events in a specific session

set lines 120 trimspool on
col event head "Waited for" format a30
col total_waits head "Total|Waits" format 999,999
col tw_ms head "Waited|for (ms)" format 999,999.99
col aw_ms head "Average|Wait (ms)" format 999,999.99
col mw_ms head "Max|Wait (ms)" format 999,999.99
select event, total_waits, time_waited*10 tw_ms,
       average_wait*10 aw_ms, max_wait*10 mw_ms
from v$session_event
where sid = &sid
/

-- check data access isue

select event
from v$session
where sid = &sid;

-- check data access waits
select SID, state, event, p1, p2
from v$session
where sid = &sid;


-- run sql advisor

1. Tuning task created for specific Sql id:


SET SERVEROUTPUT ON
DECLARE
  l_sql_tune_task_id  VARCHAR2(100);
BEGIN
  l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
                          sql_id      => 'bxa13by3718uw',
                          scope       => DBMS_SQLTUNE.scope_comprehensive,
                          time_limit  => 60,
                          task_name   => 'bxa13by3718uw_tuning_task',
                          description => 'Tuning task for statement bxa13by3718uw.');
  DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/


2. Executing the tuning task:

EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => 'bxa13by3718uw_tuning_task');

3. Displaying the recommendations:

Once the tuning task has executed successfully the recommendations can be displayed using the REPORT_TUNING_TASK function.

SET LONG 10000;
SET PAGESIZE 1000
SET LINESIZE 200

SELECT DBMS_SQLTUNE.report_tuning_task('bxa13by3718uw_tuning_task') AS recommendations FROM dual;

SET PAGESIZE 24


Based on the tuning advisor recommendation we have to take corrective actions. These recommendation could be:

1) Gather Statistics
2) Create Index
3) Drop Index
4) Join orders
5) Create sql profiles and many more

After corrective action from tuning advisor run the SQL again and see the improvement.

Friday, April 06, 2018

PERFORMANCE BOTTLENECK CHECK USING OS TOOLS

A.REAL TIME PERFORMANCE TUNING USING OS TOOLS


TOOL1:-TOP UTILITY

check in TOP with column S where it shows ‘R’ means running and ‘S’ means sleeping.


TOOL 2:-SAR UTILITY WITH -U OPTION TO CHECK CPU AND IO BOTTLENECK
sar -u 10 8

TOOL 3:VMSTAT REPORT
vmstat 1 10
r column is runnable processes

TOOL 4:TO IDENTIFY DISK BOTTLENECK
sar -d 5 2

TOOL 5:-SAR -B TO REPORT DISK USAGE

TOOL 6:-SAR -Q TO FIND PROCESSES UNDER QUEUE.WE NEED TO LOOK BLOCKED SECTION

TOOL 7:-TO IDENTIFY MEMORY USAGE USING SAR -R


TOOL 8. REAL TIME PERFORMANCE TUNING USING ORATOP REPORT
./oratop -f -d -i 10 / as sysdba

Wednesday, November 29, 2017

oratop

Pre- requisite

download oratop
set  oracle environment
helpful commands


oratop -i 5 / as sysdba
oratop -bdfi5 "/ as sysdba"
to remote database
oratop -f -i 5 sys/pass@db as sysdba


FOR HELP press h  and get the interactive key and enter in the main screen for example t is for table space






Wednesday, September 21, 2011

log file sync" wait is topping AWR



From the AWR report, we can see that log file sync average wait time was 24 ms.

We normally expect the average wait time for log file sync less than 5ms.

So, first, please check if the disk I/O for redo logs.

High 'log file sync' waits could be caused by various reasons, some of these are:
1. slower writes to redo logs
2. very high number of COMMITs
3. insufficient redo log buffers
4. checkpoint
5. process post issues

The five reasons  listed above  are examples of reasons that could cause 'log file sync' we need more information to determine the reason for the wait,
 then we can make recommendations.

Please also download and run the script from note 1064487.1.

When a user session(foreground process) COMMITs (or rolls back), the session's redo information needs to be flushed to the redo logfile. The user session will post the LGWR to write all redo required from the log buffer to the redo log file. When the LGWR has finished it will post the user session.

The user session waits on this wait event while waiting for LGWR to post it back to confirm all redo changes are safely on disk.

This may be described further as the time user session/foreground process spends waiting for redo to be flushed to make the commit durable.

Therefore, we may think of these waits as commit latency from the foreground process (or commit client generally).

For further information about log file sync, please refer to MOS note 34592.1 and note 857576.1 How to Tune Log File Sync.


1. For analysis check AWR 

1.1 "log file sync" wait is topping AWR:

Top 5 Timed Foreground Events

Event Waits Time(s) Avg wait (ms) % DB time Wait Class
log file sync 59,558 3,275 55 54.53 Commit <===== average wait time 55 ms. for 8 hrs. Very high.
DB CPU 1,402 23.34

1.2. Most wait time is contributed by "log file parallel write":

Event Waits %Time -outs Total Wait Time (s) Avg wait (ms) Waits /txn % bg time
db file parallel write 136,730 0 3,957 29 2.44 42.37
log file parallel write 61,635 0 2,810 46 1.10 30.09 <===== 46 ms or 84% of "log file sync" time

2. Output of script from note 1064487.1
Wait histogram also shows the same:
INST_ID EVENT WAIT_TIME_MILLI WAIT_COUNT
---------- ------------------------------------- -------------------------- ----------------------
1 log file sync 1 176
1 log file parallel write 1 117
1 LGWR wait for redo copy 1 150

1 log file sync 2 3013
1 log file parallel write 2 3433
1 LGWR wait for redo copy 2 8

1 log file sync 4 15254
1 log file parallel write 4 18064
1 LGWR wait for redo copy 4 6

1 log file sync 8 44676
1 log file parallel write 8 51155
1 LGWR wait for redo copy 8 9

2.2. Spikes of log file sync are really bad (hundreds of ms):

APPROACH: These are the minutes where the avg log file sync time
was the highest (in milliseconds).
MINUTE INST_ID EVENT
--------------------------------------------------------------------------- ---------- ------------------------------
TOTAL_WAIT_TIME WAITS AVG_TIME_WAITED
----------------- ---------- -----------------
Aug18_0311 1 log file sync
48224.771 58 831.462

Aug18_0312 1 log file sync
100701.614 117 860.698

Aug18_0313 1 log file sync
20914.552 33 633.774

Aug18_0613 1 log file sync
84651.481 93 910.231

Aug18_0614 1 log file sync
139550.663 139 1003.962

2.3. User commits averaged 2/sec, which is low. (Caveat: this number is an 8-hr average.)


2.  oswatcher data, to pinpoint where the IO bottleneck is


From the oswatcher data,

I see extreme IO contention across almost all of the disks between 4-7AM. Disk utilization is between 80-100% with worst IO response time over 200-300 ms. Sdc and sdd are the busiest disks with util constantly above 80%. Example:

avg-cpu: %user %nice %system %iowait %steal %idle
         69.62 1.48  13.46   15.44   0.00   0.00

Device: rrqm/s wrqm/s r/s  w/s rsec/s  wsec/s avgrq-sz avgqu-sz await svctm %util
   sdc 5.21   0.65 119.54 7.49 8932.90 834.85 76.89    33.03    240.00 7.87 100.00 <=== This disk is saturated
  sdc1 5.21   0.65 119.54 7.49 8932.90 834.85 76.89    33.03    240.00 7.87 100.00

  sdd 4.89 0.33 119.87 7.82 9386.32 103.58 74.32 6.64 52.81 7.68 98.05 <=== Same with this one
 sdd1 4.89 0.33 119.87 7.82 9386.32 103.58 74.32 6.64 52.81 7.68 98.05

  sde 0.00 0.33 0.65 8.47 5.21 232.57 26.07 1.79 201.43 92.86 84.69 <=== High utilization @85%
  sde1 0.00 0.33 0.65 8.47 5.21 232.57 26.07 1.79 201.43 92.86 84.69

I also noticed that there were many DBMS jobs running from ~ 7 different databases at the same time. CPU util is ~80%.

zzz ***Sun Aug 21 06:02:00 EDT 2011
top - 06:02:04 up 18 days, 13:51, 6 users, load average: 16.87, 8.64, 4.56
Tasks: 1042 total, 22 running, 1019 sleeping, 0 stopped, 1 zombie
Cpu(s): 69.9%us, 10.2%sy, 0.3%ni, 0.0%id, 18.8%wa, 0.2%hi, 0.6%si, 0.0%st
Mem: 49458756k total, 49155380k used, 303376k free, 951836k buffers
Swap: 4194296k total, 1548904k used, 2645392k free, 39128504k cached

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
7680 oracle 15 0 2255m 90m 80m S 12.9 0.2 0:00.80 ora_j002_oracl1 <=== db 1


3. Trace the LGWR while running a dummy DELETE transaction.

3.1) create a dummy user table that has, say 1 million rows.
3.2) At the OS prompt, run
strace -fo lgwr_strace.out -r -p <LGWR_PID>
3.3) From a different window, sqlplus session:
DELETE FROM <dummy_table>;
3.4) COMMIT; -- IMPORTANT. To trigger a log flush.
3.5) CTRL-C the strace and upload the lgwr_strace.out file.


Conclusion
All this indicates IO capacity/hot disk issue. You are over-leveraging the server in terms of IO capacity (especially on the 2 disks: sdc and sde).

You would experience the same slow IO issue in other databases if those 2 disks are shared across the other DBs.

Action Plan

1. Review ASM diskgroup configuration. Make sure the diskgroups are spanned across all available disks.
Example: avoid creating a DATA diskgroup on a couple of disks that are shared among ALL your databases.
2. Consider using EXTERNAL disk redundancy for your DEV databases (especially the REDO logs) to reduce IO load provided that
3. Stagger the DBMS job schedules across multiple DBs so that the workload is more evenly distributed throughout the day,
especially if the jobs are of a similar nature and all run in the say, 4-7AM window.

Hope this helps! Rupam

Tuesday, September 20, 2011

Disk IO rate on Oracle Database Sever


From Unix Server

iostat -d -m
iostat -d /dev/sdc -m -x 2
   where
         /dev/sdc is the name of the disk  ( refer my earlier post on how to map ASM device to physical disks)
         await is disk response time
         svctm is time to process i/o request by disk

hostname : tiger

From OEM:
Targets / tiger / performance / under the Disk I/O utilization click ‘Total I/Os per second’ / change view data to last 31 days. See statistics on the left side of the page.

In OEM:
Targets / +ASM_tiger / Performance / Bottom of the page – Disk Group I/O Cumulative Statistics

OEM is Targets / Hosts. Click the Total IO/sec header to sort the list to see what other hosts are similar to tiger. Scroll down to find tiger . This is the same variable as noted above but for the last 24 hours (instead of last 31 days).

Hope this help! Rupam

Saturday, May 28, 2011

SQL Profile – create manually


Symptom
Sql execution is too long

Cause
After automatic statistics collection on table, the execution plan changed. It is no more picking the index and doing full table scan.

solution
Step 1. Find the SQL ID that needs a profile,
               in this example: 50ux45v27k6ab

Step 2. Find the hint that introduces a good plan
               In this example: INDEX(TRAIN_SHEET_OSPOINT PK_TRAIN_SHEET_OSPOINT)

Step 3. Run following anonymous PLQSL block
DECLARE
cl_sql_text CLOB; 
BEGIN
SELECT sql_text  
INTO cl_sql_text  
FROM gv$sqlarea where sql_id = '50ux45v27k6ab' and rownum = 1; 
DBMS_SQLTUNE.IMPORT_SQL_PROFILE(sql_text => cl_sql_text,  
profile => sqlprof_attr(‘INDEX(TRAIN_SHEET_OSPOINT PK_TRAIN_SHEET_OSPOINT)'),  
name => 'USE_PK_FOR_UPDATE',  
category => 'DEFAULT', 
force_match => TRUE); 
end; 
/

Hope this helps! Rupam

Monday, February 21, 2011

explian plan


steps:-
1. create plan table (global temporary table) @?/rdbms/admin/catplan
2. populate plan table
   Note : 235530.1
   SQL> explain plan for
       
3. Displaying The Execution Plan
  SQL> set linesize 150 
  SQL>  select plan_table_output from table(dbms_xplan.display('PLAN_TABLE',null,'ALL'));
or

select * from  table(dbms_xplan.display('plan_table',null,'serial'));
or
select * from table(dbms_xplan.display);
or
@?/rdbms/admin/utlxpls
or 
More details can be found in $ORACLE_HOME/rdbms/admin/dbmsxpln.sql
or
  select * from table(dbms_xplan.display(null, null));
or
select plan_table_output from table(dbms_xplan.display('plan_table',null,'advanced'));

Hope this help! Rupam

Monday, January 10, 2011

Find Sessions with the Highest CPU Consumption


Monday, January 10, 2011


The following queries will allow you to find the sessions currently logged into the database that have accumulated the most time on CPU or for certain wait events. Use them to identify potential sessions to trace using 10046.

These queries are filtering the sessions based on logon times less than 4 hours and the last call occurring within 30 minutes. This is to find more currently relevant sessions instead of long running ones that accumulate a lot of time but aren't having a performance problem. You may need to adjust these values to suit your environment.

Find Waits in the Database causing Performance issue

Monday, January 10, 2011


The following queries will allow you to find the sessions currently logged into the database that have accumulated the most time on CPU or for certain wait events. Use them to identify potential sessions to trace using 10046.


Run following sqls in the order
    @sess_waits   <-- shows sid on clock
    @sql_text        <-- show the sql for sid
    @sqlplan         <-- show sqlplan for sql_id
    @wait_sess      <-- list all the waits in db
    @wait             <-- waits for sid


Wednesday, January 05, 2011

Query on Dynamic View is slow ( v$ views)

 QUERY PERFORMANCE SLOW FOR V$ VIEWS


PROBLEM:
--------
Query performance containing v$ views (v$sql, v$session) are slow as compared
to same query using RULE hints.

Friday, December 10, 2010

Blocking in Oracle Database

Follow the steps to locate and terminate blocking session from Oracle database (10g & up). Blocking_session_status contains ‘VALID’ when blocking_session is populated in 10g and up.
steps:
1. Display blocked session and their blocking session details
2. Find what is Blocking session Doing
3. Find sid and serial # of blocking session
4.  To terminate the session:

Wednesday, October 06, 2010

AWR

Oracle Database Performance

AWR

Metalink Note:276103.1

STATISTICS_LEVEL initialization parameter must be set to the
TYPICAL or ALL to enable the Automatic Workload Repository


ADDM Report

Oracle Database Performance

ADDM Report

Option 1 : OEM
               Database -> Advisor Center -> ADDM
Option 2 : using sqlplus

@$ORACLE_HOME/rdbms/admin/addmrpt.sql  
Input : begin_snap
           ending_snap
and      filename
            

Hope this help. Regards Rupam

ADDM

Oracle Database Performance

ADDM

The Automatic Database Diagnostic Monitor ( ADDM ) is an advisor which detects problem area' s in the database and and which gives recommendations.


Friday, June 22, 2007

SQL - Joins

Equijoins or Inner Join


SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A, Table_B
3   WHERE Table_A.letter = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A

SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A INNER JOIN Table_B
3      ON Table_A.letter = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A


Self Joins


SQL >SELECT A1.letter, A2.letter
2    FROM Table_A A1, Table_A A2
3   WHERE A1.letter = A2.letter;

LETTER     LETTER
---------- ----------
A          A
B          B
SQL >SELECT A1.letter, A2.letter
2    FROM Table_A A1 INNER JOIN Table_A A2
3      ON A1.letter = A2.letter;

LETTER     LETTER
---------- ----------
A          A
B          B

Left Outer Joins


SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A, Table_B
3   WHERE Table_A.letter = Table_B.letter(+);

LETTER     LETTER
---------- ----------
A          A
B

SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A LEFT OUTER JOIN Table_B
3      ON Table_A.letter = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A
B

Right Outer Joins


SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A, Table_B
3   WHERE Table_A.letter(+) = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A
C
SQL >SELECT Table_A.letter, Table_B.letter
  2  FROM Table_A RIGHT OUTER JOIN Table_B
3  ON Table_A.letter = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A
C

Full Outer Joins


SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A, Table_B
3   WHERE Table_A.letter = Table_B.letter(+)
4   UNION
5  SELECT Table_A.letter, Table_B.letter
6    FROM Table_A, Table_B
7   WHERE Table_A.letter(+) = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A
B
C
SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A FULL OUTER JOIN Table_B
3      ON Table_A.letter = Table_B.letter;

LETTER     LETTER
---------- ----------
A          A
B
C

Cartesian Products


SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A, Table_B;

LETTER     LETTER
---------- ----------
A          A
A          C
B          A
B          C

SQL >SELECT Table_A.letter, Table_B.letter
2    FROM Table_A CROSS JOIN Table_B;

LETTER     LETTER
---------- ----------
A          A
A          C
B          A
B          C


Reference Document dbasupport.com 

Monday, May 07, 2007

what is my session doing

-- sessions in non-RAC
set linesize 132
Prompt "Oracle Sessions"
column osuser format A08 Head "OS User"
column user format A08 Head "User"
column module format A15 Head "Module"
column action format A25 Head "Action"
column logon_time format A15 Head "Logon Time"

select sid,
s.serial#,
spid,
substr(osuser,1,12) osuser,
substr(s.username,1,15) "user",
status,
decode(p.background,'1','Y','N') background,
decode(s.lockwait,null,'N','Y') lockwait,
decode(p.latchwait,null,'N','Y') latchwait,
substr(to_char(logon_time,'dd-mon-yy hh24:mi'),1,18) logon_time,
substr(module,1,45) module,
action
from v$session s,
v$process p
where s.username not in (' ','SYS','PATROL')
and p.addr=s.paddr
order by status desc, logon_time
/

set lines 80

-- sessions in RAC

set linesize 132
Prompt "RAC Oracle Sessions"
column inst_id format 9 Head "Inst|Id."
column osuser format A08 Head "OS User"
column user format A08 Head "User"
column module format A15 Head "Module"
column action format A25 Head "Action"
column logon_time format A15 Head "Logon Time"
select inst_id, sid, serial#,
substr(osuser,1,12) osuser, substr(username,1,15) "user",
status,
substr(to_char(logon_time,'dd-mon-yy hh24:mi'),1,18) logon_time,
substr(module,1,45) module, action
from gv$session
where username not in (' ','SYS','PATROL')
order by status desc;

-- 'Session Reponse in terms of |Waiting|IO Operation|CPU Operation'
ttitle 'Session Reponse in terms of |Waiting|IO Operation|CPU Operation'

Column event format a30
Column sid format 9999
Column session_cpu heading "CPU|used"
Column physical_reads heading "physical|reads"
Column consistent_gets heading "logical|reads"
Column seconds_in_wait heading "seconds|waiting"

select a.sid,
a.value session_cpu,
c.physical_reads,
c.consistent_gets,
d.event,
d.seconds_in_wait
from v$sesstat a,
v$statname b,
v$sess_io c,
v$session_wait d
where a.sid like '&Sid'
and b.name = 'CPU used by this session'
and a.statistic# = b.statistic#
and a.sid=c.sid
and a.sid=d.sid;


-- WHAT IS SESSION doing, we have pid

SELECT /*+ ordered */ p.spid, s.sid, s.serial#, s.username,
TO_CHAR(s.logon_time, 'mm-dd-yyyy hh24:mi') logon_time,
s.last_call_et, st.value, s.sql_hash_value, s.sql_address, sq.sql_text
FROM v$statname sn, v$sesstat st, v$process p, v$session s, v$sql sq
WHERE s.paddr=p.addr
AND s.sql_hash_value = sq.hash_value and s.sql_Address = sq.address
AND s.sid = st.sid
AND st.STATISTIC# = sn.statistic#
AND sn.NAME = 'CPU used by this session'
AND p.spid = &osPID -- parameter to restrict for a specific PID
AND s.status = 'ACTIVE'
ORDER BY st.value desc;

-- v$session_wait, current waits on the system
SELECT event,
sum(decode(wait_time,0,1,0)) "Curr",
sum(decode(wait_time,0,0,1)) "Prev",
count(*)"Total"
FROM v$session_wait
GROUP BY event
ORDER BY count(*);

-- v$session_event, cummulative session waits
SELECT event, total_waits waits, total_timeouts timeouts,
time_waited total_time, average_wait avg
FROM v$session_event
WHERE sid = &sid
ORDER BY time_waited DESC;

-- V$SESSTAT, session-level summary of resource usage since session startup
SELECT ses.sid
, DECODE(ses.action,NULL,'online','batch') "User"
, MAX(DECODE(sta.statistic#,9,sta.value,0))
/greatest(3600*24*(sysdate-ses.logon_time),1) "Log IO/s"
, MAX(DECODE(sta.statistic#,40,sta.value,0))
/greatest(3600*24*(sysdate-ses.logon_time),1) "Phy IO/s"
, 60*24*(sysdate-ses.logon_time) "Minutes"
FROM V$SESSION ses
, V$SESSTAT sta
WHERE ses.status = 'ACTIVE'
AND sta.sid = ses.sid
AND sta.statistic# IN (9,40)
GROUP BY ses.sid, ses.action, ses.logon_time
ORDER BY
SUM( DECODE(sta.statistic#,40,100*sta.value,sta.value) )
/ greatest(3600*24*(sysdate-ses.logon_time),1) DESC;

-- V$SYSTEM_EVENT , Finding the Total Waits on the System

SELECT event, total_waits waits, total_timeouts timeouts,
time_waited total_time, average_wait avg
FROM V$SYSTEM_EVENT
ORDER BY 4 DESC;

Sunday, April 22, 2007

SQL Performance related Dynamic Views

What is my sesison doing

steps
1. find sid of the session from v$session
2. check v$Session_wait for last wait activity
3. check v$session_event for commuvative waits
4. check v$sesstat for resource usage stats



from where and what



my sid v$mystat
rownum=1

others sid v$session ,v$process

what's up v$sesstat v$statname v$sess_io v$session_wait
CPU used by this session

which segment v$sesion_wait
buffer bust waits db file sequential read db file scattered read free buffer waits

which latch v$session_wait v$latchname
latch free


which sql v$sqltext v$sqlarea v$session
sid






Current State Views

V$SESSION - Sessions currently connected to the instance

v$session_wait - last/current wait
This is a key view for finding bottlenecks. It tells what every session in the
database is currently waiting for (or the last event waited for by the session
if it is not waiting for anything). This view can be used as a starting point
to find which direction to proceed in when a system is experiencing performance
problems.
Since 10g, Oracle displays the v$session_wait information also in the v$session view.

Summary Since Session Startup - cummulative

v$mystat - Resource usage summary for your own session
This view records statistical data about the session that accesses it.

v$session_event - Session-level summary of all the waits for current sessions
This view summarizes wait events for every session. While V$SESSION_WAIT shows
the current waits for a session, V$SESSION_EVENT provides summary of all the
events the session has waited for since it started.

v$sesstat - session-level summary of resource usage since session startup
V$SESSTAT stores session-specific resource usage statistics, beginning at login
and ending at logout.
Includes session logical reads, CPU used by this session, db block changes,
redo size, physical writes, parse count (hard), parse count (total),
sorts (memory), and sorts (disk).
V$SESSTAT can be used to find sessions with the following:

* The highest resource usage
* The highest average resource usage rate (ratio of resource usage to logon time)
* The current resource usage rate (delta between two snapshots)


v$sysstat - Summary of resource usage
V$SYSSTAT stores instance-wide statistics on resource usage, cumulative since
the instance was started.
Similar to V$SESSTAT, this view stores the following types of statistics:

* A count of the number of times an action occurred (user commits)
* A running total of volumes of data generated, accessed, or manipulated (redo size)
* If TIMED_STATISTICS is true, then the cumulative time spent performing some
actions (CPU used by this session)
The data in this view is used for monitoring system performance. Derived statistics, such as the buffer cache hit ratio and soft parse ratio, are computed from V$SYSSTAT data.


v$system_event - cummulative Instance wide summary of resources waited for
This view displays the count (total_waits) of all wait events since startup of the instance.
This view is a summary of waits for an event by an instance. While V$SESSION_WAIT
shows the current waits on the system, V$SYSTEM_EVENT provides a summary of all
the event waits on the instance since it started. It is useful to get a historical
picture of waits on the system. By taking two snapshots and doing the delta on
the waits, you can determine the waits on the system in a given time interval.

v$waitstat - Break down of buffer waits by block class
total_waits where event='buffer busy waits' is equal the sum of count in v$system_event.
This view keeps a summary all buffer waits since instance startup. It is useful
for breaking down the waits by class if you see a large number of buffer busy
waits on the system.

LINK
oracle 9i performance document
oracle 10g performance document

Friday, April 20, 2007

HOW THE RULE-BASED OPTIMIZER WORKS

But first, let’s start at the beginning…
The rule-based optimizer (RBO) has only a small amount of information to use in deciding upon an execution plan for a SQL statement:
• The text of the SQL statement itself
• Basic information about the objects in the SQL statement, such as the tables, clusters, and views in the FROM clause and the data type of the columns referenced in the other clauses
• Basic information about indexes associated with the tables referenced by the SQL statement
• Data dictionary information is only available for the local database. If you’re referencing a remote database, the remote dictionary information is not available to the RBO…
In order to determine the execution plan, the RBO first examines the WHERE clause of the statement, separating each predicate from one another for evaluation, starting from the bottom of the statement. It applies a score for each predicate, using the fifteen access methods ordered by their alleged merit:
1. Single row by ROWID
2. Single row by cluster join
3. Single row by hash cluster key with unique key
4. Single row by unique index
5. Cluster join
6. Hash cluster key
7. Indexed cluster key
8. Composite key
9. Single-column non-unique index
10. Bounded range search on indexed columns
11. Unbounded range search on indexed columns
12. Sort-merge join
13. MAX or MIN of indexed column
14. ORDER BY on indexed columns
15. Full table-scan




Suggest you check out:

www.evdbt.com/SearchIntelligenceCBO.doc

which is a pretty good paper on this topic.

Optimizer Settings

o optimizer_index_caching - percentage of blocks expected to be found in the buffer cache during an index hit. default of 0 implies that every (logical) LIO is a (physical) PIO.

o optimizer_index_cost_adj - represents relative cost of PIO's for indexed access vs full scan. Default value of 100 indicates that an indexed access is just as costly as a full
access.