Skip to content
pvmehta.com

pvmehta.com

  • Home
  • About Me
  • Toggle search form
  • Find_table_size.sql Oracle
  • Getting started with notebook Python/PySpark
  • Changing Instance Name ( No DB_NAME) Oracle
  • Find average Row Length and other table size calculation. metalink notes Oracle
  • USER_TABLES.Freelists Oracle
  • Process Map for CPU and Memory for OS processes Linux/Unix
  • Temporary Tablespsace Temp tablespace behaviour Oracle
  • shutdown linux Linux/Unix
  • Backup and Recovery Scenarios Oracle
  • compile_inv.sql Oracle
  • Find Command Linux/Unix
  • Giving Grant on v$DATABASE Oracle
  • tar and untar a dolder with all its subfolder. Linux/Unix
  • How to calculate PROCESSES parameter Oracle
  • Jai Shree Ram Oracle

myfile

Posted on 02-Aug-2005 By Admin No Comments on myfile

****************************************************

File Name : a.sql

****************************************************

create or replace view ats_dba_waiters as

select /*+ all_rows */ w.session_id waiting_session,

h.session_id holding_session,

w.lock_type,

h.mode_held,

w.mode_requested,

w.lock_id1,

w.lock_id2

from ats_dba_lock w, ats_dba_lock h

where h.blocking_others = ‘Blocking’

and h.mode_held != ‘None’

and h.mode_held != ‘Null’

and w.mode_requested != ‘None’

and w.lock_type = h.lock_type

and w.lock_id1 = h.lock_id1

and w.lock_id2 = h.lock_id2

/

****************************************************

File Name : a1.sql

****************************************************

—select chr(bitand(1415053318,16777216)/16777216)||

–select chr(bitand(1415053318,4294967295)/4294967294)||

–chr(bitand(1415053318,16711680)/65535) “enqueue name”

–from dual

–/

–select bitand(1415053318,65535) from dual

–/

select chr(bitand(1415053318,-16777216)/16777215) || chr(bitand(1415053318,16711680)/65535) “Lock”

–bitand(1415053318, 65536) “Mode”

from dual

/

****************************************************

File Name : a2.sql

****************************************************

col Lock format a4

col Mode format a4

select chr(bitand(1415053318,-16777216)/16777215) || chr(bitand(1415053318,16711680)/65535)

“Lock”, to_char(bitand(1415053318,65535)) “Mode”

from dual

/

****************************************************

File Name : a4.sql

****************************************************

set pages 2000

select username,status,SID,SERIAL# from v$session a

where SID in (select distinct sid from v$sesstat b

where b.statistic# in(139,140,141))

and username != ‘ ‘

order by 2 desc

/

****************************************************

File Name : a5.sql

****************************************************

select ‘alter system kill session ‘||””||v$session.sid||’,’||v$session.serial#||”” ||’ ;’

from v$session,v$session_Wait

where v$session_Wait.event = ‘library cache pin’ and v$session.username = ‘SATISH’

and v$Session.sid = v$session_Wait.sid

and v$session.status = ‘ACTIVE’

/

****************************************************

File Name : aa.sql

****************************************************

set serveroutput on

set feedback off

DECLARE

good_date char(20);

good_date1 char(20);

BEGIN

good_date:=user;

good_date1:=sysdate;

dbms_output.put_line(‘Startup User:’||good_date);

END;

/

****************************************************

File Name : active_cursor.sql

****************************************************

column sid format 999

column sql_text format a75 word_wrapped

select

s.sid,

c.kglnaobj sql_text

from

sys.x$kglpn p,

sys.x$kglcursor c,

sys.v$session s

where

p.inst_id = userenv(‘Instance’) and

c.inst_id = userenv(‘Instance’) and

p.kglpnhdl = c.kglhdadr and

c.kglhdadr != c.kglhdpar and

p.kglpnses = s.saddr

order by

s.sid

/

****************************************************

File Name : actual_user.sql

****************************************************

select count(code)

from ats_employees

where code in (select username from v$session

where username not in(‘9999′,’BKGR’,’MERCORA’,’BLOOMORA’,

‘TAXUSER’,’BBXUSER’,’FAXUSER’,’CCUSER’,’EXPUSER’,

‘QDBA’,’TUNER’));

****************************************************

File Name : add_logfile.sql

****************************************************

set term on echo on

set concat +

alter database add logfile ‘/ORADATA&1/800P/800P_redo&2.rdo’ size 50M;

set concat .

****************************************************

File Name : al.sql

****************************************************

alter tablespace temp coalesce

/

****************************************************

File Name : al1.sql

****************************************************

alter tablespace temp1 coalesce

/

****************************************************

File Name : all_param.sql

****************************************************

set linesize 128

column name format a42

select

x.ksppinm name,

decode(bitand(ksppiflg/256,1),1,’TRUE’,’FALSE’) sesmod,

decode(

bitand(ksppiflg/65536,3),

1,’IMMEDIATE’,

2,’DEFERRED’,

3,’IMMEDIATE’,

‘FALSE’

) sysmod,

ksppdesc description

from

sys.x$ksppi x

where

x.inst_id = userenv(‘Instance’) and

translate(ksppinm,’_’,’#’) like ‘#%’

order by

1

/

****************************************************

File Name : all_params_v7.sql

****************************************************

set linesize 132

column name format a42

column value format a64

select

x.ksppinm name,

y.ksppstvl value,

y.ksppstdf isdefault,

decode(bitand(y.ksppstvf,7),1,’MODIFIED’,4,’SYSTEM_MOD’,’FALSE’) ismod,

decode(bitand(y.ksppstvf,2),2,’TRUE’,’FALSE’) isadj

from

sys.x_$ksppi x,

sys.x_$ksppcv y

where

x.indx = y.indx

order by

translate(x.ksppinm, ‘ _’, ‘ ‘)

/

****************************************************

File Name : all_value.sql

****************************************************

set linesize 132

column name format a42

column value format a20

select

x.ksppinm name,

y.ksppstvl value,

y.ksppstdf isdefault,

decode(bitand(y.ksppstvf,7),1,’MODIFIED’,4,’SYSTEM_MOD’,’FALSE’) ismod,

decode(bitand(y.ksppstvf,2),2,’TRUE’,’FALSE’) isadj

from

sys.x$ksppi x,

sys.x$ksppcv y

where

x.inst_id = userenv(‘Instance’) and

y.inst_id = userenv(‘Instance’) and

x.indx = y.indx

order by

translate(x.ksppinm, ‘ _’, ‘ ‘)

/

****************************************************

File Name : all_value1.sql

****************************************************

set linesize 132

column name format a42

column value format a20

select

x.ksppinm name,

y.ksppstvl value,

y.ksppstdf isdefault,

decode(bitand(y.ksppstvf,7),1,’MODIFIED’,4,’SYSTEM_MOD’,’FALSE’) ismod,

decode(bitand(y.ksppstvf,2),2,’TRUE’,’FALSE’) isadj

from

sys.x$ksppi x,

sys.x$ksppcv y

where

x.inst_id = userenv(‘Instance’) and

y.inst_id = userenv(‘Instance’) and

x.indx = y.indx

and x.ksppinm like ‘%rollback%’

order by

translate(x.ksppinm, ‘ _’, ‘ ‘)

/

****************************************************

File Name : alp.sql

****************************************************

select sid,serial#,OSUSER,machine,status from v$session where OSUSER like ‘alpine%’;

****************************************************

File Name : ana.sql

****************************************************

select table_name,avg_row_len from dba_Tables

where table_name in (

‘ATS_FLORISTS_TRACKING’,

‘ATS_BLOOMNET_FORMS’

)

/

****************************************************

File Name : ana1.sql

****************************************************

analyze table ats_florist_wire_Tracking compute statistics;

analyze table ats_flr_bonus_plan compute statistics;

analyze table ats_bloomnet_forms compute statistics;

****************************************************

File Name : analyze.sql

****************************************************

execute my_newjobs(‘ATS’,’ATS_TELEPHONES’,’07-10-1998:04:00:00′,’NONE’);

execute my_newjobs(‘ATS’,’ATS_ZIP_SURROUNDS’,’07-10-1998:04:00:00′,’NONE’);

execute my_newjobs(‘ATS’,’ATS_ADDRESSES’,’07-12-1998:03:00:00′,’SYSDATE+7′);

exit

****************************************************

File Name : analyze_ats.sh

****************************************************

#!/bin/sh

echo “ANALYZE SCHEMA OF ATS HAS STARTED”|mailx skumar@1800flowers.com

ORACLE_HOME=/oracle/app/oracle/product/8.1.7;export ORACLE_HOME

ORACLE_SID=800P2;export ORACLE_SID

/oracle/app/oracle/product/8.1.7/bin/svrmgrl << EOF
connect internal

EXECUTE DBMS_UTILITY.ANALYZE_SCHEMA(‘ATS’,’COMPUTE’);

disconnect;

exit

EOF

echo “ANALYZE SCHEMA OF ATS HAS completed `date`”|mailx skumar@1800flowers.com

****************************************************

File Name : analyze_schema.sql

****************************************************

set term on echo on

spool $LOGS/analyze_schema.log

execute dbms_utility.analyze_schema(‘&1′,’&2’,NULL,NULL,NULL);

exit

****************************************************

File Name : analyze_table_APR_15.sql

****************************************************

ananlyze table ATS_TELEPHONES compute statitics ;

ananlyze table WIRE_SERV_ORD compute statitics ;

****************************************************

File Name : anon_pin.sql

****************************************************

SQL> declare

2 /* DONT_KEEP_ME */

3 addr varchar2(10);

4 hash number;

5 cursor anon is

6 select address, hash_value

7 from v$sqlarea

8 where command_type = 47 — command type for anonymous block

9 and executions < 2* parse_calls;
10 begin

11 open anon;

12 loop

13 fetch anon into addr, hash;

14 exit when anon%notfound;

15 dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

16 end loop;

17 end;

18 /

PL/SQL procedure successfully completed.

SQL>

SQL> spool off

****************************************************

File Name : anon_plsql_keep.sql

****************************************************

declare

/* DONT_KEEP_ME */

addr varchar2(10);

hash number;

cursor anon is

select address, hash_value

from v$sqlarea

where command_type = 47 — command type for anonymous block

and executions < 2* parse_calls;
begin

open anon;

loop

fetch anon into addr, hash;

exit when anon%notfound;

dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

end loop;

end;

/

declare

/* DONT_KEEP_ME */

addr varchar2(10);

hash number;

cursor anon is

select address, hash_value

from v$sqlarea

where command_type = 3 — SQL – Select

and executions >50;

begin

open anon;

loop

fetch anon into addr, hash;

exit when anon%notfound;

dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

end loop;

end;

/

declare

/* DONT_KEEP_ME */

addr varchar2(10);

hash number;

cursor anon is

select address, hash_value

from v$sqlarea

where command_type = 2 — SQL – Insert

and executions >20;

begin

open anon;

loop

fetch anon into addr, hash;

exit when anon%notfound;

dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

end loop;

end;

/

declare

/* DONT_KEEP_ME */

addr varchar2(10);

hash number;

cursor anon is

select address, hash_value

from v$sqlarea

where command_type = 6 — SQL – Update

and executions >20;

begin

open anon;

loop

fetch anon into addr, hash;

exit when anon%notfound;

dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

end loop;

end;

/

declare

/* DONT_KEEP_ME */

addr varchar2(10);

hash number;

cursor anon is

select address, hash_value

from v$sqlarea

where command_type = 7 — SQL – Delete

and executions >20;

begin

open anon;

loop

fetch anon into addr, hash;

exit when anon%notfound;

dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

end loop;

end;

/

****************************************************

File Name : ats_lockers.sql

****************************************************

create or replace view ats_lockers

( BLOCK_STATUS,BLOCK_OSUSER,BLOCK_MACHINE,NO_BLOCKED,TIME_HELD,lock_type,

BLOCK_UNAME,BLOCK_SID,BLOCK_SERIAL#,OBJ_LOCKED) as

SELECT

l2.status,

l2.osuser,substr(l2.machine,1,20) machine,a.total

,L2.ctime H_TIME

,l2.type lock_type

,substr(nvl (L2.username, q$cvar.get_bpname (L2.paddr)),1,20) H_USERNAME

,L2.sid H_SID

,decode (L2.username, null, 0, L2.serial) H_SER#

,SUBSTR(RTRIM(decode (L2.obj, 0, to_char (L2.id2),

q$cvar.objschema (L2.obj)))||’.’||Rtrim(decode (L2.obj, 0, to_char (L2.id1),

q$cvar.objname (L2.obj))),1,30) H_SCHOBJ

FROM

sys.ats_lock2 L2,

(select HOLDING_SESSION hs,count(*) total from dba_waiters

group by holding_session) a

WHERE

a.hs = l2.sid

and L2.block > 0

and l2.username is not null

/

/

****************************************************

File Name : ats_lockers_cp.sql

****************************************************

create or replace view ats_lockers

( BLOCK_STATUS,BLOCK_OSUSER,BLOCK_MACHINE,NO_BLOCKED,TIME_HELD,lock_type,

BLOCK_SID,BLOCK_SERIAL#,BLOCK_UNAME,OBJ_LOCKED) as

SELECT

l2.status,

l2.osuser,

substr(l2.machine,1,20) machine,

a.total,

L2.ctime H_TIME,

l2.type lock_type,

L2.sid H_SID,

decode (L2.username, null, 0, L2.serial) H_SER#,

l2.username,

c.owner||’.’||c.object_name OBJLCK

FROM

sys.ats_lock2 L2,

(select HOLDING_SESSION hs,count(*) total from sys.dba_waiters

group by holding_session) a,

sys.dba_objects c

WHERE

a.hs = l2.sid

and L2.block > 0

and l2.username is not null

and l2.obj = c.object_id

/

****************************************************

File Name : ats_test_lock.sql

****************************************************

create or replace view ats_lockers

( BLOCK_STATUS,BLOCK_OSUSER,BLOCK_MACHINE,NO_BLOCKED,TIME_HELD,lock_type,

BLOCK_SID,BLOCK_SERIAL#,BLOCK_UNAME,OBJ_LOCKED) as

SELECT

l2.status,

l2.osuser,

substr(l2.machine,1,20) machine,

a.total,

L2.ctime H_TIME,

l2.type lock_type,

L2.sid H_SID,

decode (L2.username, null, 0, L2.serial) H_SER#,

l2.username,

c.owner||’.’||c.object_name OBJLCK

FROM

sys.ats_lock2 L2,

(select HOLDING_SESSION hs,count(*) total from sys.dba_waiters

group by holding_session) a,

sys.dba_objects c

WHERE

a.hs = l2.sid

and L2.block > 0

and l2.username is not null

and l2.obj = c.object_id

/

****************************************************

File Name : ats_v_rep_activity_monitor.sql

****************************************************

CREATE OR REPLACE VIEW ATS_V_REP_ACTIVITY_MONITOR ( EPE_CODE,

PAYTIMTYPE_CODE, EPTR_DATE, CLOCK_IN, CLOCK_OUT,

DURATION_TIME, STATUS, DPT_CODE, TLR_CODE,

LAST_NAME ) AS

SELECT /*+USE_CONCAT ORDERED FIRST_ROWS INDEX (A EMP_TIME_REC_STAT_EPE_CD_I) */

A.EPE_CODE

, A.PAYTIMTYPE_CODE

, A.EPTR_DATE

, A.CLOCK_IN

, A.CLOCK_OUT

, A.DURATION_TIME

, A.STATUS

, B.DPT_CODE

, B.tlr_code

, B.LAST_NAME

FROM

ATS_EMPLOYEE_TIME_RECORDS_1 A,

ATS_EMPLOYEES B

WHERE A.EPE_CODE = B.CODE

AND exists (select /*+Index(t tlr_pk) */ 1 from

ats_telecenters t

where B.TLR_CODE=T.CODE

AND A.EPTR_DATE >= TRUNC(SYSDATE+T.TIME_ZONE_DIFF/24))

and A.PAYTIMTYPE_CODE IN (‘B’,’P’,’M’)

AND A.STATUS = ‘A’

/

****************************************************

File Name : au.sql

****************************************************

set lines 132

set pages 2000

select a.active “Active Users”, b.tot “Total Users”,C.CD “Actual Users”

from

(select count(*) Active From v$session where username <> ‘ ‘ and status = ‘ACTIVE’) a,

(select count(*) Tot From v$session where username <> ‘ ‘ and status <> ‘KILLED’ ) b,

(select count(code) CD

from ats_employees

where code in (select username from v$session

where username not in(‘9999′,’BKGR’,’MERCORA’,’BLOOMORA’,

‘TAXUSER’,’BBXUSER’,’FAXUSER’,’CCUSER’,’EXPUSER’,’QDBA’,’TUNER’))) c

/

select username,sid,serial#,to_char(sysdate,’DD-MON-YYYY HH24:MI’) from v$session where status = ‘ACTIVE’ and username <> ‘ ‘

/

****************************************************

File Name : avail.sh

****************************************************

df -k | grep -i “/EMCdb”|awk ‘{tot += $2; used += $3; avail += $4;} END {print “Total”,tot/1024/1024,”Used “,used/1024/1024,”Avail “avail/1024/1024, “Avail % ” avail*100/tot, “Used % ” used*100/tot}’

df -k | grep -i “/testdb”|awk ‘{tot += $2; used += $3; avail += $4;} END {print “Total”,tot/1024/1024,”Used “,used/1024/1024,”Avail “avail/1024/1024, “Avail % ” avail*100/tot, “Used % ” used*100/tot}’

df -k | grep -i “/emc3830″|awk ‘{tot += $2; used += $3; avail += $4;} END {print “Total”,tot/1024/1024,”Used “,used/1024/1024,”Avail “avail/1024/1024, “Avail % ” avail*100/tot, “Used % ” used*100/tot}’

****************************************************

File Name : avlspc.sql

****************************************************

–/*________________________________________________________________________

—

–MODULE NAME : avlspc.sql

—

–SYNOPSIS : sqlplus / @avlspc.sql

—

–DESCRIPTION : This script will produce a report (avlspc.dbname.dt) listing

— of available space in all tablspaces.

—

–Limitations : MUST BE RUN FROM ORACLE DBA ACCOUNT

–_________________________________________________________________________*/

set pages 2000

column Tablespace heading ‘Tablespace|Name’ format a20

column sumb format 999,999,999,999

column extents format 9999

column bytes format 99,999,999,999

column largest format 99,999,999,999

column Tot_Size heading ‘Total|Bytes’ format 999,999,999,999

column Tot_Free heading ‘Free|Bytes’ format 999,999,999,999

column Pct_Free heading ‘Pct|Free’ format 999

column Chunks_Free heading ‘Chunks’ format 99999

column Max_Free heading ‘Biggest|Chunk’ format 9,999,999,999

break on report

compute sum of Tot_Free on report

compute sum of Tot_Size on report

column dbname noprint new_value DBName

column dt noprint new_value Dt

set feedback off

select name dbname from v$database;

select to_char(sysdate, ‘MMDDYY’) dt from dual;

set echo off pagesize 22 linesize 132 pause on

set pause More…

spool $RPT/avlspc.&DBName..&Dt

PROMPT SPACE AVIALABLE IN TABLESPACES

select a.tablespace_name Tablespace,

sum(a.tots) Tot_Size,

sum(a.sumb) Tot_Free,

sum(a.sumb)*100/sum(a.tots) Pct_Free,

sum(a.largest) Max_Free,

sum(a.chunks) Chunks_Free

from

(

select tablespace_name,

0 tots,sum(bytes) sumb,

max(bytes) largest,

count(*) chunks

from sys.dba_free_space

group by tablespace_name

union

select tablespace_name,

sum(bytes) tots,

0,

0,

0

from sys.dba_data_files

group by tablespace_name) a

group by tablespace_name

order by 4 desc

/

spool off

clear breaks

set pagesize 24 feedback on linesize 80 pause off

clear breaks columns

****************************************************

File Name : b.sql

****************************************************

create or replace view ats_dba_lock as

select

sid session_id,

decode(type,

‘MR’, ‘Media Recovery’,

‘RT’, ‘Redo Thread’,

‘UN’, ‘User Name’,

‘TX’, ‘Transaction’,

‘TM’, ‘DML’,

‘UL’, ‘PL/SQL User Lock’,

‘DX’, ‘Distributed Xaction’,

‘CF’, ‘Control File’,

‘IS’, ‘Instance State’,

‘FS’, ‘File Set’,

‘IR’, ‘Instance Recovery’,

‘ST’, ‘Disk Space Transaction’,

‘TS’, ‘Temp Segment’,

‘IV’, ‘Library Cache Invalidation’,

‘LS’, ‘Log Start or Switch’,

‘RW’, ‘Row Wait’,

‘SQ’, ‘Sequence Number’,

‘TE’, ‘Extend Table’,

‘TT’, ‘Temp Table’,

type) lock_type,

decode(lmode,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(lmode)) mode_held,

decode(request,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(request)) mode_requested,

to_char(id1) lock_id1, to_char(id2) lock_id2,

ctime last_convert,

decode(block,

0, ‘Not Blocking’, /* Not blocking any other processes */

1, ‘Blocking’, /* This lock blocks other processes */

2, ‘Global’, /* This lock is global, so we can’t tell */

to_char(block)) blocking_others

from viv_lock

/

****************************************************

File Name : backup_controlfile.sql

****************************************************

set term off echo off

alter database backup controlfile to ‘&1’;

exit

****************************************************

File Name : bad_indexes.sql

****************************************************

col name heading ‘Index Name’ format a30

col del_lf_rows heading ‘Deleted|Leaf Rows’ format 99999999

col lf_rows_used heading ‘Used|Leaf Rows’ format 99999999

col ibadness heading ‘% Deleted|Leaf Rows’ format 999.99999

SELECT name,

del_lf_rows,

lf_rows – del_lf_rows lf_rows_used,

to_char(del_lf_rows / decode(LF_ROWS, 0, 1, LF_ROWS)*100,’999.99999′) ibadness

FROM index_statistics

/

****************************************************

File Name : become_another_user.sql

****************************************************

REM* become_another_user.sql

REM*

REM* This script is valid for both Oracle7 and Oracle Version 6.

REM* It generates the commands necessary to allow you to

REM* temporarily become another user.

REM*

REM* It MUST be run from a DBA account.

REM*

REM* Input variables: The username of the account to be taken over

REM*

REM*

set pagesize 0 feedback off verify off echo off termout off

REM*

REM* Create a file called reset.sql to hold the commands generated

REM*

REM*

spool $SCRIPTS/reset.sql

prompt set feedback off verify off echo off termout off

REM*

REM* Select the encrypted password from DBA_USERS’

REM*

REM*

Select ‘alter user &&1 identified by values ‘||””||password||””||’;’

From dba_users where username = upper(‘&&1’);

prompt host rm $SCRIPTS/reset.sql

prompt exit

spool off

exit

****************************************************

File Name : bi.sql

****************************************************

set term off echo off

set pagesize 60 feedback off heading off verify off

col report_date format a20 new_value rptdate noprint

var dnl_id number

define dnl_id=&&1

select to_char(sysdate,’MM/DD/YY HH24:MI’) report_date from dual;

rem spool d:intertest

set concat +

set concat .

prompt Interactive Problem Report. Batch ID &&1, Date: &&rptdate

prompt Details With No Header

prompt

select distinct order_id1 from ats_int_det_tmp

where order_id1 not in (select order_id from

ats_int_head_tmp) and download_id=:dnl_id;

/

****************************************************

File Name : bind_var.sql

****************************************************

–The address of the sql that has more versions from v$sqlarea

select a.address,a.position,a.datatype,a.max_length,a.array_len,a.bind_name

from v$sql_bind_metadata a, v$sql_Shared_cursor b

where a.address = b.address

and KGLHDPAR = ‘CD22BA58’

order by 2,3,4

/

****************************************************

File Name : bind_var_dump.sql

****************************************************

exec dbms_system.set_ev(584,58072,10046,8,”);

****************************************************

File Name : bits.sql

****************************************************

select

round((congets.value+dbgets.value-physreads.value)*100/

(congets.value+dbgets.value),4) “BUFFER HIT RATIO”

from v$sysstat congets,

v$sysstat dbgets,

v$sysstat physreads

where congets.name=’consistent gets’

and dbgets.name = ‘db block gets’

and physreads.name = ‘physical reads’

/

select

ds.value/decode( (ds.value+ms.value) ,0,1,(ds.value+ms.value))*100 “Disk Sort Ratio”

from v$sysstat ds,

v$sysstat ms

where ms.name=’sorts (memory)’

and ds.name=’sorts (disk)’

/

select

round((sum(waits) / sum(gets)) * 100,2)||’%’ “Rollback Wait Ratio”

from v$rollstat

/

select sum(gets-getmisses)*100/sum(gets) “Dictionary Cache Hit Ratio”

from v$rowcache

/

****************************************************

File Name : bits_rep.sql

****************************************************

declare

begin

select

round((congets.value+dbgets.value-physreads.value)*100/(congets.value+dbgets.value),4)

into buff_hit_rat

from v$sysstat congets,

v$sysstat dbgets,

v$sysstat physreads

where congets.name=’consistent gets’

and dbgets.name = ‘db block gets’

and physreads.name = ‘physical reads’;

select

ds.value/decode( (ds.value+ms.value) ,0,1,(ds.value+ms.value))*100

into disk_sort_rat

from v$sysstat ds,

v$sysstat ms

where ms.name=’sorts (memory)’

and ds.name=’sorts (disk)’;

select

round((sum(waits) / sum(gets)) * 100,2)

into rollback_rat

from v$rollstat;

select sum(gets-getmisses)*100/sum(gets)

into diction_rat

from v$rowcache;

insert into bits (measured_date,buffer_hit_ratio,disk_sort_ratio,rollback_wait_ratio,dictionary_hit_ratio)

values (to_date(‘&1′,’YYYYMMDD’), buff_hit_rat,disk_sort_rat,rollback_rat,diction_rat)

commit;

end;

/

exit

/

****************************************************

File Name : block_ident.sql

****************************************************

select distinct owner, segment_name, segment_type

from dba_extents where file_id = &1

and &2 between block_id and block_id+blocks-1;

;

****************************************************

File Name : block_on_hot_latches.sql

****************************************************

column segment_name format a40

select /*+ ordered */

e.owner ||’.’|| e.segment_name segment_name,

e.extent_id extent#,

x.dbablk – e.block_id + 1 block#,

e.file_id file#

from

sys.v_$latch_children l,

( select

avg(sleeps) sleeps

from

sys.v_$latch_children

where

name = ‘cache buffers chains’

) a,

sys.x$bh x,

dba_extents e

where

l.name = ‘cache buffers chains’ and

l.sleeps > 2 * a.sleeps and

x.hladdr = l.addr and

x.inst_id = userenv(‘Instance’) and

e.file_id = x.file# + 1 and

x.dbablk between e.block_id and e.block_id + e.blocks – 1

/

****************************************************

File Name : bmark.sql

****************************************************

set echo off

set feedback off

set verify off

set pagesize 999

spool bmark.lis

Doc

Benchmark Performance Statistics : Release 1

Author: Mark Gurry “Oracle Performance Tuning”

Description: This script is an early release of a total database tuning

script.

Hints: It is best to run this script as SYS because some of the

tables/views may not be accessible to other users. Most

of the scripts will run successfully as other DBA users

if you do not have access to the SYS account. You must

run the script in SQL*Plus NOT SQL*DBA.

You are required to run $ORACLE_HOME/rdbms/admin/catparr.sql

prior to running this script, to receive buffer cache

information. You only need to run the catparr script once,

and the views that it creates will remain in place.

Inputs: The script will request two pieces of information from you.

Both are being asked to avoid lengthy printouts. Note that

even if you do no answer Y or y, the output results will be

in the region of 15 pages.

(1) Do you request all of the INIT.ORA parameters listed

Print_init_ora_parameters_y_n To have them listed,

enter Y or y.

(2) Do you wish to look inside the buffer cache to receive

a full list of objects. The size of this output and the

length of time that it takes to run will be directly

proportional to the DB_BLOCK_BUFFERS setting. The larger

the setting, the longer the run will take and the larger

the size of the output.

#

define init.ora = ‘&&Print_init_ora_parameters_y_n’

Doc

Before we start, it is always nice to work out the versions of the

the database server. This may prove useful if we need to compare this

output against a future release of Oracle

#

select *

from v$version

/

ttitle ‘ INIT.ORA Parameters ‘

column name format a30

column value format a32

select name, value

from v$parameter

where ‘&&Print_init_ora_parameters_y_n’ in (‘y’,’Y’);

ttitle ‘ Undocumented Parameters’

column ksppinm format a34

column ksppivl format a45

select ksppinm, ksppivl from x$ksppi

where substr(ksppinm,1,1) = ‘_’

and ‘&&Print_init_ora_parameters_y_n’ in (‘y’,’Y’);

column value format 999,999,999,999

doc

The following listing gives details of the Shared Global Area

breakdown in memory. The more significant information is the

reading for “free memory”, which indicates that the SHARED_POOL_SIZE

INIT.ORA parameter may be reduced if the free memory is excessive.

If it is low, you should NOT be decreasing the SHARED_POOL_SIZE.

Be careful however, because Oracle tends to maintain some free

memory even when the buffer cache is flooded with activity and

should be made larger.

Other figures that are useful are the size of the buffer cache

“db_block_buffers” which is usually required to be at least 20 Meg

for optimum performance, the sql_area, which is where all of the

shared SQL is placed, the dictionary cache, which is where Oracle’s

dictionary is placed, and the “log buffer” which is where all

changes are written prior to writing to your redo logs.

The log buffer should typically be at least 32078 or larger.

The “shared_sql” and “dictionary_cache” sizes are affected by the

size that you set the SHARED_POOL_SIZE INIT.ORA parameter to.

Unfortunately, the dictionary cache is tuned automatically and not

very well by the kernel. Most sites operate most effeciently with

a shared pool size of at least 30000000.

#

ttitle ‘ SGA Statistic Listing ‘

select *

from v$sgastat;

ttitle ‘ The Hit Ratio ‘

select

sum(decode(name, ‘consistent gets’,value, 0)) “Consis Gets”,

sum(decode(name, ‘db block gets’,value, 0)) “DB Blk Gets”,

sum(decode(name, ‘physical reads’,value, 0)) “Phys Reads”,

(sum(decode(name, ‘consistent gets’,value, 0)) +

sum(decode(name, ‘db block gets’,value, 0)) –

sum(decode(name, ‘physical reads’,value, 0)))

/

(sum(decode(name, ‘consistent gets’,value, 0)) +

sum(decode(name, ‘db block gets’,value, 0)) ) * 100 “Hit Ratio”

from v$sysstat st;

doc

The following output is of Oracle’s dictionary cache the is

stored in memory, in the System Global Area. The dictionary is

tuned automatically by Oracle. The three columns displayed are the

dictionary cache parameter, the count that Oracle has set the parameter

to and the number of times that Oracle has had to reload the dictionary

information from disk. When Oracle is first started and objects are

being accessed for the first time, a miss occurs because a disk read

has been required to access the information. Ideally from then on,

there will be no more misses because the dictionary info will be

nicely placed in memory. Unfortunately this is not the case. Oracle’s

self tuning mechainism does not appear to work very well.

In the following query, the ideal output would be to see the

the getmisses less than or equal to the count, which implies that

the parameter has been set sufficiently high enough to fit all of

the dictionary items into memory without having to flush them out

and then reload them.

If you are getting deplorable figures, i.e. the getmisses considerably

higher than the count, increase the SHARED_POOL_SIZE. If this has no

effect, then join the club requesting that Oracle re-introduce the ability

for DBAs to tune the dictionary cache.

#

ttitle ‘ Dictionary Cache (Part of Shared Buffer Pool)’

select parameter, count, getmisses

from v$rowcache

where getmisses > count;

doc

The following script shows the spread of disk I/O’s. Ideally the

disk I/O’s should be even across disks. If the disk I/O on one

of the disks is too high, consider moving one of the datafiles on

that disk to another disk. If you are using raw devices, it is

handy to make the raw devices consistent sizes for this purpose.

If you can’t move one of the datafiles, consider moving objects

into tablespaces on different disks.

If there is a large amount of activity on one of the disks, there

is often an untuned query causing the damage. Be aware of which

table is causing the problems. The V$SQLAREA table has a column

called disk reads as well as the SQL statement that was performed.

If you select all statements with > 1000 disk reads, and order it

by disk reads desc, it is often an indicator of the problem query.

See the selection from the table later in this script.

One trick that is often done is to alternate rollbacks one disk to

the next into alternate tablespaces, for example, rollback1 will be

created on the rollback_disk1 tablespace, rollback2 on rollback_disk2

tablespace, rollback3 on rollback_disk1 tablespace, rollback4 on

rollback_disk2 tablespace and so on. Of course, you must have the

rollback_disk1 tablespace on a separate disk drive to rollback_disk2.

#

drop table tot_read_writes;

create table tot_read_writes

as select sum(phyrds) phys_reads, sum(phywrts) phys_wrts

from v$filestat;

ttitle ‘ Disk I/O s by Datafile ‘

column name format a30;

column phyrds format 999,999,999;

column phywrts format 999,999,999;

column read_pct format 999.99;

column write_pct format 999.99;

select name, phyrds, phyrds * 100 / trw.phys_reads read_pct,

phywrts, phywrts * 100 / trw.phys_wrts write_pct

from tot_read_writes trw, v$datafile df, v$filestat fs

where df.file# = fs.file#

order by phyrds desc;

doc

The next group of figures are the those for table accesses.

The “table fetch row continued rows” have been accessed and the row has

either been chained or migrated. Both situations result from part of

a row has been forced into another block. The distinction is for

chained rows, a block is physically to large to fit in one physical

block.

In these cases, you should look at increasing the db_block_size

next time you re-build your database, and for other environments, e.g.

when you move your application into production. Migrated rows are rows

that have been expanded, and can no longer fit into the same block. In these

cases, the index entries will point to the original block address, but the

row will be moved to a new block. The end result is that FULL TABLE SCANS

will run no slower, because the blocks are read in sequence regardless of

where the rows are. Index selection of the row will cause some degradation

to response times, because it continually has to read an additional block.

To repair the migration problem, you need to increase the PCTFREE on the

offending table.

The other values include “table scans (long tables)” which is a scan

of a table that has > 5 database blocks and table scans (short tables)

which is a count of Full Table Scans with 5 or less blocks. These values

are for Full Table Scans only. Any Full Table Scan of a long table can

be potentially crippling to your application’s performance. If the number

of long table scans is significant, there is a strong possibility that

SQL statements in your application need tuning or indexes need to be added.

To get an appreciation of how many rows and blocks are being accessed on

average for the long full table scans:

Average Long Table Scan Blocks =

table scan blocks gotten – (short table scans * 5)

/ long table scans

Average Long Table Scan Rows =

table scan rows gotten – (short table scans * 5)

/ long table scans

The output also includes values for “table scan (direct read)” which

are those reads that have bypassed the buffer cache, table scans

(rowid ranges) and table scans (cache partitions).

#

select name, value

from v$sysstat

where name like ‘%table %’

/

drop view Full_Table_Scans;

create view Full_Table_Scans as

select

ss.username||'(‘||se.sid||’) ‘ “User Process”,

sum(decode(name,’table scans (short tables)’,value)) “Short Scans”,

sum(decode(name,’table scans (long tables)’, value)) “Long Scans”,

sum(decode(name,’table scan rows gotten’,value)) “Rows Retreived”

from v$session ss, v$sesstat se, v$statname sn

where se.statistic# = sn.statistic#

and ( name like ‘%table scans (short tables)%’

OR name like ‘%table scans (long tables)%’

OR name like ‘%table scan rows gotten%’ )

and se.sid = ss.sid

and ss.username is not null

group by ss.username||'(‘||se.sid||’) ‘

/

column “User Process” format a20;

column “Long Scans” format 999,999,999;

column “Short Scans” format 999,999,999;

column “Rows Retreived” format 999,999,999;

column “Average Long Scan Length” format 999,999,999;

ttitle ‘ Table Access Activity By User ‘

select “User Process”, “Long Scans”, “Short Scans”, “Rows Retreived”

from Full_Table_Scans

order by “Long Scans” desc;

ttitle ‘Average Scan Length of Full Table Scans by User ‘

select “User Process”, ( “Rows Retreived” – (“Short Scans” * 5))

/ ( “Long Scans” ) “Average Long Scan Length”

from Full_Table_Scans

where “Long Scans” != 0

order by “Long Scans” desc;

doc

The ideal is to have as much sorting in memory as possible. The

amount of memory available for sorting in memory is set by assigning

a value to the INIT.ORA parameter SORT_AREA_SIZE. If there is a large

amount of sorting being done on disk, consider enlarging the

SORT_AREA_SIZE. Be aware that this parameter applies to all users

and there must be sufficient memory to adjust the parameter upwards.

Some sorts to disk are simply too large to be done in memory. In these

cases, make sure that the DEFAULT INITIAL and NEXT extents are sized

sufficiently large enough to avoid unnecessary dynamic extension.

#

ttitle ‘ Checking any Disk Sorts’

select name, value from v$sysstat

where name like ‘sort%’;

doc

The following query indicates the amount of rollbacks performed

on the transaction tables.

(i) ‘transaction tables consistent reads – undo records applied’

is the total # of undo records applied to rollback transaction

tables only

It should be < 10% of the total number of consistent changes (ii) ‘transaction tables consistent read rollbacks’
is the number of times the transaction tables were rolled back

It should be less than 0.1 % of the value of consistent gets

If either of these scenarios occur, consider creating more rollback

segments, or a greater number of extents in each rolback segment. A

rollback segment equates to a transaction table and an extent is like

a transaction slot in the table.

Another interesting approach that Oracle mentions is to do a

SELECT COUNT(*) FROM TNAME(s); where the TNAMES are the tables

that the blocks that have been modified and committed occur in.

This marks the transactions as committed and later queries do not

have to find the status of the transactions in the transaction tables

to determine the status of the transactions.

#

ttitle ‘Amount of Rollbacks on Transaction Tables’

select name, value

from v$sysstat

where name in

(‘consistent gets’,

‘consistent changes’,

‘transaction tables consistent reads – undo records applied’,

‘transaction tables consistent read rollbacks’);

select ‘Tran Table Consistent Read Rollbacks > 1% of Consistent Gets’ aa,

‘Action: Create more Rollback Segments’

from v$sysstat

where decode (name,’transaction tables consistent read rollbacks’,value)

* 100

/

decode (name,’consistent gets’,value) > 0.1

and name in (‘transaction tables consistent read rollbacks’,

‘consistent gets’)

and value > 0

;

select ‘Undo Records Applied > 10% of Consistent Changes’ aa,

‘Action: Create more Rollback Segments’

from v$sysstat

where decode

(name,’transaction tables consistent reads – undo records applied’,value)

* 100

/

decode (name,’consistent changes’,value) > 10

and name in

(‘transaction tables consistent reads – undo records applied’,

‘consistent changes’)

and value > 0

;

doc

The last two values returned in the following query are the number

of times data blocks have been rolled back. If the number of rollbacks

is continually growing, it can be due to inappropriate work practice.

Try breaking long running queries into shorter queries, or find another

method of querying hot blocks in tables that are continually changing.

#

select name , value

from v$sysstat

where name in

(‘data blocks consistent reads – undo records applied’,

‘no work – consistent read gets’,

‘cleanouts only – consistent read gets’,

‘rollbacks only – consistent read gets’,

‘cleanouts and rollbacks – consistent read gets’)

;

doc

Each rollback segment has a transaction table that controls the

transactions accessing the rollback segment. Oracle documentation

says that the transaction table has approximately 30 slots in the

table if your database has a 2k block size. The following query

lists the number of waits on a slot in the transaction tables. The

ideal is to have the waits zero, but in the real world this is not

always achievable. The should be as close to zero as possible.

At the very worst, the ratio of gets to waits should be around 99%.

#

select usn “Rollback Table”, Gets, Waits , xacts “Active Transactions”

from v$rollstat;

doc

It is important that rollback segments do not extend very often.

Dynamic extension is particularly damaging to performance, because

each extent used (or freed) is written to disk immediately. See the

uet$ and fet$ system tables.

Some sites have a large amount of performance degradation when

the optimal value is set, because the rollback is continually

shrinking and extending. This situation has been improved to

make the SMON less active where the PCTINCREASE is set to 0.

Note: in this case, free extents will not be coalesced. When

a rollback throws extents after it has shrunk back, it will hopefully

find an extent of the correct size. If you would like the coalescing

to continue, set the PCTINCREASE on the tablespace to 1.

We usually recommend NOT to use the OPTIMAL setting.

The listing below provides figures on how many times each rollback

segment has had to extend and shrink.

#

select usn, extends, shrinks, hwmsize, aveshrink

from v$rollstat;

doc

The following query shows you the amount of overall changes that are

made to data blocks in the database ‘db block changes’. The second

value returned is the number of blocks that have been rolled back

‘rollback changes – undo records applied’ and the third value is the

number of rollback transactions ‘transaction rollbacks’.

When a rollback takes place, it can hold many resources until the

rollback is complete. If the rollbacks are significant in size, i.e.

the cause of the rollbacks should be investigated. A way to check

this is to check ‘rollback changes – undo records applied’ /

‘transaction rollbacks’.

If the overall percentage of rows rolled back as compared to those

changes is significant (> .5%), you should question why are so many

rows being rolled back. The causes could be many, including a network

failure where sessions are continually being lost. Consider introducing

SAVEPOINTS where appropriate or using shorter transactions to have

fewer rows to rollback (i.e. more frequent commits and less rows being

processed).

#

doc

ttitle ‘Get all V$SYSSTAT’

column value format 999999999;

select * from v$sysstat;

#

doc

The following query displays information on wait contention for

an Oracle object. The two figures of particular importance are

the ‘data block’ and the ‘undo header’ waits. The undo header

indicates a wait for rollback segment headers which can be solved by

adding rollback segments.

The data block wait is a little harder to find the cause of and

a little harder to fix. Basically, transactions are contending for

hot data blocks, because it is being held by another transaction,

or contending for shared resources within the block. e.g. transaction

entries (set by the INITRANS parameter) and rows. The INITRANS

storage parameter sets the number of transaction slots set aside

within each table/index. The default INITRANS is 1. If more than

one transaction is waiting to access a block, a second transaction

slot will have to be created. Each transaction slot uses 23 bytes.

The ideal count on the data block waits is 0. This is usually not

achievable in the real world, because the storage overhead of increasing

the INITRANS is usually not justified given the large amount of

storage overhead that it will introduce. Data block contention can cause

problems and enlarging INITRANS can improve performance, so don’t

dismiss the idea of enlarging INITRANS immediately. Potential

performance improvements CAN be significant.

Identifying the blocks that are experiencing contention is quite

difficult to catch. Your best chance is to examine the output from the

query from the V$SESSION_WAIT table below. You may consider increasing

the PCTFREE in the table to have fewer rows per block, or make a design

change to your application to have fewer transactions accessing the same

block.

#

ttitle ‘Get All Waits’

column count format 9999999;

select class, count

from v$waitstat;

ttitle ‘Sessions experiencing block level contention’

select ss.username, sw.p1 “File”, sw.p2 “Block”

from v$session_wait sw, v$session ss

where event = ‘buffer busy waits’

and ss.sid = sw.sid;

ttitle ‘ The Object that has Experienced Contention ‘

doc

column “Owner” format a16

column “Segment Name” format a30

select owner “Owner” , segment_name “Segment Name”

from dba_extents

where (file_id, block_id)

in

(select file_id, block_id

from dba_extents, v$session_wait vw

where file_id = vw.p1

and (p1 , p2 )

in

(select p1 , p2

from v$session_wait

where event = ‘buffer busy waits’)

and block_id= (select max(block_id)

from dba_extents

where block_id < vw.p2 ))
/

#

doc

The following query indicates a transaction waiting for resources

within a block currently held by another transaction. This can

be caused by having to throw another transaction slot in the

block.

In extreme cases, throwing many transaction slots into a

block can cause the migration of a row, which will have a similar

effect to chaining, when the block is accessed via an index, i.e.

two blocks may have to be read to retrieve a row. Remember that each

transaction slot uses 23 bytes. The smaller the DB_BLOCK_SIZE the

greater the possibility of row migration. The other cause of the

locks in the following query is that a row within the block are

sought after by two separate transactions. This problem is usually

only fixable through an application change, where you postpone the

changes to the rows until the last possible moment in the transaction.

#

ttitle ‘Transactions Experiencing Lock Contention’

select *

from v$lock

where type = ‘TX’;

Doc

The following query scans through the buffer cache and counts the number

of buffers in the various states. The three main states are CUR which is

blocks read but not dirtied, CR which are blocks that have been dirtied

and are remaining in cache with the intention of supplying the new values

to queries about to start up. FREE indicates buffers that are usable to

place new data being read into the buffer cache. You occasionally get

buffers in a status of READ which are those buffers currently being read

into the buffer cache.

The major information from the query is if the FREE count is high, say

> 50% of overall buffers, you may consider decreasing the DB_BLOCK_BUFFERS

parameter. Note however, that Oracle attempts to maintain a free count >

0, so consistently having free buffers does not automatically imply that

you should have lower the parameter DB_BLOCK_BUFFERS.

ttitle ‘ Free Buffer in Buffer Cache’

To create the view v$bh, which is used by this script, you must run

the script $ORACLE_HOME/rdbms/admin/catparr.sql

#

ttitle ‘ Current Buffer Cache Usage ‘

select status, count(*)

from v$bh

group by status;

drop table bh_temp;

create table bh_temp

as select * from v$bh;

doc

This is required for pre-7.1 of the database. Use the script below for

all release 7.1 and after. Note: You MUST run the script

$ORACLE_HOME/rdbms/admin/catparr.sql prior to running this script.

ttitle ‘ Detailed Buffer Cache Usage by Objects ‘

column owner format a12;

column segment_type format a10;

column segment_name format a22;

column tablespace_name format a16;

column “Num Buffers” format 9999;

select e.owner, e.segment_type, e.segment_name, tablespace_name, count(*)

“Num Buffers”

from dba_extents e , bh_temp b

where file# / 4 = e.file_id

and b.block# between e.block_id and e.block_id + e.blocks

group by e.owner, e.segment_type, e.segment_name, tablespace_name;

Remember that the buffer cache stores Tables, Indexes, Dictionary Tables,

Sort Temporary Tables and Rollback Segments. Oracle 7.1, 7.2 and 7.3

of Oracle introduce options to bypass the buffer cache for some of these

operations.

See the 7.2 parameter SORT_DIRECT_TRUE which bypasses the buffer cache and

allows sorts to run as much as 3 times as fast.

In 7.1.6 parallel table scans can bypass the buffer cache if you set

compatible=7.1.6

In 7.2 Oracle turns off logging (not strictly buffer cache) if you use the

UNRECOVERABLE option. When building an index, you can bypass writing to

redo logs by setting this parameter. The direct load path is used also to

bypass the buffer cache. One interesting point is that INRECOVERABLE is

the default when Archiving is not enabled.

#

set pagesize 66

ttitle ‘ Breakdown of what is Currently Being Stored in the Buffer Cache’

select kind, name, status, count(*)

from v$cache

where substr(‘&Look_inside_Buffer_Cache?’,1,1) in (‘y’,’Y’)

group by kind, name, status;

doc

When you enlarge the DB_BLOCK_BUFFERS, if you see decreases in the

values returned in the following query, it is almost always associated

with a performance improvement. Keep in mind that there are two aspects to

buffer cache tuning (i) having data in memory is up to several thousand

times faster than finding it on disk and (ii) when Oracle is reading data

into memory and is forced to clear buffers quickly because buffer cache

is too small, it often does so in “panic mode” which can have a harmful

effect on performance.

This means that the HIT RATIO alone tells only part of the story.

The following figures tell us how much panicking the DBWR has had to do.

It is best if the cache is sufficiently large enough to clean blocks out

using the normal mechanisms rather than in panic mode.

NOTE: The DBWR process writes to disk under the following circumstances

(i) When a process dirties a buffer and the number of dirty buffers in the

buffer cache reaches the count set by the parameter DB_BLOCK_WRITE_BATCH.

If this is the case 50% of the dirty buffers are written to disk.

(ii) When a process searches DB_BLOCK_MAX_SCAN_CNT buffers in the list

without finding a free buffer. If this is the case it signals the

DBWR to write to make way for free buffers.

(iii) Every 3 seconds (when a timeout occurs).

(iv) When a checkpoint occurs the LGWR instructs the DBWR to write.

The last situation is interesting because it implies that badly tuned

checkpoints will potentially cause DBWR problems.

The rows returned in the query below indicate the following:

DBWR Checkpoints: is the number of times that checkpoints were sent to the

database writer process DBWR. The log writer process hands a list of modified

blocks that are to be written to disk. The “dirty” buffers to be written

are pinned and the DBWR commences writing the data out to the database.

It is usually best to keep the DBWR checkpoints to a minimum, although

if there are too many dirty blocks to write out to disk at the one time

due to a “lazy” DBWR, there may be a harmful effect on response times for

the duration of the write. See the parameters LOG_CHECKPOINT_INTERVAL and

LOG_CHECKPOINT_TIMEOUT which have a direct effect on the regularity of

checkpoints. The size of your red logs can also have an effect on the

number of checkpoints if the LOG_CHECKPOINT_INTERVAL is set to a size

larger than your redo logs and the LOG_CHECKPOINT_TIMEOUT is longer than

the time it takes fill a redo log or it has not been set.

DBWR timeouts: the # times that the DBWR looked for dirty blocks to

write to the database. Timeouts occur every 3 seconds if the DBWR is idle.

DBWR make free requests: is the number of messages recieved requesting the

database writer process to make the buffers free. This value is a key

indicator as to how effectively your DB_BLOCK_BUFFERS parameter is tuned.

If you increase DB_BLOCK_BUFFERS and this value decreases markedly, there

is a very high likelihood that the DB_BLOCK_BUFFERS was set too low.

DBWR free buffers found: is the number of buffers that the DBWR found

on the lru chain that were already clean. You can divide this value by

the DBWR make free requests to obtain the number of buffers that were

found which were free and clean (i.e. did NOT have to be written to disk).

DBWR lru scans: the number of times that the database writer scans the lru

for more buffers to write. The scan can be invoked either by a make free

request or by a checkpoint.

DBWR summed scan depth: can be divided by DBWR lru scans to determine the

length of the scans through the buffer cache. This is NOT the number of

buffers scanned. if the write batch is filled and a write takes place

to disk, the scan depth halts.

DBWR buffers scanned: is the total number of buffers scanned when looking

for dirty buffers to write to disk and create free space. The count

includes both dirty and clean buffers. It does NOT halt like the

DBWR summed scan depth.

#

ttitle ‘The Amount of Times Buffers Have Had to Be Cleaned Out’

select name , value

from v$sysstat

where name like ‘DBW%’;

ttitle ‘The Average Length of the Write Request Queue’

column “Write Request Length” format 999,999.99

select decode (name, ‘summed dirty queue length’, value)

/

decode (name, ‘write requests’, value) “Write Request Length”

from v$sysstat

where name in ( ‘summed dirty queue length’

,’write requests’)

and value > 0

/

doc

The information listed in the next query is the count for “Dirty Buffers

Inspected”. This figure indicates that the DBWR process can’t keep up

through natural atrition and a dirty buffer has been aged out through

the LRU queue, when a user process has been looking for a free buffer

to use. This value should ideally be zero. The value is probably THE key

indicator of the DB_BLOCK_BUFFERS init.ora parameter being set too small,

particularly if you enlarge the DB_BLOCK_BUFFERS parameter and the value

reduces after each decrease.

Also included in the output, is the value for “Free Buffers Inspected”.

This figure indicates the number of times a user process has scanned the

LRU list for free buffers. A high value would indicate that there are too

many dirty blocks on the LRU list and the user process had to stop because

the dirty queue was at its threshold.

#

column “Dirty Buffers” format 999,999,999;

column “Free Buffers Inspected” format 999,999,999;

ttitle ‘Lazy DBWR Indicators – Buffers Inspected’

select decode (name, ‘dirty buffers inspected’, value) “Dirty Buffers”,

decode (name, ‘free buffer inspected’, value) “Free Buffers Inspected”

from v$sysstat

where name in ( ‘dirty buffers inspected’

,’free buffer inspected’)

and value > 0

/

doc

The following query breaks down hit ratios by user. The lower the hit ratio

the more disk reads that have to be performed to find the data that the user

is requesting. If a user is getting a low hit ratio (say < 60%), it is often
caused because the user not using indexes effectively or an absence of

indexes. It can sometimes be quite OK to get a low hit ratio if the user

is accessing data that has not been accessed before and cannot be shared

amongst users. Note: OLTP applications ideally have a hit ratio in the mid

to high 90s.

The second query lists the tables that the user processes with a hit ratio

less than 60% were accessing. Check the tables to ensure that there are no

missing indexes.

#

ttitle ‘ User Hit Ratios’

column “Hit Ratio” format 999.99

column “User Session” format a15;

select se.username||'(‘|| se.sid||’)’ “User Session”,

sum(decode(name, ‘consistent gets’,value, 0)) “Consis Gets”,

sum(decode(name, ‘db block gets’,value, 0)) “DB Blk Gets”,

sum(decode(name, ‘physical reads’,value, 0)) “Phys Reads”,

(sum(decode(name, ‘consistent gets’,value, 0)) +

sum(decode(name, ‘db block gets’,value, 0)) –

sum(decode(name, ‘physical reads’,value, 0)))

/

(sum(decode(name, ‘consistent gets’,value, 0)) +

sum(decode(name, ‘db block gets’,value, 0)) ) * 100 “Hit Ratio”

from v$sesstat ss, v$statname sn, v$session se

where ss.sid = se.sid

and sn.statistic# = ss.statistic#

and value != 0

and sn.name in (‘db block gets’, ‘consistent gets’, ‘physical reads’)

group by se.username, se.sid;

drop table user_hit_ratios;

create table user_hit_ratios as

(select se.username||'(‘|| se.sid||’)’ “User Session”,

sum(decode(name, ‘consistent gets’,value, 0)) “Consistent Gets”,

sum(decode(name, ‘db block gets’,value, 0)) “DB Block Gets”,

sum(decode(name, ‘physical reads’,value, 0)) “Physical Reads”,

(sum(decode(name, ‘consistent gets’,value, 0)) +

sum(decode(name, ‘db block gets’,value, 0)) –

sum(decode(name, ‘physical reads’,value, 0)))

/

(sum(decode(name, ‘consistent gets’,value, 0)) +

sum(decode(name, ‘db block gets’,value, 0)) ) * 100 “Hit Ratio”

from v$sesstat ss, v$statname sn, v$session se

where ss.sid = se.sid

and sn.statistic# = ss.statistic#

and value != 0

and sn.name in (‘db block gets’, ‘consistent gets’, ‘physical reads’)

group by se.username, se.sid);

break on “User Session”

doc

ttitle ‘Objects Being Used by Users with Hit Ratio < 60' select se0.username||'(‘|| se0.sid||’)’ “User Session”,
substr(owner, 1,12) “Object Owner”,

substr(object,1,30) “Object”

from v$access ac, v$session se0

where ac.sid = se0.sid

and ob_typ = 2

and 60 >

(select “Hit Ratio” from user_hit_ratios

where se0.username||'(‘|| se0.sid||’)’ = “User Session”)

order by username, se0.sid, owner ;

column “User Session” format a12;

ttitle ‘Cursors that Users currently have Open Where User Hit Ratio < 60%' select distinct username||'(‘||v$session.sid||’)’ “User Session”, sql_text
from v$open_cursor , v$session

where v$session.saddr = v$open_cursor.saddr

and 60 >

(select “Hit Ratio” from user_hit_ratios

where username||'(‘||user_hit_ratios.sid||’)’ = “User Session”)

order by username, v$session.sid;

/

ttitle ‘Cursors Currently Running for Users with Hit Ratio < 60% ' select username||'(‘||v$session.sid||’)’ “User Session”, sql_text
from v$open_cursor , v$session

where v$session.sql_address = v$open_cursor.address

and v$session.sql_hash_value = v$open_cursor.hash_value

and 60 >

(select “Hit Ratio” from user_hit_ratios

where username||'(‘||user_hit_ratios.sid||’)’ = “User Session”)

order by username, v$session.sid;

/

#

column “Response” format 999,999,999.99;

column nl newline;

ttitle ‘List Statements in Shared Pool with the Most Disk Reads’

select sql_text nl, ‘Executions=’|| executions nl,

‘Expected Response Time in Seconds= ‘,

disk_reads / decode(executions, 0, 1, executions) / 50 “Response”

from v$sqlarea

where disk_reads / decode(executions,0,1, executions) / 50 > 10

order by executions desc;

column “Response” format 999,999,999.99

ttitle ‘List Statements in Shared Pool with the Buffer Scans’

select sql_text nl, ‘Executions=’|| executions nl,

‘Expected Response Time in Seconds= ‘,

buffer_gets / decode(executions, 0, 1, executions) / 500 “Response”

from v$sqlarea

where buffer_gets / decode(executions, 0,1, executions) / 500 > 10

order by executions desc;

ttitle ‘List Statements in Shared Pool with the Most Loads’

select sql_text, loads

from v$sqlarea a

where loads > 100

order by loads desc;

doc

column username format a12;

column ses.sid format 999999;

ttitle ‘User Resource Usage’

select ses.sid, ses.username, sn.name, sest.value

from v$session ses, v$statname sn, v$sesstat sest

where ses.sid=sest.sid

and sn.statistic# = sest.statistic#

and sest.value is not null

and sest.value != 0

order by ses.username, ses.sid, sn.name;

column “User Session” format a12;

ttitle ‘Cursors that Users currently have Open’

select username||'(‘||v$session.sid||’)’ “User Session”, sql_text

from v$open_cursor , v$session

where v$session.saddr = v$open_cursor.saddr

/

ttitle ‘Cursors Currently Running for a User ‘

select username||'(‘||v$session.sid||’)’ “User Session”, sql_text

from v$open_cursor , v$session

where v$session.sql_address = v$open_cursor.address

and v$session.sql_hash_value = v$open_cursor.hash_value

/

#

doc

The following figures are the reloads required for SQL, PL/SQL,

packages and procedures. The ideal is to have zero reloads because

a reload by definitions is where the object could not be maintained

in memory and Oracle was forced to throw it out of memory, and then

a request has been made for it to be brought back in. If your reloads

are very high, try enlarging the SHARED_POOL_SIZE parameter and

re-check the figures. If the figures continue to come down, continue

the SHARED_POOL_SIZE in increments of 5 Meg.

#

ttitle ‘ Total Shared Pool Reload Stats ‘

select namespace, reloads

from v$librarycache;

doc

The following three queries obtain information on the SHARED_POOL_SIZE.

The first query lists the packages, procedures and functions in the

order of largest first.

The second query lists the number of reloads. Reloads can be very

damaging because memory has to be shuffled within the shared pool area

to make way for a reload of the object.

The third parameter lists how many times each object has been executed.

Oracle has provided a procedure which is stored in $ORACLE_HOME/rdbms/admin

called dbmspool.sql The SQL program produces 3 procedures. A procedure

called keep (i.e. dbms_shared_pool.keep) can be run to pin a procedure in

memory to ensure that it will not have to be re-loaded.

Oracle 7.1.6 offers 2 new parameters that allow space to be reserved for

procedures/packages above a selected size. This gives greater control

over the avoidance of fragmentation in the SHARED POOL.

See the parameters SHARED_POOL_RESERVED_SIZE and

SHARED_POOL_RESERVED_MIN_ALLOC.

They are listed later in this report.

#

set pagesize 999

column owner format a16

column name format a36

column sharable_mem format 999,999,999

column executions format 999,999,999

ttitle ‘ Memory Usage of Shared Pool Order – Biggest First’

select owner, name||’ – ‘||type name, sharable_mem from v$db_object_cache

where sharable_mem > 10000

and type in (‘PACKAGE’, ‘PACKAGE BODY’, ‘FUNCTION’, ‘PROCEDURE’)

order by sharable_mem desc

/

ttitle ‘ Loads into Shared Pool – Most Loads First’

select owner, name||’ – ‘||type name, loads , sharable_mem from v$db_object_cache

where loads > 3

and type in (‘PACKAGE’, ‘PACKAGE BODY’, ‘FUNCTION’, ‘PROCEDURE’)

order by loads desc

/

ttitle ‘ Executions of Objects in the Shared Pool – Most Executions First’

select owner, name||’ – ‘||type name, executions from v$db_object_cache

where executions > 100

and type in (‘PACKAGE’, ‘PACKAGE BODY’, ‘FUNCTION’, ‘PROCEDURE’)

order by executions desc

/

doc

The next query lists the number of open cursors that each user is

currently utilising. Each SQL statement that is executed is stored

partly in the Shared SQL Area and partly in the Private SQL Area.

The private area is further broken into 2 parts, the persistent area

and the runtime area. The persistent area is used for binding info.

The larger the number of columns in a query, the larger the persistent

area. The size of the runtime area depends on the complexity of the

statement. The type of statement is also a factor. An insert, update

or delete statement will use more runtime area than a select.

For insert, update and delete statements, the runtime area is freed

immediately after the statement has been executed. For a query, the

runtime area is cleared only after all rows have been fetched or the

query is cancelled.

What has all this got to do with open cursors?

A private SQL area continues to exist until the corresponding cursor

is closed. Note: the runtime area is freed but the persistent (binding)

area remains open. If the statement is re-used, leaving cursors open is

not bad practice, if you have sufficient memory on your machine. Leaving

cursors that are not likely to be used again is bad practice, once

again, particularly if you are short of memory. The number of private

areas is limited by the setting of OPEN_CURSORS init.ora parameter. The

user process will continue to operate, despite having reached the OPEN_

CURSOR limit. Cursors will be flushed and will need to be pe-parsed the

next time they are accessed.

Recursive calls are used to handle the re-loading of the cursors if

the have to be re-binded after being closed.

The data in the following query lists each user process, the number of

recursive calls (the lower the better), the total opened cursors

cumulative and the current opened cursors. If the number of current opened

cursors is high (> 50), question why curors are not being closed. If the

number of cumulative opened cursors and recursive calls is significantly

larger for some of the users, determine what transaction they are running

and determine if they can leave cursors open to avoid having to re-bind

the statements and avoid the associated CPU requirements.

#

drop view user_cursors;

create view user_cursors as

select

ss.username||'(‘||se.sid||’) ‘ user_process,

sum(decode(name,’recursive calls’,value)) “Recursive Calls”,

sum(decode(name,’opened cursors cumulative’,value)) “Opened Cursors”,

sum(decode(name,’opened cursors current’,value)) “Current Cursors”

from v$session ss, v$sesstat se, v$statname sn

where se.statistic# = sn.statistic#

and ( name like ‘%opened cursors current%’

OR name like ‘%recursive calls%’

OR name like ‘%opened cursors cumulative%’)

and se.sid = ss.sid

and ss.username is not null

group by ss.username||'(‘||se.sid||’) ‘

/

set pagesize 999

ttitle ‘Per Session Current Cursor Usage ‘

column USER_PROCESS format a25;

column “Recursive Calls” format 999,999,999;

column “Opened Cursors” format 99,999;

column “Current Cursors” format 99,999;

select * from user_cursors

order by “Recursive Calls” desc

/

doc

The next output lists the CPU usage on a per-user basis. If a user process

has considerably more CPU usage, it is worth investigating. The causes can

be many, ranging from untuned SQL statements, indexes missing, cursors

being closed too often, or an ad hoc user running rampant. The high CPU

usage may also be acceptable depending on the type of tasks that the person

is performing.

#

ttitle ‘ CPU Used By Session Information ‘

select substr(name,1,30) parameter,

ss.username||'(‘||se.sid||’) ‘ user_process, value

from v$session ss, v$sesstat se, v$statname sn

where se.statistic# = sn.statistic#

and name like ‘%CPU used by this session%’

and se.sid = ss.sid

order by substr(name,1,25), value desc

/

ttitle ‘ Internal Oracle Locking Problems ‘

set heading off

select ‘Warning: Enqueue Timeouts are ‘||value||’. They should be zero’ line1,

‘Increase the INIT.ora parameter ENQUEUE_RESOURCES’

from v$sysstat

where name = ‘enqueue timeouts’

and value > 0

/

doc

The following report lists tables without any indexes on then whatsoever.

It is unusual for tables not to need an index. Even small tables require

an index to guarantee uniqueness. Small tables also require indexes for

joining, because a full table scan will always drive a query (unless a

hint is used). If you are scanning through many rows in a large table

using an index range scan and are looking up a reference table to expand

a code into the description stored in the smaller table, the query will

take considerably longer because the small table will be the driving

table. Larger tables can drag a machine to its knees if they are

continually accessed without going through an index.

#

ttitle ‘Report on all Tables Without Indexes’

select owner, table_name from all_tables

MINUS

select owner, table_name from all_indexes;

doc

The next enquiry gives you a list of indexes that have the same column

as the leading column in the index. These indexes can cause problems if

queries use the incorrect index. e.g. Oracle will utilise the index that

was created most recently if two indexes are of equal ranking. This can

cause different indexes to be utilised from one environment to the next

e.g. from DEV to QA to PROD. Each environment may have had its indexes

created in a different sequence. I strongly recommend that you use hints

in you programs to overcome these problems and force specific queries to

use a specified index.

The following information does not automatically indicate that an index

is incorrect, but each index should be viewed to justify its existence.

#

column table_owner format a20;

column table_name format a26;

column column_name format a26;

ttitle ‘Indexes which may be Superfluous’

select table_owner, table_name ,column_name

from all_ind_columns

where column_position =1

group by table_owner, table_name , column_name

having count(*) > 1

/

Doc

The following output lists all foreign keys that do not have an index

on the Child table, for example, we have a foreign key on the EMP table

to make sure that it has a valid DEPT row existing. The foreign key is

placed on the EMP (deptno) column pointing to the DEPT (deptno) primary

key.

Obviously the parent table DEPT requires an index on deptno for the

foreign key to point to. The effect of the foreign key that is not

widely known is that unless an index is placed on the child table on

the columns that are used in the foreign key, a share lock occurs on the

parent table for the duration of the insert, update or delete on the

child table.

What is a share lock, you ask? The effect of a share lock is that all

query users hoping to access the table have to wait until a single update

user on the table completes his/her update. Update users cannot perform

their update until all query users complete their queries against the table.

The bottom line is that if the parent table is a volatile table, the

share lock can cause the most incredible performance degradation. At a

recent benchmark, we had the entire benchmark grind to a halt because of this

locking situation. If the parent table is a non-volatile table, you may

be able to get away without the index on the child table, because the lock

on the parent table is of no importance.

The negative factor of the index on the child table is that I have observed

tables with as many as 30 indexes on them and the performance degradation

has been caused by maintaining the excessive number of indexes. My advice

to these sites has been to only use foriegn key constraints on columns

that have an index which can be used for other purposes (e.g. reporting)

or that point to a non-volatile reference table. Most tables have difficulty

maintaining acceptable performance if they have > 10 indexes on them.

You may wish to take the foreign keys offline during the day and put them

online at night to report any errors into an exceptions table. You should

do this when the parent table is not being accessed.

#

ttitle ‘ Foreign Constraints and Columns Without an Index on Child Table’

select acc.owner||’-> ‘||acc.constraint_name||'(‘||acc.column_name

||'[‘||acc.position||’])’||’ ***** Missing Index’

from all_cons_columns acc, all_constraints ac

where ac.constraint_name = acc.constraint_name

and ac.constraint_type = ‘R’

and (acc.owner, acc.table_name, acc.column_name, acc.position) in

(select acc.owner, acc.table_name, acc.column_name, acc.position

from all_cons_columns acc, all_constraints ac

where ac.constraint_name = acc.constraint_name

and ac.constraint_type = ‘R’

MINUS

select table_owner, table_name, column_name, column_position

from all_ind_columns)

order by acc.owner, acc.constraint_name, acc.column_name, acc.position;

doc

Having multiple extents on objects causes performance degradation when

performing full scans. The throwing of the extents requires recursive

calls to the uet$ and fet$ tables (used extents and free extents

dictionary tables) which is also particularly damaging to performance

if done too often. Most of the database objects below can potentially

require re-building, but keep the following exceptions in mind…

I have observed performance degradation as much as 10 times longer

runtime for multiple extents compared to a single extent.

(1) Parallel data loading and other parallel processing depends on

objects having multiple extents for them to operate correctly.

(2) Rollback segments require multiple extents to service multiple users

sharing the rollback segment.

(3) Multiple extents on a very large table will have a much less

harmful effect than multiple extents on a smaller table. Of course, the

re-building of the table (and its indexes) may take an excessive amount

of time.

If you do need to do a re-org, consider the UNRECOVERABLE option

to bypass the buffer cache and parallel index loading, to speed up the

re-build.

One other thing you may consider is to have a lower PCTFREE when

rebuilding the table and then altering the table to enlarge the PCTFREE

to a larger value after the tables data has been loaded. Make sure that

you re-load you data without indexes, constraints and triggers. Add the

indexes and constraints after the data has been loaded. Add the triggers

also, but keep in mind that you may have to perform the tasks that the

trigger would have performed, because the trigger only becomes effective

on data created after the trigger has been created.

#

column segment_name format a26;

column owner format a12;

column tablespace_name format a12;

column seg_count format a14;

column sizing format 999,999,999;

break on owner on tablespace_name;

ttitle ‘ List All Segments with More than 5 Extents ‘

select owner, tablespace_name, segment_name||

decode(segment_type,’TABLE’,'[T]’, ‘INDEX’, ‘[I]’,

‘ROLLBACK’,'[R]’, ‘[O]’) segment_name

, sum(bytes) sizing,

decode(count(*),1,to_char(count(*)),

2,to_char(count(*)),

3,to_char(count(*)),

4,to_char(count(*)),

5,to_char(count(*)),

to_char(count(*))||’ < Re-build') seg_count
from dba_extents

group by owner, tablespace_name, segment_name||

decode(segment_type,’TABLE’,'[T]’, ‘INDEX’, ‘[I]’,

‘ROLLBACK’,'[R]’, ‘[O]’)

having count(*) > 5;

break on tablespace_name;

doc

The next figures list the free space on a per tablespace to assist

with the re-building of the table.

#

ttitle ‘ Show Free Space in Total By Tablespace’

select tablespace_name, sum(bytes) sizing

from dba_free_space

group by tablespace_name;

ttitle ‘ List Free Extent Sizes per Tablespace’

select tablespace_name, bytes sizing

from user_free_space

where bytes > 512000

order by tablespace_name, bytes desc;

doc

The following output lists the sizes of all datafiles being used by

the database (excluding control files)

Make sure that your data files are evenly spread across disks from a

performance perspective.

#

column file_name format a50;

column bytes format 999,999,999,999

ttitle ‘ Data File Sizes ‘

select file_name, bytes

from dba_data_files

/

column name format a14;

column “Total Free Space” format 99,999,999,999

column “Largest Free Extent” format 99,999,999,999

column “Default Initial Extent” format 9,999,999

ttitle ‘Additional Extent Information’

select name, sum(length)*4096 “Total Free Space”,

max(length)*4096 “Largest Free Extent”,

dflinit*4096 “Default Initial Extent”

from sys.fet$ a, sys.ts$ b

where a.ts# =b.ts#

group by name , dflinit

/

doc

The next output is not strictly tuning, but it gives you a list of all

database objects that will fail when they attempt to throw their next extent

due to a lack of a free extent that is of sufficient size in the same

tablespace as where the object resides. If the problem happens to occur

on a dictionary table, the whole database can potentially freeze, which I

suppose is response related.

#

ttitle ‘Database Objects that will have Trouble Throwing Extents’

column owner format a10;

column segment_name format a22;

column segment_type format a10;

column tablespace_name format a14;

column next_extent format 999,999,999;

SELECT seg.owner, seg.segment_name,

seg.segment_type, seg.tablespace_name,

t.next_extent

FROM sys.dba_segments seg,

sys.dba_tables t

WHERE (seg.segment_type = ‘TABLE’

AND seg.segment_name = t.table_name

AND seg.owner = t.owner

AND NOT EXISTS

(select tablespace_name

from dba_free_space free

where free.tablespace_name = t.tablespace_name

and bytes >= t.next_extent ))

UNION

SELECT seg.owner, seg.segment_name,

seg.segment_type, seg.tablespace_name,

DECODE (seg.segment_type,

‘CLUSTER’, c.next_extent)

FROM sys.dba_segments seg,

sys.dba_clusters c

WHERE (seg.segment_type = ‘CLUSTER’

AND seg.segment_name = c.cluster_name

AND seg.owner = c.owner

AND NOT EXISTS

(select tablespace_name

from dba_free_space free

where free.tablespace_name = c.tablespace_name

and bytes >= c.next_extent ))

UNION

SELECT seg.owner, seg.segment_name,

seg.segment_type, seg.tablespace_name,

DECODE (seg.segment_type,

‘INDEX’, i.next_extent )

FROM sys.dba_segments seg,

sys.dba_indexes i

WHERE (seg.segment_type = ‘INDEX’

AND seg.segment_name = i.index_name

AND seg.owner = i.owner

AND NOT EXISTS

(select tablespace_name

from dba_free_space free

where free.tablespace_name = i.tablespace_name

and bytes >= i.next_extent ))

UNION

SELECT seg.owner, seg.segment_name,

seg.segment_type, seg.tablespace_name,

DECODE (seg.segment_type,

‘ROLLBACK’, r.next_extent)

FROM sys.dba_segments seg,

sys.dba_rollback_segs r

where (seg.segment_type = ‘ROLLBACK’

AND seg.segment_name = r.segment_name

AND seg.owner = r.owner

AND NOT EXISTS

(select tablespace_name

from dba_free_space free

where free.tablespace_name = r.tablespace_name

and bytes >= r.next_extent ))

/

doc

The following output lists latch contention. A latch is used to protect

data structures inside the SGA and provide fast access to the database

buffers. A process that needs a latch has to own the latch which it must

access from a hash table. If a process has problems obtaining a latch, it

must wait until it is able to obtain one. Latch contention is more

predominant on multi CPU applications. Spinning on a latch avoids the

more costly operation of accessing the latch via conventional operating

system queueing mechanism.

The output from the following report which can be tuned are the redo

latches. The redo latches are the “redo allocation” and the “redo copy”

latches. The redo allocation latch serially writes all changes to the

database to the log buffer. On a single CPU system, you cannot repair

contention on this latch, and in fact latches should be minimal on a

single CPU system.

Latch contention tends to be much more evident on

multi CPU machines. If you have a multi-CPU machine, you must set the

INIT.ora parameter equal to the number of CPUs of your machine. Setting

this parameter allows a second latch (copy latch) to access the log buffer.

All changed data which is written to the log buffer which is larger than the

value specified in the parameter LOG_SMALL_ENTRY_MAX_SIZE is written to the

copy latch and all those smaller that or equal to the size use the redo

allocation latch. If you experience contention on the copy latch, you should

decrease the LOG_SMALL_ENTRY_MAX_SIZE to force more entries through the

redo allocation latch. If the redo allocation latch has the problem, you

can increase LOG_SMALL_ENTRY_MAX_SIZE to force more entries through the

redo copy latch.

Another interesting latch contention figure is that for “cache buffer chains”

and “cache buffer lru chains”. This is latch waits on buffer cache accesses.

The worst case I have seen on these waits was when a production DBA had

decided to turn on DB_LRU_EXTENDED_STATISTICS and DB_BLOCK_LRU_STATISTICS.

The DBA got some magnificent reports on the effect of increasing and

decreasing the DB_BLOCK_BUFFERS (buffer cache) but the production users

weren’t too happy with the significant response degradation.

If you get latch contention on the a multi CPU computer, you can decrease

the spin_count. The default spin count on most machines is set to 200. I

know of at least one benchmark on HP’s where the spin_count was set to 1,

to achieve optimal throughput. I have been told that on single CPU machines

you can increase a value “_Latch_Wait_postings” to say 20 and this will

provide a similar response improvement. Note: the _ in front of the parameter

name indicates that it is a secret parameter. We are never totally sure if

the secret parameters work. They appear to be on again/ off again from one

version of Oracle to the next. See the output at the beginning of this report

for a full list of undocumented parameters.

Speaking of undocumented parameters, we used to be able to decrease the

_DB_WRITER_MAX_SCAN_CNT and increase the _DB_BLOCK_WRITE_BATCH to avoid latch

contention. Whether the parameters take effect will vary from one version of

Oracle to the next. Try them out on your system only if you are experiencing

latch contention.

I’ve observed latch contention on the library cache. Stay tuned on how to

overcome this problem. I’ll have to learn this one as well.

#

ttitle ‘ Latch Gets and Misses ‘

select substr(name,1,25), gets, misses,

immediate_gets, immediate_misses

from v$latch

where misses > 0

or immediate_misses > 0

/

Doc

The following query shows the minimum and maximum times between log switches.

Typically, the minimum time should exceed a few minutes. The average figure

may be effected by no overnight activity taking place. If the switches are

less than 30 seconds on a regular basis (see the second query), I would

suggest that you should enlarge the size of the redo log files.

#

column “Min Minutes BW Checkpoints” format 999,999.99;

column “Avg Minutes BW Checkpoints” format 999,999.99;

ttitle ‘Minimum and Average time Between Checkpoints’

select min(to_number(to_date(lh2.first_time,’mm/dd/yy hh24:mi:ss’)

– to_date(lh1.first_time,’mm/dd/yy hh24:mi:ss’) )

* 24 * 60) “Min Minutes BW Checkpoints”,

avg(to_number(to_date(lh2.first_time,’mm/dd/yy hh24:mi:ss’)

– to_date(lh1.first_time,’mm/dd/yy hh24:mi:ss’) )

* 24 * 60) “Avg Minutes BW Checkpoints”

from v$loghist lh1, v$loghist lh2

where lh1.sequence# + 1 = lh2.sequence#

and lh1.sequence# <
(select max (sequence#)

from v$loghist )

/

drop view min_bw_checkpoints;

create view min_bw_checkpoints as

select to_number(to_date(lh2.first_time,’mm/dd/yy hh24:mi:ss’)

– to_date(lh1.first_time,’mm/dd/yy hh24:mi:ss’) )

* 24 * 60 “Minutes BW Checkpoints”

from v$loghist lh1, v$loghist lh2

where lh1.sequence# + 1 = lh2.sequence#

and lh1.sequence# <
(select max (sequence#)

from v$loghist )

/

column “Minutes BW Checkpoints” format 999,999.99

ttitle ‘Minutes Between Checkpoints Listing Smaller Time Diffs First’

select “Minutes BW Checkpoints”

from min_bw_checkpoints

order by “Minutes BW Checkpoints” asc

/

doc

The following output assists you with tuning the LOG_BUFFER. The size of the

log buffer is set by assigning a value to the INIT.ora parameter LOG_BUFFER.

All changes are written to your redo logs via the log buffer. If your log

buffer is too small it can cause excessive disk I/Os on the disks that

contain your redo logs. The problem can be made worse if you have archiving

turned on because as well as writing to the redo logs, Oracle has to also

read from the redo logs and copy the file to the archive logs. To overcome

this problem, I suggest that you have 4 redo logs, typically 5 Meg or larger

in size and alternate the redo logs from one disk to another, that is

redo log 1 is on disk 1 , redo log 2 is on disk 2, redo log 3 is on disk 1

and redo log 4 is on disk 2.

This will ensure that the previous log being archived will be on a different

disk to the redo log being written to.

The following statistics also indicate inefficiencies with the log buffer

being too small. Typically a large site will have the LOG_BUFFER 500k or

larger.

The “redo log space wait time” indicates that the user process had to wait to

get space in the redo file. This indicates that the current log buffer was

being written from and the process would have to wait. Enlarging the log

buffer usually overcomes this problem. The closer the value is to zero, the

better your log buffer is tuned.

The “redo log space request” indicates the number of times a user process has

to wait for space in redo log buffer. It is often caused by the archiver being

lazy and the log writer can’t write from the log buffer to the redo log

because the redo log has not been copied by the ARCH process. One possible

cause of this problem is where Hot Backups are taking place on files that are

being written to heavily. Note: for the duration of the hot backups, an

entire block is written out to the log buffer and the redo logs for each

change to the database, as compared to just the writing the characters that

have been modified.

There is a parameter _LOG_BLOCKS_DURING_BACKUP which is supposed to overcome

the Hot backup problem. It will pay to check if the parameter is functional

for your version of the RDBMS with Oracle. It can avoid severe bottlenecks.

A sensible approach for overnight processing is to time your Hot Backups, if

they are really required, (a lot of sites have them just for the sake of saying

that they are running them) to occur when the datafiles being backed up have

very little or preferably NO activity occurring against them.

The “redo buffer allocation retries” are where the redo writer is waiting for

the log writer to complete the clearing out of all of the dirty buffers from

the buffer cache. Only then, can the redo writer continue onto the next

redo log. This problem is usually caused by having the LOG_BUFFER parameter

too small, but can also be caused by having the buffer cache too small (see

the DB_BLOCK_BUFFERS parameter).

#

ttitle ‘Extra LOG_BUFFER and Redo Log Tuning Information ‘

select substr(name, 1,25) , value

from v$sysstat

where name like ‘redo%’

and value > 0

/

doc

Oracle 7.1.5 introduced a new mechanism for improving the performance of

the shared pool area. When a user loads a large package or

procedure into the shared pool it has to search for large contiguous pieces

of memory. If there is not enough memory available, it has to make the

free memory available. This is particularly damaging to performance.

The new mechanism introduced in 7.1.5 allows memory to be reserved to

satisfy loading in large packages/procedures without having too disruptive

an effect on the shared pool area performance. Smaller objects will not

be able to fragment the area because all objects smaller than the size

specified in the parameter SHARED_POOL_RESERVED_MIN_ALLOC will be placed

into a shared pool area especially reserved for the smaller objects.

The total amount of space given to the larger area is specified by the

parameter SHARED_POOL_RESERVED_SIZE. The amount of space assigned to the

small objects is the SHARED_POOL_SIZE less the SHARED_POOL_RESERVED_SIZE.

There is also a new procedure that controls the amount of flushing from

the shared pool to make way for new objects being moved into the pool. The

RDBMS will continue to flush unused objects from the buffer pool until enough

free memory is available to fit the object into the shared pool. If there is

not enough available memory even after all of the objects have been flushed,

Oracle presents a 4031 error. The problem is that to get to a state of finding

that there is not enough memory can be particularly resource consuming.

The dbms_shared_pool.ABORT_REQUEST_THRESHOLD parameter sets the limit on

the size of objects allowed to flush the shared pool if the free space is

not sufficient to satisfy the request size. All objects larger than the

setting (valid range is 5,000 to 2,147,483,647) will immediately return an

error 4031 is suuficient free space is not available.

#

ttitle ‘ The Reserve Pool Settings for the Shared Pool Area’

select substr(name,1,32) “Parameter”, substr(value,1,12) “Setting”

from v$parameter

where name like ‘%reser%’

/

set heading off

column next_line format a60 newline

ttitle ‘ Shared Pool Reserved Size Recommendation’

select ‘You may need to increase the SHARED_POOL_RESERVED_SIZE’ next_line,

‘Request Failures = ‘||request_failures

from v$shared_pool_reserved

where request_failures > 0

and 0 != ( select to_number(value)

from v$parameter

where name = ‘shared_pool_reserved_size’ )

;

select ‘You may be able to decrease the SHARED_POOL_RESERVED_SIZE’ next_line,

‘Request Failures = ‘||request_failures

from v$shared_pool_reserved

where request_failures < 5
and 0 != ( select to_number(value)

from v$parameter

where name = ‘shared_pool_reserved_size’ )

;

ttitle ‘ Checking Locations of Database Files’

select value

from v$parameter

where name = ‘log_archive_dest’

UNION

select name

from v$datafile

UNION

select member

from v$logfile

/

column owner owner format a10;

column column_name format a25;

column “Characteristics” format a40;

break on owner on column_name;

ttitle ‘ Columns with Inconsistent Data Lengths ‘

select owner, column_name

, table_name||’ ‘||data_type||'(‘||

decode(data_type, ‘NUMBER’, data_precision, data_length)||’)’ “Characteristics”

from all_tab_columns

where (column_name, owner)

IN

(select column_name, owner

from all_tab_columns

group by column_name, owner

having min(decode(data_type, ‘NUMBER’, data_precision, data_length))

< max(decode(data_type, 'NUMBER', data_precision, data_length)) )
and owner not in (‘SYS’, ‘SYSTEM’)

and ‘&Check_column_lengths_yn’ in (‘Y’,’y’, ‘YES’)

/

ttitle ‘ Listing all Invalid Objects ‘

select owner, object_type, object_name, status

from all_objects

where status = ‘INVALID’

ORDER BY owner, object_type, object_name

/

ttitle ‘ Listing all Triggers and their Status’

select table_name, trigger_name, status

from all_triggers

order by table_name, trigger_name

/

ttitle ‘ Listing all Pinned Packages ‘

select name, kept

from v$db_object_cache

where kept not like ‘N%’

/

ttitle ‘ Tablespace Details ‘

select tablespace_name, initial_extent, next_extent, pct_increase

from dba_tablespaces

/

ttitle ‘Users that Have The SYSTEM Tablespace as Their Default’

select username

from dba_users

where default_tablespace = ‘SYSTEM’ OR temporary_tablespace=’SYSTEM’

/

spool off

doc

Now drop all of the temporary tables used for performance checking

#

drop table tot_read_writes;

drop view Full_Table_Scans;

drop table bh_temp;

drop table user_hit_ratios;

drop view user_cursors;

drop view min_bw_checkpoints;

****************************************************

File Name : bring_roll_online.sql

****************************************************

alter rollback segment R91 online ;

****************************************************

File Name : buff_block_ident.sql

****************************************************

select a.sid,b.hladdr,TS#,file#,DBARFIL,DBABLK,b.obj

from x$bh b, v$session_wait a

where a.p1raw=b.hladdr

and a.event = ‘latch free’ and a.p2 = 26

/

****************************************************

File Name : buff_busy.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_WHICH_DOING_SCATTERED_READ,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’buffer busy waits’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : buff_version.sql

****************************************************

SELECT dbarfil , dbablk, class, count(*)

FROM x$bh

GROUP BY dbarfil, dbablk,class

HAVING count(*) > 40

/

****************************************************

File Name : buffer_chain.sql

****************************************************

select substr(name,1,30),file#,buf#,DBARFIL,DBABLK,gets,sleeps,b.obj

from v$latch_children a,x$bh b

where a.addr = b.hladdr

and sleeps > 100 order by 7;

****************************************************

File Name : buffer_pool_miss_rate.sql

****************************************************

select

p.bp_name buffer_pool,

decode(sum(s.pread),

0, ‘ not used’,

to_char(

100 * sum(s.pread) /

decode(sum(s.dbbget + s.conget), 0, 1, sum(s.dbbget + s.conget)),

‘9990.00’

) || ‘%’

) miss_rate

from

sys.x$kcbwds s,

sys.x$kcbwbpd p

where

s.inst_id = userenv(‘Instance’) and

p.inst_id = userenv(‘Instance’) and

s.set_id >= p.bp_lo_sid and

s.set_id <= p.bp_hi_sid and
p.bp_size != 0

group by

p.bp_name

/

****************************************************

File Name : build_histogram.sql

****************************************************

analyze table ats.ats_bloomnet_forms compute statistics for columns status;

exit;

****************************************************

File Name : cabuff_latch.sql

****************************************************

select indx,ksusesql, ksusesqh

from x$ksuse where indx

in

(

select sid

from v$session_wait

where event = ‘latch free’

and p2 = 66

)

order by 2

/

****************************************************

File Name : cache_buf_chain_perf.sql

****************************************************

set pages 9999;

column bhr format 9.99

column mydate heading ‘yr. mo dy Hr.’ forat a20

column MSEC heading ‘Miss/Sec’ format 0099.99

column SSEC heading ‘Sleep/Sec’ format 0099.99

select

to_char(snap_time,’yyyy-mm-dd HH24 MI SS’) mydate,

(new.gets – old.gets) GETS,

(new.misses – old.misses) MISSES,

(new.misses – old.misses)/3600 “MSEC”,

(new.sleeps – old.sleeps) SLEEPS,

(new.sleeps – old.sleeps)/3600 “SSEC”

from

perfstat.STATS$LATCH old,

perfstat.STATS$LATCH new,

perfstat.stats$snapshot sn

where new.latch#= 26

and new.latch# = old.latch#

and new.snap_id = sn.snap_id

and old.snap_id = sn.snap_id-1

—group by to_char(snap_time,’yyyy-mm-dd HH24′)

order by 1

;

****************************************************

File Name : cache_buff_chain.sql

****************************************************

select FILE#,DBARFIL,DBABLK, OBJ from x$bh a,v$session_wait b

where a.hladdr = b.p1raw and b.p2=66

order by 1,3

/

****************************************************

File Name : cache_buff_ins.sql

****************************************************

insert into vivek.cache_buff_chain(FILE#,BLOCK#,CLASS#,OBJD)

select FILE#,DBABLK,class,OBJ from x$bh a,v$session_wait b

where a.hladdr = b.p1raw and b.p2=26

;

****************************************************

File Name : cache_latch.sql

****************************************************

set lines 132

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a20 heading “Machine”

col INDX format 9999 heading “SID”

select /*+ USE_NL(b c) */ a.kslltnum,a.addr,e.KSLLWNAM||'[‘||e.KSLLWLBL||’]’,a.kslltwhy,a.kslltwhr,c.KSUSESQH,

c.KSUSESQL,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from x$ksllt a, v$session_Wait b,x$ksuse c,x$kslwsc d,x$ksllw e

where b.p1raw=a.addr

and p2 =66

and b.sid=c.indx and

a.kslltwhr=d.indx

and d.indx=e.indx

and bitand(c.ksspaflg,1)!=0 and bitand(c.ksuseflg,1)!=0

and d.inst_id=userenv(‘Instance’)

and e.inst_id = userenv(‘Instance’)

/

****************************************************

File Name : cachelatch.sql

****************************************************

select indx,ksusesql, ksusesqh

from x$ksuse where indx

in

(

select sid

from v$session_wait

where event = ‘latch free’

and p2 = 66

)

order by 2

/

****************************************************

File Name : cachesql.sql

****************************************************

select indx,ksusesql, ksusesqh

from x$ksuse where indx

in

(

select sid

from v$session_wait

where event not in(

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqcls – consumer closing TQ’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Message Fragment Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘Null event’,

‘PL/SQL lock timer’,

‘Parallel Query Idle Wait – Slaves’,

‘Replication Dequeue’,

‘SQL*Net message from client’,

‘buffer deadlock’,

‘dispatcher timer’,

‘io done’,

‘pipe get’,

‘pmon timer’,

‘rdbms ipc message’,

‘rdbms ipc message block’,

‘rdbms ipc reply’,

‘slave wait’,

‘smon timer’,

‘virtual circuit status’)

and p2 = 66

)

/

****************************************************

File Name : calc_free_space.sql

****************************************************

— $Id: calc_free_space.sql,v 1.3 1993/11/18 13:15:55 pbaumgar Exp $

— $Log: calc_free_space.sql,v $

–Revision 1.3 1993/11/18 13:15:55 pbaumgar

–Used @@ to run nested command files.

—

–Revision 1.2 1993/09/30 13:16:30 pbaumgar

–Testing log contents

—

–Revision 1.1 1993/09/29 19:03:15 pbaumgar

–Initial revision

delete from free_space

/

@$SCRIPTS/contig_free_space

****************************************************

File Name : calc_headroom.sql

****************************************************

set termout off

@$SCRIPTS/calc_free_space

set feedb off

spool $LOGS/headroom.lst

@$SCRIPTS/headroom

@$SCRIPTS/headroom2

@$SCRIPTS/headroom3

spool off

exit

****************************************************

File Name : cb1.sql

****************************************************

select count(*) “cCHILD”, sum(GETS) “sGETS”, sum(MISSES) “sMISSES”,

sum(SLEEPS) “sSLEEPS”

from v$latch_children where name = ‘cache buffers chains’;

****************************************************

File Name : cb2.sql

****************************************************

prompt “— Child latches having sleeps greater than sleep_count —”

select CHILD#,ADDR,GETS,MISSES,SLEEPS from v$latch_children

where SLEEPS > 10 and name = ‘cache buffers chains’

order by SLEEPS desc

/

****************************************************

File Name : cb3.sql

****************************************************

prompt “— Blocks in hash buchets controlled by above child latches —”

select /*+ ordered */

e.owner ||’.’|| e.segment_name segment_name,

e.extent_id extent#,

x.dbablk – e.block_id + 1 block#,

l.child#

from

sys.v$latch_children l,

sys.x$bh x,

sys.dba_extents e

where

l.name = ‘cache buffers chains’ and

l.sleeps > 10 and

x.hladdr = l.addr and

e.file_id = x.file# and

x.dbablk between e.block_id and e.block_id + e.blocks – 1;

****************************************************

File Name : cb4.sql

****************************************************

select /*+ ordered */

hladdr,FILE#,DBARFIL,DBABLK,CLASS,STATE,OBJ,l.latch#,l.gets,l.misses,l.sleeps,l.spin_gets

from

sys.v$latch_children l,

sys.x$bh x

where

l.name = ‘cache buffers chains’ and

l.sleeps > 10 and

x.hladdr = l.addr

/

****************************************************

File Name : check_archdest.sh

****************************************************

#!/bin/sh

USED_SPACE=`df -k /database1 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

if [ $USED_SPACE -gt 85 ]

then

mailx -s “Space is low in ARCHDEST $USED_SPACE%” oracle < /dev/null
fi

if [ $USED_SPACE -gt 92 ]

then

echo “Space is low in ARCHDEST(/database1) in PANTHER $USED_SPACE% ” | mailx -s “PANTHER ISSUE” 8774544468@skytel.com 8774537913@skytel.com 8774520236@skytel.com 8774472907@skytel.com 8666714349@skytel.com

fi

****************************************************

File Name : check_archdest2.sh

****************************************************

#!/bin/sh

USED_SPACE=`df -k /EMCdb5 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

if [ $USED_SPACE -gt 85 ]

then

mailx -s “Space is low in ARCHDEST $USED_SPACE%” oracle < /dev/null
fi

if [ $USED_SPACE -gt 92 ]

then

echo “Space is low in ARCHDEST(/EMCdb5) in PANTHER $USED_SPACE% ” | mailx -s “PANTHER ISSUE” 8774544468@skytel.com 8774537913@skytel.com 8774520236@skytel.com 8774472907@skytel.com 8666714349@skytel.com

fi

****************************************************

File Name : check_backup_mode.sql

****************************************************

spool $SCRIPTS/end_backup_mode.sql

select ‘alter database datafile ‘||””||name||””||’ end backup;’

name from v$backup v1, v$datafile v2 where

v1.file#=v2.file#

and v1.status=’ACTIVE’

/

spool off

****************************************************

File Name : check_changes.sql

****************************************************

set feedback off;

set term off

set pagesize 60;

set newpage 0;

set linesize 80;

col object_name format a30

col timestamp format a20

spool $RPT/check_changes.rpt

select object_name, object_type, status, timestamp

from dba_objects

where owner=’ATS’

and substr(timestamp,1,10) = to_char(sysdate-1,’YYYY-MM-DD’)

/

spool off

exit

****************************************************

File Name : check_extents.sql

****************************************************

set feedback off;

set term off

set pagesize 60;

set newpage 0;

set linesize 80;

col db_name new_value instance

select ‘INSTANCE NAME’ description, value db_name from v$parameter

where upper(name) = ‘DB_NAME’

/

ttitle center instance ‘ TABLESPACE/FILE/EXTENTS REPORT’

column tablespace_name format a15 heading ‘TABLESPACE|NAME’

column segment_name format a20 heading ‘TABLE|NAME’

column extents format 99999 heading ‘EXTENTS’

column max_extents format 99999 heading ‘MAXEXTENTS’

column owner format a10

column segment_type format a7 heading ‘TABLE|TYPE’

break on tablespace_name skip 2 on report

spool $RPT/check_extents.rpt

select tablespace_name,segment_name,segment_type, owner, extents, max_extents

from dba_segments

where segment_type not in (‘CACHE’,’ROLLBACK’,’DEFERRED ROLLBACK’)

and (extents/decode(max_extents,0,1,max_extents))*100 > 25

order by tablespace_name,owner,segment_name

/

spool off

exit

****************************************************

File Name : check_index.sql

****************************************************

select index_name, blevel,

decode(blevel,0,’OK BLEVEL’,1,’OK BLEVEL’,

2,’OK BLEVEL’,3,’OK BLEVEL’,4,’OK BLEVEL’,’BLEVEL HIGH’) OK

from dba_indexes

where owner=’ATS’

/

****************************************************

File Name : check_listener.sh

****************************************************

/opt/app/oracle/scripts/all_listener.sh |grep “successfully”|wc -l

****************************************************

File Name : check_locks.sql

****************************************************

SET ECHO off

REM NAME: TFSCLOCK.SQL

REM USAGE:”@path/tfsclock”

REM ————————————————————————

REM REQUIREMENTS:

REM SELECT on V$LOCK, V$SESSION, SYS.USER$, SYS.OBJ$

REM ————————————————————————

REM PURPOSE:

REM The following locking information script provides fully DECODED

REM information regarding the locks currently held in the database.

REM The report generated is fairly complex and difficult to read,

REM but has considerable detail.

REM

REM The TFTS series contains scripts to provide (less detailed) lock

REM information in a formats which are somewhat less difficult to read:

REM TFSMLOCK.SQL and TFSLLOCK.SQL.

REM ————————————————————————

REM EXAMPLE:

REM Too complex to show a representative sample here

REM

REM ————————————————————————

REM DISCLAIMER:

REM This script is provided for educational purposes only. It is NOT

REM supported by Oracle World Wide Technical Support.

REM The script has been tested and appears to work as intended.

REM You should always run new scripts on a test instance initially.

REM ————————————————————————

REM Main text of script follows:

set lines 200

set pagesize 66

break on Kill on sid on username on terminal

column Kill heading ‘Kill String’ format a13

column res heading ‘Resource Type’ format 999

column id1 format 9999990

column id2 format 9999990

column locking heading ‘Lock Held/Lock Requested’ format a40

column lmode heading ‘Lock Held’ format a20

column request heading ‘Lock Requested’ format a20

column serial# format 99999

column username format a10 heading “Username”

column terminal heading Term format a6

column tab format a30 heading “Table Name”

column owner format a9

column LAddr heading “ID1 – ID2” format a18

column Lockt heading “Lock Type” format a40

column command format a25

column sid format 990

rem L.SID||’,’||S.SERIAL# Kill,

spool check_locks.log

select

nvl(S.USERNAME,’Internal’) username,

L.SID,

nvl(S.TERMINAL,’None’) terminal,

decode(command,

0,’None’,decode(l.id2,0,U1.NAME||’.’||substr(T1.NAME,1,20),’None’)) tab,

decode(command,

0,’BACKGROUND’,

1,’Create Table’,

2,’INSERT’,

3,’SELECT’,

4,’CREATE CLUSTER’,

5,’ALTER CLUSTER’,

6,’UPDATE’,

7,’DELETE’,

8,’DROP’,

9,’CREATE INDEX’,

10,’DROP INDEX’,

11,’ALTER INDEX’,

12,’DROP TABLE’,

13,’—‘,

14,’—‘,

15,’ALTER TABLE’,

16,’—‘,

17,’GRANT’,

18,’REVOKE’,

19,’CREATE SYNONYM’,

20,’DROP SYNONYM’,

21,’CREATE VIEW’,

22,’DROP VIEW’,

23,’—‘,

24,’—‘,

25,’—‘,

26,’LOCK TABLE’,

27,’NO OPERATION’,

28,’RENAME’,

29,’COMMENT’,

30,’AUDIT’,

31,’NOAUDIT’,

32,’CREATE EXTERNAL DATABASE’,

33,’DROP EXTERNAL DATABASE’,

34,’CREATE DATABASE’,

35,’ALTER DATABASE’,

36,’CREATE ROLLBACK SEGMENT’,

37,’ALTER ROLLBACK SEGMENT’,

38,’DROP ROLLBACK SEGMENT’,

39,’CREATE TABLESPACE’,

40,’ALTER TABLESPACE’,

41,’DROP TABLESPACE’,

42,’ALTER SESSION’,

43,’ALTER USER’,

44,’COMMIT’,

45,’ROLLBACK’,

46,’SAVEPOINT’,

47,’PL/SQL EXECUTE’,

48,’SET TRANSACTION’,

49,’ALTER SYSTEM SWITCH LOG’,

50,’EXPLAIN’,

51,’CREATE USER’,

52,’CREATE ROLE’,

53,’DROP USER’,

54,’DROP ROLE’,

55,’SET ROLE’,

56,’CREATE SCHEMA’,

57,’CREATE CONTROL FILE’,

58,’ALTER TRACING’,

59,’CREATE TRIGGER’,

60,’ALTER TRIGGER’,

61,’DROP TRIGGER’,

62,’ANALYZE TABLE’,

63,’ANALYZE INDEX’,

64,’ANALYZE CLUSTER’,

65,’CREATE PROFILE’,

66,’DROP PROFILE’,

67,’ALTER PROFILE’,

68,’DROP PROCEDURE’,

70,’ALTER RESOURCE COST’,

71,’CREATE SNAPSHOT LOG’,

72,’ALTER SNAPSHOT LOG’,

73,’DROP SNAPSHOT LOG’,

74,’CREATE SNAPSHOT’,

75,’ALTER SNAPSHOT’,

76,’DROP SNAPSHOT’,

84,’-‘,

85,’TRUNCATE TABLE’,

86,’TRUNCATE CLUSTER’,

87,’-‘,

88,’ALTER VIEW’,

89,’-‘,

90,’-‘,

91,’CREATE FUNCTION’,

92,’ALTER FUNCTION’,

93,’DROP FUNCTION’,

94,’CREATE PACKAGE’,

95,’ALTER PACKAGE’,

96,’DROP PACKAGE’,

97,’CREATE PACKAGE BODY’,

98,’ALTER PACKAGE BODY’,

99,’DROP PACKAGE BODY’,

command||’ – ???’) COMMAND,

decode(L.LMODE,1,’No Lock’,

2,’Row Share’,

3,’Row Exclusive’,

4,’Share’,

5,’Share Row Exclusive’,

6,’Exclusive’,’NONE’) lmode,

decode(L.REQUEST,1,’No Lock’,

2,’Row Share’,

3,’Row Exclusive’,

4,’Share’,

5,’Share Row Exclusive’,

6,’Exclusive’,’NONE’) request,

l.id1||’-‘||l.id2 Laddr,

l.type||’ – ‘||

decode(l.type,

‘BL’,’Buffer hash table instance lock’,

‘CF’,’Cross-instance function invocation instance lock’,

‘CI’,’Control file schema global enqueue lock’,

‘CS’,’Control file schema global enqueue lock’,

‘DF’,’Data file instance lock’,

‘DM’,’Mount/startup db primary/secondary instance lock’,

‘DR’,’Distributed recovery process lock’,

‘DX’,’Distributed transaction entry lock’,

‘FI’,’SGA open-file information lock’,

‘FS’,’File set lock’,

‘IR’,’Instance recovery serialization global enqueue lock’,

‘IV’,’Library cache invalidation instance lock’,

‘MB’,’Master buffer hash table instance lock’,

‘MM’,’Mount definition gloabal enqueue lock’,

‘MR’,’Media recovery lock’,

‘RE’,’USE_ROW_ENQUEUE enforcement lock’,

‘RT’,’Redo thread global enqueue lock’,

‘RW’,’Row wait enqueue lock’,

‘SC’,’System commit number instance lock’,

‘SH’,’System commit number high water mark enqueue lock’,

‘SN’,’Sequence number instance lock’,

‘SQ’,’Sequence number enqueue lock’,

‘ST’,’Space transaction enqueue lock’,

‘SV’,’Sequence number value lock’,

‘TA’,’Generic enqueue lock’,

‘TD’,’DDL enqueue lock’,

‘TE’,’Extend-segment enqueue lock’,

‘TM’,’DML enqueue lock’,

‘TT’,’Temporary table enqueue lock’,

‘TX’,’Transaction enqueue lock’,

‘UL’,’User supplied lock’,

‘UN’,’User name lock’,

‘WL’,’Being-written redo log instance lock’,

‘WS’,’Write-atomic-log-switch global enqueue lock’,

‘TS’,decode(l.id2,0,’Temporary segment enqueue lock (ID2=0)’,

‘New block allocation enqueue lock (ID2=1)’),

‘LA’,’Library cache lock instance lock (A=namespace)’,

‘LB’,’Library cache lock instance lock (B=namespace)’,

‘LC’,’Library cache lock instance lock (C=namespace)’,

‘LD’,’Library cache lock instance lock (D=namespace)’,

‘LE’,’Library cache lock instance lock (E=namespace)’,

‘LF’,’Library cache lock instance lock (F=namespace)’,

‘LG’,’Library cache lock instance lock (G=namespace)’,

‘LH’,’Library cache lock instance lock (H=namespace)’,

‘LI’,’Library cache lock instance lock (I=namespace)’,

‘LJ’,’Library cache lock instance lock (J=namespace)’,

‘LK’,’Library cache lock instance lock (K=namespace)’,

‘LL’,’Library cache lock instance lock (L=namespace)’,

‘LM’,’Library cache lock instance lock (M=namespace)’,

‘LN’,’Library cache lock instance lock (N=namespace)’,

‘LO’,’Library cache lock instance lock (O=namespace)’,

‘LP’,’Library cache lock instance lock (P=namespace)’,

‘LS’,’Log start/log switch enqueue lock’,

‘PA’,’Library cache pin instance lock (A=namespace)’,

‘PB’,’Library cache pin instance lock (B=namespace)’,

‘PC’,’Library cache pin instance lock (C=namespace)’,

‘PD’,’Library cache pin instance lock (D=namespace)’,

‘PE’,’Library cache pin instance lock (E=namespace)’,

‘PF’,’Library cache pin instance lock (F=namespace)’,

‘PG’,’Library cache pin instance lock (G=namespace)’,

‘PH’,’Library cache pin instance lock (H=namespace)’,

‘PI’,’Library cache pin instance lock (I=namespace)’,

‘PJ’,’Library cache pin instance lock (J=namespace)’,

‘PL’,’Library cache pin instance lock (K=namespace)’,

‘PK’,’Library cache pin instance lock (L=namespace)’,

‘PM’,’Library cache pin instance lock (M=namespace)’,

‘PN’,’Library cache pin instance lock (N=namespace)’,

‘PO’,’Library cache pin instance lock (O=namespace)’,

‘PP’,’Library cache pin instance lock (P=namespace)’,

‘PQ’,’Library cache pin instance lock (Q=namespace)’,

‘PR’,’Library cache pin instance lock (R=namespace)’,

‘PS’,’Library cache pin instance lock (S=namespace)’,

‘PT’,’Library cache pin instance lock (T=namespace)’,

‘PU’,’Library cache pin instance lock (U=namespace)’,

‘PV’,’Library cache pin instance lock (V=namespace)’,

‘PW’,’Library cache pin instance lock (W=namespace)’,

‘PX’,’Library cache pin instance lock (X=namespace)’,

‘PY’,’Library cache pin instance lock (Y=namespace)’,

‘PZ’,’Library cache pin instance lock (Z=namespace)’,

‘QA’,’Row cache instance lock (A=cache)’,

‘QB’,’Row cache instance lock (B=cache)’,

‘QC’,’Row cache instance lock (C=cache)’,

‘QD’,’Row cache instance lock (D=cache)’,

‘QE’,’Row cache instance lock (E=cache)’,

‘QF’,’Row cache instance lock (F=cache)’,

‘QG’,’Row cache instance lock (G=cache)’,

‘QH’,’Row cache instance lock (H=cache)’,

‘QI’,’Row cache instance lock (I=cache)’,

‘QJ’,’Row cache instance lock (J=cache)’,

‘QL’,’Row cache instance lock (K=cache)’,

‘QK’,’Row cache instance lock (L=cache)’,

‘QM’,’Row cache instance lock (M=cache)’,

‘QN’,’Row cache instance lock (N=cache)’,

‘QO’,’Row cache instance lock (O=cache)’,

‘QP’,’Row cache instance lock (P=cache)’,

‘QQ’,’Row cache instance lock (Q=cache)’,

‘QR’,’Row cache instance lock (R=cache)’,

‘QS’,’Row cache instance lock (S=cache)’,

‘QT’,’Row cache instance lock (T=cache)’,

‘QU’,’Row cache instance lock (U=cache)’,

‘QV’,’Row cache instance lock (V=cache)’,

‘QW’,’Row cache instance lock (W=cache)’,

‘QX’,’Row cache instance lock (X=cache)’,

‘QY’,’Row cache instance lock (Y=cache)’,

‘QZ’,’Row cache instance lock (Z=cache)’,’????’) Lockt

from V$LOCK L,

V$SESSION S,

SYS.USER$ U1,

SYS.OBJ$ T1

where L.SID = S.SID

and T1.OBJ# = decode(L.ID2,0,L.ID1,1)

and U1.USER# = T1.OWNER#

and S.TYPE != ‘BACKGROUND’

order by 1,2,5

/

rem DL, Direct Loader Index Creation

rem IN, Instance Number

rem IS, Instance State

rem KK, Redo Log “Kick”

rem PF, Password File

rem PI, Parallel Slaves

rem PR, Process Startup

rem PS, Parallel Slave Synchronization

rem SM, SMON

rem TS, Temporary Segment (also TableSpace)

****************************************************

File Name : check_log.sql

****************************************************

col member format a40

select member,a.group#,b.status from v$logfile a, v$log b where

a.group#=b.group#

/

****************************************************

File Name : check_logfiles.sql

****************************************************

connect internal

spool $LOGS/archlist.log

archive log list

spool off

exit

****************************************************

File Name : check_obj.sql

****************************************************

———————————————————-

— Lists all the objects Userwise that are invalid ——

———————————————————-

set pages 2000 lines 90

column owner format a15

column object_name format a40 heading ‘Object Name’

column object_type format a13 heading ‘Type’

column Status format a7

select owner,object_name,object_type,status

–,to_char(last_ddl_time,’DD-MON-YYYY HH24:MI SS’)

from dba_objects

where status = ‘INVALID’

order by 1,3,2;

****************************************************

File Name : check_prod.sh

****************************************************

a=`rsh sunflower1 “ps -ef|grep -v grep|grep ora_pmon_800P”|wc -l`

#a=`”ps -ef|grep -v grep|grep ora_pmon_800P”|wc -l`

if [ $a -lt 1 ]

then

echo “800P seems to be down. Pls check” | mailx 8774544468@skytel.com 8774537913@skytel.com 8774520236@skytel.com 8774472907@skytel.com 8666714349@skytel.com vivek@1800flowers.com

fi

****************************************************

File Name : check_recover.sh

****************************************************

#!/bin/sh -x

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_800P.log| grep “arch”|tail -1|cut -c48-57`

LAST_FILE=`rsh sunflower1 “ls -latr /db5/archlog/800P/*.arc”|grep “arch”|tail -1|cut -f5 -d’/’|cut -c5-14`

NO_LOG_45MIN=`rsh sunflower1 “/usr/local/bin/find /db5/archlog/800P/*.arc -mmin -45 |wc -l”`

DIFFER=”` expr $LAST_FILE – $RECOVERED `”

if [ $DIFFER -gt 12 ] && [ $NO_LOG_45MIN -gt 8 ]

then

echo “Recovery of 800P STBY is lagging by $DIFFER logs, But Log generation in last 45 minutes is $NO_LOG_45MIN” | mailx -s “800P – Standby Recovery Alert” dbaoracle@1800flowers.com

exit

fi

if [ $DIFFER -gt 12 ]

then

echo “Recovery of 800P STBY is lagging by $DIFFER logs” | mailx 8774544468@skytel.com 8774537913@skytel.com 8774520236@skytel.com 8774472907@skytel.com 8666714349@skytel.com 8774538204@skytel.com

else

echo “Recovery is lagging behind by $DIFFER logs `date`” >>/tmp/lagging_behind_log.log

fi

****************************************************

File Name : check_recover1.sh

****************************************************

#!/bin/sh

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_800P.log| grep “arch”|tail -1|cut -c48-57`

LAST_FILE=`rsh sunflower1 “ls -latr /db6/archlog/800P/*.arc|grep “arch”|tail -1|cut -f5 -d’/’|cut -c5-14`

DIFFER=”` expr $LAST_FILE – $RECOVERED `”

if [ $DIFFER -gt 5 ]

then

echo “Recovery of 800P STBY is lagging by $DIFFER logs” | mailx 8774472907@skytel.com

fi

****************************************************

File Name : check_recover2.sh

****************************************************

#!/bin/sh

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_800P.log| grep “arch”|tail -1|cut -c48-57`

LAST_FILE=`rsh sunflower1 “ls -latr /db6/archlog/800P/*.arc|grep “arch”|tail -1|cut -f5 -d’/’|cut -c5-14`

DIFFER=”` expr $LAST_FILE – $RECOVERED `”

if [ $DIFFER -gt 5 ]

then

echo “Recovery of 800P STBY is lagging by $DIFFER logs” | mailx 8774472907@skytel.com

fi

****************************************************

File Name : check_recover_viv.sh

****************************************************

#!/bin/sh

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_800P.log| grep “arch”|tail -1|cut -c48-57`

LAST_FILE=`rsh sunflower1 “ls -latr /db5/archlog/800P/*.arc”|grep “arch”|tail -1|cut -f5 -d’/’|cut -c5-14`

DIFFER=”` expr $LAST_FILE – $RECOVERED `”

if [ $DIFFER -gt 12 ]

then

echo “Recovery of 800P STBY is lagging by $DIFFER logs” | mailx 8774544468@skytel.com 8774537913@skytel.com 8774520236@skytel.com 8774472907@skytel.com 8666714349@skytel.com 8774538204@skytel.com

else

echo “Recovery is lagging behind by $DIFFER logs `date`” >>/tmp/lagging_behind_log.log

fi

****************************************************

File Name : check_renfil.sh

****************************************************

#!/bin/sh

# g is the file containing file_name from v$datafile of the source

# 800Lfil is ls -latr /db*/oradata/800L/* |awk ‘{print “$9}’ output

while read col1 col2 col3 col4 col5 col6 col7

do

a=`echo $col5|awk -F/ ‘{print $4}’`

b=`echo $col7|awk -F/ ‘{print $4}’`

##echo $a “t” $b

if [ $a != $b ]

then

echo $col1 $col2 $col3 $col4 $col5 $col6 $col7 “<<<<---- NOT OK"
else

if [ $a = “800P” ]

then

echo $col1 $col2 $col3 $col4 $col5 $col6 $col7 “<<<<---- NOT OK"
fi

if [ $b = “800P” ]

then

if [ $a != “800P” ]

then

echo $col1 $col2 $col3 $col4 $col5 $col6 $col7 “<<<<---- NOT OK"
fi

fi

fi

a=” ”

b=” ”

done <"./renamefile.sql" ****************************************************
File Name : check_seq.sql

****************************************************

set lines 90

set pages 20000

select SEQUENCE_OWNER,sequence_name,last_number,CACHE_SIZE,ORDER_FLAG

from dba_Sequences

where sequence_owner not in (‘SYSTEM’,’SYS’)

order by 1,2

/

****************************************************

File Name : check_standby.sh

****************************************************

#!/bin/sh

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_STANDBY.log| grep “arch”|tail -1|cut -c48-57`

LAST_FILE=`rsh sunflower1 “ls -latr /db5/archlog/800P/*.arc”|grep “arch”|tail -1|cut -f5 -d’/’|cut -c5-14`

DIFFER=”` expr $LAST_FILE – $RECOVERED `”

if [ $DIFFER -gt 12 ]

then

echo “Recovery of 800P STBY is lagging by $DIFFER logs” | mailx arunc@1800flowers.com 8774544468@skytel.com 8774537913@skytel.com 8774520236@skytel.com 8774472907@skytel.com 8666714349@skytel.com

fi

****************************************************

File Name : check_statistics.sql

****************************************************

set feedback off;

set term off

set pagesize 60;

set newpage 0;

set linesize 80;

col db_name new_value instance

select ‘INSTANCE NAME’ description, value db_name from v$parameter

where upper(name) = ‘DB_NAME’

/

ttitle center instance ‘TABLES THAT ARE MISSING STATISTICS’

column table_name format a20 heading ‘TABLE|NAME’

column owner format a10

spool $RPT/check_statistics.rpt

select table_name, owner

from dba_tables

where num_rows is null

and owner = ‘ATS’

/

select table_name,index_name, owner

from dba_indexes

where num_rows is null

and owner = ‘ATS’

/

spool off

exit

****************************************************

File Name : check_tablespace.sql

****************************************************

set linesize 120

set pagesize 200

column table_name format a30

column next_extent format 999,999,999,999,999

column tablespace_name format a30

column ds.tablespace_name format a30

select table_name,next_extent,tablespace_name from dba_Tables

where NEXT_EXTENT > (select max(bytes) from dba_free_Space a where a.tablespace_name = dba_tables.tablespace_name)

/

select index_name,next_extent,tablespace_name from dba_indexes

where NEXT_EXTENT > (select max(bytes) from dba_free_Space a where a.tablespace_name = dba_indexes.tablespace_name)

/

select tablespace_name from dba_segments where NEXT_EXTENT>(select max(bytes) from dba_free_Space a

where a.tablespace_name=dba_segments.tablespace_name)

/

select ds.tablespace_name from dba_segments ds,(select tablespace_name, max(bytes) byt from

dba_free_space group by tablespace_name) df

where ds.tablespace_name=df.tablespace_name(+) and next_extent>nvl(byt,0)

/

****************************************************

File Name : check_tablespaces.sql

****************************************************

set feedback off;

set term off

set pagesize 60;

set newpage 0;

set linesize 132

col db_name new_value instance

select ‘INSTANCE NAME’ description, value db_name from v$parameter

where upper(name) = ‘DB_NAME’

/

ttitle instance ‘ TABLESPACE/FILE/CREATOR CROSS REFERENCE’

column tablespace_name format a15 heading ‘TABLESPACE|NAME’

column segment_name format a40 heading ‘TABLE|NAME’

column blocks format 9,999,999 heading ‘SIZE’

column extents format 9999 heading ‘EXTENTS’

column owner format a15

column segment_type format a7 heading ‘TABLE|TYPE’

compute sum of blocks on tablespace_name

compute sum of extents on tablespace_name

compute sum of blocks on report

compute sum of extents on report

break on tablespace_name skip page on report

spool $RPT/check_tablespaces_$ORACLE_SID.rpt

select tablespace_name,segment_name,segment_type, owner, blocks, extents

from dba_segments

where segment_type not in (‘TEMPORARY’,’ROLLBACK’,’DEFERRED ROLLBACK’)

and owner not in (‘SYS’)

order by tablespace_name,owner,segment_name

/

spool off

exit

****************************************************

File Name : check_tbs.sql

****************************************************

col file_name format a50

set lines 132

select file_name,bytes from dba_data_Files

where tablespace_name = UPPER(‘&1’)

/

****************************************************

File Name : check_test.sql

****************************************************

select member,b.status from v$logfile a, v$log b where

a.group#=b.group#

/

****************************************************

File Name : checkrbs.sql

****************************************************

prompt ROLLBACK STATISTICS:

prompt

spool $RPT/checkrbs.log

ttitle off;

set linesize 132

column extents format 999 heading ‘Extents’

column rssize format 999,999,999 heading ‘Size in|Bytes’

column optsize format 999,999,999 heading ‘Optimal|Size’

column hwmsize format 99,999,999 heading ‘High Water|Mark’

column shrinks format 9,999 heading ‘Number of|Shrinks’

column wraps format 9,999 heading ‘Number of|Wraps’

column extends format 999,999 heading ‘Number of|Extends’

column aveactive format 999,999,999 heading ‘Average size|Active Extents’

column rownum noprint

select rssize, optsize, hwmsize, shrinks, wraps, extends, aveactive

from v$rollstat

order by rownum

/

****************************************************

File Name : checkrbs2.sql

****************************************************

prompt ROLLBACK STATISTICS:

prompt

spool $RPT/checkrbs2.log

ttitle off;

set linesize 132

column name format a10 heading ‘Name’

column extents format 999 heading ‘Extents’

column rssize format 999,999,999 heading ‘Size in|Bytes’

column optsize format 999,999,999 heading ‘Optimal|Size’

column hwmsize format 99,999,999 heading ‘High Water|Mark’

column shrinks format 9,999 heading ‘Number of|Shrinks’

column wraps format 9,999 heading ‘Number of|Wraps’

column extends format 999,999 heading ‘Number of|Extends’

column aveactive format 999,999,999 heading ‘Average size|Active Extents’

column rownum noprint

select name, rssize, optsize, hwmsize, shrinks, wraps, extends, aveactive

from v$rollstat, v$rollname

where v$rollname.usn=v$rollstat.usn

order by rownum

/

****************************************************

File Name : child_sleep.sql

****************************************************

@accept LatchType “Latch type” “cache buffers %”

column name format a48

column sleeps format a20

break on name

select

name,

to_char(min(sleeps)) ||

decode(

max(sleeps) – min(sleeps),

0, null,

‘ to ‘ || to_char(max(sleeps))

) sleeps,

count(*) latches

from

sys.v$latch_children

where

name like ‘&LatchType’

group by

name,

trunc(round(log(2, sleeps+1), 37))

/

undefine LatchType

****************************************************

File Name : chk.sql

****************************************************

set feedback off;

set pagesize 60;

set newpage 0;

set linesize 80;

col object_name format a30

col timestamp format a20

select object_name, object_type, status, timestamp

from user_objects

where

substr(timestamp,1,10) = to_char(sysdate-1,’YYYY-MM-DD’)

/

exit

****************************************************

File Name : chk_extent.sql

****************************************************

select segment_name,segment_type,extents,max_Extents,next_extent,owner from dba_segments

where 40 > (max_extents – extents);

****************************************************

File Name : chm_check.sql

****************************************************

alter function “1193”.ATS_INT_MAIN_MULTI compile;

alter procedure SUBBU.VAL_SPECIAL_REPLACE_ORDER compile;

****************************************************

File Name : coalesce_temp.sql

****************************************************

set term off echo off

col dt heading ‘Date/Time’

col cnt heading ‘# free Chunks’

col big heading ‘Biggest Chunk’

col tot heading ‘Total Free space’

spool /db3/oracle/statistics/temp_coal.log

select substr(to_char(sysdate,’MON-DD-YYYY:HH24:MI:SS’),1,22) dt,count(blocks) cnt, max(bytes) big, sum(bytes) tot

from dba_free_space

where tablespace_name = ‘TEMP’

/

alter tablespace temp coalesce

/

select substr(to_char(sysdate,’MON-DD-YYYY:HH24:MI:SS’),1,22) dt,count(blocks) cnt, max(bytes) big, sum(bytes) tot

from dba_free_space

where tablespace_name = ‘TEMP’

/

spool off

/

exit

****************************************************

File Name : comp.sh

****************************************************

./a1|awk ‘{print $9″t”$5}’|awk -F/ ‘{print $4″ “$5}’|sort

****************************************************

File Name : cons1.sql

****************************************************

select substr(table_name,1,25) Table_name,

substr(constraint_name,1,20),constraint_type,search_condition

from dba_constraints

where table_name = ‘ATS_PRODUCTS’

****************************************************

File Name : cons_info.sql

****************************************************

set lines 132

set pages 2000

column column_name format a40

break on constraint_name

accept val1 prompt “Enter Table Name:”

select constraint_name,column_name,position

from dba_cons_columns

where table_name = upper(‘&val1’)

/

select constraint_name,constraint_type,r_constraint_name,search_condition

from dba_constraints

where table_name = upper(‘&val1’)

/

****************************************************

File Name : const_info.sql

****************************************************

set lines 132

set pages 2000

accept val1 prompt “Enter Table Name:”

select owner,constraint_name,constraint_type,status

from dba_constraints where table_name = upper(‘&val1’)

/

****************************************************

File Name : contig_free_space.sql

****************************************************

— $Id: contig_free_space.sql,v 1.2 1994/03/24 20:02:51 pbaumgar Exp $

— $Log: contig_free_space.sql,v $

–Revision 1.2 1994/03/24 20:02:51 pbaumgar

–*** empty log message ***

—

–Revision 1.1 1993/09/29 18:59:24 pbaumgar

–Initial revision

—

— contig_free_space.sql

— Paul Baumgartel, Sept. 24, 1993

— From ORACLE User Resource, March 1992

— Calculates contiguous extents of free space per ORACLE tablespace

declare

ts_name varchar2(30);

coalesce_cursor binary_integer;

coalesce_buffer varchar2(100);

result binary_integer;

cursor get_ts is

select tablespace_name from sys.dba_tablespaces;

begin

open get_ts;

loop

fetch get_ts into ts_name;

exit when get_ts%notfound;

coalesce_buffer := ‘alter tablespace ‘||ts_name||’ coalesce’;

coalesce_cursor := dbms_sql.open_cursor;

dbms_sql.parse(coalesce_cursor, coalesce_buffer, dbms_sql.native);

result := dbms_sql.execute(coalesce_cursor);

dbms_sql.close_cursor(coalesce_cursor);

end loop;

close get_ts;

end;

/

****************************************************

File Name : contig_free_space2.sql

****************************************************

create or replace view greatest_contig_free (tablespace_name, length) as

select t1.tablespace_name, nvl(max(bytes),0) from dba_free_space t1,

dba_tablespaces t2 where t1.tablespace_name(+) = t2.tablespace_name

group by t1.tablespace_name

/

****************************************************

File Name : convert_rowid.sql

****************************************************

set serveroutput on size 100000

declare

cursor sel_rowid is

select rowid from ats_sys_parameters;

my_rowid rowid;

rowid_type number;

object_number number;

relative_fno number;

block_number number;

row_number number;

begin

open sel_rowid;

dbms_output.put_line(‘ROWID Object# RELFILE# BLOCK# ROW#’);

loop

fetch sel_rowid into my_rowid;

exit when sel_rowid%notfound;

dbms_rowid.rowid_info(my_rowid, rowid_type, object_number,relative_fno, block_number, row_number);

dbms_output.put_line(my_rowid||’ ‘||object_number||’ ‘||relative_fno||

‘ ‘||block_number||’ ‘||row_number);

end loop;

end;

/

****************************************************

File Name : copy_misslog.sh

****************************************************

#!/bin/sh -x

CORRUPT_LOG=’a’

CORRUPT_LOG=`tail -6 /oracle/app/oracle/admin/800P/bdump/alert_800P.log|grep “Media Recovery Log”|tail -1|cut -f5 -d’/’|cut -c1-18`

if [ $CORRUPT_LOG -ne ‘ ‘ ]

then

echo “Nothing to worry”

else

echo $CORRUPT_LOG

# `rcp -p sunflower1:/db5/archlog/800P/$CORRUPT_LOG /database1/archlog/800P/.`

fi

****************************************************

File Name : copy_new.sql

****************************************************

rcp /ORADATA1/800P/800P_addr_data1.dbf sunshine1:/LOADATA1/800P/800P_addr_data1.dbf

****************************************************

File Name : copy_partlog.sh

****************************************************

#!/bin/sh -x

CORRUPT_LOG=’a’

CORRUPT_LOG=`tail -10 /oracle/app/oracle/admin/800P/bdump/a.log|grep “ORA-00334:”|tail -1|cut -f5 -d’/’|cut -c1-18`

if [ $CORRUPT_LOG -ne ‘ ‘ ]

then

echo “Nothing to worry”

else

`rcp -p sunflower1:/db5/archlog/800P/$CORRUPT_LOG /database1/archlog/800P/.`

fi

****************************************************

File Name : count_daily_orders.sql

****************************************************

set verify off echo off

col ord_cnt format 999,999 heading ‘Orders’

col ord_date heading ‘Date’

select ”’&1”’ ord_date, count(dt_crtd) ord_cnt from ats_orders

where dt_crtd >= to_date(‘&&1’||’00:00:00′,’DD-MON-YYHH24:MI:SS’)

and dt_crtd <= to_date('&&1'||'23:59:59',
‘DD-MON-YYHH24:MI:SS’)

/

****************************************************

File Name : count_obj.sql

****************************************************

select owner,object_type,status,count(*) from dba_objects

where owner not in (‘SYS’,’SYSTEM’,’TUNER’)

group by owner,object_type,status

order by 1,2,3;

****************************************************

File Name : count_user.sql

****************************************************

select ‘Total Users ‘||count(*) From v$session where username <> ‘ ‘;

select ‘Active Users ‘||count(*) From v$session where username <> ‘ ‘ and status = ‘ACTIVE’;

****************************************************

File Name : cpu_usage.sql

****************************************************

select * from v$sesstat where statistic#=12 order by value;

****************************************************

File Name : cpu_user_cap.sql

****************************************************

select to_char(a.start_date,’DD-MON-YYYY-HH24:MI:SS’),ACTUAL_USER,TOTAL_USERS,USER_CPU,SYSTEM_CPU,IDLE_CPU,WAIT_CPU

from STATS$VMSTAT2 a,STATS$TOTALUSERS b

where b.MEASURED_DATE=a.START_DATE

and a.start_date >= trunc(sysdate -1)

and a.start_date < trunc(sysdate )
/

****************************************************

File Name : cr.sql

****************************************************

alter rollback segment r&1 offline

/

drop rollback segment r&&1;

create rollback segment r&&1

storage(

initial 2M next 2M minextents 20

optimal 41943040)

tablespace rbs

/

alter rollback segment r&&1 online

/

****************************************************

File Name : cre_idx.sql

****************************************************

CREATE INDEX cust_cust_type_I

ON ats_customers(cust_type)

INITRANS 9 MAXTRANS 255 PCTFREE 30

TABLESPACE cust_index

STORAGE (INITIAL 25M NEXT 25M MINEXTENTS 1 MAXEXTENTS 300 FREELISTS 9 PCTINCREASE 0);

****************************************************

File Name : cre_ind.sql

****************************************************

CREATE INDEX hld_lnk_shr_tim_etd_i

ON hold_link_share(time_entered)

INITRANS 9 MAXTRANS 255 PCTFREE 30

TABLESPACE misc_index_2

STORAGE (INITIAL 20M NEXT 20M MINEXTENTS 1 MAXEXTENTS 300 FREELISTS 9 PCTINCREASE 0);

****************************************************

File Name : cre_ord_custid_fk.sql

****************************************************

ALTER TABLE ATS_ORDERS ADD CONSTRAINT ODR_CUSTID_FK

FOREIGN KEY (CUST_ID)

REFERENCES ATS.ATS_CUSTOMERS (id)

enable novalidate;

ALTER TABLE ATS_ORDERS ADD CONSTRAINT ODR_BILLCUSTID_FK

FOREIGN KEY (BILL_TO_CUST_ID)

REFERENCES ATS.ATS_CUSTOMERS (id)

enable novalidate;

****************************************************

File Name : cre_roll.sql

****************************************************

create rollback segment &1

storage(

initial 2M next 2M minextents 20

optimal 40M)

tablespace &2

/

****************************************************

File Name : cre_rolll.sql

****************************************************

@@cre_roll.sql ‘R71’ ‘BATCH_RBS’

@@cre_roll.sql ‘R72’ ‘BATCH_RBS’

@@cre_roll.sql ‘R73’ ‘BATCH_RBS’

@@cre_roll.sql ‘R74’ ‘BATCH_RBS’

@@cre_roll.sql ‘R75’ ‘BATCH_RBS’

@@cre_roll.sql ‘R76’ ‘BATCH_RBS’

****************************************************

File Name : cre_seq.sql

****************************************************

CREATE SEQUENCE ATS.ats_id_seq start with 500000000

INCREMENT BY 1 MAXVALUE 999999999

MINVALUE 1 CACHE 1000;

****************************************************

File Name : cre_temp.sql

****************************************************

select ‘alter user ‘||'”‘||username||'”‘||’ temporary tablespace = ‘||”’TEMP1”’||’;’

from dba_users where temporary_Tablespace = ‘TEMP1’;

****************************************************

File Name : cre_ts.sql

****************************************************

create tablespace test_data_viv

datafile ‘/testdb12/oradata/800P2/test_data_1’ size 250M

default storage (initial 1M next 1M minextents 1 maxextents 5000 pctincrease 0)

online;

****************************************************

File Name : cre_ts1.sql

****************************************************

alter tablespace temp1 add datafile ‘/ORADATA9/800P/800P_temp1_2.dbf’ size 1000M;

****************************************************

File Name : create_rbs.sql

****************************************************

create rollback segment r&1

storage(

optimal 8000000)

tablespace rbs&2

/

alter rollback segment r&&1 online

/

****************************************************

File Name : create_rbs_tbs.sql

****************************************************

create tablespace rbs&1

datafile ‘&2’

size 300M

default storage(

initial 409600

next 409600

minextents 20

maxextents 500

pctincrease 0

)

/

****************************************************

File Name : create_text.sql

****************************************************

select ‘spool ‘||a.name||’.pkg’||chr(10)||

‘select text from dba_source where name = ‘||””||a.name||””||’ owner = ‘||””||’ATS’||””||’;’||chr(10)||

‘spool off’

from

(select object_name name from dba_objects where object_type = ‘PACKAGE’ and owner = ‘ATS’) a

/

****************************************************

File Name : create_users.sql

****************************************************

set term on echo on

set verify on

create user &1 identified by &&1

default tablespace users

temporary tablespace temp

quota unlimited on users

/

grant connect, resource to &&1;

****************************************************

File Name : csi.sql

****************************************************

select csi_id,csi_status_code,odr_odr_number,customer_last_name,odr_date,agreed_delivery_datetime,total_amount,

csi_queue_type,cpy_abbr,pmn_promotion_code,dt_crtd,wire_status_code,scratch_pad,exp_ind,cust_id,id,rowid

from ats_v_csi_queues_new

where csi_queue_type = ‘csiq’ and exp_ind = ‘n’

order by dt_crtd

/

****************************************************

File Name : curr_sess_sql.sql

****************************************************

select sid,serial#,sql_address,sql_hash_value,PREV_SQL_ADDR,PREV_HASH_VALUE from v$session

where sid = &1

/

****************************************************

File Name : da1.sql

****************************************************

——————————————————–

—– This package generates the script for compiling

—– various objects

——————————————————-

set pages 5000

select

owner,trigger_name

from dba_triggers

where owner in (‘ATS’,’1193′,’SHISHIR’,’SATISH’,’BLOOMORA’,’EXPUSER’,’6344′,’NAVEEN’,’CHANDRA’,’BKGR’,’MERCORA

‘)

/

****************************************************

File Name : db_link.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped heading “DB LINK QUERY”

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_WHICH_DOING_SCATTERED_READ,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’SQL*Net message from dblink’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : db_link_info.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped heading “DB LINK QUERY”

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_WAITING_ON_DB_LINK,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’SQL*Net message from dblink’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : db_stA.sql

****************************************************

define prefix=’v’

set document off

doc

$Source: H:SQLRCSdb_stat.sql $

$Revision: 1.4 $

$Author: gharriso $

$Date: 1996/02/12 09:56:16 $

This SQL*PLUS script reports on some “interesting” performance and

load related ratios.

Guy Harrison

gharriso@werple.mira.net.au

#

— @stat_ctl

column name format a30 heading “Ratio ”

column notes format a35 heading “Comments”

column value format 99990.9999 heading “Value”

column seq noprint

set feedback off

set pagesize 56

set lines 80

set pagesize 56

set newpage 0

set termout off

drop table gh$derived_stats;

column instname new_value instance_name noprint

column repdate new_value print_date noprint

select substr(name,1,20) instname,to_char(sysdate,’DD/MM/YY:HH24:MI’) repdate from v$database;

set termout on

spool 800P.stat

rem

rem Temporary table to hold results

rem

create table gh$derived_stats

(name varchar2(60),

value number,

notes varchar2(80),

seq number);

DOC

——————————————————–

Calculate Buffer cache hit ratio since last bounce

——————————————————–

#

insert into gh$derived_stats (name,value,seq)

select ‘buffer cache hit ratio’,

round((congets.value+dbgets.value-physreads.value)*100/

(congets.value+dbgets.value),4) “HIT RATE”,1

from &prefix.$sysstat congets,

&prefix.$sysstat dbgets,

&prefix.$sysstat physreads

where congets.name=’consistent gets’

and dbgets.name = ‘db block gets’

and physreads.name = ‘physical reads’

/

update gh$derived_stats

set notes=’*** May need to increase db_block_buffers’

where name=’buffer cache hit ratio’

and value <90
/

DOC

———————————————————

Ratio of recursive calls to user calls. Recursive calls

are SQL statements generated by ORACLE. High values can

indicate excessive dynamic or non-sharable SQL, excessive

rows dynamic segment extention or free space fragmentation or

an inadequately sized shared pool.

insert into gh$derived_stats(name,value,seq)

select ‘recursive calls/total calls’,

(rc.value/(rc.value+uc.value))*100,10

from &prefix.$sysstat rc,

&prefix.$sysstat uc

where rc.name=’recursive calls’

and uc.name=’user calls’

/

update gh$derived_stats

set notes=’*** Fragmentation? Dynamic SQL? Shared pool?’

where name=’recursive calls/total calls’

and value > 20

/

#

DOC

—————————————————

Data dictionary cache (row cache) hit rates. Low

values may mean that the shared pool is too small.

However, ORACLE doesn’t always size the dictionary

cache appropriately (or so it seems)

————————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘dictionary cache hit rate’,

sum(gets-getmisses)*100/sum(gets),1

from v$rowcache;

update gh$derived_stats

set notes=’*** high dictionary cache miss’

where name=’dictionary cache hit rate’

and value <98
/

DOC

————————————————-

Ratio of small (< SMALL_TABLE) to large table scans. We hope for predominantly small scans, otherwise there
may be untuned SQL out there

—————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘short/total table scan ratio’,sc.value/(sc.value+ls.value)*100,

12

from &prefix.$sysstat ls,

&prefix.$sysstat sc

where sc.name=’table scans (short tables)’

and ls.name=’table scans (long tables)’;

update gh$derived_stats

set notes=’*** Too many long table scans?’

where name=’short/total table scan ratio’

and value > <90 DOC
————————————————–

Disk sort ratio. Disk sorts are IO intensive as well

as poorly implemented in ORACLE prior to 7.2.

To reduce disk sorts, increase SORT_AREA_SIZE or

tune the SQL

————————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘disk sort ratio’,ds.value/

decode( (ds.value+ms.value) ,0,1,(ds.value+ms.value))*100

,10

from &prefix.$sysstat ds,

&prefix.$sysstat ms

where ms.name=’sorts (memory)’

and ds.name=’sorts (disk)’

/

update gh$derived_stats

set notes=’*** Too many disk sorts?’

where name=’disk sort ratio’

and value > 10;

DOC

————————————————-

Buffer busy ratio. High values May indicate that there are

tables with insufficient free lists or too few

rollback segments or extents

————————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘buffer busy wait ratio’,

(bbw.total_waits*100/(cg.value+dbg.value)),5

from &prefix.$system_event bbw,

&prefix.$sysstat cg,

&prefix.$sysstat dbg

where bbw.event=’buffer busy waits’

and cg.name =’consistent gets’

and dbg.name=’db block gets’

/

update gh$derived_stats

set notes=’*** RBack/Freelist contention?’

where name=’buffer busy wait ratio’

and value > 1;

/

DOC

————————————————–

Free buffer wait raio. High values are often associated

with disk sorts. In 7.2 try SORT_DIRECT_WRITES=TRUE.

In earlier versions, try making temporary tablespace

raw (in UNIX or NT)

—————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘free buffer wait ratio’,

(bbw.total_waits*100/(cg.value+dbg.value)),5

from &prefix.$system_event bbw,

&prefix.$sysstat cg,

&prefix.$sysstat dbg

where bbw.event=’free buffer waits’

and cg.name =’consistent gets’

and dbg.name=’db block gets’

/

update gh$derived_stats

set notes=’*** Disk sort/inode contention?’

where name=’free buffer wait ratio’

and value > 1;

/

DOC

————————————————-

Library cache hit rate. Low values suggest that

there is dynamic or unsharable SQL being submitted

————————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘library cache get hit ratio’,

sum(gethits)*100/sum(gets),1

from &prefix.$librarycache

/

update gh$derived_stats

set notes=’*** dynamic SQL?’

where name=’library cache get hit ratio’

and value < 85
/

DOC

————————————————-

Library cache pin hit ratio. Low values indicate

that the shared pool is too small

————————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘library cache pin hit ratio’,

sum(pinhits)*100/sum(pins),1

from &prefix.$librarycache

/

update gh$derived_stats

set notes=’*** Shared Pool too small’

where name=’library cache pin hit ratio’

and value < 90
/

DOC

—————————————————–

session_cached_cursor efficiency. This is the %age

of parse requests which appear to have been satisfied

via cached session cursors. Only relevent for 7.1 and

above, and only if session_cached_cursors is non-zero

——————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘cached cursor efficiency’,(1-(l.gets/s.value))*100,9

from &prefix.$librarycache l,

&prefix.$sysstat s,

v$parameter p

where l.namespace=’SQL AREA’

and s.name=’parse count’

and p.name=’session_cached_cursors’

and p.value != ‘0’

/

DOC

————————————————

redo log space ratio is the number of times a redo

write had to wait because there was no space in the

log buffer. High values may indicate a need to

increase log_buffer.

————————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘redo space wait ratio’,

(sw.value)*100/lw.value,9.2

from &prefix.$sysstat sw,

&prefix.$sysstat lw

where sw.name=’redo log space requests’

and lw.name=’redo writes’

/

update gh$derived_stats set notes=’*** log buffer too small?’

where name = ‘redo space wait ratio’

and value > 1;

DOC

—————————————————–

Rate at which chained rows are encountered. Indicates

that PCTFREE for a table is too low. Use analyse table

to locate the chained rows

——————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘chained fetch ratio’,

rfcr.value*100/(tsrg.value+tfbr.value),6

from &prefix.$sysstat rfcr,

&prefix.$sysstat tsrg,

&prefix.$sysstat tfbr

where rfcr.name=’table fetch continued row’

and tsrg.name=’table scan rows gotten’

and tfbr.name=’table fetch by rowid’;

update gh$derived_stats

set notes=’*** PCTFREE too low for a table’

where name=’chained fetch ratio’

and value > .01

/

DOC

———————————————-

Parse/execute ratio. High values usually mean

that cursors are not being reused within the

application.

———————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘parse/execute’,

pc.value*100/decode(ec.value,0,1,ec.value),9

from &prefix.$sysstat ec,

&prefix.$sysstat pc

where ec.name=’execute count’

and pc.name=’parse count’;

update gh$derived_stats

set notes=’***high parse rate’

where name=’parse/execute’

and value > 20;

DOC

———————————————–

Parse CPU usage ratio. Proportion of time

spent parsing. High values probably associated

with poor SQL cache hit rates (dynamic SQL)

———————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘CPU parse overhead’,

pc.value*100/decode(ec.value,0,1,ec.value),9

from &prefix.$sysstat ec,

&prefix.$sysstat pc

where ec.name=’CPU used by this session’

and pc.name=’parse time cpu’;

update gh$derived_stats

set notes=’***high parse overhead’

where name=’CPU parse overhead’

and value > 15;

DOC

——————————————–

Latch get rates. Low values are usually

significant performance problems, but the

specific action depends on the latch

——————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘Willing to wait latch get rate’,

(sum(gets)-sum(misses))*100/sum(gets),4

from &prefix.$latch;

insert into gh$derived_stats(name,value,seq)

select ‘Immediate latch get rate’,

(sum(immediate_gets)-sum(immediate_misses))*100/

sum(immediate_gets),4

from &prefix.$latch;

update gh$derived_stats

set notes=’*** Poor latch hit rate’

where name like ‘%latch get rate’

and value < 99; DOC
—————————————————-

Ratio of rows got from an index vs rows got via

tablescan. Low values may indicate poor SQL tuning

or indexing but remember that tablescans return more

rows anyway, so a few tablescans can perturb this

ratio

—————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘rows from idx/total rows’,

(r.value/(r.value+s.value))*100,12

from &prefix.$sysstat r,

&prefix.$sysstat s

where r.name=’table fetch by rowid’

and s.name=’table scan rows gotten’

;

DOC

———————————————

Most of the following ratios give some idea of

the application profile (eg transaction size,

sort size, etc)

———————————————

#

rem ————————————

rem Block changes per transaction

rem ———————————–

insert into gh$derived_stats(name,value,seq)

select ‘blk changes per transctn’,bc.value/t.value,99

from &prefix.$sysstat bc,

&prefix.$sysstat t

where bc.name=’db block changes’

and t.name=’user commits’

/

rem ————————————–

rem Calls per transaction

rem ————————————–

insert into gh$derived_stats(name,value,seq)

select ‘calls per transctn’,c.value/t.value,99

from &prefix.$sysstat c,

&prefix.$sysstat t

where c.name=’user calls’

and t.name=’user commits’

/

rem ————————————–

rem Rows per sort

rem ————————————–

insert into gh$derived_stats(name,value,seq)

select ‘rows per sort’,r.value/

decode( (d.value+m.value) ,0,1, (d.value+m.value) ) ,99

from &prefix.$sysstat r,

&prefix.$sysstat d,

&prefix.$sysstat m

where r.name=’sorts (rows)’

and d.name=’sorts (disk)’

and m.name=’sorts (memory)’;

rem ————————————–

rem Database writer statistics

rem ————————————–

DOC

——————————————

Average scan depth is the average number of

blocks scanned by the DBWR. Very high values

(>500?) may indicate DBWR is working too hard.

Having a very high value of db_files is known to

cause this problem.

———————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘DBWR Avg scan depth’,

dbs.value/dls.value,13

from &prefix.$sysstat dbs,

&prefix.$sysstat dls

where dbs.name=’DBWR summed scan depth’

and dls.name=’DBWR lru scans’

/

insert into gh$derived_stats(name,value,seq)

select ‘DBWR Avg buffers scanned’,

dbs.value/dls.value,13

from &prefix.$sysstat dbs,

&prefix.$sysstat dls

where dbs.name=’DBWR buffers scanned’

and dls.name=’DBWR lru scans’

update gh$derived_stats set notes=’*** DB_FILES too high?’

where name = ‘DBWR Avg scan depth’

and value > 256

/

DOC

——————————————

Free buffer count is the number of clean

buffers on the LRU chain. Very low values

may indicate that DBWR is not keeping up.

———————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘DBWR LRU free buffers’,

dbs.value/dls.value,13

from &prefix.$sysstat dbs,

&prefix.$sysstat dls

where dbs.name=’DBWR free buffers found’

and dls.name=’DBWR lru scans’

/

DOC

—————————————–

Summed scan depth/buffers scanned. Should

be close to 1 if DBWR is keeping up

—————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘DBWR summed scan/buffer scan’,

dbs.value/dls.value,13

from &prefix.$sysstat dbs,

&prefix.$sysstat dls

where dbs.name=’DBWR summed scan depth’

and dls.name=’DBWR buffers scanned’

/

update gh$derived_stats set notes=’*** DBWR falling behind?’

where name = ‘DBWR summed scan/buffer scan’

and (value > 2 or value <.5)
/

DOC

——————————————

Number of dirty blocks after DBWR write

completed

——————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘Dirty list after DBWR write’,

dbs.value/dls.value,13

from &prefix.$sysstat dbs,

&prefix.$sysstat dls

where dbs.name=’summed dirty queue length’

and dls.name=’write requests’

/

DOC

——————————————-

dirty buffers inspected/free buffer requested.

I think that this gives a fairly inaccurate

indication of the number of times a foreground

encounters a dirty block when looking for a

free block. Ratio should be very low.

——————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘Dirty buffers/free buf req %’,

dbs.value/dls.value*100,13

from &prefix.$sysstat dbs,

&prefix.$sysstat dls

where dbs.name=’dirty buffers inspected’

and dls.name=’free buffer requested’

/

update gh$derived_stats set notes=’*** DBWR falling behind?’

where name = ‘Dirty buffers/free buf req %’

and value > 5

/

rem ————————————-

rem Consistent change ratio (not usefull?)

rem ————————————-

insert into gh$derived_stats(name,value,seq)

select ‘consistent change ratio’,

(cg.value-cc.value)*100/cg.value,99

from &prefix.$sysstat cg,

&prefix.$sysstat cc

where cg.name=’consistent gets’

and cc.name=’consistent changes’

rem —————————————–

rem Enqueues

rem —————————————-

insert into gh$derived_stats(name,value,seq)

select ‘enqueue success (no wait)’,

100-(ew.value*100/er.value),8

from &prefix.$sysstat ew,

&prefix.$sysstat er

where ew.name=’enqueue waits’

and er.name=’enqueue requests’

insert into gh$derived_stats(name,value,seq)

select ‘enqueue success (no timeout)’,

100-(ew.value*100/er.value),8

from &prefix.$sysstat ew,

&prefix.$sysstat er

where ew.name=’enqueue timeouts’

and er.name=’enqueue requests’

insert into gh$derived_stats(name,value,seq)

select ‘commits/(commits+rollbacks)’,

(c.value/(r.value+c.value))*100,99

from &prefix.$sysstat r,

&prefix.$sysstat c

where r.name=’user rollbacks’

and c.name=’user commits’;

insert into gh$derived_stats(name,value,seq)

select ‘cursors/transaction’,

oc.value/(r.value+c.value),99

from &prefix.$sysstat c,

&prefix.$sysstat r,

&prefix.$sysstat oc

where c.name=’user commits’

and r.name=’user rollbacks’

and oc.name=’cumulative open cursors’;

rem select ‘free buffer inspects/scan’,

rem i.value/s.value,7

rem from &prefix.$sysstat s,

rem &prefix.$sysstat i

rem where i.name=’free buffer inspected’

rem and r.name=’user rollbacks’

rem and oc.name=’cumulative open cursors’;

ttitle center ‘Database efficiency indicators: ‘ instance_name right print_date skip center period_comment_ skip 2

break on seq skip 1

select seq,name,value,notes from gh$derived_stats

order by seq,name;

drop table gh$derived_stats;

set feedback on ;

spool off

****************************************************

File Name : db_stS.sql

****************************************************

define prefix=’gh’

set document off

#

# @stat_ctl

column name format a30 heading “Ratio ”

column notes format a35 heading “Comments”

column value format 99990.9999 heading “Value”

column seq noprint

set feedback off

set pagesize 56

set lines 80

set pagesize 56

set newpage 0

set termout off

drop table gh$derived_stats;

column instname new_value instance_name noprint

column repdate new_value print_date noprint

select substr(name,1,20) instname,to_char(sysdate,’DD/MM/YY:HH24:MI’) repdate from v$database;

set termout on

spool 800P.stat1

rem

rem Temporary table to hold results

rem

create table gh$derived_stats

(name varchar2(60),

value number,

notes varchar2(80),

seq number);

DOC

——————————————————–

Calculate Buffer cache hit ratio since last bounce

——————————————————–

#

insert into gh$derived_stats (name,value,seq)

select ‘buffer cache hit ratio’,

round((congets.value+dbgets.value-physreads.value)*100/

(congets.value+dbgets.value),4) “HIT RATE”,1

from v$sysstat congets,

v$sysstat dbgets,

v$sysstat physreads

where congets.name=’consistent gets’

and dbgets.name = ‘db block gets’

and physreads.name = ‘physical reads’

/

update gh$derived_stats

set notes=’*** May need to increase db_block_buffers’

where name=’buffer cache hit ratio’

and value <90
/

DOC

———————————————————

Ratio of recursive calls to user calls. Recursive calls

are SQL statements generated by ORACLE. High values can

indicate excessive dynamic or non-sharable SQL, excessive

rows dynamic segment extention or free space fragmentation or

an inadequately sized shared pool.

insert into gh$derived_stats(name,value,seq)

select ‘recursive calls/total calls’,

(rc.value/(rc.value+uc.value))*100,10

from v$sysstat rc,

v$sysstat uc

where rc.name=’recursive calls’

and uc.name=’user calls’

/

update gh$derived_stats

set notes=’*** Fragmentation? Dynamic SQL? Shared pool?’

where name=’recursive calls/total calls’

and value > 20

/

#

DOC

—————————————————

Data dictionary cache (row cache) hit rates. Low

values may mean that the shared pool is too small.

However, ORACLE doesn’t always size the dictionary

cache appropriately (or so it seems)

————————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘dictionary cache hit rate’,

sum(gets-getmisses)*100/sum(gets),1

from v$rowcache;

update gh$derived_stats

set notes=’*** high dictionary cache miss’

where name=’dictionary cache hit rate’

and value <98
/

DOC

————————————————-

Ratio of small (< SMALL_TABLE) to large table scans. We hope for predominantly small scans, otherwise there
may be untuned SQL out there

—————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘short/total table scan ratio’,sc.value/(sc.value+ls.value)*100,

12

from v$sysstat ls,

v$sysstat sc

where sc.name=’table scans (short tables)’

and ls.name=’table scans (long tables)’;

update gh$derived_stats

set notes=’*** Too many long table scans?’

where name=’short/total table scan ratio’

and value > <90 DOC
————————————————–

Disk sort ratio. Disk sorts are IO intensive as well

as poorly implemented in ORACLE prior to 7.2.

To reduce disk sorts, increase SORT_AREA_SIZE or

tune the SQL

————————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘disk sort ratio’,ds.value/

decode( (ds.value+ms.value) ,0,1,(ds.value+ms.value))*100

,10

from v$sysstat ds,

v$sysstat ms

where ms.name=’sorts (memory)’

and ds.name=’sorts (disk)’

/

update gh$derived_stats

set notes=’*** Too many disk sorts?’

where name=’disk sort ratio’

and value > 10;

DOC

————————————————-

Buffer busy ratio. High values May indicate that there are

tables with insufficient free lists or too few

rollback segments or extents

————————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘buffer busy wait ratio’,

(bbw.total_waits*100/(cg.value+dbg.value)),5

from v$system_event bbw,

v$sysstat cg,

v$sysstat dbg

where bbw.event=’buffer busy waits’

and cg.name =’consistent gets’

and dbg.name=’db block gets’

/

update gh$derived_stats

set notes=’*** RBack/Freelist contention?’

where name=’buffer busy wait ratio’

and value > 1;

/

DOC

————————————————–

Free buffer wait raio. High values are often associated

with disk sorts. In 7.2 try SORT_DIRECT_WRITES=TRUE.

In earlier versions, try making temporary tablespace

raw (in UNIX or NT)

—————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘free buffer wait ratio’,

(bbw.total_waits*100/(cg.value+dbg.value)),5

from v$system_event bbw,

v$sysstat cg,

v$sysstat dbg

where bbw.event=’free buffer waits’

and cg.name =’consistent gets’

and dbg.name=’db block gets’

/

update gh$derived_stats

set notes=’*** Disk sort/inode contention?’

where name=’free buffer wait ratio’

and value > 1;

/

DOC

————————————————-

Library cache hit rate. Low values suggest that

there is dynamic or unsharable SQL being submitted

————————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘library cache get hit ratio’,

sum(gethits)*100/sum(gets),1

from v$librarycache

/

update gh$derived_stats

set notes=’*** dynamic SQL?’

where name=’library cache get hit ratio’

and value < 85
/

DOC

————————————————-

Library cache pin hit ratio. Low values indicate

that the shared pool is too small

————————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘library cache pin hit ratio’,

sum(pinhits)*100/sum(pins),1

from v$librarycache

/

update gh$derived_stats

set notes=’*** Shared Pool too small’

where name=’library cache pin hit ratio’

and value < 90
/

DOC

—————————————————–

session_cached_cursor efficiency. This is the %age

of parse requests which appear to have been satisfied

via cached session cursors. Only relevent for 7.1 and

above, and only if session_cached_cursors is non-zero

——————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘cached cursor efficiency’,(1-(l.gets/s.value))*100,9

from v$librarycache l,

v$sysstat s,

v$parameter p

where l.namespace=’SQL AREA’

and s.name=’parse count’

and p.name=’session_cached_cursors’

and p.value != ‘0’

/

DOC

————————————————

redo log space ratio is the number of times a redo

write had to wait because there was no space in the

log buffer. High values may indicate a need to

increase log_buffer.

————————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘redo space wait ratio’,

(sw.value)*100/lw.value,9.2

from v$sysstat sw,

v$sysstat lw

where sw.name=’redo log space requests’

and lw.name=’redo writes’

/

update gh$derived_stats set notes=’*** log buffer too small?’

where name = ‘redo space wait ratio’

and value > 1;

DOC

—————————————————–

Rate at which chained rows are encountered. Indicates

that PCTFREE for a table is too low. Use analyse table

to locate the chained rows

——————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘chained fetch ratio’,

rfcr.value*100/(tsrg.value+tfbr.value),6

from v$sysstat rfcr,

v$sysstat tsrg,

v$sysstat tfbr

where rfcr.name=’table fetch continued row’

and tsrg.name=’table scan rows gotten’

and tfbr.name=’table fetch by rowid’;

update gh$derived_stats

set notes=’*** PCTFREE too low for a table’

where name=’chained fetch ratio’

and value > .01

/

DOC

———————————————-

Parse/execute ratio. High values usually mean

that cursors are not being reused within the

application.

———————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘parse/execute’,

pc.value*100/decode(ec.value,0,1,ec.value),9

from v$sysstat ec,

v$sysstat pc

where ec.name=’execute count’

and pc.name=’parse count’;

update gh$derived_stats

set notes=’***high parse rate’

where name=’parse/execute’

and value > 20;

DOC

———————————————–

Parse CPU usage ratio. Proportion of time

spent parsing. High values probably associated

with poor SQL cache hit rates (dynamic SQL)

———————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘CPU parse overhead’,

pc.value*100/decode(ec.value,0,1,ec.value),9

from v$sysstat ec,

v$sysstat pc

where ec.name=’CPU used by this session’

and pc.name=’parse time cpu’;

update gh$derived_stats

set notes=’***high parse overhead’

where name=’CPU parse overhead’

and value > 15;

DOC

——————————————–

Latch get rates. Low values are usually

significant performance problems, but the

specific action depends on the latch

——————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘Willing to wait latch get rate’,

(sum(gets)-sum(misses))*100/sum(gets),4

from v$latch;

insert into gh$derived_stats(name,value,seq)

select ‘Immediate latch get rate’,

(sum(immediate_gets)-sum(immediate_misses))*100/

sum(immediate_gets),4

from v$latch;

update gh$derived_stats

set notes=’*** Poor latch hit rate’

where name like ‘%latch get rate’

and value < 99;
DOC

—————————————————-

Ratio of rows got from an index vs rows got via

tablescan. Low values may indicate poor SQL tuning

or indexing but remember that tablescans return more

rows anyway, so a few tablescans can perturb this

ratio

—————————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘rows from idx/total rows’,

(r.value/(r.value+s.value))*100,12

from v$sysstat r,

v$sysstat s

where r.name=’table fetch by rowid’

and s.name=’table scan rows gotten’

;

DOC

———————————————

Most of the following ratios give some idea of

the application profile (eg transaction size,

sort size, etc)

———————————————

#

rem ————————————

rem Block changes per transaction

rem ———————————–

insert into gh$derived_stats(name,value,seq)

select ‘blk changes per transctn’,bc.value/t.value,99

from v$sysstat bc,

v$sysstat t

where bc.name=’db block changes’

and t.name=’user commits’

/

rem ————————————–

rem Calls per transaction

rem ————————————–

insert into gh$derived_stats(name,value,seq)

select ‘calls per transctn’,c.value/t.value,99

from v$sysstat c,

v$sysstat t

where c.name=’user calls’

and t.name=’user commits’

/

rem ————————————–

rem Rows per sort

rem ————————————–

insert into gh$derived_stats(name,value,seq)

select ‘rows per sort’,r.value/

decode( (d.value+m.value) ,0,1, (d.value+m.value) ) ,99

from v$sysstat r,

v$sysstat d,

v$sysstat m

where r.name=’sorts (rows)’

and d.name=’sorts (disk)’

and m.name=’sorts (memory)’;

rem ————————————–

rem Database writer statistics

rem ————————————–

DOC

——————————————

Average scan depth is the average number of

blocks scanned by the DBWR. Very high values

(>500?) may indicate DBWR is working too hard.

Having a very high value of db_files is known to

cause this problem.

———————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘DBWR Avg scan depth’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR summed scan depth’

and dls.name=’DBWR lru scans’

/

insert into gh$derived_stats(name,value,seq)

select ‘DBWR Avg buffers scanned’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR buffers scanned’

and dls.name=’DBWR lru scans’

update gh$derived_stats set notes=’*** DB_FILES too high?’

where name = ‘DBWR Avg scan depth’

and value > 256

/

DOC

——————————————

Free buffer count is the number of clean

buffers on the LRU chain. Very low values

may indicate that DBWR is not keeping up.

———————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘DBWR LRU free buffers’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR free buffers found’

and dls.name=’DBWR lru scans’

/

DOC

—————————————–

Summed scan depth/buffers scanned. Should

be close to 1 if DBWR is keeping up

—————————————–

#

insert into gh$derived_stats(name,value,seq)

select ‘DBWR summed scan/buffer scan’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR summed scan depth’

and dls.name=’DBWR buffers scanned’

/

update gh$derived_stats set notes=’*** DBWR falling behind?’

where name = ‘DBWR summed scan/buffer scan’

and (value > 2 or value <.5)
/

DOC

——————————————

Number of dirty blocks after DBWR write

completed

——————————————

#

insert into gh$derived_stats(name,value,seq)

select ‘Dirty list after DBWR write’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’summed dirty queue length’

and dls.name=’write requests’

/

DOC

——————————————-

dirty buffers inspected/free buffer requested.

I think that this gives a fairly inaccurate

indication of the number of times a foreground

encounters a dirty block when looking for a

free block. Ratio should be very low.

——————————————-

#

insert into gh$derived_stats(name,value,seq)

select ‘Dirty buffers/free buf req %’,

dbs.value/dls.value*100,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’dirty buffers inspected’

and dls.name=’free buffer requested’

/

update gh$derived_stats set notes=’*** DBWR falling behind?’

where name = ‘Dirty buffers/free buf req %’

and value > 5

/

rem ————————————-

rem Consistent change ratio (not usefull?)

rem ————————————-

insert into gh$derived_stats(name,value,seq)

select ‘consistent change ratio’,

(cg.value-cc.value)*100/cg.value,99

from v$sysstat cg,

v$sysstat cc

where cg.name=’consistent gets’

and cc.name=’consistent changes’

rem —————————————–

rem Enqueues

rem —————————————-

insert into gh$derived_stats(name,value,seq)

select ‘enqueue success (no wait)’,

100-(ew.value*100/er.value),8

from v$sysstat ew,

v$sysstat er

where ew.name=’enqueue waits’

and er.name=’enqueue requests’

insert into gh$derived_stats(name,value,seq)

select ‘enqueue success (no timeout)’,

100-(ew.value*100/er.value),8

from v$sysstat ew,

v$sysstat er

where ew.name=’enqueue timeouts’

and er.name=’enqueue requests’

insert into gh$derived_stats(name,value,seq)

select ‘commits/(commits+rollbacks)’,

(c.value/(r.value+c.value))*100,99

from v$sysstat r,

v$sysstat c

where r.name=’user rollbacks’

and c.name=’user commits’;

insert into gh$derived_stats(name,value,seq)

select ‘cursors/transaction’,

oc.value/(r.value+c.value),99

from v$sysstat c,

v$sysstat r,

v$sysstat oc

where c.name=’user commits’

and r.name=’user rollbacks’

and oc.name=’cumulative open cursors’;

rem select ‘free buffer inspects/scan’,

rem i.value/s.value,7

rem from v$sysstat s,

rem v$sysstat i

rem where i.name=’free buffer inspected’

rem and r.name=’user rollbacks’

rem and oc.name=’cumulative open cursors’;

ttitle center ‘Database efficiency indicators: ‘ instance_name right print_date skip center period_comment_ skip 2

break on seq skip 1

select seq,name,value,notes from gh$derived_stats

order by seq,name;

drop table gh$derived_stats;

set feedback on ;

spool off

****************************************************

File Name : dba_2pc_neighbors.sql

****************************************************

COL local_tran_id FORMAT a13

COL in_out FORMAT a6

COL database FORMAT a25

COL dbuser_owner FORMAT a15

COL interface FORMAT a3

SELECT local_tran_id, in_out, database, dbuser_owner, interface

FROM dba_2pc_neighbors

/

****************************************************

File Name : dba_2pc_pending.sql

****************************************************

COL local_tran_id FORMAT a13

COL global_tran_id FORMAT a30

COL state FORMAT a8

COL mixed FORMAT a3

COL host FORMAT a10

COL commit# FORMAT a10

SELECT local_tran_id, global_tran_id, state, mixed, host, commit#

FROM dba_2pc_pending

/

****************************************************

File Name : dbwr_wait.sql

****************************************************

select

decode(

sum(w.total_waits),

0, ‘NONE’,

to_char(

nvl(100 * sum(l.total_waits) / sum(w.total_waits), 0),

‘99990.00’

) || ‘%’

) sync_waits

from

sys.v$bgprocess b,

sys.v$session s,

sys.v$session_event l,

sys.v$session_event w

where

b.name like ‘DBW_’ and

s.paddr = b.paddr and

l.sid = s.sid and

l.event = ‘log file sync’ and

w.sid = s.sid and

w.event = ‘db file parallel write’

/

****************************************************

File Name : depen.sql

****************************************************

set pages 2000

select substr(a.owner,1,10),a.name,a.type,b.status,last_ddl_Time

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘&1’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

order by 3

/

****************************************************

File Name : depen1.sql

****************************************************

set pages 2000

select substr(a.owner,1,10),a.name,a.type,b.status,last_ddl_Time

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘&1’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

order by 3

/

****************************************************

File Name : depen_tp.sql

****************************************************

set pages 2000 lines 132

column date_time format a20

select substr(a.owner,1,10),a.name,a.type,b.status,to_char(last_ddl_Time,’MM-DD-YYYY-HH24:MI:SS’) Date_time

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘&1’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

order by 3

/

****************************************************

File Name : depen_with_compile.sql

****************************************************

set pagesize 10000

select ‘alter ‘||decode(a.type,’PACKAGE BODY’,’PACKAGE’,a.type)||’ “‘||substr(a.owner,1,10)||'”.’||a.name||’ compile;’ to_run

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘&1’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

and b.status=’INVALID’

/

****************************************************

File Name : dependency.sql

****************************************************

column object_name format a40

column owner format a15

SELECT owner, object_type, object_name

FROM dba_objects

—WHERE status = ‘INVALID’

—AND

where object_name IN (SELECT referenced_name

FROM dba_dependencies

WHERE name = upper(‘&1’));

****************************************************

File Name : depends.sql

****************************************************

set pagesize 60

set linesize 132

rem depends.sql

col for_owner format a10 heading ‘FOR OWN’

col for_table format a25 heading ‘FOR TBL’

col pri_owner format a10 heading ‘PRI OWN’

col pri_table format a25 heading ‘PRI TBL’

col for_col format a25 heading ‘FOR COL’

col pri_col format a25 heading ‘PRI COL’

rem

spool depends.log

select a.owner for_owner, a.table_name for_table, c.column_name for_col,

b.owner pri_owner, b.table_name pri_table, d.column_name pri_col

from dba_constraints a, dba_constraints b,

dba_cons_columns c, dba_cons_columns d

where

a.r_constraint_name = b.constraint_name

and a.constraint_type=’R’

and b.constraint_type = ‘P’

and a.r_owner=b.owner

and a.constraint_name = c.constraint_name

and b.constraint_name = d.constraint_name

and a.owner=c.owner

and a.table_name = c.table_name

and b.owner=d.owner

and b.table_name=d.table_name

and a.owner not in (‘SYS’,’SYSTEM’)

order by a.owner

/

spool off

exit

****************************************************

File Name : diction.sql

****************************************************

ttitle – center ‘Dictionary Cache Statistics Report’ skip 2

col parameter heading ‘Parameter Name’ format a20 justify c trunc

col count heading ‘Entries|Allocated’ format 9999999990 justify c

col usage heading ‘Entries|Used’ format 9999999990 justify c

col gets heading ‘Gets’ format 9999999990 justify c

col getmisses heading ‘Get|Misses’ format 9999999990 justify c

col pctused heading ‘Pct|Used’ format 990.0 justify c

col pctmisses heading ‘Pct|Misses’ format 990.0 justify c

col action heading ‘Rec”d|Action’ format a6 justify c

select

parameter,

count,

usage,

100*nvl(usage,0)/decode(count,null,1,0,1,count) pctused,

gets,

getmisses,

100*nvl(getmisses,0)/decode(gets,null,1,0,1,gets) pctmisses,

decode(

greatest(100*nvl(usage,0)/decode(count,null,1,0,1,count),80),

80, ‘ Lower’,

decode(least(100*nvl(getmisses,0)/decode(gets,null,1,0,1,gets),10),

10, ‘*Raise’, ‘ Ok’)

) action

from

v$rowcache

order by

1

/

****************************************************

File Name : dir_path.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col kslednam format a17 heading “Writ/READ”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX on KSLEDNAM

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_on_Dirpath_read_write,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

,e.kslednam

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and (e.kslednam =’direct path write’

or e.kslednam =’direct path read’)

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : disab_trig.sql

****************************************************

select ‘alter trigger ats.’||trigger_name||’ disable ;’

from dba_triggers

where table_name in

(

‘ATS_DAY_END_EXCEPTIONS’,

‘INT_ORDER_ITEMS’

)

/

****************************************************

File Name : disable_cons.sql

****************************************************

set linesize 150 term on echo on pagesize 0 feedback off

select ‘alter table ‘||owner||’.’||table_name||’ disable constraint ‘||

constraint_name ||’;’

from dba_constraints where owner =’ATS’

and constraint_type <> ‘C’

spool discons.sql

/

spool off

****************************************************

File Name : disable_trig_repl.sql

****************************************************

alter trigger “ATS”.ACTION_SECURITY_PRE_INS_DBT disable;

alter trigger “ARUN”.PRE_UPD_SYS_ISS_AG_DBT disable;

****************************************************

File Name : disable_trigger.sql

****************************************************

——————————————————–

—– This package generates the script for compiling

—– various objects

——————————————————-

set pages 5000

select ‘alter trigger ‘||

‘ “‘||

owner||'”.’||trigger_name||’ disable; ‘

from dba_triggers

where owner in (‘ATS’,’1193′,’SHISHIR’,’SATISH’,’BLOOMORA’,’EXPUSER’,’6344′,’NAVEEN’,’CHANDRA’,’BKGR’,’MERCORA

‘)

/

****************************************************

File Name : disk.sql

****************************************************

select sid,value from v$sesstat where statistic#=140 and value !=0 ;

****************************************************

File Name : disk_sort.sql

****************************************************

set lines 132

column username format a10

column tablespace format a10

column sql_text format a50 wrapped

select a.username,b.TABLESPACE,b.blocks,c.sql_Text

from v$session a,v$sort_usage b,v$sqlarea c

where b.SESSION_ADDR = a.saddr

and b.SQLADDR = c.ADDRESS

and b.SQLHASH = c.HASH_VALUE

/

****************************************************

File Name : disp_con.sql

****************************************************

col network format a4

col receive format a10

col status format a10

select name, paddr, network, status, accept, owned, created, idle, busy

from v$dispatcher

/

****************************************************

File Name : dp1.sql

****************************************************

****************************************************

File Name : drop_logfile.sql

****************************************************

set term on echo on

set concat +

alter database drop logfile ‘/ORADATA&1/800P/800P_redo&2.rdo’;

set concat .

****************************************************

File Name : dropind.sql

****************************************************

select ‘drop index ats.’||a.index_name || ‘ ;’

from

(select index_name

from dba_ind_columns

where table_name in

(

‘ATS_DAY_END_EXCEPTIONS’,

‘INT_ORDER_ITEMS’

)

and column_name in (‘PRODUCT_CODE’,’PDT_PRODUCT_CODE’,’PDT_CODE’,

‘ADD_ON’,’PROD_CODE’,’PRD_CODE’,’SECOND_CHOICE’,’TRACKING_NUMBER’,

‘TRACKING_NO’,’SECOND_CHOICE_PDT’)) a

/

****************************************************

File Name : dual_alternative.sql

****************************************************

create view dual_view as select dummy from x$dual;

grant select on dual_view to public;

rename dual to dual_table;

rename dual_view to dual;

****************************************************

File Name : dump.sql

****************************************************

accept Structure char prompt “Structure to dump :”

accept Level number prompt “Level of dump :”

set termout off

alter session set max_dump_file_size = unlimited

/

set termout onprompt

prompt alter session set events ‘immediate trace name &Structure level &Level’

set feedback on

alter session set events ‘immediate trace name &Structure level &Level’

/

****************************************************

File Name : end_backup_mode.sql

****************************************************

NAME

——————————————————————————–

0 rows selected.

****************************************************

File Name : enq_sql.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_waiting_on_ENQUEUE,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’enqueue’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : enqueue_type.sql

****************************************************

accept enqueue_num char prompt “Enqueue Number:”

col Lock format a4

col Mode format a4

select chr(bitand(&enqueue_num,-16777216)/16777215) || chr(bitand(&enqueue_num,16711680)/65535)

“Lock”, to_char(bitand(&enqueue_num,65535)) “Mode”

from dual

/

****************************************************

File Name : enqueue_wait.sql

****************************************************

break on SID on ROW_WAIT_OBJ# on ROW_WAIT_FILE# on ROW_WAIT_BLOCK# on ROW_WAIT_ROW#

select /*+ FIRST_ROWS */ a.SID, a.ROW_WAIT_OBJ#,a.ROW_WAIT_FILE#,a.ROW_WAIT_BLOCK#,a.ROW_WAIT_ROW#

,c.sql_text

from v$session a,

v$session_wait b,

v$sqltext c

where a.sid = b.sid

and b.event=’enqueue’

and a.SQL_ADDRESS = c.address

and a.SQL_HASH_VALUE = c.HASH_VALUE

order by 1,2,3,4,5,piece

/

****************************************************

File Name : ex.sql

****************************************************

declare

ret_val varchar2(100);

in1 varchar2(50);

in2 varchar2(100);

begin

in1:=NULL;

in2:=’0′;

ret_val:=F_Get_Sys_parameter(in1,in2);

dbms_output.put_line(ret_val);

end;

/

****************************************************

File Name : exp.sql

****************************************************

SELECT operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer FROM plan_table WHERE statement_id = ‘Emp_Sal’ ORDER BY id;

****************************************************

File Name : exper.sql

****************************************************

column aa format 999

column serial# format 99999

SELECT sid,serial#, a.KGLPNMOD aa, a.KGLPNREQ, substr(b.username,1,14), substr(c.KGLNAOBJ,1,35), c.KGLOBTYP

FROM x$kglpn a, v$session b, x$kglob c

WHERE a.KGLPNUSE = b.saddr and

upper(c.KGLNAOBJ) like ‘%’ and a.KGLPNHDL = c.KGLHDADR

and KGLOBTYP = 9

;

****************************************************

File Name : extgrow.sql

****************************************************

create table extgrow

(segname varchar2(81) not null

,segown varchar2(30) not null

,growdate date not null

,segtype varchar2(17)

,segtbs varchar2(30)

,exts number

,nextext number

,tbsfree number

,hwm number

,totbytes number

,usedbytes number

,contigfree number

,freepct number

)

tablespace tools

storage (initial 819200 next 819200

minextents 10

maxextents 505

pctincrease 0

)

/

alter table extgrow add constraint extgrow_pk primary key(segown, segname, growdate)

using index tablespace tools

storage (initial 819200 next 819200

minextents 10

maxextents 505

pctincrease 0

)

/

****************************************************

File Name : extgrow2.sql

****************************************************

et pages 2000

column segname format a40

column usedbytes format 999,999,999,999

select segname,usedbytes from extgrow

where growdate = ‘&1’

and segname = ‘&2’

/

****************************************************

File Name : file_info.sql

****************************************************

accept RFNO number prompt “Relative Fno :”

select file_name,file_id,tablespace_name from dba_data_files

where relative_fno = &RFNO

/

****************************************************

File Name : file_io.sql

****************************************************

select file_name,PHYRDS,PHYWRTS,(PHYRDS+PHYWRTS) TOTIO,READTIM,WRITETIM,AVGIOTIM

from v$filestat a,

dba_data_files b

where a.file#=b.file_id

and file_name like ‘/ORADATA23%’

order by 4

/

****************************************************

File Name : file_io_stats.sql

****************************************************

col file_name format a50

col tablespace_name format a25

SELECT a.tablespace_name,

a.file_name,

b.file#,

b.phyblkrd,

b.phyblkwrt,

b.phyrds,

b.phywrts,

(b.phyrds+b.phywrts) total_io ,

readtim,

writetim ,

round(readtim/decode(phyrds,0,1,phyrds),2) avgreadtime,

round(writetim/decode(phywrts,0,1,phywrts),2) avgwritetime

FROM sys.v_$filestat b, sys.dba_data_files a

WHERE b.file# = a.file_id

ORDER BY total_io desc

/

****************************************************

File Name : file_io_sys.sql

****************************************************

select file_name,PHYRDS,PHYWRTS,(PHYRDS+PHYWRTS) TOTIO,READTIM,WRITETIM,AVGIOTIM

from v$filestat a,

dba_data_files b

where a.file#=b.file_id

order by 4

/

****************************************************

File Name : file_io_tbswise.sql

****************************************************

select tablespace_name,sum(PHYRDS+PHYWRTS),sum(PHYBLKRD+PHYBLKWRT)

from v$filestat a, dba_data_files b

where a.file#=b.file_id

group by tablespace_name

order by 3,2;

****************************************************

File Name : file_sum.sql

****************************************************

select substr(file_name,1,10),sum(PHYRDS),sum(PHYWRTS),sum(READTIM),sum(WRITETIM),sum(PHYRDS+PHYWRTS)

from v$filestat,dba_data_files

where v$filestat.FILE# = dba_data_files.FILE_ID

group by substr(file_name,1,10)

/

****************************************************

File Name : file_sum_tbs.sql

****************************************************

select tablespace_name,sum(PHYRDS),sum(PHYWRTS),sum(READTIM),sum(WRITETIM),sum(PHYRDS+PHYWRTS)

from MAY9200222,dba_data_files

where v$filestat.FILE# = dba_data_files.FILE_ID

group by tablespace_name

order by 6

/

****************************************************

File Name : file_sys_io.sql

****************************************************

select substr(file_name,1,10),sum(PHYRDS+PHYWRTS),sum(PHYBLKRD+PHYBLKWRT)

from v$filestat a, dba_data_files b

where a.file#=b.file_id

group by substr(file_name,1,10)

order by 3,2

/

****************************************************

File Name : file_wait.sql

****************************************************

set lines 132

col name format a50

col “Avg Time” format 9999999.99

select name, count,TIME,(time/count) “Avg Time”

from x$kcbfwait, v$datafile

where indx + 1 = file#

and count>0

order by 3,2

/

****************************************************

File Name : file_wait_cum.sql

****************************************************

set lines 132

col name format a50

col “Avg Time” format 9999999.99

select substr(name,1,10),sum(time),sum(count)

from x$kcbfwait, v$datafile

where indx + 1 = file#

and count>0

group by substr(name,1,10)

order by 3,2

/

****************************************************

File Name : fileio.sql

****************************************************

set pages 2000

set lines 132

column pbr format 99999999999 heading ‘Physical|Blk Read’

column pbw format 99999999 heading ‘Physical|Blks Wrtn’

column pyr format 99999999 heading ‘Physical|Reads’

column readtim format 99999999 heading ‘Read|Time’

column name format a40 heading ‘DataFile Name’

column writetim format 99999999 heading ‘Write|Time’

ttitle center ‘Tablespace Report’ skip 2

compute sum of f.phyblkrd, f.phyblkwrt on reportrem

select substr(file_name,1,10) name,sum(f.phyblkrd) pbr,sum(f.phyblkwrt) pbw,sum(f.readtim),sum(f.writetim)

from v$filestat f, dba_Data_files fs

where f.file# = fs.file_id

group by substr(file_name,1,10)

/

****************************************************

File Name : find_sql.sql

****************************************************

select sql_text from v$sqlarea where address = ‘&1’;

****************************************************

File Name : fk.sql

****************************************************

set pages 2000

set lines 90

select a.constraint_name,a.constraint_type,a.table_name,a.delete_rule,a.status

from dba_constraints a

where a.r_constraint_name =

(

select distinct b.constraint_name from dba_constraints b

where b.constraint_type = ‘P’

and b.table_name = Upper(‘&1’)

)

/

****************************************************

File Name : fk1.sql

****************************************************

select a.constraint_name,a.constraint_type,a.table_name,a.delete_rule,a.status

from dba_constraints a

where a.r_constraint_name =

(

select distinct b.constraint_name from dba_constraints b

where b.constraint_type = ‘P’

and b.table_name = Upper(‘&1’)

)

/

****************************************************

File Name : fk_info.sql

****************************************************

set lines 132

col owner format a5

col table_name format a35

col column_name format a40

accept fk_name char prompt “Enter FK NAME :”

select owner,table_name,column_name,position

from dba_cons_columns

where constraint_name = Upper(‘&fk_name’)

order by 4

/

select owner,table_name,constraint_name,column_name,position

from dba_cons_columns

where (owner,constraint_name) =

(select r_owner,r_constraint_name from dba_constraints

where constraint_name = Upper(‘&fk_name’))

/

****************************************************

File Name : flush_shared_pool.sql

****************************************************

alter system flush shared_pool;

exit

****************************************************

File Name : fopen_wait.sql

****************************************************

select a.SID, a.ROW_WAIT_OBJ#,a.ROW_WAIT_FILE#,a.ROW_WAIT_BLOCK#,a.ROW_WAIT_ROW#

from v$session a,

v$session_wait b

where a.sid = b.sid

and b.event=’file open’

order by 4,5

/

****************************************************

File Name : force_logswitch.sql

****************************************************

set term off echo off

alter system switch logfile;

exit

****************************************************

File Name : fragmentation.sql

****************************************************

set feedback off;

set term off

set pagesize 60;

set newpage 0;

set linesize 80;

truncate table freesp;

declare

fileid number(9);

filename char(255);

tsname char(30);

Cursor tablespaces is

select file_name, file_id, tablespace_name from dba_data_files;

Begin

Open tablespaces;

Loop

Fetch tablespaces into filename, fileid, tsname;

Exit when tablespaces%notfound;

declare

first number(6);

blocks number(6);

last number(6);

tfirst number(6);

tblocks number(6);

tlast number(6);

Cursor free is

select block_id a, blocks b, block_id+blocks c

from dba_free_space

where file_id = fileid

order by block_id;

begin

Open free;

Fetch free into first, blocks, last;

if free%notfound

then

goto close_free;

end if;

Loop

Fetch free into tfirst, tblocks, tlast;

Exit when free%notfound;

If tfirst = last

Then

blocks := blocks + tblocks;

last := tlast;

Else

Insert into freesp

values (filename, tsname, first, blocks, last-1);

commit;

first := tfirst;

blocks := tblocks;

last := tlast;

End if;

End Loop;

Insert into freesp

values (filename, tsname, first, blocks, last-1);

Commit;

<>

close free;

End;

End Loop;

Commit;

close tablespaces;

End;

/

set term off

set echo off linesize 132

col db_name new_value instance

select ‘INSTANCE NAME’ description, value db_name from v$parameter

where upper(name) = ‘DB_NAME’

/

ttitle center instance ‘ TABLESPACE FRAGMENTATION REPORT’

col tspace heading ‘TABLESPACE|NAME’ format a15 trunc

col fname heading ‘FILE’ FORMAT A50 trunc

col first heading ‘START|BLOCK’ FORMAT 999,999

COL blocks HEADING ‘BLOCKS|REMAINING’ FORMAT 99,999,999

break on report on tspace skip 1 on fname skip 1

compute sum of blocks on fname

compute sum of blocks on tspace

compute sum of blocks on report

spool frag_$ORACLE_SID.rpt

select tspace, fname, first, blocks

from freesp order by tspace,fname,first;

spool off;

exit

****************************************************

File Name : free_file_space.sql

****************************************************

set lines 132

column tn format a15 heading “TBS Name”

column bi format 99999999 heading “Block id”

column bytes format 99999999999.99 heading “Cont. Free Byte”

column fi format 999 heading “File id”

column fn format a40 heading “File name”

column bl format 9999999 heading “# Blocks”

select a.tablespace_name tn,a.block_id bi,a.bytes/1024/1024 bytes,b.file_name fn,b.file_id fi,a.blocks bl

from dba_free_space a,dba_data_Files b

where a.tablespace_name = upper(‘&1’)

and a.file_id = b.file_id

order by 3

/

****************************************************

File Name : free_space.sql

****************************************************

set heading on pagesize 25 feedback off echo off

set space 2

ttitle center ‘Tablespace Sizing Information’ Skip 2

column tablespace_name format a15 heading ‘TS Name’

column sbytes format 999,999,999,999 heading ‘Total Bytes’

column fbytes format 999,999,999,999 heading ‘Free Bytes’

column kount format 9999 heading ‘Ext’

column pct format 999.9 heading ‘PCT’

compute sum of fbytes on tablespace_name

compute sum of sbytes on tablespace_name

compute sum of sbytes on report

compute sum of fbytes on report

break on report

rem Here must grant select on DBA_FREE_SPACE directly to the

rem creator of this view, else error occurs indicating that you cannot create

rem view using role privs

rem create or replace view sum_tbsp_free as

rem select sum(bytes) bytes, count(bytes) num_chks, tablespace_name

rem from sys.dba_free_space

rem group by tablespace_name

rem /

rem kept Marlene’s query, just substituted the view for DBA_FREE_SPACE and

rem removed SUMS/COUNT verb from associated attributes

rem group by using “b” items works because of 1-to-1 relationship

set term off echo off

spool $RPT/free_space.log

select a.tablespace_name, sum(a.bytes) sbytes, b.bytes fbytes,

b.num_chks kount, (b.bytes/sum(a.bytes))*100 pct

from dba_data_files a, sum_tbsp_free b

where a.tablespace_name = b.tablespace_name

group by a.tablespace_name, b.bytes,b.num_chks

order by a.tablespace_name

/

set linesize 80

ttitle off

spool off

exit

****************************************************

File Name : free_tablespace.sql

****************************************************

select b.file_id “File #”,

b.tablespace_name “Tablespace Name”,

b.bytes “# bytes”,

(b.bytes – sum(nvl(a.bytes,0))) “# used”,

sum(nvl(a.bytes,0)) “# free”,

(sum(nvl(a.bytes,0))/(b.bytes))*100 “% free”

from sys.dba_free_space@merc6 a, sys.dba_data_files@merc6 b

where a.file_id(+) = b.file_id

group by b.tablespace_name, b.file_id, b.bytes

order by b.tablespace_name

/

****************************************************

File Name : free_tabspace.sql

****************************************************

column fn format a40

select file_name fn,BLOCK_ID,dba_free_space.BYTES, dba_data_Files.bytes “FS”

from dba_free_space,dba_data_files

where dba_free_space.FILE_ID=dba_data_files.FILE_ID

and dba_free_space.tablespace_name = UPPER(‘&1’)

order by 3

/

****************************************************

File Name : freesp.sql

****************************************************

Create table freesp

( fname char(255),

Tspace char(30),

First number(6),

Blocks number(6),

Last number(6))

tablespace users

storage (initial 8K next 4K pctincrease 0)

pctfree 0;

****************************************************

File Name : freesp_merc6.sql

****************************************************

set heading on pagesize 25 feedback off echo off

set space 2

ttitle center ‘Tablespace Sizing Information’ Skip 2

column tablespace_name format a15 heading ‘TS Name’

column sbytes format 999,999,999,999 heading ‘Total Bytes’

column fbytes format 999,999,999,999 heading ‘Free Bytes’

column kount format 9999 heading ‘Ext’

column pct format 999.9 heading ‘PCT’

compute sum of fbytes on tablespace_name

compute sum of sbytes on tablespace_name

compute sum of sbytes on report

compute sum of fbytes on report

break on report

rem Here must grant select on DBA_FREE_SPACE directly to the

rem creator of this view, else error occurs indicating that you cannot create

rem view using role privs

rem create or replace view sum_tbsp_free as

rem select sum(bytes) bytes, count(bytes) num_chks, tablespace_name

rem from sys.dba_free_space

rem group by tablespace_name

rem /

rem kept Marlene’s query, just substituted the view for DBA_FREE_SPACE and

rem removed SUMS/COUNT verb from associated attributes

rem group by using “b” items works because of 1-to-1 relationship

set term off echo off

spool $RPT/free_space_merc6.log

select a.tablespace_name, sum(a.bytes) sbytes, b.bytes fbytes,

b.num_chks kount, (b.bytes/sum(a.bytes))*100 pct

from dba_data_files@merc6 a, sum_tbsp_free@merc6 b

where a.tablespace_name = b.tablespace_name

group by a.tablespace_name, b.bytes,b.num_chks

order by a.tablespace_name

/

set linesize 80

ttitle off

spool off

exit

****************************************************

File Name : freespace.sql

****************************************************

REM

REM freespace.sql

REM By Margaret Murray (mostly) and Paul Vallee (for getting rid of the temp

REM table)

REM Copyright 1999 by Margaret Murray and Paul Vallee

REM Distribution permitted as long as no fee is charged and this copyright

REM notice is intact.

REM

column tablespace_name format a15

column TS_NAME format a12

column NAME format a55

column pieces format 990 hea PCS

column TS_SIZE format 999999999

column LARGESTPC format a9

column TOTALFREE format a9

column PCT_FREE format a9

column WHATSUSED format 999999999

column PCT_USED format a9

column M_BYTES format a9

column PROB forma a4

select tablespace_name TS_NAME,

pieces,

ts_size TS_SIZE,

largest_chunk||’M’ LARGESTPC,

total_free||’M’ TOTALFREE,

round((total_free/ts_size)*100,2)||’%’ PCT_FREE,

ts_size-total_free WHATSUSED,

100-round((total_free/ts_size)*100,2)||’%’ PCT_USED,

decode(100-round((total_free/ts_size)*100,0),85,’+’,86,’+’,87,’+’,88,’+’,89,

‘++’,90,’++’,91,’++’,92,’++’,93,’++’,94,’+++’,95,’+++’,96,’+++’,97,’++++’,98

,’+++++’,99,’+++++’,”) PROB

from (

select dfs.tablespace_name,

count(*) pieces,

round(max(dfs.bytes)/1024/1024,2) largest_chunk,

round(sum(dfs.bytes)/1024/1024,2) total_free

from dba_free_space dfs

group by tablespace_name ) q1,

(

select tablespace_name other_tname, round(sum(ddf.bytes)/1024/1024,2)

ts_size

from dba_data_files ddf

group by tablespace_name ) q2

where q1.tablespace_name = q2.other_tname

order by round((total_free/ts_size)*100,2) asc

spool $RPT/freespace.log

/

exit

****************************************************

File Name : ft_scans.sql

****************************************************

select distinct obj

from x$bh

where bitand(flag,power(2,19)) = power(2,19):

****************************************************

File Name : gen_beginbkup1.sql

****************************************************

set echo off feedback off heading off termout off

spool &1

select ‘alter tablespace ‘||tablespace_name||’ begin backup;’

from dba_tablespaces

where tablespace_name in (‘ATLAS_INDEX’,’CUST_INDEX’,’MISC_INDEX’,’TEMP’,’TEMP1′,’INTERACT_DATA’,’INTERACT_INDEX’,’RBS5′,’RBS6′,’MERCHANT_DATA’,’MERCHANT_INDEX’,’ORD_INDEX’,’LOAD_INDEX’,’TEMP_INDEX’,’SYSTEM’)

/

exit

****************************************************

File Name : gen_comp.sql

****************************************************

——————————————————–

—– This package generates the script for compiling

—– various objects

——————————————————-

set pages 5000

select ‘prompt ‘||owner||’.’||object_name||’ – ‘|| object_type|| chr(10)||

‘alter ‘||

decode(object_type,’PACKAGE BODY’,’PACKAGE’,object_type)||’ “‘||

owner||'”.’||object_name||’ compile ‘||

decode(object_type,’PACKAGE BODY’,’BODY;’,’;’)

from dba_objects

where status = ‘INVALID’

/

****************************************************

File Name : gen_compile.sql

****************************************************

——————————————————–

—– This package generates the script for compiling

—– various objects

——————————————————-

set pages 5000

select ‘prompt ‘||a.owner||’.’||a.object_name||’ – ‘||a.object_type|| chr(10)||

‘alter ‘||

decode(a.object_type,’PACKAGE BODY’,’PACKAGE’,object_type) || ‘ “‘||

a.owner||'”.’||a.object_name||’ compile ‘||

decode(a.object_type,’PACKAGE BODY’,’BODY;’,’;’)

||decode(a.object_type,’VIEW’,chr(10)||’grant select on “‘||a.owner||'”.’||a.object_name||’ to public ;’, ‘ ‘)

from

dba_objects a

where a.status = ‘INVALID’

/

****************************************************

File Name : gen_endbkup.sql

****************************************************

set echo off feedback off heading off termout off

spool &1

select ‘alter tablespace ‘||tablespace_name||’ end backup;’

from dba_tablespaces

/

exit

****************************************************

File Name : gen_endbkup1.sql

****************************************************

set echo off feedback off heading off termout off

spool &1

select ‘alter tablespace ‘||tablespace_name||’ end backup;’

from dba_tablespaces

where tablespace_name in (‘ATLAS_INDEX’,’CUST_INDEX’,’MISC_INDEX’,’TEMP’,’TEMP1′,’INTERACT_DATA’,’INTERACT_INDEX’,’RBS5′,’RBS6′,’MERCHANT_DATA’,’MERCHANT_INDEX’,’ORD_INDEX’,’LOAD_INDEX’,’TEMP_INDEX’,’SYSTEM’)

/

exit

****************************************************

File Name : gen_file_name.sql

****************************************************

set pages 2000

set lines 100

select ‘rename datafile ‘||””||rtrim(name)||””|| ‘ to ‘||””||rtrim(name)||””||’ ;’ from v$datafile

/

****************************************************

File Name : gen_kill.sql

****************************************************

set pagesize 0 term off echo off

spool $LOGS/killjobs.lst

select ‘kill -9 ‘||pid

from killjobs;

****************************************************

File Name : gen_kill_locks.sql

****************************************************

set term off echo off pagesize 0 trimspool on

SELECT /*+ ordered use_nl(l), use_nl(s) +*/

‘alter system kill session ‘||””||l.sid||’,’||s.serial#||””||’;’

from v$longlocks l, v$session s

where

l.held_sec > 900

and s.sid=l.sid

and l.blocker=’**BLOCKING**’

spool kill.lst

/

****************************************************

File Name : gen_obj_comp.sql

****************************************************

——————————————————–

—– This package generates the script for compiling

—– various objects

——————————————————-

set pages 2000

select ‘prompt ‘||a.owner||’.’||a.name||’ – ‘||a.type|| chr(10)||

‘alter ‘||

decode(a.type,’PACKAGE BODY’,’PACKAGE’,object_type) || ‘ “‘||a.owner||'”.’||a.name||’ compile ‘||

decode(a.type,’PACKAGE BODY’,’BODY;’,’;’)

||decode(a.type,’VIEW’,chr(10)||’grant select on “‘||a.owner||'”.’||a.name||’ to public ;’, ‘ ‘)

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘&1’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

—and b.status = ‘INVALID’

order by 1

/

****************************************************

File Name : gen_obj_script.sql

****************************************************

select ‘spool ‘||a.object_name||decode(a.object_type,’FUNCTION’,’.FUN’,’PACKAGE’,’.PKG’,’PROCEDURE’,’.PRC’,’TRIGGER’,’.TRIG’)|| chr(10)||

‘set pages 2000 lines 132 head off feed off’|| chr(10) ||

‘select text from dba_source where name = ‘||””||upper(a.object_name)||””||’ and owner = ‘||

””||upper(a.owner)||””||’ ;’|| chr(10)||

‘spool off’||chr(10)

from

( select object_name,object_type,owner from dba_objects

where object_type in (‘TRIGGER’)

and owner in (‘ATS’,’1193′,’SHISHIR’,’SATISH’,’BLOOMORA’,’EXPUSER’,’6344′,’NAVEEN’,’CHANDRA’,’BKGR’,’MERCORA’)

— and owner = ‘ATS’

) a

;

****************************************************

File Name : gen_pre_ins_dbt.sql

****************************************************

select ‘CREATE OR REPLACE TRIGGER ‘||table_name||’_PRE_INS_DBT’||chr(10)||

‘BEFORE INSERT’||chr(10)||’ON ‘|| table_name ||chr(10)||’FOR EACH ROW’||chr(10)||

‘DECLARE’||chr(10)||’BEGIN ‘||chr(10)||’ BEGIN’||chr(10)||

‘ set_audit_proc(‘||””||’I’||””||’, :new.usr_crtd, :new.dt_crtd,’||chr(10)||

‘ :new.usr_mdfd, :new.dt_mdfd);’||chr(10)||

‘ END;’||chr(10)||

‘END;’||chr(10)||’/’

from dba_tables

where table_name in

(

select table_name from dba_tables where table_name in (select distinct table_name from dba_tab_columns

where owner = ‘ATS’ and (column_name in (‘DT_CRTD’, ‘DT_MDFD’)))

minus

select table_name from dba_triggers where

(owner,trigger_name) in (

select a.owner,a.name

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘SET_AUDIT_PROC’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

and b.objecT_type = ‘TRIGGER’

and b.owner = ‘ATS’

)

)

and owner = ‘ATS’

/

****************************************************

File Name : gen_pre_upd_trig.sql

****************************************************

select ‘CREATE OR REPLACE TRIGGER ‘||table_name||’_PRE_UPD_DBT’||chr(10)||

‘BEFORE UPDATE’||chr(10)||’ON ‘|| table_name ||chr(10)||’FOR EACH ROW’||chr(10)||

‘DECLARE’||chr(10)||’BEGIN ‘||chr(10)||’ BEGIN’||chr(10)||

‘ set_audit_proc(‘||””||’U’||””||’, :new.usr_crtd, :new.dt_crtd,’||chr(10)||

‘ :new.usr_mdfd, :new.dt_mdfd);’||chr(10)||

‘ END;’||chr(10)||

‘END;’||chr(10)||’/’

from dba_tables

where table_name in

(

select table_name from dba_tables where table_name in (select distinct table_name from dba_tab_columns

where owner = ‘ATS’ and (column_name in (‘DT_CRTD’, ‘DT_MDFD’)))

minus

select table_name from dba_triggers where

(owner,trigger_name) in (

select a.owner,a.name

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘SET_AUDIT_PROC’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

and b.objecT_type = ‘TRIGGER’

and b.owner = ‘ATS’

)

)

and owner = ‘ATS’

/

****************************************************

File Name : genhot.sql

****************************************************

ALTER TABLESPACE ADDR_DATA BEGIN BACKUP;

HOST cp /ORADATA1/800P/800P_addr_data1.dbf /db4/oradata/800P/.;

HOST cp /ORADATA1/800P/800P_addr_data2.dbf /db4/oradata/800P/.;

ALTER TABLESPACE ADDR_DATA END BACKUP;

ALTER TABLESPACE ADDR_INDEX BEGIN BACKUP;

HOST cp /ORADATA2/800P/800P_addr_index1.dbf /db4/oradata/800P/.;

HOST cp /ORADATA2/800P/800P_addr_index2.dbf /db4/oradata/800P/.;

ALTER TABLESPACE ADDR_INDEX END BACKUP;

EXIT

****************************************************

File Name : genhot1.sql

****************************************************

compress -v /db4/oradata/800P/800P_addr_data1.dbf

compress -v /db4/oradata/800P/800P_addr_data2.dbf

compress -v /db4/oradata/800P/800P_addr_index1.dbf

compress -v /db4/oradata/800P/800P_addr_index2.dbf

compress -v /db4/oradata/800P/800P_zip_index1.dbf

****************************************************

File Name : genhota.sql

****************************************************

ALTER TABLESPACE MISC_INDEX BEGIN BACKUP;

HOST cp /ORADATA2/800P/800P_misc_index1.dbf /db4/oradata/800P/.;

ALTER TABLESPACE MISC_INDEX END BACKUP;

ALTER TABLESPACE ORD_DATA BEGIN BACKUP;

HOST cp /ORADATA1/800P/800P_ord_data1.dbf /db4/oradata/800P/.;

HOST cp /ORADATA1/800P/800P_ord_data2.dbf /db4/oradata/800P/.;

HOST cp /ORADATA1/800P/800P_ord_data3.dbf /db4/oradata/800P/.;

ALTER TABLESPACE ORD_DATA END BACKUP;

EXIT

****************************************************

File Name : genhotb.sql

****************************************************

ALTER TABLESPACE PHONE_DATA BEGIN BACKUP;

HOST cp /ORADATA1/800P/800P_phone_data1.dbf /db4/oradata/800P/.;

HOST cp /ORADATA1/800P/800P_phone_data2.dbf /db4/oradata/800P/.;

ALTER TABLESPACE PHONE_DATA END BACKUP;

ALTER TABLESPACE PHONE_INDEX BEGIN BACKUP;

HOST cp /ORADATA2/800P/800P_phone_index1.dbf /db4/oradata/800P/.;

HOST cp /ORADATA2/800P/800P_phone_index2.dbf /db4/oradata/800P/.;

ALTER TABLESPACE PHONE_INDEX END BACKUP;

EXIT

****************************************************

File Name : genhotbackup.sql

****************************************************

SET heading OFF

SET echo OFF

SET feedback OFF

SET pagesize 500

SET termout OFF

COLUMN tbsp_name NOPRINT

COLUMN stmt_order NOPRINT

COLUMN stmt_text FORMAT A80

SPOOL $SCRIPTS/hotbackup.sql

SELECT DISTINCT

t.tablespace_name tbsp_name, 1 stmt_order,

‘ALTER TABLESPACE ‘||t.tablespace_name||’ BEGIN BACKUP;’ stmt_text

FROM sys.dba_tablespaces t

UNION

SELECT t.tablespace_name tbsp_name, 2 stmt_order,

‘ HOST ls ‘ || f.file_name || ‘ | cpio -oBv > $DEVICE’ || ‘;’ stmt_text

FROM sys.dba_tablespaces t, sys.dba_data_files f

WHERE t.tablespace_name = f.tablespace_name

UNION

SELECT DISTINCT t.tablespace_name tbsp_name, 3 stmt_order,

‘ALTER TABLESPACE ‘||t.tablespace_name||’ END BACKUP;’ stmt_text

FROM sys.dba_tablespaces t

ORDER BY 1,2

/

SELECT ‘EXIT’ FROM dual

/

SPOOL off

EXIT

****************************************************

File Name : gentesthot.sql

****************************************************

SET heading OFF

SET echo OFF

SET feedback OFF

SET pagesize 500

SET termout OFF

COLUMN tbsp_name NOPRINT

COLUMN stmt_order NOPRINT

COLUMN stmt_text FORMAT A80

SPOOL $SCRIPTS/genhot.sql

SELECT DISTINCT

t.tablespace_name tbsp_name, 1 stmt_order,

‘ALTER TABLESPACE ‘||t.tablespace_name||’ BEGIN BACKUP;’ stmt_text

FROM sys.dba_tablespaces t

UNION

SELECT t.tablespace_name tbsp_name, 2 stmt_order,

‘ HOST cp ‘ || f.file_name || ‘ /db4/oradata/800P/.’|| ‘;’ stmt_text

FROM sys.dba_tablespaces t, sys.dba_data_files f

WHERE t.tablespace_name = f.tablespace_name

UNION

SELECT DISTINCT t.tablespace_name tbsp_name, 3 stmt_order,

‘ALTER TABLESPACE ‘||t.tablespace_name||’ END BACKUP;’ stmt_text

FROM sys.dba_tablespaces t

ORDER BY 1,2

/

SELECT ‘EXIT’ FROM dual

/

SPOOL off

EXIT

****************************************************

File Name : gentesthot1.sql

****************************************************

set heading off

SET echo OFF

SET feedback OFF

SET pagesize 500

SET termout OFF

COLUMN tbsp_name NOPRINT

COLUMN stmt_order NOPRINT

COLUMN stmt_text FORMAT A80

SPOOL $SCRIPTS/genhot1.sql

SELECT t.tablespace_name tbsp_name, 2 stmt_order,

‘compress -v /db4/oradata/800P/’ ||substr(f.file_name,16) stmt_text

FROM sys.dba_tablespaces t, sys.dba_data_files f

WHERE t.tablespace_name = f.tablespace_name

ORDER BY 1,2

/

SPOOL off

EXIT

****************************************************

File Name : get_sid.sql

****************************************************

set lines 132 pages 2000

accept val1 number prompt “Enter Unix PID:”

column sid heading “Oracle SID”

column spid heading “Unix PID”

column sql_address heading “Address of Current SQL”

column hash_value heading “Hash value of Curr SQL”

column username heading “Oracle Username”

column machine heading “Machine name” format a30

column kill_script heading “Unix Kill script”

select a.sid,b.spid ,a.sql_address,a.SQL_HASH_VALUE,a.username,a.machine,’kill -9 ‘||b.SPID kill_script

from v$session a,

v$process b

where a.paddr=b.addr and b.spid = &val1

/

****************************************************

File Name : get_spid.sql

****************************************************

set lines 132 pages 2000

accept val1 number prompt “Enter Oracle SID:”

column spid heading “Unix PID”

column sql_address heading “Address of Current SQL”

column username heading “Oracle Username”

column machine heading “Machine name” format a30

column kill_script heading “Unix Kill script”

select spid ,a.sql_address,a.username,a.machine,’kill -9 ‘||b.SPID kill_script

from v$session a,

v$process b

where a.paddr=b.addr and a.sid = &val1

/

****************************************************

File Name : hash_chain_length.sql

****************************************************

SELECT hash_value, count(*)

FROM v$sqlarea

GROUP BY hash_value

HAVING count(*) > 5

;

****************************************************

File Name : headroom.sql

****************************************************

col total_expansion format 9,999,999,990

col length format 9,999,999,990

col headroom format 9,999,999,990

select i.tablespace_name, i.total_expansion, g.length,

g.length – i.total_expansion headroom

from expansion_list i,

greatest_contig_free g

where i.tablespace_name = g.tablespace_name

order by g.length – i.total_expansion

/

****************************************************

File Name : headroom2.sql

****************************************************

set linesize 100

col tablespace_name format a15

col segment_name format a30

col largest_extent format 9,999,999,990

col length format 9,999,999,990

col headroom format 9,999,999,990

select i.tablespace_name,

h.segment_name,

g.length – i.largest_extent headroom,

i.largest_extent,

g.length

from largest_ext i,

greatest_contig_free g,

largest_seg h

where i.tablespace_name = g.tablespace_name

and h.tablespace_name = g.tablespace_name

order by i.tablespace_name, g.length – i.largest_extent

/

****************************************************

File Name : headroom3.sql

****************************************************

set linesize 100

col tablespace_name format a15

col segment_name format a30

col largest_extent format 9,999,999,990

col length format 9,999,999,990

col headroom format 9,999,999,990

col bytes format 9,999,999,990 heading “Total Free Bytes”

col pct format 999.99 heading “Pct Free”

select i.tablespace_name,

b.bytes – i.largest_extent headroom,

i.largest_extent,

b.bytes,

((b.bytes – i.largest_extent)/(b.bytes))*100 pct

from largest_ext i,

sum_tbsp_free b

where i.tablespace_name = b.tablespace_name

order by i.tablespace_name, b.bytes – i.largest_extent

/

****************************************************

File Name : headroom_v_t.sql

****************************************************

rem this is run once only to create the views and table that will be used

rem by the headroom script…. should be run from an account with DBA

rem privs…. make sure to directly grant select on dba_free_space and

rem dba_segments to the account that will run this script

rem

create or replace view greatest_contig_free (tablespace_name, length) as

select t1.tablespace_name, nvl(max(bytes),0) from dba_free_space t1,

dba_tablespaces t2 where t1.tablespace_name(+) = t2.tablespace_name

group by t1.tablespace_name

/

create table free_space

(tablespace_name varchar2(30)

, file_id number

, start_id number

, end_id number

,length number)

tablespace users

/

create view expansion_list as

select tablespace_name, sum(next_extent) total_expansion from dba_segments

where segment_type =’TABLE’ or segment_type =’INDEX’

group by tablespace_name

/

create view largest_ext as

select tablespace_name, max(next_extent) largest_extent from dba_segments

where segment_type =’TABLE’ or segment_type =’INDEX’

group by tablespace_name

/

create or replace view largest_seg as

select segment_name, ds.tablespace_name from dba_segments ds, largest_ext le

where next_extent = largest_extent

and ds.tablespace_name = le.tablespace_name

/

****************************************************

File Name : hidden_v7.sql

****************************************************

set linesize 128

column name format a42

select

x.ksppinm name,

decode(bitand(ksppiflg/256,1),1,’TRUE’,’FALSE’) sesmod,

decode(

bitand(ksppiflg/65536,3),

1,’IMMEDIATE’,

2,’DEFERRED’,

3,’IMMEDIATE’,

‘FALSE’

) sysmod,

ksppdesc description

from

sys.x_$ksppi x

where

translate(ksppinm,’_’,’#’) like ‘#%’

order by

1

/

****************************************************

File Name : highwater_sessions.sql

****************************************************

set term off echo off

col datetime format a20

spool /db3/oracle/statistics/highwater_sessions.log

select sessions_current, sessions_highwater,

to_char(sysdate,’MM/DD/YY HH24:MI:SS’) datetime from v$license

/

select count(*) transactions from v$transaction

/

spool off

/

exit

/

****************************************************

File Name : hot_hash_latches.sql

****************************************************

select

l.child#,

l.sleeps,

sum(decode(x.state, 1, 1, 0)) cur_buffers,

sum(decode(x.state, 3, 1, 0)) cr_buffers

from

sys.v_$latch_children l,

( select

avg(sleeps) sleeps

from

sys.v_$latch_children

where

name = ‘cache buffers chains’

) a,

sys.x$bh x

where

l.name = ‘cache buffers chains’ and

l.sleeps > 2 * a.sleeps and

x.hladdr = l.addr and

x.inst_id = userenv(‘Instance’)

group by

l.child#,

l.sleeps

order by

2 desc

/

****************************************************

File Name : hotbackup.sql

****************************************************

ALTER TABLESPACE ADDR_DATA BEGIN BACKUP;

HOST ls /ORADATA1/800P/800P_addr_data1.dbf | cpio -oBv > $DEVICE;

HOST ls /ORADATA1/800P/800P_addr_data2.dbf | cpio -oBv > $DEVICE;

ALTER TABLESPACE ADDR_DATA END BACKUP;

ALTER TABLESPACE ADDR_INDEX BEGIN BACKUP;

HOST ls /ORADATA2/800P/800P_addr_index1.dbf | cpio -oBv > $DEVICE;

HOST ls /ORADATA2/800P/800P_addr_index2.dbf | cpio -oBv > $DEVICE;

ALTER TABLESPACE ADDR_INDEX END BACKUP;

EXIT

****************************************************

File Name : i2.sql

****************************************************

CREATE INDEX ATS.APP_ERRORS_DT_CRTD ON ATS.ATS_APP_ERRORS

(DT_CRTD)

LOGGING

TABLESPACE MISC_DATA

PCTFREE 10

INITRANS 2

MAXTRANS 255

STORAGE (

INITIAL 1M

NEXT 1M

MINEXTENTS 1

MAXEXTENTS 505

PCTINCREASE 0

FREELISTS 1

FREELIST GROUPS 1

BUFFER_POOL DEFAULT

)

NOPARALLEL;

****************************************************

File Name : ideal_cache_size.sql

****************************************************

select /*+ ordered use_hash(b) */

n.bp_name buffer_pool,

count(*) current_buffers,

count(*) +

count(decode(lru_flag, 0, decode(tch, 0, null, 1, null, 1))) –

count(decode(state, 0, 1, decode(lru_flag, 8, decode(tch, 0, 1, 1, 1))))

ideal_buffers

from

(

select /*+ ordered */

p.bp_name,

s.addr

from

sys.x$kcbwbpd p,

sys.x$kcbwds s

where

s.inst_id = userenv(‘Instance’) and

p.inst_id = userenv(‘Instance’) and

s.set_id >= p.bp_lo_sid and

s.set_id <= p.bp_hi_sid and
p.bp_size != 0

) n,

sys.x$bh b

where

b.inst_id = userenv(‘Instance’) and

b.set_ds = n.addr

group by

n.bp_name

/

****************************************************

File Name : ident_sess.sql

****************************************************

select b.sid,b.serial#,a.pid,b.username from v$process a,v$session b

where a.addr = b.paddr

and b.machine like ‘FLOWERS_NTEXPRESS1%’

/

****************************************************

File Name : idle9.sql

****************************************************

select ‘alter system kill session ‘||””||SID||’,’||SERIAL#||””||’;’ from v$session

where username = ‘9999’

and ((sysdate – logon_time)*24*60) > 5

and status = ‘INACTIVE’;

****************************************************

File Name : idx_info.sql

****************************************************

select index_name,column_name,column_position from dba_ind_columns

where table_name = upper(‘&1’);

****************************************************

File Name : ind.sql

****************************************************

select index_owner,index_name,column_name,column_position from dba_ind_columns

where table_name = UPPER(‘&1’)

order by 2,4

/

****************************************************

File Name : ind_cols.sql

****************************************************

set lines 90

set pages 2000

column table_name heading ‘TABLE NAME’ format a30

column index_name heading ‘Index Name’ format a30

column column_name heading ‘Col Name’ format a18

column column_position heading ‘Position’ format 99

break on table_name skip 1

select table_name,index_name,column_name,column_position from dba_ind_columns

where table_name in (select table_name from dba_indexes where tablespace_name = ‘EMP_INDEX’)

/

****************************************************

File Name : indana.sql

****************************************************

set lines 100

break on table_name skip 1

column column_position format 9

column column_name format a15

column index_name format a30

select table_name,index_name,column_name,column_position from dba_ind_columns

where table_name in (

‘ATS_FLORISTS_TRACKING’,

‘ATS_BLOOMNET_FORMS’

)

/

****************************************************

File Name : index_analyze_report.sql

****************************************************

set pagesize 60;

set linesize 132;

set echo off;

set feedback off;

column c1 format a40 heading ‘Index’;

column c2 format 999,999,999 heading ‘#rep Keys’

column c3 format 999,999,999 heading ‘Dist. Keys’;

column c4 format 999,999 heading ‘#Del Leaf rows’;

column c5 format 99,999 heading ‘Blk Height’;

column c6 format 9,999,999 heading ‘Gets per access’;

select distinct

name c1,

most_repeated_key c2,

distinct_keys c3,

del_lf_Rows c4,

height c5,

blks_gets_per_access c6

from index_statistics

where

height > 3

or

del_lf_rows > 10

order by name;

****************************************************

File Name : index_analyze_stats.sql

****************************************************

select name,DEL_LF_ROWS*100/decode(LF_ROWS, 0, 1, LF_ROWS) PCT_DELETED,

(LF_ROWS-DISTINCT_KEYS)*100/ decode(LF_ROWS,0,1,LF_ROWS) DISTINCTIVENESS

from index_statistics

order by 2

/

–select index_name, blevel, decode(blevel,0,’OK BLEVEL’,1,’OK BLEVEL’, 2,’OK BLEVEL’,3,’OK BLEVEL’,4,’OK BLEVEL’,’BLEVEL HIGH’) OK

–from dba_indexes

–where owner = ‘ATS’

–order by 2

/

select name,DEL_LF_ROWS*100/decode(LF_ROWS, 0, 1, LF_ROWS) PCT_DELETED,height,blocks

from index_statistics

where DEL_LF_ROWS*100/decode(LF_ROWS, 0, 1, LF_ROWS)>10

or height >3

/

****************************************************

File Name : index_info.sql

****************************************************

set lines 132

set pages 2000

break on index_name

accept val1 prompt “Enter Table Name:”

column index_name format a40

column column_name format a40

select indeX_name,column_name,column_position from dba_ind_columns

where table_name = upper(‘&val1’)

order by 1,3

/

select owner,indeX_name,to_char(last_analyzed,’DD-MON-YYYY HH24:MI SS’) from dba_indexes

where table_name = upper(‘&val1’)

order by 1,3

/

****************************************************

File Name : ins_kill.sql

****************************************************

set verify off term off echo off heading off

set serveroutput on

execute ins_killjobs(&1);

exit

****************************************************

File Name : insert_latch.sql

****************************************************

select address,version_count from v$sqlarea where address in

(‘CD2AA52C’,

‘BD7CA8B4’

)

order by 2

/

****************************************************

File Name : inuse.sql

****************************************************

select name from v$rollname n, v$rollstat s

where xacts > 0

and n.usn=s.usn

/

****************************************************

File Name : invalobj.sql

****************************************************

set echo off verify off term off feedback off

set pagesize 60

spool invalobj.log

ttitle –

center ‘Verify Stored Procedures’ skip 2

col Oown format a10 heading ‘Owner’ word_wrapped

col Oname format a30 heading ‘Object Name’ trunc

col Otype format a12 heading ‘Object Type’ trunc

col Prob format a13 heading ‘Problem’ trunc

break on oown skip 1 on otype

select A.Owner Oown,

A.Object_Name Oname,

A.Object_Type Otype,

‘Miss Pkg Body’ Prob

from DBA_OBJECTS A

where A.Object_Type = ‘PACKAGE’

and A.Owner =’ATS’

and not exists

(select ‘x’

from DBA_OBJECTS B

where B.Object_Name = A.Object_Name

and B.Owner = A.Owner

and B.Object_Type = ‘PACKAGE BODY’)

union

select Owner Oown,

Object_Name Oname,

Object_Type Otype,

‘Invalid Obj’ Prob

from DBA_OBJECTS

where Object_Type in

(‘PROCEDURE’,’PACKAGE’,’FUNCTION’,’TRIGGER’,’PACKAGE BODY’,’VIEW’)

and Owner = ‘ATS’

and Status != ‘VALID’

order by 1,4,3,2

/

spool off

****************************************************

File Name : keeper.sql

****************************************************

set feedback on

declare

cursor candidate_objects is

select /*+ ordered */

decode(

x.kglhdnsp,

0, x.kglhdpar ||’,’|| x.kglnahsh, — ‘address,hash_value’ for cursors

x.kglnaown ||’.’|| x.kglnaobj — ‘schema.object_name’ for others

),

decode(x.kglhdnsp, 0, ‘C’, decode(x.kglobtyp, 6, ‘Q’, 12, ‘R’, ‘P’))

from

(

select

to_number(w.value) – to_number(r.value) pool_body

from

sys.v$parameter w,

sys.v$parameter r

where

w.name = ‘shared_pool_size’ and

r.name = ‘shared_pool_reserved_size’

) a,

(

select

sum(p.ksmchsiz) used_memory

from

sys.x$ksmsp p

where

p.inst_id = userenv(‘Instance’) and

p.ksmchcls in (‘free’, ‘recr’, ‘freeabl’)

) b,

sys.x$kglob x

where

x.inst_id = userenv(‘Instance’) and

x.kglhdkmk = 0 and — not yet kept

(

x.kglobtyp in (6, 7, 8, 9, 12) or — keepable database objects

( — or

x.kglobhs6 > 0 and — loaded

x.kglhdnsp = 0 and — cursors

x.kglobt12 >= 3 and — with 3 or more parse calls

b.used_memory < a.pool_body * .8 -- if abundant memory
)

)

group by

decode(kglhdnsp, 0, kglhdpar ||’,’|| kglnahsh, kglnaown ||’.’|| kglnaobj),

decode(kglhdnsp, 0, ‘C’, decode(kglobtyp, 6, ‘Q’, 12, ‘R’, ‘P’))

having

count(decode(bitand(kglobflg, 1), 0, 1)) = 0 and — no invalid version

count(*) <= 4; -- no more than 4 versions object_name varchar2(160);
object_type char(1);

begin

open candidate_objects;

loop

fetch candidate_objects into object_name, object_type;

exit when candidate_objects%notfound;

dbms_shared_pool.keep(object_name, object_type);

end loop;

end;

/

****************************************************

File Name : kept.sql

****************************************************

select

type,

count(*) objects,

sum(decode(kept, ‘YES’, 1, 0)) kept,

sum(loads) – count(*) reloads,

count(distinct owner) owners

from

sys.v$db_object_cache

where

type != ‘NOT LOADED’

group by

type

order by

2 desc

/

****************************************************

File Name : kgl_bucket_count.sql

****************************************************

select

least(8, ceil(log(2, ceil(count(*) / 509)))) “INDEX”

from

sys.x$kglob o

where

o.inst_id = userenv(‘Instance’) and

o.kglhdadr = o.kglhdpar

/

****************************************************

File Name : kill.sql

****************************************************

alter system kill session ‘53,5945’ ;

****************************************************

File Name : kill_event.sql

****************************************************

select ‘alter system kill session ‘||””||a.sid||’,’||a.serial#||”” ||’ ;’

from v$session a,v$session_wait b

where a.sid=b.sid

and b.event = ‘library cache pin’

and a.username is not null;

select ‘kill -9 ‘||b.spid

from v$session a,v$process b,v$session_wait c

where a.paddr=b.addr

and a.sid=c.sid

and c.event=’library cache pin’

and a.username is not null;

****************************************************

File Name : kill_sess.sql

****************************************************

select ‘alter system kill session ‘||””||sid||’,’||serial#||”” ||’ ;’ from v$session

where sid = &1;

****************************************************

File Name : ktuxe.sql

****************************************************

accept SEGNO number prompt “Rollback Segment# :”

accept SLTNO number prompt “Wrap# :”

column KTUXEPUSN format 99

column KTUXECFL format a4

select a.KTUXEUSN “UndoS#”,

a.KTUXESLT “SLOT”,

a.KTUXESQN “Wrap”,

a.KTUXESTA “Status”,

b.OBJECT_ID “OBJ#”,

b.SESSION_ID “Blocker SID”,

c.file#,

c.dbablk

from x$ktuxe a,

v$locked_object b,

x$bh c

where a.KTUXEUSN = b.xidusn

and a.KTUXESLT = b.xidslot

and a.KTUXESQN = b.xidsqn

and a.KTUXESTA = ‘ACTIVE’

and c.CR_XID_USN = a.KTUXEUSN

and c.CR_XID_SLT = a.KTUXESLT

and c.CR_XID_SQN = a.KTUXESQN

and c.mode_held = 1

and a.KTUXEUSN = &SEGNO

and a.KTUXESLT = &SLTNO;

****************************************************

File Name : l.sql

****************************************************

—

—

— view renamed to v$longlocks

—

— See XVIEW.SQL

—

set linesize 120

set pages 20000

col SID format 99999

col type format a4

col “HELD SEC” format 999999

col OSUSER format a9

col PROCESS format a15

col TERMINAL format a25

col BLOCKER format a15

col first_name format a7 tru

col last_name format a9 tru

col req format 999

col hld format 999

set feedback off

spo junklock.txt

prompt Subj: People are running Crazy ………….

prompt

prompt Locking Report:

prompt

select * from v$longlocks

/

prompt

prompt

spo off

set feed on

—-exit;

****************************************************

File Name : latch.sql

****************************************************

set term off echo off pagesize 60 feedback off verify off

spool latches.log

col name format a15

col gets format 999999999

col misses format 9999999

col immediate_gets heading ‘IMMED GETS’ format 999999999

col immediate_misses heading ‘IMMED MISS’ format 9999999

col sleeps format 999999

prompt LATCH CONTENTION:

prompt

prompt GETS – # of successful willing-to-wait requests for a latch

prompt MISSES – # of times an initial willing-to-wait request was unsuccessful

prompt IMMEDIATE_GETS – # of successful immediate requests for each latch

prompt IMMEDIATE_MISSES = # of unsuccessful immediate requests for each latch

prompt SLEEPS – # of times a process waited and requests a latch after an initial

prompt willing-to-wait request

prompt

prompt If the latch requested with a willing-to-wait request is not

prompt available, the requesting process waits a short time and requests again.

prompt If the latch requested with an immediate request is not available,

prompt the requesting process does not wait, but continues processing

prompt

set head on

select name, gets, misses, immediate_gets, immediate_misses, sleeps

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

set head off

select ‘Ratio of MISSES to GETS: ‘||

round((sum(misses)/(sum(gets)+0.00000000001) * 100),2)||’%’

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

select ‘Ratio of IMMEDIATE_MISSES to IMMEDIATE_GETS: ‘||

round((sum(immediate_misses)/

(sum(immediate_misses+immediate_gets)+0.00000000001) * 100),2)||’%’

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

prompt

prompt If either ratio exceeds 1%, performance will be affected.

prompt

prompt Decreasing the size of LOG_SMALL_ENTRY_MAX_SIZE reduces the number of

prompt processes copying information on the redo allocation latch.

prompt

prompt Increasing the size of LOG_SIMULTANEOUS_COPIES will reduce contention for

prompt redo copy latches.

prompt

prompt SYSTEM EVENTS:

prompt

prompt Not sure of the value of this section yet but it looks interesting.

prompt

col event format a30 heading ‘Event’

col total_waits format 9999999999 heading ‘Total|Waits’

col time_waited format 999999999999 heading ‘Time Wait|In Hndrds’

col total_timeouts format 99999999999 heading ‘Timeout’

col average_wait heading ‘Average|Time’ format 999999.999

set pages 999

select * from v$system_event

/

prompt

prompt ——————————————————————————–

spool off

exit

****************************************************

File Name : latch_free.sql

****************************************************

set feedback off

set head off

set lines 132

column name heading “Name” format a30

column a heading “Event” format a30

SELECT EVENT a,P2,name,WAIT_TIME,SECONDS_IN_WAIT

from v$session_wait,v$latchname where P2=latch#

and event not in (‘SQL*Net message from client’,’rdbms ipc message’,’pmon timer’,’smon timer’,

‘SQL*Net message to client’,’SQL*Net message from dblink’)

/

****************************************************

File Name : latch_get.sql

****************************************************

column name format a30 heading “LATCH TYPE” trunc

column simple_gets format a18 heading “SIMPLE GETS” justify right

column spin_gets format a14 heading “SPIN GETS” justify right

column sleep_gets format a14 heading “SLEEP GETS” justify right

select

l.name,

substr(

to_char(

l.gets – l.misses,

‘999999999990’

),

4

) ||

‘ ‘ ||

substr(

to_char(

100 * (l.gets – l.misses) / l.gets,

‘999.00’

),

2

) ||

‘%’ simple_gets,

substr(

to_char(

l.spin_gets,

‘999999990’

),

4

) ||

‘ ‘ ||

substr(

to_char(

100 * l.spin_gets / l.gets,

‘90.00’

),

2

) ||

‘%’ spin_gets,

substr(

to_char(

l.misses – l.spin_gets,

‘9999990’

),

2

) ||

‘ ‘ ||

substr(

to_char(

100 * (l.misses – l.spin_gets) / l.gets,

‘90.00’

),

2

) ||

‘%’ sleep_gets

from

v$latch l

where

l.gets > 0

order by

l.name

/

****************************************************

File Name : latch_issue.sql

****************************************************

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_BEING_RUN,decode(s.KSUSSP2,66,’CACHE BUFFER CHAIN’,106,’LIBRARY CACHE’,105,’SHARED POOL’,107,’LIBRARY CACHE LOAD LOCK’,95,’ROW CACHE OBJECTS’,2,’SESSION ALLOCATION’,s.KSUSSP2)||'(‘||s.indx||’,’||c.KSUUDNAM||’,’||c.KSUSEUNM||’,’||c.KSUSEMNM||’)’ EVENT_WITH_OSUSER

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’latch free’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : latch_miss.sql

****************************************************

select DBAFIL,DBABLK,MODE_HELD,sum(b.miss),count(*)

from x$bh a ,(select sum(misses) miss, latch#,substr(name,1,20),addr,count(*) From v$latch_children

where latch#=39

group by latch#,name,addr

having sum(misses) > 0) b

where b.addr = a.hladdr

group by DBAFIL,DBABLK,MODE_HELD

order by 4

/

****************************************************

File Name : latch_name.sql

****************************************************

select name from v$latchname where latch# = &1

/

****************************************************

File Name : latch_sleep.sql

****************************************************

set lines 132

column name format a30

column impact format 999,999,999

select

l.name name,

l.sleeps * l.sleeps / (l.misses – l.spin_gets) impact,

lpad(to_char(100 * l.sleeps / l.gets, ‘990.00’) || ‘%’, 10) sleep_rate,

l.waits_holding_latch,

l.level#

from

v$latch l

where

l.sleeps > 0

order by

2 desc

/

****************************************************

File Name : latch_spin.sql

****************************************************

column name format a30 heading “LATCH TYPE”

column spin_gets heading “SPIN GETS” format 999999999

column sleep_gets heading “SLEEP GETS” format 99999999

column hit_rate format a13 heading “SPIN HIT RATE”

select

l.name,

l.spin_gets spin_gets,

l.misses – l.spin_gets sleep_gets,

lpad(to_char(100 * l.spin_gets / l.misses, ‘990.00’) || ‘%’, 13) hit_rate

from

v$latch l

where

l.misses > 0

order by

l.misses – l.spin_gets desc

/

set heading off

select

‘ALL LATCHES’ name,

sum(l.spin_gets) spin_gets,

sum(l.misses – l.spin_gets) sleep_gets,

lpad(

to_char(100 * sum(l.spin_gets) / sum(l.misses), ‘990.00’) || ‘%’,

13

) hit_rate

from

v$latch l

where

l.misses > 0

/

set heading on

****************************************************

File Name : latch_sql.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_WHICH_DOING_SCATTERED_READ,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’latch free’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : latch_where.sql

****************************************************

set recsep off

column name format a30 heading “LATCH TYPE”

column location format a40 heading “CODE LOCATION and [LABEL]”

column kslsleep format 999999999 heading “SLEEPS”

break on name

select

l.name,

rpad(lw.ksllwnam, 40) ||

decode(lw.ksllwlbl, null, null, ‘[‘ || lw.ksllwlbl || ‘]’) location,

wsc.kslsleep

from

x$kslwsc wsc,

x$ksllw lw,

v$latch l

where

wsc.kslsleep > 0 and

lw.indx = wsc.indx and

l.name = wsc.ksllasnam

order by

l.sleeps desc,

wsc.kslsleep desc

/

****************************************************

File Name : latchname.sql

****************************************************

select name from v$latchname where latch#=&1

/

****************************************************

File Name : lf.sql

****************************************************

SELECT SID,EVENT,P2,WAIT_TIME,SECONDS_IN_WAIT

from v$session_wait where p2=26

/

****************************************************

File Name : lgwr_stats.sql

****************************************************

column write_size format 9999999999999 heading “Avgerage Log|Write Size”

column threshold format 9999999999999 heading “Background|Write Theshold”

select

ceil(b.value/w.value) * x.lebsz write_size,

ceil(p.value/x.lebsz/3) * x.lebsz threshold

from

(select value from sys.v$sysstat where name = ‘redo blocks written’) b,

(select value from sys.v$sysstat where name = ‘redo writes’) w,

(select max(lebsz) lebsz from sys.x$kccle where inst_id = userenv(‘Instance’)) x,

(select value from sys.v$parameter where name = ‘log_buffer’) p

where

w.value > 0

/

column sync_cost_ratio format 990.00 heading “Sync Cost Ratio”

select s.average_wait/t.average_wait sync_cost_ratio

from

(select average_wait from sys.v$system_event where event = ‘log file parallel write’) t,

(select average_wait from sys.v$system_event where event = ‘log file sync’) s

where t.average_wait > 0

/

****************************************************

File Name : lib_cache.sql

****************************************************

column object_name format a60

select /*+ ordered */

l.child# latch#,

o.kglnaobj object_name

from

( select

count(*) latches,

avg(sleeps) sleeps

from

sys.v$latch_children

where

name = ‘library cache’

) a,

sys.v$latch_children l,

( select

s.buckets *

power(

2,

least(

8,

ceil(log(2, ceil(count(*) / s.buckets)))

)

) buckets

from

( select

decode(y.ksppstvf,

0, 509,

1, 1021,

2, 2039,

3, 4093,

4, 8191,

5, 16381,

6, 32749,

7, 65521,

8, 131071,

509

) buckets

from

sys.x$ksppi x,

sys.x$ksppcv y

where

x.ksppinm = ‘_kgl_bucket_count’ and

y.indx = x.indx

) s,

sys.x$kglob c

where

c.kglhdadr = c.kglhdpar

group by

s.buckets

) b,

sys.x$kglob o

where

l.name = ‘library cache’ and

l.sleeps > 2 * a.sleeps and

mod(mod(o.kglnahsh, b.buckets), a.latches) + 1 = l.child# and

o.kglhdadr = o.kglhdpar

/

****************************************************

File Name : lib_cache_pin.sql

****************************************************

————————————————————

—- This script finds the objects that is causing the wait

—- on library cache pin

————————————————————

select substr(b.event,1,10),b.sid,KGLNAOWN,KGLNAOBJ,addr

from x$kglob a,v$session_Wait b

where b.p1raw = a.KGLHDADR

— and b.p2=60

and b.event in (‘library cache pin’,’row cache objects’)

— or p2 = 60)

— and b.p1=’2701798036′

/

****************************************************

File Name : lib_cache_ratio.sql

****************************************************

column namespace heading “Library Object”

column gets format 9,999,999,999 heading “Gets”

column gethitratio format 999.99 heading “Get Hit%”

column pins format 9,999,999,999 heading “Pins”

column pinhitratio format 999.99 heading “Pin Hit%”

column reloads format 9,999,999 heading “Reloads”

column invalidations format 9,999,999 heading “Invalid”

column db format a10

set pages 58 lines 80

start title80 “Library Caches Report”

–define output = rep_out&dblib_cache

— spool &output

select

namespace,

gets,

gethitratio*100 gethitratio,

pins,

pinhitratio*100 pinhitratio,

RELOADS,

INVALIDATIONS

from

v$librarycache

/

spool off

pause Press enter to continue

set pages 22 lines 80

ttitle off

undef output

****************************************************

File Name : lib_cache_stats.sql

****************************************************

REM ————————————————————————

REM REQUIREMENTS:

REM SELECT on V$ Tables

REM ————————————————————————

REM PURPOSE:

REM This report provides information critical to aid in tuning the

REM shared pool’s library cache. The shared pool resides resides

REM within the system global area (SGA). The shared pool

REM contains both the library cache and the data dictionary cache.

REM

REM OS memory monitoring tools should always be used in conjunction

REM with memory related reports.

REM

REM Output definitions:

REM

REM Size – The value of the instance paramter shared_pool_size

REM Used sharable – Total memory used which contains memory structures

REM that can be shared between users, such as a SQL statement parse

REM tree.

REM Used persistent – Total memory used which contains memory

REM structures that will remain regardless of who runs the statement

REM or how many times the statement is run.

REM Used runtime – Total memory used which contains memory structures

REM that each user owns and no one else can access, such as the

REM current rowid (when running MTS).

REM Available – Total Size minus Total Used.

REM Number of SQL statements – The number of SQL statements currently

REM loaded in the shared pool’s library cache.

REM Number of programatic constructs – The number of SQL programatic

REM constructs (procedures, functions, etc.) currently loaded into

REM the shared pool’s library cache.

REM Kept programatic construct chunks – The number of programatic

REM constructs that have been pinned by someone into the library

REM cache. Programatic constructs can be manually pinned in the

REM library cache. In the “code” this is referred to as a “keep.”

REM Kept programatic construct chunks size – The total size (bytes)

REM of kept programatic constructs in the library cache.

REM Pinned statements – The number of SQL statements currently pinned

REM in the library cache. These “pinnings” are implicit and are

REM different than a “kept” construct.

REM Pinned statement size – The total size (bytes) of pinned SQL

REM statements residing in the library cache.

REM ————————————————————————

REM EXAMPLE:

REM Shared Pool`s Library Cache Information

REM

REM

REM Size : 3500000

REM Used (total) : 3172791

REM sharable : 2149391

REM persistent : 174708

REM runtime : 878892

REM Available : 327209

REM Number of SQL statements : 229

REM Number of programatic constructs : 179

REM Kept programatic construct chunks : 0

REM Kept programatic construct chunks size : 0

REM Pinned statements : 14

REM Pinned statements size : 847200

REM

REM ————————————————————————

REM DISCLAIMER:

REM This script is provided for educational purposes only. It is NOT

REM supported by Oracle World Wide Technical Support.

REM The script has been tested and appears to work as intended.

REM You should always run new scripts on a test instance initially.

REM ————————————————————————

REM Main text of script follows:

rem set echo on feedback on

set pagesize 80

set verify off

set heading off

set feedback off

set termout off

col sp_size format 999,999,999 justify right

col x_sp_used format 999,999,999 justify right

col sp_used_shr format 999,999,999 justify right

col sp_used_per format 999,999,999 justify right

col sp_used_run format 999,999,999 justify right

col sp_avail format 999,999,999 justify right

col sp_sz_pins format 999,999,999 justify right

col sp_no_pins format 999,999 justify right

col sp_no_obj format 999,999 justify right

col sp_no_stmts format 999,999 justify right

col sp_sz_kept_chks format 999,999,999 justify right

col sp_no_kept_chks format 999,999 justify right

col val2 new_val x_sp_size noprint

select value val2

from v$parameter

where name=’shared_pool_size’

/

col val2 new_val x_sp_used noprint

select sum(sharable_mem+persistent_mem+runtime_mem) val2

from v$sqlarea

/

col val2 new_val x_sp_used_shr noprint

col val3 new_val x_sp_used_per noprint

col val4 new_val x_sp_used_run noprint

col val5 new_val x_sp_no_stmts noprint

select sum(sharable_mem) val2,

sum(persistent_mem) val3,

sum(runtime_mem) val4,

count(*) val5

from v$sqlarea

/

col val2 new_val x_sp_no_obj noprint

select count(*) val2 from v$db_object_cache

/

col val2 new_val x_sp_avail noprint

select &x_sp_size-&x_sp_used val2

from dual

/

col val2 new_val x_sp_no_kept_chks noprint

col val3 new_val x_sp_sz_kept_chks noprint

select decode(count(*),”,0,count(*)) val2,

decode(sum(sharable_mem),”,0,sum(sharable_mem)) val3

from v$db_object_cache

where kept=’YES’

/

col val2 new_val x_sp_no_pins noprint

select count(*) val2

from v$session a, v$sqltext b

where a.sql_address||a.sql_hash_value = b.address||b.hash_value

/

col val2 new_val x_sp_sz_pins noprint

select sum(sharable_mem+persistent_mem+runtime_mem) val2

from v$session a,

v$sqltext b,

v$sqlarea c

where a.sql_address||a.sql_hash_value = b.address||b.hash_value and

b.address||b.hash_value = c.address||c.hash_value

/

set termout on

set heading off

ttitle –

center ‘Shared Pool`s Library Cache Information’ skip 2

select ‘Size : ‘

||&x_sp_size sp_size,

‘Used (total) : ‘

||&x_sp_used,

‘ sharable : ‘

||&x_sp_used_shr sp_used_shr,

‘ persistent : ‘

||&x_sp_used_per sp_used_per,

‘ runtime : ‘

||&x_sp_used_run sp_used_run,

‘Available : ‘

||&x_sp_avail sp_avail,

‘Number of SQL statements : ‘

||&x_sp_no_stmts sp_no_stmts,

‘Number of programatic constructs : ‘

||&x_sp_no_obj sp_no_obj,

‘Kept programatic construct chunks : ‘

||&x_sp_no_kept_chks sp_no_kept_chks,

‘Kept programatic construct chunks size : ‘

||&x_sp_sz_kept_chks sp_sz_kept_chks,

‘Pinned statements : ‘

||&x_sp_no_pins sp_no_pins,

‘Pinned statements size : ‘

||&x_sp_sz_pins sp_sz_pins

from dual

/

ttitle off

set heading on

set feedback on

****************************************************

File Name : lib_latch.sql

****************************************************

set lines 132

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a20 heading “Machine”

col INDX format 9999 heading “SID”

select /*+ USE_NL(b c) */ a.kslltnum,a.addr,e.KSLLWNAM||'[‘||e.KSLLWLBL||’]’,a.kslltwhy,a.kslltwhr,c.KSUSESQL,

c.KSUSESQH,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from x$ksllt a, v$session_Wait b,x$ksuse c,x$kslwsc d,x$ksllw e

where b.p1raw=a.addr

and p2 in(106,105,95,66)

and b.sid=c.indx and

a.kslltwhr=d.indx

and d.indx=e.indx

and bitand(c.ksspaflg,1)!=0 and bitand(c.ksuseflg,1)!=0

and d.inst_id=userenv(‘Instance’)

and e.inst_id = userenv(‘Instance’)

/

–col sql_text heading “SQL Waiting on LIB CACHE latch or Shared Pool latch”

–select sql_text

–from v$sql

–where address in

–(select /*+ USE_NL(b c) */ c.KSUSESQL

–from x$ksllt a,

–v$session_Wait b,

–x$ksuse c,

–x$kslwsc d,

–x$ksllw e

–where b.p1raw=a.addr

–and p2 in(106,105,95)

–and b.sid=c.indx and

–a.kslltwhr=d.indx

–and d.indx=e.indx

–and bitand(c.ksspaflg,1)!=0 and bitand(c.ksuseflg,1)!=0

—-and d.inst_id=userenv(‘Instance’)

–and e.inst_id = userenv(‘Instance’)

–)

–/

****************************************************

File Name : lib_pin.sql

****************************************************

#column KGLNAOBJ format a10

select KGLNAOBJ ,KGLPNCNT,KGLPNMOD,KGLPNREQ,KGLPNDMK,KGLPNSPN

from x$kglob a , x$kglpn b where a.KGLHDADR = b.KGLPNHDL

and rownum<10
/

****************************************************

File Name : lib_pin_hold.sql

****************************************************

select a.addr,substr(e.kslednam,1,10),s.inst_id,s.indx,a.KGLNAOWN,a.KGLNAOBJ

from x$kglob a,x$kglpn c,x$ksled e, x$ksusecst s

where bitand(s.ksspaflg,1)!=0

and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam = ‘library cache pin’

and s.ksussp1r = a.KGLHDADR

and a.KGLHDADR = c.KGLPNHDL

and KGLPNLCK !=’00’

/

****************************************************

File Name : library_cache_eff.sql

****************************************************

SELECT INITCAP(namespace),

gets,

ROUND(gethitratio * 100, 0),

pins,

ROUND(pinhitratio * 100, 0),

reloads,

gethits,

pinhits

FROM sys.v_$librarycache

ORDER BY gets DESC

/

****************************************************

File Name : library_stats.sql

****************************************************

select

namespace,

gets locks,

gets – gethits loads,

pins,

reloads,

invalidations

from

sys.v_$librarycache

where

gets > 0

order by

2 desc

/

****************************************************

File Name : libsql.sql

****************************************************

select indx,ksusesql, ksusesqh

from x$ksuse where indx

in

(

select sid

from v$session_wait

where event not in(

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqcls – consumer closing TQ’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Message Fragment Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘Null event’,

‘PL/SQL lock timer’,

‘Parallel Query Idle Wait – Slaves’,

‘Replication Dequeue’,

‘SQL*Net message from client’,

‘buffer deadlock’,

‘dispatcher timer’,

‘io done’,

‘pipe get’,

‘pmon timer’,

‘rdbms ipc message’,

‘rdbms ipc message block’,

‘rdbms ipc reply’,

‘slave wait’,

‘smon timer’,

‘virtual circuit status’)

and p2 = 66

)

/

****************************************************

File Name : libsql1.sql

****************************************************

select a.p2,b.indx,b.ksusesql, b.ksusesqh

from

(

select sid,p2

from v$session_wait

where event not in(

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqcls – consumer closing TQ’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Message Fragment Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘Null event’,

‘PL/SQL lock timer’,

‘Parallel Query Idle Wait – Slaves’,

‘Replication Dequeue’,

‘SQL*Net message from client’,

‘buffer deadlock’,

‘dispatcher timer’,

‘io done’,

‘pipe get’,

‘pmon timer’,

‘rdbms ipc message’,

‘rdbms ipc message block’,

‘rdbms ipc reply’,

‘slave wait’,

‘smon timer’,

‘virtual circuit status’)

and p2 in (106,66)

) a,

x$ksuse b

where b.indx=a.sid

/

****************************************************

File Name : list_cons.sql

****************************************************

set pagesize 0

set term on echo on

spool $LOGS/cons.lst

select table_name, constraint_name, constraint_type, status from

dba_constraints where owner=’ATS’ and constraint_type <> ‘C’

order by table_name, constraint_type, status

/

spool off

****************************************************

File Name : lname.sql

****************************************************

select name from v$latchname where latch#= &1

/

****************************************************

File Name : lock.sql

****************************************************

select * from dba_dml_locks where session_id=&1;

****************************************************

File Name : lock_info.sql

****************************************************

select /*+USE_NL (b a)*/

a.sid “Blocking Sid”,b.sid “Waiting SID”,a.ctime “Locked time by Blocker”,a.lmode “Locked Mode”,b.lmode “Request Mode”

from v$lock a,

(select id1,id2,sid,lmode from v$lock where request >0) b

where a.id1 = b.id1

and a.id2 = b.id2

and block >0

/

****************************************************

File Name : lock_obj.sql

****************************************************

/* This query will defined the objects that are involved in the locking conflict:*/

column username format a10

column lockwait format a10

column sql_text format a80

column object_owner format a14

column object format a15

select b.username username, c.sid sid, c.owner object_owner,

c.object object, b.lockwait, a.sql_text SQL

from v$sqltext a, v$session b, v$access c

where a.address=b.sql_address and

a.hash_value=b.sql_hash_value and b.sid = c.sid and c.owner != ‘SYS’

/

****************************************************

File Name : lock_wait.sql

****************************************************

set verify off

column machine format a20 heading “APPL.|MACHINE”

column sid format 99999

column serial# format 99999

column spid format 99999 heading “ORACLE|SERVER|PROCESS”

column process format 99999 heading “USER|APPL.|PROCESS”

column username format a12

rem

select

s.username, s.status, s.sid, s.serial#,

p.spid, s.machine, s.process, s.lockwait

from v$session s, v$process p

where s.lockwait is not null

and s.paddr = p.addr

/

****************************************************

File Name : lockedobj.sql

****************************************************

set term off echo off feedback off

spool $LOGS/lockedobj.log

col blocker format a15 heading ‘Blocker’

col blocked format a15 heading ‘Blocked’

col locked_object format a30 heading ‘Locked Object’

select a.username Blocker,

b.username Blocked,

c.object_name Locked_Object

from v$session a,

v$session b,

dba_objects c,

v$locked_object d,

dba_waiters e

where e.holding_session = a.sid

and e.waiting_session = b.sid

and c.object_id = d.object_id

and d.session_id = e.holding_session

/

spool off

exit

****************************************************

File Name : log_block_size.sql

****************************************************

select

max(l.lebsz) log_block_size

from

sys.x_$kccle l

where

l.inst_id = ‘800P’

/

****************************************************

File Name : log_phy_read.sql

****************************************************

select a.sid,c.status,a.value “Log Read” , b.value “Phy Read” ,d.value “Const Get”

from v$sesstat a,v$sesstat b,v$session c,v$sesstat d

where a.sid = b.sid

and a.sid = d.sid

and a.STATISTIC# = 9

and b.STATISTIC# = 39

and d.STATISTIC# = 38

and a.sid = c.sid

and c.status = ‘ACTIVE’

order by 3

/

****************************************************

File Name : logstat.sql

****************************************************

set term on echo on

col member format a45

select b.status, a.member from v$logfile a, v$log b

where a.group#=b.group#

/

****************************************************

File Name : logsync.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_waiting_on_ENQUEUE,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’log file sync’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : look_longlocks.sql

****************************************************

—

—

— view renamed to v$longlocks

—

— See XVIEW.SQL

—

set linesize 120

col SID format 99999

col type format a4

col “HELD SEC” format 999999

col OSUSER format a9

col PROCESS format a11

col TERMINAL format a15

col BLOCKER format a15

col first_name format a7 tru

col last_name format a9 tru

col req format 999

col hld format 999

set feedback off

spo junklock.txt

prompt Subj: People are running Crazy ………….

prompt

prompt Locking Report:

prompt

select * from v$longlocks

/

prompt

prompt

spo off

—-exit;

****************************************************

File Name : lsleep.sql

****************************************************

select hladdr “LATCH ADDRESS”,

dbarfil “RFILE#”,

FILE# “File#”,

dbablk “BLOCK#”,

gets,

lc.sleeps

from x$bh bh,

v$latch_children lc

where lc.addr=bh.hladdr

and state!=0 /* ie not FREE */

and sleeps>10000

order by sleeps desc

/

****************************************************

File Name : lst_chain.sql

****************************************************

set lines 132

break on report

compute sum of chain_cnt on report

compute sum of num_rows on report

select owner,table_name,num_rows,chain_cnt,avg_row_len,(chain_cnt*avg_row_len)/1024/1024 “MB”

from dba_Tables where chain_cnt >0

and owner != ‘6344’

order by 4;

****************************************************

File Name : m.sql

****************************************************

SELECT

l2.block,l2.status,l2.osuser,substr(l2.machine,1,20) machine,a.total

,L2.ctime H_TIME

,l2.type lock_type

,substr(nvl (L2.username, q$cvar.get_bpname (L2.paddr)),1,20) H_USERNAME

,L2.sid H_SID

,decode (L2.username, null, 0, L2.serial) H_SER#

,SUBSTR(RTRIM(decode (L2.obj, 0, to_char (L2.id2),

q$cvar.objschema (L2.obj)))||’.’||Rtrim(decode (L2.obj, 0, to_char (L2.id1), q$cvar.objname (L2.obj))),

1,30) H_SCHOBJ

FROM

sys.ats_lock2 L2,

(select HOLDING_SESSION hs,count(*) total from dba_waiters

group by holding_session) a

WHERE

a.hs = l2.sid

and L2.block > 0

and l2.username is not null

/

****************************************************

File Name : m0.sql

****************************************************

KSUSEUNM KSUSEMNM

select l2.rsrce l2_rsrce,decode(l2.request,0,’hold’,’wait’) l2_holdwait,l2.block l2_block,l2.ctime l2_ctime,nvl(l2.username,q$cvar.get_bpname(l2.paddr)) l2_username,l2.sid l2_sessid,decode(l2.username, null ,0,l2.serial) l2_sess_serial,l2.type l2_locktype,decode(l2.lmode,0,’none’,1,’null’,2,’row-s (ss)’,3,’row-x (sx)’,4,’share’,5,’s/row-x (ssx)’,6,’exclusive’,to_char(l2.lmode)) l2_heldmode,decode(l2.request,0,’none’,1,’null’,2,’row-s (ss)’,3,’row-x (sx)’,4,’share’,5,’s/row-x (ssx)’,6,’exclusive’,to_char(l2.request)) l2_requestmode,decode(l2.obj,0,to_char(l2.id1),q$cvar.objname(l2.obj)) l2_objname,decode(l2.obj,0,to_char(l2.id2),q$cvar.objschema(l2.obj)) l2_objschema,obj l2_obj

from sys.q$lock2 l2

where l2.block > 0 or l2.request > 0

order by 1,2,4 desc

/

****************************************************

File Name : m01.sql

****************************************************

create or replace view ats_lockers ( BLOCK_STATUS,BLOCK_OSUSER,BLOCK_MACHINE,NO_BLOCKED,TIME_HELD,lock_type,BLOCK_UNAME,

BLOCK_SID,BLOCK_SERIAL#,OBJ_LOCKED) as

SELECT

l2.status,l2.osuser,substr(l2.machine,1,20) machine,a.total

,L2.ctime H_TIME

,l2.type lock_type

,substr(nvl (L2.username, q$cvar.get_bpname (L2.paddr)),1,20) H_USERNAME

,L2.sid H_SID

,decode (L2.username, null, 0, L2.serial) H_SER#

,SUBSTR(RTRIM(decode (L2.obj, 0, to_char (L2.id2), q$cvar.objschema (L2.obj)))||’.’||Rtrim(decode (L2.obj, 0, to_char (L2.id1), q$cvar.objname (L2.obj))),1,30) H_SCHOBJ

FROM

sys.ats_lock2 L2,

(select HOLDING_SESSION hs,count(*) total from dba_waiters

group by holding_session) a

WHERE

a.hs = l2.sid

and L2.block > 0

and l2.username is not null

/

****************************************************

File Name : max_cache_cursors.sql

****************************************************

select

max(count(*)) max_cacheable_cursors

from

( select

p.kglobt18 schema# — parsing schema number

from

sys.x$kglcursor p

where

p.kglobt12 > 2 — enough parse_calls

union all

select

s.kglntsnm schema# — authorized schema number

from

sys.x$kglcursor c,

sys.x$kglsn s

where

c.kglobt12 > 2 and

s.kglhdadr = c.kglhdadr

)

group by

schema#

/

****************************************************

File Name : max_extents.sql

****************************************************

select index_name ,owner

from dba_indexes a

where

(max_Extents -3 ) <= (select count(*) from dba_extents where segment_name = index_name
and owner = a.owner )

union all

select table_name ,owner

from dba_tables b

where

(max_Extents -3 ) <= (select count(*) from dba_extents where segment_name = table_name
and owner = b.owner );

****************************************************

File Name : max_odr_num.sql

****************************************************

select odr_number,to_char(dt_crtd,’DD-MON-YYYY HH24:MI SS’) from atS_orders where

dt_crtd =

(

select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ max(dt_Crtd) from ats_orders a

where dt_crtd >= trunc(sysdate ) and dt_crtd < trunc(sysdate+1 ) and version =1
);

****************************************************

File Name : max_sess_cache_cursor.sql

****************************************************

select max(count(*)) max_cacheable_cursors

from

( select

p.kglobt18 schema# — parsing schema number

from

sys.x$kglcursor p

where

p.kglobt12 > 2 — enough parse_calls

union all

select

s.kglntsnm schema# — authorized schema number

from sys.x$kglcursor c,

sys.x$kglsn s

where

c.kglobt12 > 2 and

s.kglhdadr = c.kglhdadr

)

group by

schema#

/

****************************************************

File Name : mikem.sql

****************************************************

rem set feedback off

rem set term off

set pagesize 100

column “Total megs needed” format 999,999.99

column tbs_free format 999,999,999.99

rem spool $RPT/space_needed.log

select segtbs, tbs_free, sum(nextext)/1024/1024 “Total megs needed”

from ops$oracle.extgrow, (select tablespace_name, sum(bytes)/1024/1024 tbs_free

from dba_free_space

group by tablespace_name) in1

where growdate = (select max(growdate) from ops$oracle.extgrow)

and (totbytes-usedbytes)/(totbytes)*100 < 5
and in1.tablespace_name = segtbs

and totbytes != 0

group by segtbs, tbs_free

order by 3 desc;

****************************************************

File Name : mill.sql

****************************************************

set pages 2000

set lines 132

column num_rows format 999,999,999,999 heading ‘# of Rows’

column table_name format a40 heading ‘Table Name’

column tablespace_name format a20 heading ‘TS’

select table_name,num_rows,tablespace_name,owner from dba_tables where num_rows >= 1000000 order by 2 desc,3

/

****************************************************

File Name : millhalf.sql

****************************************************

set pages 2000

set lines 132

column num_rows format 999,999,999,999 heading ‘# of Rows’

column table_name format a40 heading ‘Table Name’

column tablespace_name format a20 heading ‘TS’

select table_name,num_rows,tablespace_name,owner from dba_tables where num_rows >= 500000

and num_rows < 1000000
order by 2 desc,3

/

****************************************************

File Name : million_rows.sql

****************************************************

set pages 2000

set lines 132

column num_rows format 999,999,999,999 heading ‘# of Rows’

column table_name format a40 heading ‘Table Name’

column tablespace_name format a20 heading ‘TS’

select table_name,num_rows,tablespace_name,chain_cnt from dba_tables where num_rows >= 1000000 order by 2 desc,3

/

****************************************************

File Name : miss_for_ind.sql

****************************************************

column constraint_name noprint

column table_name format a48

break on constraint_name skip 1 on table_name

select /*+ ordered */

n.name constraint_name,

u.name ||’.’|| o.name table_name,

c.name column_name

from

(

select /*+ ordered */ distinct

cd.con#,

cc.obj#

from

sys.cdef$ cd,

sys.ccol$ cc,

sys.tab$ t

where

cd.type# = 4 and — foriegn key

cc.con# = cd.con# and

t.obj# = cc.obj# and

bitand(t.flags, 6) = 0 and — table locks enabled

not exists ( — column not indexed

select

null

from

sys.icol$ ic,

sys.ind$ i

where

ic.bo# = cc.obj# and

ic.intcol# = cc.intcol# and

ic.pos# = cc.pos# and

i.obj# = ic.obj# and

bitand(i.flags, 1049) = 0 — index must be valid

)

) fk,

sys.obj$ o,

sys.user$ u,

sys.ccol$ cc,

sys.col$ c,

sys.con$ n

where

o.obj# = fk.obj# and

o.owner# != 0 and — ignore SYS

u.user# = o.owner# and

cc.con# = fk.con# and

c.obj# = cc.obj# and

c.intcol# = cc.intcol# and

n.con# = fk.con#

order by

2, 1, 3

/

****************************************************

File Name : miss_for_index.sql

****************************************************

ttitle ‘Foreign Keys with Indexes Missing on Child Table’

SELECT acc.owner||’-> ‘||acc.constraint_name||'(‘||acc.column_name

||'[‘||acc.position||’])’||’ ***** Missing Index’

FROM dba_cons_columns acc, dba_constraints ac

WHERE ac.constraint_name = acc.constraint_name

AND ac.constraint_type = ‘R’

AND (acc.owner, acc.table_name, acc.column_name, acc.position)

IN

(SELECT acc.owner, acc.table_name, acc.column_name, acc.position

FROM dba_cons_columns acc, dba_constraints ac

WHERE ac.constraint_name = acc.constraint_name

AND ac.constraint_type = ‘R’

MINUS

SELECT table_owner, table_name, column_name, column_position

FROM dba_ind_columns)

ORDER BY acc.owner, acc.constraint_name,

acc.column_name, acc.position;

****************************************************

File Name : miss_ind_for.sql

****************************************************

declare

pl_cons_column VARCHAR2(30);

pl_foreign_key VARCHAR2(2000);

pl_ind_column VARCHAR2(30);

pl_ind_name VARCHAR2(30);

pl_ind_owner VARCHAR2(30);

pl_index VARCHAR2(2000);

/*

Cursor c1 simply selects each Foreign Key constraint from the

DBA View DBA_CONSTRAINTS. No need at this stage to limit the

query to ‘ENABLED’ constraints, we’ll simply report the status

in the log file. For each constraint, we’ll construct the column list,

using cursor c2, which combine to form the foreign key constraint

returned in cursor c1

*/

CURSOR c1 IS SELECT constraint_name,owner,table_name,status

FROM dba_constraints

WHERE constraint_type=’R’;

CURSOR c2(cons_name VARCHAR2,cons_owner VARCHAR2) IS SELECT column_name

FROM dba_cons_columns

WHERE constraint_name=cons_name

AND owner=cons_owner

ORDER BY dba_cons_columns.position;

/*

For each returned constraint, we need to fins a matching index, firstly

we fetch each index name with c3, and then construct the index columns

with cursor c4 in their correct order until we find a match with the

foreign key constraint

*/

CURSOR c3(ind_table varchar2,tab_owner varchar2) IS

SELECT index_name, owner

FROM dba_indexes

WHERE table_name=ind_table

AND table_owner=tab_owner;

CURSOR c4(ind_name varchar2,ind_owner varchar2) IS

SELECT column_name

FROM dba_ind_columns

WHERE INDEX_NAME=ind_name

AND INDEX_OWNER=ind_owner

ORDER BY dba_ind_columns.column_position;

BEGIN

FOR c1_rec in c1 LOOP

/* looping for each foreign key constraint */

pl_cons_column := NULL;

pl_foreign_key := NULL;

pl_ind_column := NULL;

pl_ind_name := NULL;

pl_ind_owner := NULL;

pl_index := NULL;

OPEN c2(c1_rec.constraint_name,c1_rec.owner);

FETCH c2 INTO pl_cons_column;

pl_foreign_key := pl_cons_column; — the first col in the foreign key

<>

LOOP

/*

constructing the foreign key columns, delimiting each column with a ‘,’

*/

FETCH c2 into pl_cons_column;

EXIT WHEN c2%NOTFOUND;

pl_foreign_key := pl_foreign_key||’,’||pl_cons_column;

END LOOP constraint_names;

/*

we now have a table and foreign key definition for which we need an index */

CLOSE c2;

OPEN c3(c1_rec.table_name,c1_rec.owner);

<>

LOOP

/* for each index found for this table */

FETCH c3 INTO pl_ind_name,pl_ind_owner;

EXIT WHEN c3%NOTFOUND;

OPEN c4(pl_ind_name,pl_ind_owner);

FETCH c4 INTO pl_ind_column;

pl_index := pl_ind_column; — the first column in the index

IF pl_index=pl_foreign_key THEN — check this doesn’t already match

CLOSE c4; — the foreign key

EXIT index_name;

END IF;

IF pl_index = SUBSTR(pl_foreign_key,1,LENGTH(pl_index)) THEN

/*

we only need construct the whole index while it’s leading edge still

matches the constrained foreign key columns

*/

<>

LOOP

/* construct the whole index in the same way as the foreign key */

FETCH c4 INTO pl_ind_column;

EXIT WHEN c4%NOTFOUND;

pl_index:= pl_index||’,’||pl_ind_column;

/*

we do not need to continue with the index name loop if we already have a

match on the foreign key or the leading edge already differs

*/

IF pl_index=pl_foreign_key OR

pl_index != SUBSTR(pl_foreign_key,1,LENGTH(pl_index))

THEN

CLOSE c4;

EXIT index_name;

END IF;

END LOOP index_columns;

END IF;

CLOSE c4;

END LOOP index_name;

CLOSE c3;

IF pl_index != pl_foreign_key OR pl_index IS NULL THEN

/* Alternative means of output having first set serveroutput using:

SET SERVEROUTPUT ON SIZE n

where n is between 2000 and 1000000 to set the output limit.

*/

DBMS_OUTPUT.PUT_LINE(c1_rec.owner||’.’||c1_rec.constraint_name);

END IF;

END LOOP;

END;

/

****************************************************

File Name : move_arch.sh

****************************************************

#!/bin/sh -x

mvis=`ps -ef |grep move_arch.sh|grep -v grep|wc -l`

echo $mvis

if [ $mvis -gt 2 ]

then

exit 1

fi

LOG_FILE=/oracle/app/oracle/admin/logs/MOVE_800P.log

COMFORT_SPACE=70

ARCH_SPACE=`df -k /database1 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_800P.log| grep “arch”|tail -1|cut -c48-57`

RECOVERED=`expr $RECOVERED – 3`

NOTIFY_LIST=’dbaoracle@1800flowers.com’

NO_FILES_MOVED=0

while [ $ARCH_SPACE -gt $COMFORT_SPACE ]

do

FIRST_FILE=`ls -latr /database1/archlog/800P/*.arc|head -1|awk ‘{print $9}’`

CURR_FILE_NO=`ls -latr /database1/archlog/800P/*.arc|head -1|cut -f5 -d’/’|cut -c5-14`

FILE_NAME=`ls -latr /database1/archlog/800P/*.arc|head -1|cut -f5 -d’/’`

if [ $CURR_FILE_NO -lt $RECOVERED ]

then

cp -p $FIRST_FILE /EMCdb5/archlog/800P/.

CURR_FILE_SZ=`ls -latr $FIRST_FILE |awk ‘{print $5}’`

CURR_FL_NAME=`echo $FIRST_FILE |cut -f5 -d’/’`

COPIED_FILE_SZ=`ls -latr /EMCdb5/archlog/800P/$CURR_FL_NAME |awk ‘{print $5}’`

if [ $CURR_FILE_SZ -eq $COPIED_FILE_SZ ]

then

echo “Removed ” $FIRST_FILE “at “`date` >> $LOG_FILE

rm $FIRST_FILE

fi

compress /EMCdb5/archlog/800P/$FILE_NAME

NO_FILES_MOVED=`expr $NO_FILES_MOVED + 1`

fi

ARCH_SPACE=`df -k /database1 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

ARCHBAK_SPC=`df -k /EMCdb5 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

done

if [ $NO_FILES_MOVED -gt 0 ]

then

mailx -s “FILES MOVED ALERT ” $NOTIFY_LIST < I have moved $NO_FILES_MOVED archivelog files from /database1/archlog/800P to /EMCdb5/archlog/800P

Pls check /EMCdb5

Currently /database1 is at $ARCH_SPACE % and /EMCdb5 is at $ARCHBAK_SPC %

– From Panther1/oracle

EOF

fi

echo “Last run at ” `date` ” to move $NO_FILES_MOVED files ” >>$LOG_FILE

****************************************************

File Name : move_arch_new.sh

****************************************************

#!/bin/sh -x

mvis=`ps -ef |grep move_arch.sh|grep -v grep|wc -l`

echo $mvis

if [ $mvis -gt 2 ]

then

exit 1

fi

LOG_FILE=/oracle/app/oracle/admin/logs/MOVE_800P.log

BACKUP_DIR=/EMCdb5/archlog/800P/

COMFORT_SPACE=70

ARCH_COMFORT_SPACE=40

ARCH_SPACE=`df -k /database1 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

RECOVERED=`egrep “Media Recovery Log” /oracle/app/oracle/admin/800P/bdump/alert_800P.log| grep “arch”|tail -1|cut -c48-57`

RECOVERED=`expr $RECOVERED – 3`

NOTIFY_LIST=’vivek@1800flowers.com’,’rshenoy@1800flowers.com’,’fdarwesh@1800flowers.com’

NO_FILES_MOVED=0

while [ $ARCH_SPACE -gt $COMFORT_SPACE ]

do

FIRST_FILE=`ls -latr /database1/archlog/800P/*.arc|head -1|awk ‘{print $9}’`

CURR_FILE_NO=`ls -latr /database1/archlog/800P/*.arc|head -1|cut -f5 -d’/’|cut -c5-14`

FILE_NAME=`ls -latr /database1/archlog/800P/*.arc|head -1|cut -f5 -d’/’`

if [ $CURR_FILE_NO -lt $RECOVERED ]

then

cp -p $FIRST_FILE /EMCdb5/archlog/800P/.

CURR_FILE_SZ=`ls -latr $FIRST_FILE |awk ‘{print $5}’`

CURR_FL_NAME=`echo $FIRST_FILE |cut -f5 -d’/’`

COPIED_FILE_SZ=`ls -latr /EMCdb5/archlog/800P/$CURR_FL_NAME |awk ‘{print $5}’`

if [ $CURR_FILE_SZ -eq $COPIED_FILE_SZ ]

then

echo “Removed ” $FIRST_FILE “at “`date` >> $LOG_FILE

rm $FIRST_FILE

fi

compress /EMCdb5/archlog/800P/$FILE_NAME

NO_FILES_MOVED=`expr $NO_FILES_MOVED + 1`

fi

ARCH_SPACE=`df -k /database1 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

done

ARCHBAK_SPC=`df -k /EMCdb5 | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

while [ $ARCHBAK_SPC -gt $ARCH_COMFORT_SPACE ]

do

BACK_FILE_NAME=`ls -latr /EMCdb5/archlog/800P/*.arc*|head -1|cut -f5 -d’/’`

rm $BACKUP_DIR$BACK_FILE_NAME

ARCHBAK_SPC=`df -k $BACKUP_DIR | tail -1 | awk ‘{print $5’} | sed ‘s/%//g’`

done

if [ $NO_FILES_MOVED -gt 0 ]

then

mailx -s “FILES MOVED ALERT ” $NOTIFY_LIST < I have moved $NO_FILES_MOVED archivelog files from /database1/archlog/800P to /EMCdb5/archlog/800P

Pls check /EMCdb5

Currently /database1 is at $ARCH_SPACE % and /EMCdb5 is at $ARCHBAK_SPC %

– From Panther1/oracle

EOF

fi

echo “Last run at ” `date` ” to move $NO_FILES_MOVED files ” >>$LOG_FILE

****************************************************

File Name : mv_db3.sql

****************************************************

ALTER DATABASE RENAME ‘/db3/oradata/800P/800P_atlas_index1.dbf’ TO ‘/db3/oradata/800P/800P_atlas_index1.dbf’;

ALTER DATABASE RENAME ‘/db3/oradata/800P/800P_sys1.dbf’ TO ‘/db3/oradata/800P/800P_sys1.dbf’;

****************************************************

File Name : mv_ts.sql

****************************************************

alter database rename file ‘/ORADATA1/800P/800P_misc_data1.dbf’

to ‘/ORADATA8/800P/800P_misc_data1.dbf’;

alter database rename file ‘/ORADATA1/800P/800P_misc_data2.dbf’

to ‘/ORADATA8/800P/800P_misc_data2.dbf’;

****************************************************

File Name : name.sql

****************************************************

select first_name,last_name,TLR_CODE from ats_employees where code = UPPER(‘&1’)

/

****************************************************

File Name : nav.sql

****************************************************

select segtbs, tbs_free, sum(nextext)/1024/1024 “Total megs needed”

from ops$oracle.extgrow, (select tablespace_name, sum(bytes)/1024/1024 tbs_free

from dba_free_space

group by tablespace_name) in1

where growdate = (select max(growdate) from ops$oracle.extgrow)

and (totbytes-usedbytes)/(totbytes)*100 < 5
and in1.tablespace_name = segtbs

group by segtbs, tbs_free

order by 3 desc

/

****************************************************

File Name : naveen.sql

****************************************************

set feedback off verify off echo off termout off

Enter value for 1: naveen

alter user naveen identified by values ‘2845E4EB614471DC’;

host rm $SCRIPTS/reset.sql

exit

****************************************************

File Name : no_dt_crtd.sql

****************************************************

select table_name from dba_tables where owner = ‘ATS’

minus

select distinct table_name from dba_Tab_columns where column_name = ‘DT_CRTD’ and owner = ‘ATS’

/

****************************************************

File Name : no_pre_trig.sql

****************************************************

select owner, table_name from dba_tables

where owner not in (‘SYS’,’SYSTEM’,’QDBA’,’ATSDBA’,’VIVEK’,’IMON’,’QUEST’,’QUEST_SPACEMGR’,’QUEST_IMPACT’,’PATROL’)

minus

select owner,table_name from dba_triggers where

(trigger_name like ‘%PRE_UPD%’ or trigger_name like ‘%UPD_DBT%’) and

owner not in (‘SYS’,’SYSTEM’,’QDBA’,’ATSDBA’,’VIVEK’,’IMON’,’QUEST’,’QUEST_SPACEMGR’,’QUEST_IMPACT’,’PATROL’)

/

****************************************************

File Name : no_stat.sql

****************************************************

select count(*) From dba_tables where rownum is null and owner in (‘6344′,’5336′,’1193′,’ATS’)

union all

select count(*) From dba_indexes where DISTINCT_KEYS is null and owner in (‘6344′,’5336′,’1193′,’ATS’)

/

****************************************************

File Name : num_set_audit_proc.sql

****************************************************

select table_name,count(*) from dba_triggers where

(owner,trigger_name) in (

select a.owner,a.name

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘SET_AUDIT_PROC’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

and b.objecT_type = ‘TRIGGER’

and b.owner = ‘ATS’

)

group by table_name

order by 1

/

****************************************************

File Name : num_version.sql

****************************************************

SELECT dbafil , dbablk, class, count(*)

FROM x$bh

GROUP BY dbafil, dbablk,class

HAVING count(*) > 5

order by 4 desc

/

****************************************************

File Name : obj.sql

****************************************************

column object_name format a30

column owner format a15

column las_ddl_time format a10

select object_name,owner,status,object_type,to_char(last_ddl_time,’DD-MON-YYYY:HH24:MI:SS’) from dba_objects

where object_name like upper(‘&1’)

/

****************************************************

File Name : obj_buff_pool.sql

****************************************************

Prompt

Prompt ##

Prompt ## Objects in Buffer Pools

Prompt ##

select kcbwbpd.bp_name, o.name, count(*) BLOCKS

from sys.x$kcbwds kcbwds,

sys.x$kcbwbpd kcbwbpd ,

sys.x$bh bh,

sys.obj$ o

where kcbwds.set_id >= kcbwbpd.bp_lo_sid

and kcbwds.set_id <= kcbwbpd.bp_hi_sid
and kcbwbpd.bp_size != 0

and bh.indx between start_buf# and end_buf#

and o.dataobj# = bh.obj

and bh.state !=0

and o.owner# !=0

group by kcbwbpd.bp_name, o.name

/

****************************************************

File Name : obj_full_tablescan.sql

****************************************************

SELECT distinct o.object_name

FROM dba_objects o,x$bh x

WHERE x.obj=o.data_object_id

AND o.object_type=’TABLE’

AND standard.bitand(x.flag,524288)>0

AND o.owner<>‘SYS’;

****************************************************

File Name : obj_latch.sql

****************************************************

select obj,addr,indx,hladdr,tch from x$bh where obj in (1489,309556)

order by 1,5;

****************************************************

File Name : obj_lock.sql

****************************************************

select /*+ORDERED */ s.sid,s.username,s.lockwait, s.process,s.osuser,w.seconds_in_wait,

decode(chr(bitand(p1,-16777216)/16777215)||chr(bitand(p1,16711680)/65535),

‘MR’, ‘Media Recovery’,

‘RT’, ‘Redo Thread’,

‘UN’, ‘User Name’,

‘TX’, ‘Transaction’,

‘TM’, ‘DML’,

‘UL’, ‘PL/SQL User Lock’,

‘DX’, ‘Distributed Xaction’,

‘CF’, ‘Control File’,

‘IS’, ‘Instance State’,

‘FS’, ‘File Set’,

‘IR’, ‘Instance Recovery’,

‘ST’, ‘Disk Space Transaction’,

‘TS’, ‘Temp Segment’,

‘IV’, ‘Library Cache Invalidation’,

‘LS’, ‘Log Start or Switch’,

‘RW’, ‘Row Wait’,

‘SQ’, ‘Sequence Number’,

‘TE’, ‘Extend Table’,

‘TT’, ‘Temp Table’,

chr(bitand(p1,-16777216)/16777215)||chr(bitand(p1,16711680)/65535))

LOCK_TYPE ,

decode(to_number(bitand(p1,65535)),

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) LOCK_MODE,

u.name||’.’||o.name

from sys.v_$session_wait w,

sys.v_$session s,

sys.obj$ o,

sys.user$ u

where w.event=’enqueue’

and w.seconds_in_wait > 2

and s.sid=w.sid

and o.obj#(+)=w.p2

—- and u.user#(+)=o.owner#

/

****************************************************

File Name : obj_on_hot_latch.sql

****************************************************

column Owner format a10

column object_name format a60

select /*+ ordered */

l.child# latch#, o.KGLNAOWN Owner,o.kglnaobj object_name,

decode(KGLOBTYP,0,’CURSOR’,7,’PROCEDURE’,8,’FUNCTION’,9,’PACKAGE’,11,’PACKAGE BODY’,12,’TRIGGER’,13,’TYPE’,

14,’TYPE BODY’,KGLOBTYP) Object_type

from ( select count(*) latches,avg(sleeps) sleeps

from sys.v$latch_children

where name = ‘library cache’ ) a,

sys.v$latch_children l,

(select s.buckets * power(2,least(8,ceil(log(2, ceil(count(*) / s.buckets))))) buckets

from ( select

decode(y.ksppstvl,0, 509,

1, 1021,

2, 2039,

3, 4093, 4, 8191, 5, 16381, 6, 32749,

7, 65521, 8, 131071, 509 ) buckets from

sys.x$ksppi x, sys.x$ksppcv y where

x.inst_id = userenv(‘Instance’) and y.inst_id = userenv(‘Instance’) and

x.ksppinm = ‘_kgl_bucket_count’ and y.indx = x.indx ) s,

sys.x$kglob c where c.inst_id = userenv(‘Instance’) and

c.kglhdadr = c.kglhdpar group by s.buckets ) b, sys.x$kglob o

where l.name = ‘library cache’ and l.sleeps > 2 * a.sleeps and

mod(mod(o.kglnahsh, b.buckets), a.latches) + 1 = l.child# and

o.inst_id = userenv(‘Instance’) and o.kglhdadr = o.kglhdpar

/

****************************************************

File Name : obj_pin.sql

****************************************************

execute dbms_shared_pool.keep(‘”ATS”.ATS_HIS_MON_PRE_INS_DBT’,’r’);

execute dbms_shared_pool.keep(‘”ATS”.ATS_PROM_LOOKUP_PRE_UPD’,’r’);

execute dbms_shared_pool.keep(‘”SHISHIR”.ATS_REPBASE_UPDATE_PKG’,’p’);

execute dbms_shared_pool.keep(‘”IWATCH4″.QUEST_IW_TRANSLATE_PARAMETER’,’p’);

****************************************************

File Name : obj_to_keep.sql

****************************************************

select distinct

decode(kglobtyp,0,’CURSOR’,7,’PROCEDURE’,8,’FUNCTION’,9,’PACKAGE’,

11,’PACKAGE BODY’,12,’TRIGGER’,13,’TYPE’,14,’TYPE BODY’,’OTHER’)

||’ – ‘||kglnaown||’.’||kglnaobj “Eligible PL/SQL objects” from x$kglob

where kglobhd4 in (select ksmchpar from x$ksmsp

where ksmchcom=’PL/SQL MPCODE’ and ksmchsiz>5120)

****************************************************

File Name : odr_hr.sql

****************************************************

—- select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ to_char(dt_Crtd,’DD/MM HH24′) “Hour”,count(1)

— from ats_orders A

— where dt_crtd >= trunc(sysdate – 364 ) and dt_crtd < trunc(sysdate - 363 ) and version =1
— group by to_char(dt_Crtd,’DD/MM HH24′)

–/

select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ to_char(dt_Crtd,’DD/MM HH24′) “Hour”,count(1)

from ats_orders A

where dt_crtd >= trunc(sysdate -1) and version =1

group by to_char(dt_Crtd,’DD/MM HH24′)

/

****************************************************

File Name : optimal_rollback_segs.sql

****************************************************

select count(*) from x$ktcxb where ktcxbflg > 0;

****************************************************

File Name : ord_5min.sql

****************************************************

break on report

compute sum of Total break on report

select /*+ INDEX (ats_orders ats_ord_dtcrtd_i) */

to_char(dt_crtd,’hh24′)||’ ‘||decode(trunc((to_number(to_char(dt_crtd,’mi’))/ 5)+1),1,’05’,2,’10’,3,’15’,

4,’20’,5,’25’,6,’30’,7,’35’,8,’40’,9,’45’,10,’50’,11,’55’,12,’59’) HHQ,

count(1) Total

from ats_orders

where dt_crtd > trunc(sysdate – 9)

and dt_crtd < trunc(sysdate - 8)
and version=1

group by

to_char(dt_crtd,’hh24′)||’ ‘||

decode(trunc((to_number(to_char(dt_crtd,’mi’))/ 5)+1 ), 1, ’05’,2,’10’,3,’15’,4,’20’,5,’25’,6,’30’,7,’35’,8,’40’,9,’45’,10,’50’,11,’55’,12,’59’)

order by 1

/

****************************************************

File Name : ord_cnt.sql

****************************************************

select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ ‘Yesterday’,count(*) from ats_orders a

where dt_crtd >= trunc(sysdate-1 ) and dt_crtd < trunc(sysdate ) and version =1;
select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ ‘Today’,count(*) from ats_orders a

where dt_crtd >= trunc(sysdate ) and dt_crtd < trunc(sysdate+1 ) and version =1;
select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ max(to_char(dt_crtd,’DD-MON-YYYY HH24 MI SS’)) from ats_orders a

where dt_Crtd >= trunc(sysdate);

select odr_number,to_char(dt_crtd,’DD-MON-YYYY HH24:MI:SS’) from ats_orders

where odr_number = (select max(odr_number) from ats_orders)

/

****************************************************

File Name : ord_count.sql

****************************************************

select /*+ INDEX (ats_orders ORDERS_ORD_TIMESTAMP) */

to_char(order_timestamp,’HH24′) “Hour” ,count(*) “Total”

from ats_orders

where order_timestamp >= trunc(sysdate-1)

and order_timestamp < trunc(sysdate)
and version = 1

and nvl(order_status_code,’X’) <> ‘D’

and order_sales_type <> ‘REP’

group by to_char(order_timestamp,’HH24′)

/

****************************************************

File Name : ord_hour.sql

****************************************************

break on report

compute sum of total break on report

column hour format a10

select /*+ INDEX (ats_orders ats_ord_dtcrtd_i) */ to_char(dt_crtd, ‘HH24’) “Hour”,

count(*) “Total”

from ats_orders

where dt_crtd >= trunc(sysdate)

and version = 1

group by to_char(dt_crtd, ‘HH24’)

/

****************************************************

File Name : ord_proc.sql

****************************************************

select /*+ INDEX(A ATS_ORD_DTCRTD_I) */ count(*) from ats_orders a

where dt_crtd >= trunc(sysdate – 340 ) and dt_crtd < trunc(sysdate +1 ) and version =1; ****************************************************
File Name : orig_tuning.sql

****************************************************

REM This script examines various V$ parameters. The script makes suggestions

REM on mods that can be made to your system if specific conditions exist. The

REM report should be run after the system has been up for at least 10 hours

REM and should be run over a period of time to get a real feel for what the

REM real condition of the database is. A one-time sample run on an inactive

REM system will not give an accurate picture of what is really occuring within

REM the database.

REM

REM If the database is shut down on a nightly basis for backups, the script can

REM be run just prior to shutdown each night to enable trending analysis.

REM

REM This script can be run on any platform but is tailored to evaluate an

REM Oracle7.0.x database. It has not yet been run on in an Oracle7.1

REM environment. The script assumes that you are running it from a DBA

REM account where CATDBSYN.SQL has been run.

REM

REM Marlene L. Theriault – Oracle Corporation – 02 November 1993

REM

REM **NOTE: Be sure to change the “spool” path to reflect your directory

REM structure.

REM

set pages 60

set verify off

set head off

col name format a45

col dbname format a10

col phyrds format 9,999,999

col phywrts format 9,999,999

set echo off termout off feedback off

set newpage 1

set linesize 80

define cr=chr(10)

REM

REM *** Change the spool path/output name here **

REM

spool $RPT/tuning_stats.txt

REM

ttitle ‘SYSTEM STATISTICS FOR ORACLE7’

select ‘DATABASE: ‘,value dbname from v$parameter where name like ‘%db_name%’;

ttitle off

select ‘LIBRARY CACHE STATISTICS:’ from dual;

select ‘PINS – # of times an item in the library cache was executed – ‘|| sum(pins),

‘RELOADS – # of library cache misses on execution steps – ‘||sum(reloads)||&cr||&cr,

‘RELOADS / PINS * 100 = ‘||round((sum(reloads) / sum(pins) * 100),2)||’%’

from v$librarycache

/

prompt Increase memory until RELOADS is near 0 but watch out for Paging/swapping.

prompt To increase library cache, increase SHARED_POOL_SIZE

prompt

prompt ** NOTE: Increasing SHARED_POOL_SIZE will increase the SGA size on VMS.

prompt

prompt Library Cache Misses indicate that the Shared Pool is not big

prompt enough to hold the shared SQL area for all concurrently open cursors.

prompt If you have no Library Cache misses (PINS = 0), you may get a small

prompt increase in performance by setting CURSOR_SPACE_FOR_TIME = TRUE which

prompt prevents ORACLE from deallocating a shared SQL area while an application

prompt cursor associated with it is open.

prompt

prompt For Multi-threaded server, add 1K to SHARED_POOL_SIZE per user.

prompt

prompt ——————————————————————————–

column xn1 format a50

column xn2 format a50

column xn3 format a50

column xv1 new_value xxv1 noprint

column xv2 new_value xxv2 noprint

column xv3 new_value xxv3 noprint

column d1 format a50

column d2 format a50

prompt HIT RATIO:

prompt

prompt Values Hit Ratio is calculated against:

prompt

select lpad(name,20,’ ‘)||’ = ‘||value xn1, value xv1

from

v$sysstat

where

statistic# = 37

/

select lpad(name,20,’ ‘)||’ = ‘||value xn2, value xv2 from

v$sysstat

where

statistic# = 38

/

select lpad(name,20,’ ‘)||’ = ‘||value xn3, value xv3 from

v$sysstat b

where

statistic# = 39

/

set pages 60

select ‘Logical reads = db block gets + consistent gets ‘, lpad(‘Logical Reads = ‘,24,’ ‘)||to_char(&xxv1+&xxv2) d1 from dual

/

select ‘Hit Ratio = (logical reads – physical reads) / logical reads’,lpad(‘Hit Ratio = ‘,24,’ ‘)||

round( (((&xxv2+&xxv1) – &xxv3) / (&xxv2+&xxv1))*100,2 )||’%’ d2

from dual

/

prompt If the hit ratio is less than 60%-70%, increase the initialization

prompt parameter DB_BLOCK_BUFFERS. ** NOTE: Increasing this parameter will

prompt increase the SGA size.

prompt

prompt ——————————————————————————–

col name format a30

col gets format 9,999,999

col waits format 9,999,999

prompt ROLLBACK CONTENTION STATISTICS:

prompt

prompt GETS – # of gets on the rollback segment header prompt WAITS – # of waits for the rollback segment header

set head on;

select name, waits, gets

from v$rollstat, v$rollname

where v$rollstat.usn = v$rollname.usn

/

set head off

select ‘The average of waits/gets is ‘||

round((sum(waits) / sum(gets)) * 100,2)||’%’ from v$rollstat

/

prompt

prompt If the ratio of waits to gets is more than 1% or 2%, consider

prompt creating more rollback segments

prompt

prompt Another way to gauge rollback contention is:

prompt

column xn1 format 9999999

column xv1 new_value xxv1 noprint

set head on

select class, count

from v$waitstat

where class in (‘system undo header’,’system undo block’,’undo header’,

‘undo block’)

/

set head off

select ‘Total requests = ‘||sum(count) xn1, sum(count) xv1 from v$waitstat

/

select ‘Contention for system undo header = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘system undo header’

/

select ‘Contention for system undo block = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘system undo block’

/

select ‘Contention for undo header = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘undo header’

/

select ‘Contention for undo block = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘undo block’

/

prompt

prompt If the percentage for an area is more than 1% or 2%, consider

prompt creating more rollback segments. Note: This value is usually very small

prompt and has been rounded to 4 places.

prompt

prompt ——————————————————————————–

prompt REDO CONTENTION STATISTICS:

prompt

prompt The following shows how often user processes had to wait for space in

prompt the redo log buffer:

select name||’ = ‘||value||&cr

from v$sysstat

where name = ‘redo log space requests’

/

prompt

prompt This value should be near 0. If this value increments consistently,

prompt processes have had to wait for space in the redo buffer. If this

prompt condition exists over time, increase the size of LOG_BUFFER in the

prompt init.ora file in increments of 5% until the value nears 0.

prompt ** NOTE: increasing the LOG_BUFFER value will increase total SGA size.

prompt

prompt ——————————————————————————–

col name format a15

col gets format 9999999

col misses format 9999999

col immediate_gets heading ‘IMMED GETS’ format 9999999

col immediate_misses heading ‘IMMED MISS’ format 9999999

col sleeps format 999999

prompt LATCH CONTENTION:

prompt

prompt GETS – # of successful willing-to-wait requests for a latch

prompt MISSES – # of times an initial willing-to-wait request was unsuccessful

prompt IMMEDIATE_GETS – # of successful immediate requests for each latch

prompt IMMEDIATE_MISSES = # of unsuccessful immediate requests for each latch

prompt SLEEPS – # of times a process waited and requests a latch after an initial

prompt willing-to-wait request

prompt

prompt If the latch requested with a willing-to-wait request is not

prompt available, the requesting process waits a short time and requests again.

prompt If the latch requested with an immediate request is not available,

prompt the requesting process does not wait, but continues processing

prompt

set head on

select name, gets, misses, immediate_gets, immediate_misses, sleeps

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

set head off

select ‘Ratio of MISSES to GETS: ‘||

round((sum(misses)/(sum(gets)+0.00000000001) * 100),2)||’%’

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

select ‘Ratio of IMMEDIATE_MISSES to IMMEDIATE_GETS: ‘||

round((sum(immediate_misses)/

(sum(immediate_misses+immediate_gets)+0.00000000001) * 100),2)||’%’

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

prompt

prompt If either ratio exceeds 1%, performance will be affected.

prompt

prompt Decreasing the size of LOG_SMALL_ENTRY_MAX_SIZE reduces the number of

prompt processes copying information on the redo allocation latch.

prompt

prompt Increasing the size of LOG_SIMULTANEOUS_COPIES will reduce contention for

prompt redo copy latches.

rem

rem This shows the library cache reloads

rem

set head on

prompt

prompt ——————————————————————————–

prompt

prompt Look at gethitratio and pinhit ratio

prompt

prompt GETHITRATIO is number of GETHTS/GETS

prompt PINHIT RATIO is number of PINHITS/PINS – number close to 1 indicates

prompt that most objects requested for pinning have been cached. Pay close

prompt attention to PINHIT RATIO.

prompt

column namespace format a20 heading ‘NAME’

column gets format 99999999 heading ‘GETS’

column gethits format 99999999 heading ‘GETHITS’

column gethitratio format 999.99 heading ‘GET HIT|RATIO’

column pins format 9999999 heading ‘PINHITS’

column pinhitratio format 999.99 heading ‘PIN HIT|RATIO’

select namespace, gets, gethits, gethitratio, pins, pinhitratio

from v$librarycache

/

rem

rem

rem This looks at the dictionary cache miss rate

rem

prompt

prompt ——————————————————————————–

prompt THE DATA DICTIONARY CACHE:

prompt

prompt

prompt Consider keeping this below 5% to keep the data dictionary cache in

prompt the SGA. Up the SHARED_POOL_SIZE to improve this statistic. **NOTE:

prompt increasing the SHARED_POOL_SIZE will increase the SGA.

prompt

rem

column dictcache format 999.99 heading ‘Dictionary Cache | Ratio %’

select sum(getmisses) / (sum(gets)+0.00000000001) * 100 dictcache

from v$rowcache

/

prompt

prompt ——————————————————————————–

prompt

prompt SYSTEM EVENTS:

prompt

prompt Not sure of the value of this section yet but it looks interesting.

prompt

col event format a37 heading ‘Event’

col total_waits format 99999999 heading ‘Total|Waits’

col time_waited format 9999999999 heading ‘Time Wait|In Hndrds’

col total_timeouts format 999999 heading ‘Timeout’

col average_wait heading ‘Average|Time’ format 999999.999

set pages 999

select * from v$system_event

/

prompt

prompt ——————————————————————————–

rem

rem

rem This looks at the sga area breakdown

rem

prompt THE SGA AREA ALLOCATION:

prompt

prompt

prompt This shows the allocation of SGA storage. Examine this before and

prompt after making changes in the INIT.ORA file which will impact the SGA.

prompt

rem

col name format a40

select name, bytes

from v$sgastat

/

set head off

select ‘total of SGA ‘||sum(bytes)

from v$sgastat

/

prompt

prompt ——————————————————————————–

rem

rem Displays all the base session statistics

rem

set head on

set pagesize 110

column name format a55 heading ‘Statistic Name’

column value format 9,999,999,999 heading ‘Result’

column statistic# heading ‘Stat#’ format 9999

ttitle center ‘Instance Statistics’ skip 2

prompt

prompt Below is a dump of the core Instance Statistics that are greater than 0.

prompt Although there are a great many statistics listed, the ones of greatest

prompt value are displayed in other formats throughout this report. Of interest

prompt here are the values for:

prompt

prompt cumulative logons

prompt (# of actual connections to the DB since last startup – good volume-of-use

prompt statistic)

prompt

prompt #93 table fetch continued row

prompt (# of chained rows – will be higher if there are a lot of long fields – if the

prompt value goes up over time, it is a good signaller of general database

prompt fragmentation)

prompt

select statistic#, name, value

from v$sysstat

where value > 0

/

prompt

prompt ——————————————————————————–

set pages 66;

set space 3;

set heading on;

prompt

prompt Parse Ratio usually falls between 1.15 and 1.45. If it is higher, then

prompt it is usually a sign of poorly written Pro* programs or unoptimized

prompt SQL*Forms applications.

prompt

prompt Recursive Call Ratio will usually be between

prompt

prompt 7.0 – 10.0 for tuned production systems

prompt 10.0 – 14.5 for tuned development systems

prompt

prompt Buffer Hit Ratio is dependent upon RDBMS size, SGA size and

prompt the types of applications being processed. This shows the %-age

prompt of logical reads from the SGA as opposed to total reads – the

prompt figure should be as high as possible. The hit ratio can be raised

prompt by increasing DB_BUFFERS, which increases SGA size. By turning on

prompt the “Virtual Buffer Manager” (db_block_lru_statistics = TRUE and

prompt db_block_lru_extended_statistics = TRUE in the init.ora parameters),

prompt you can determine how many extra hits you would get from memory as

prompt opposed to physical I/O from disk. **NOTE: Turning these on will

prompt impact performance. One shift of statistics gathering should be enough

prompt to get the required information.

prompt

ttitle left ‘Ratios for this Instance’ skip 2

column pcc heading ‘Parse|Ratio’ format 99.99

column rcc heading ‘Recsv|Cursr’ format 99.99

column hr heading ‘Buffer|Ratio’ format 999,999,999.999

column rwr heading ‘Rd/Wr|Ratio’ format 999,999.9

column bpfts format 999,999 heading ‘Blks per|Full TS’

REM Modified for O7.1 to reverse ‘cumulative opened cursors’ to

REM ‘opened cursors cumulative’

REM was:sum(decode(a.name,’cumulative opened cursors’,value,.00000000001)) pcc,

REM and:sum(decode(a.name,’cumulative opened cursors’,value,.00000000001)) rcc,

select

sum(decode(a.name,’parse count’,value,0)) /

sum(decode(a.name,’opened cursors cumulative’,value,.00000000001)) pcc,

sum(decode(a.name,’recursive calls’,value,0)) /

sum(decode(a.name,’opened cursors cumulative’,value,.00000000001)) rcc,

(1-(sum(decode(a.name,’physical reads’,value,0)) /

sum(decode(a.name,’db block gets’,value,.00000000001)) +

sum(decode(a.name,’consistent gets’,value,0))) * (-1)) hr,

sum(decode(a.name,’physical reads’,value,0)) /

sum(decode(a.name,’physical writes’,value,.00000000001)) rwr,

(sum(decode(a.name,’table scan blocks gotten’,value,0)) –

sum(decode(a.name,’table scans (short tables)’,value,0)) * 4) /

sum(decode(a.name,’table scans (long tables)’,value,.00000000001)) bpfts

from v$sysstat a

/

prompt

prompt ——————————————————————————–

prompt This looks at overall i/o activity against individual files within a

prompt tablespace

prompt

prompt Look for a mismatch across disk drives in terms of I/O

prompt

prompt Also, examine the Blocks per Read Ratio for heavily accessed

prompt TSs – if this value is significantly above 1 then you may have

prompt full tablescans occurring (with multi-block I/O)

prompt

prompt If activity on the files is unbalanced, move files around to balance

prompt the load. Should see an approximately even set of numbers across files.

prompt

set pagesize 100;

set space 1

column pbr format 99999999 heading ‘Physical|Blk Read’

column pbw format 999999 heading ‘Physical|Blks Wrtn’

column pyr format 999999 heading ‘Physical|Reads’

column readtim format 99999999 heading ‘Read|Time’

column name format a40 heading ‘DataFile Name’

column writetim format 99999999 heading ‘Write|Time’

ttitle center ‘Tablespace Report’ skip 2

compute sum of f.phyblkrd, f.phyblkwrt on report

rem

select fs.name name,f.phyblkrd pbr,f.phyblkwrt pbw,f.readtim, f.writetim

from v$filestat f, v$datafile fs

where f.file# = fs.file#

order by fs.name

/

prompt

prompt ——————————————————————————–

prompt GENERATING WAIT STATISTICS:

prompt

prompt This will show wait stats for certain kernel instances. This may show

prompt the need for additional rbs, wait lists, db_buffers

prompt

ttitle center ‘Wait Statistics for the Instance’ skip 2

column class heading ‘Class Type’

column count format 99,999,999 heading ‘Times Waited’

column time heading ‘Total Times’ format 99,999,999

select class, count, time

from v$waitstat

where count > 0

order by class

/

prompt

prompt Look at the wait statistics generated above (if any). They will

prompt tell you where there is contention in the system. There will

prompt usually be some contention in any system – but if the ratio of

prompt waits for a particular operation starts to rise, you may need to

prompt add additional resource, such as more database buffers, log buffers,

prompt or rollback segments

prompt

prompt ——————————————————————————–

prompt ROLLBACK STATISTICS:

prompt

ttitle off;

set linesize 132

column extents format 999 heading ‘Extents’

column rssize format 999,999,999 heading ‘Size in|Bytes’

column optsize format 999,999,999 heading ‘Optimal|Size’

column hwmsize format 99,999,999 heading ‘High Water|Mark’

column shrinks format 9,999 heading ‘Number of|Shrinks’

column wraps format 9,999 heading ‘Number of|Wraps’

column extends format 999,999 heading ‘Number of|Extends’

column aveactive format 999,999,999 heading ‘Average size|Active Extents’

column rownum noprint

select rssize, optsize, hwmsize, shrinks, wraps, extends, aveactive

from v$rollstat

order by rownum

/

rem

prompt

prompt ——————————————————————————–

set linesize 80

break on report

compute sum of gets waits writes on report

ttitle center ‘Rollback Statistics’ skip 2

select rownum, extents, rssize, xacts, gets, waits, writes

from v$rollstat

order by rownum

/

ttitle off

set heading off

ttitle off

prompt

prompt ——————————————————————————–

prompt

prompt SORT AREA SIZE VALUES:

prompt

prompt To make best use of sort memory, the initial extent of your Users

prompt sort-work Tablespace should be sufficient to hold at least one sort

prompt run from memory to reduce dynamic space allocation. If you are getting

prompt a high ratio of disk sorts as opposed to memory sorts, setting

prompt sort_area_retained_size = 0 in init.ora will force the sort area to be

prompt released immediately after a sort finishes.

prompt

column value format 999,999,999,999

select ‘INIT.ORA sort_area_size: ‘||value

from v$parameter where name like ‘sort_area_size’;

select a.name, value

from v$statname a, v$sysstat

where a.statistic# = v$sysstat.statistic#

and a.name in (‘sorts (disk)’,’sorts (memory)’,’sorts (rows)’)

/

prompt

prompt ——————————————————————————–

set heading on

set space 2

prompt

prompt This looks at Tablespace Sizing – Total bytes and free bytes

prompt

ttitle center ‘Tablespace Sizing Information’ Skip 2

column tablespace_name format a30 heading ‘TS Name’

column sbytes format 999,999,999,999 heading ‘Total Bytes’

column fbytes format 9,999,999,999 heading ‘Free Bytes’

column kount format 999 heading ‘Ext’

compute sum of fbytes on tablespace_name

compute sum of sbytes on tablespace_name

compute sum of sbytes on report

compute sum of fbytes on report

break on report

rem Here must grant select on DBA_FREE_SPACE directly to the

rem creator of this view, else error occurs indicating that you cannot create

rem view using role privs

create or replace view sum_tbsp_free as

select sum(bytes) bytes, count(bytes) num_chks, tablespace_name

from sys.dba_free_space

group by tablespace_name

/

rem kept Marlene’s query, just substituted the view for DBA_FREE_SPACE and

rem removed SUMS/COUNT verb from associated attributes

rem group by using “b” items works because of 1-to-1 relationship

select a.tablespace_name, sum(a.bytes) sbytes, b.bytes fbytes,

b.num_chks kount

from dba_data_files a, sum_tbsp_free b

where a.tablespace_name = b.tablespace_name

group by a.tablespace_name, b.bytes,b.num_chks

order by a.tablespace_name

/

set linesize 80

prompt

prompt A large number of Free Chunks indicates that the tablespace may need

prompt to be defragmented and compressed.

prompt

prompt ——————————————————————————–

set heading off

ttitle off

column value format 99,999,999,999

select ‘Total Physical Reads’, value

from v$sysstat

where statistic# = 39

/

prompt

prompt If you can significantly reduce physical reads by adding incremental

prompt data buffers…do it. To determine whether adding data buffers will

prompt help, set db_block_lru_statistics = TRUE and

prompt db_block_lru_extended_statistics = TRUE in the init.ora parameters.

prompt You can determine how many extra hits you would get from memory as

prompt opposed to physical I/O from disk. **NOTE: Turning these on will

prompt impact performance. One shift of statistics gathering should be enough

prompt to get the required information.

prompt

set heading on

clear computes

ttitle off

prompt

prompt ——————————————————————————–

prompt CHECKING FOR FRAGMENTED DATABASE OBJECTS:

prompt

prompt Fragmentation report – If number of extents is approaching Maxextents,

prompt it is time to defragment the table.

prompt

column owner noprint new_value owner_var

column segment_name format a30 heading ‘Object Name’

column segment_type format a9 heading ‘Table/Indx’

column sum(bytes) format 999,999,999 heading ‘Bytes Used’

column count(*) format 999 heading ‘No.’

break on owner skip page 2

ttitle center ‘Table Fragmentation Report’ skip 2 –

left ‘creator: ‘ owner_var skip 2

select a.owner, segment_name, segment_type, sum(bytes), max_extents, count(*)

from dba_extents a, dba_tables b

where segment_name = b.table_name

having count(*) > 3

group by a.owner, segment_name, segment_type, max_extents

order by a.owner, segment_name, segment_type, max_extents

/

ttitle center ‘Index Fragmentation Report’ skip 2 –

left ‘creator: ‘ owner_var skip 2

select a.owner, segment_name, segment_type, sum(bytes), max_extents, count(*)

from dba_extents a, dba_indexes b

where segment_name = index_name

having count(*) > 3

group by a.owner, segment_name, segment_type, max_extents

order by a.owner, segment_name, segment_type, max_extents

/

prompt

prompt ——————————————————————————–

spool off

exit

****************************************************

File Name : overall_stats.sql

****************************************************

col share_mem format 99999999999.99

col persistent_mem format 99999999999.99

col RUNTIM_MEM format 99999999999.99

select /*+ rule */ sum(sharable_mem)/1024 share_mem ,

sum(persistent_mem)/1024 persistent_mem ,sum(runtime_mem)/1024 runtim_mem ,

sum(sorts) sorts ,sum(executions) exec ,sum(parse_calls) parse ,

sum(disk_reads) disk_reads ,sum(buffer_gets) buffer_gets ,

count(*) cursor_count ,

decode(instr(sql_text,’$ ‘),0,’other users’,’sys (recursive)’)

from sys.v$sqlarea

group by decode(instr(sql_text,’$ ‘),0,’other users’,’sys (recursive)’)

order by decode(instr(sql_text,’$ ‘),0,’other users’,’sys (recursive)’) desc

/

****************************************************

File Name : p2compile.sql

****************************************************

SQL> @gen_compile

SQL> ——————————————————–

SQL> —– This package generates the script for compiling

SQL> —– various objects

SQL> ——————————————————-

SQL> set pages 5000

SQL> select ‘prompt ‘||a.owner||’.’||a.object_name||’ – ‘||a.object_type|| chr(10)||

2 ‘alter ‘||

3 decode(a.object_type,’PACKAGE BODY’,’PACKAGE’,object_type) || ‘ “‘||

4 a.owner||'”.’||a.object_name||’ compile ‘||

5 decode(a.object_type,’PACKAGE BODY’,’BODY;’,’;’)

6 ||decode(a.object_type,’VIEW’,chr(10)||’grant select on “‘||a.owner||'”.’||a.object_name||’ to public ;’, ‘ ‘)

7 from

8 dba_objects a

9 where a.status = ‘INVALID’

10 /

‘PROMPT’||A.OWNER||’.’||A.OBJECT_NAME||’-‘||A.OBJECT_TYPE||CHR(10)||’ALTER’

——————————————————————————–

prompt ATS. ATS_SUPERBASE_LOOKUP_PRE_DEL – TRIGGER

alter TRIGGER “ATS”. ATS_SUPERBASE_LOOKUP_PRE_DEL compile ;

SQL> spool off

****************************************************

File Name : p2compileafterstats.sql

****************************************************

SQL> @gen_compile

SQL> ——————————————————–

SQL> —– This package generates the script for compiling

SQL> —– various objects

SQL> ——————————————————-

SQL> set pages 5000

SQL> select ‘prompt ‘||a.owner||’.’||a.object_name||’ – ‘||a.object_type|| chr(10)||

2 ‘alter ‘||

3 decode(a.object_type,’PACKAGE BODY’,’PACKAGE’,object_type) || ‘ “‘||

4 a.owner||'”.’||a.object_name||’ compile ‘||

5 decode(a.object_type,’PACKAGE BODY’,’BODY;’,’;’)

6 ||decode(a.object_type,’VIEW’,chr(10)||’grant select on “‘||a.owner||'”.’||a.object_name||’ to public ;’, ‘ ‘)

7 from

8 dba_objects a

9 where a.status = ‘INVALID’

10 /

‘PROMPT’||A.OWNER||’.’||A.OBJECT_NAME||’-‘||A.OBJECT_TYPE||CHR(10)||’ALTER’

——————————————————————————–

prompt SYS.DBMS_IJOB – PACKAGE BODY

alter PACKAGE “SYS”.DBMS_IJOB compile BODY;

SQL> spool off

****************************************************

File Name : package_lock.sql

****************************************************

column aa format 999

column serial# format 99999

SELECT sid,

serial#,

a.KGLPNMOD aa,

a.KGLPNREQ,

substr(b.username,1,14),

substr(c.KGLNAOBJ,1,35),

c.KGLOBTYP

FROM x$kglpn a,

v$session b,

x$kglob c

WHERE a.KGLPNUSE = b.saddr

and a.KGLPNHDL = c.KGLHDADR

and c.KGLNAOBJ= upper(‘PKG_UPDATE_WEB_DATA’)

/

****************************************************

File Name : perf.sql

****************************************************

ttitle ‘DATA DICTIONARY CACHE RATIO REPORT’ skip 2

column “Data Dict. Gets” format 999,999,999

column “Data Dict. cache misses” format 999,999,999

column dictcache format 999.99 heading ‘Dictionary Cache Ratio %’

select sum(gets) “Data Dict. Gets”,

sum(getmisses) “Data Dict. cache misses”,

sum(getmisses) / (sum(gets)+0.00000000001) * 100 dictcache

from v$rowcache;

ttitle ‘COMPUTE SUM OF VALUE kbval ON REPORT’ skip 2

column name format a20 heading “SGA Segment”

column value format 999,999,999,990 heading “Size|(Bytes)”

column kbval format 999,999,990.9 heading “Size|(Kb)” break on report

select name, value, round(value/1024,1) kbval

from v$sga;

col f1 format a55 heading ‘Redo Log File Name’

col f2 format 9999 heading ‘Group’

col f3 format a10 heading ‘Status’

ttitle ‘Redo Log File Names Report’ skip 2 break on f2 skip

select GROUP# f2, STATUS f3,

MEMBER f1 from v$logfile

order by GROUP#,MEMBER;

ttitle ‘REDO CONTENTION REPORT’ skip 2

column value format 999,999,999

select substr(name,1,30) Name, value from v$sysstat

where name = ‘redo log space requests’;

ttitle ‘GET WAIT RATIO ROLLBACK REPORT’ skip 2

column “Ratio” format 999.99999999

column name format A15

column “PERCENT”

select name, waits, gets,

100-(waits/gets) “Ratio”, (waits/gets)*100 “PERCENT”

from v$rollstat a, v$rollname b where a.usn = b.usn;

ttitle ‘ROLLBACK GENERAL INFORMATION’ skip 2

select rssize,

optsize, hwmsize, shrinks,

wraps, extends, aveactive

from v$rollstat order by rownum;

ttitle ‘Sorts Disk/Memory’ skip 2

select substr(name,1,30) “Statistic Name”, value

from v$sysstat where name in (‘sorts (memory)’,’sorts (disk)’);

ttitle ‘High water marks report’ skip 2

col event format a37 heading ‘Event’

col total_waits format 99999999 heading ‘Total|Waits’

col time_waited format 9999999999 heading ‘Time Wait|In Hndrds’

col total_timeouts format 999999 heading ‘Timeout’

col average_wait heading ‘Average|Time’ format 999999.999

select * from v$system_event;

column pct heading “Hit Ratio (%)” format 999.9

ttitle ‘Buffer Cache Checks – Goal, above 95%’ skip 2

select ((1- (sum(decode(a.name,’physical reads’,value,0)))/

(sum(decode(a.name,’db block gets’,value,0)) +

sum(decode(a.name,’consistent gets’,value,0)))) * 100) “PERCENT”

from v$sysstat a;

set heading off

column sum_pins format 999,999,999

column sum_reloads format 999,999,999

column hit_ratio format 999.99999

ttitle ‘PINS and Library Cache’ skip 2

select ‘PINS – # of times an item in the library cache was executed – ‘||

sum(pins) sum_pins,

‘RELOADS – # of library cache misses on execution steps – ‘||

sum(reloads) sum_reloads,

‘Pin hit ratio should be close to 1.0 – ‘||

ROUND((sum(reloads)/sum(pins)),6) hit_ratio

from v$librarycache;

ttitle ‘FREE MEMORY IN SHARED POOL REPORT’ skip 2

select name, (bytes/1024/1024) “Free Memory in MB” from v$sgastat

where name = ‘free memory’;

column name format A35

ttitle ‘OBJECTS IN CACHE REPORT’ skip 2

select name,

sharable_mem from v$db_object_cache

where sharable_mem > 10000

and type in (‘PACKAGE’,’PACKAGE BODY’,’FUNCTION’,’PROCEDURE’);

ttitle ‘RELOADS-library cache misses’ skip 2

column libcache format 99.99 heading ‘Library Cache Miss Ratio %’

select sum(pins) “Executes”,

sum(reloads) “Reloads While Executing”,

(sum(reloads)/sum(pins)*100) libcache from v$librarycache;

column name heading “Latch Type” format a25

column pct_miss heading “Misses/Gets (%)” format 999.99999

column pct_immed heading “Immediate Misses/Gets (%)” format 999.99999

ttitle ‘Latch Contention Analysis Report’ skip 2

select n.name,

misses*100/(gets+1) pct_miss,

immediate_misses*100/(immediate_gets+1) pct_immed

from v$latchname n,v$latch l where n.latch# = l.latch#

and n.name in(‘%cache buffer%’,’%protect%’);

ttitle ‘Buffer Contention Specific – PARAMETERS PRINTED IF > 0’ skip 2

select class,count from v$waitstat

where class in (‘data blocks’,’segment header’,

‘undo header’,’undo block’);

ttitle ‘Packages in dba_object_size NOT owned by SYS or SYSTEM’ skip 2

column total_bytes format 9999999 heading ‘Total|Bytes’

column “OBJECT” format A25

column type format A15

select owner || ‘.’ || name OBJECT, type,

to_char(sharable_mem/1024,’9,999.9′) “SPACE(K)”,

loads, executions execs, kept

from v$db_object_cache

where type in (‘FUNCTION’,’PACKAGE’,’PACKAGE BODY’,’PROCEDURE’)

and owner not in (‘SYS’,’SYSTEM’) and kept = ‘NO’

and sharable_mem > 100000 order by owner, name;

****************************************************

File Name : perf_ana.sql

****************************************************

select to_char(measured_date,’MM-DD-YYYY HH24:MI:SS’),a.actual_user,a.active_users,a.total_users,b.user_cpu,

b.system_cpu,b.idle_cpu, RUNQUE_WAITS,CONTEXT_SWITCHES

from stats$totalusers a,stats$vmstat2 b,STATS$USERSESSION c

where a.measured_date=b.start_date

and b.start_date = c.start_date

–and a.measured_date >=to_date(‘20040129001500′,’YYYYMMDDHH24MISS’)

and a.measured_date >= trunc(sysdate)

/

****************************************************

File Name : perf_arthur.sql

****************************************************

col AVG_ACTIVE_USR format 999999.99

col AVG_TOT_USR format 9999.99

col AVG_USR_CPU format 9999.99

col AVG_SYS_CPU format 99.99

col AVG_IDLE_CPU format 99.99

col AVG_WAIT_CPU format 99.99

col TOT_ODR format 99999999

col AVG_ACT_USR format 999999.99

col RUNQ format 999.99

col CSW format 99999.99

select to_char(measured_date,’MM/DD HH24′) “Hour”,min(a.total_users) “Min Tot Usr”, max(a.total_users) “Max Tot Usr”,

avg(a.total_users) AVG_TOT_USR,avg(b.user_cpu) AVG_USR_CPU,min(100-(b.user_cpu+system_CPU)) “MIN IDLE CPU”,

max(100-(b.user_cpu+system_CPU)) “Max IDLE CPU”,avg(100-(b.user_cpu+system_CPU)) “Avg IDLE CPU”,

min(b.user_cpu+system_CPU) “MIN USG CPU”,

max((b.user_cpu+system_CPU)) “Max USG CPU”,avg((b.user_cpu+system_CPU)) “Avg Usg CPU”

from stats$totalusers a,stats$vmstat2 b

where a.measured_date=b.start_date

and a.measured_date >= trunc(sysdate -5)

and a.measured_date <= trunc(sysdate+1)
group by to_char(measured_date, ‘MM/DD HH24’)

/

****************************************************

File Name : perf_hr.sql

****************************************************

col AVG_ACTIVE_USR format 999999.99

col AVG_TOT_USR format 9999.99

col AVG_USR_CPU format 9999.99

col AVG_SYS_CPU format 99.99

col AVG_IDLE_CPU format 99.99

col AVG_WAIT_CPU format 99.99

col TOT_ODR format 99999999

col AVG_ACT_USR format 999999.99

col RUNQ format 999.99

col CSW format 99999.99

select to_char(measured_date,’MM/DD HH24′) “Hour”,avg(a.actual_user) AVG_ACT_USR,avg(a.active_users) AVG_ACTIVE_USR,

avg(a.total_users) AVG_TOT_USR,avg(b.user_cpu) AVG_USR_CPU,avg(RUNQUE_WAITS) RUNQ,avg(CONTEXT_SWITCHES) CSW,

avg(b.system_cpu) AVG_SYS_CPU,avg(b.idle_cpu) AVG_IDLE_CPU,avg(b.wait_cpu) AVG_WAIT_CPU, sum(tot_orders) TOT_ODR

from stats$totalusers a,stats$vmstat2 b,STATS$USERSESSION c

where a.measured_date=b.start_date

and b.start_date = c.start_date

and a.measured_date >=to_date(‘05012003000000′,’MMDDYYYYHH24MISS’)

and a.measured_date <=to_date('05112003595959','MMDDYYYYHH24MISS')
group by to_char(measured_date, ‘MM/DD HH24’)

/

****************************************************

File Name : perf_richm.sql

****************************************************

select /*+ORDERED FIRST_ROWS*/to_char(measured_date,’MM-DD-YYYY HH24:MI:SS’),a.actual_user,a.active_users,a.total_users,b.user_cpu,

b.system_cpu,b.idle_cpu,b.wait_cpu, tot_orders

from stats$totalusers a,stats$vmstat2 b ,STATS$USERSESSION c

where b.start_date between a.measured_date and a.measured_date + 1/8640

and c.start_date between a.measured_date and a.measured_date + 1/8640

and a.measured_date >= to_date(‘20021219130000′,’RRYYMMDDHH24MISS’)

and a.measured_date <= to_date('20021219140000','RRYYMMDDHH24MISS')
/

****************************************************

File Name : perf_viv.sql

****************************************************

select /*+ORDERED FIRST_ROWS*/to_char(measured_date,’MM-DD-YYYY HH24:MI:SS’),a.actual_user,a.active_users,a.total_users,b.user_cpu,

b.system_cpu,b.idle_cpu,b.wait_cpu, tot_orders

from stats$totalusers a,stats$vmstat2 b ,STATS$USERSESSION c

where b.start_date between a.measured_date and a.measured_date + 1/8640

and c.start_date between a.measured_date and a.measured_date + 1/8640

and a.measured_Date >= trunc(sysdate)

— and a.measured_date >=to_date(‘20020502000000′,’YYYYMMDDHH24MISS’)

— and a.measured_date <=to_date('20020512235959','YYYYMMDDHH24MISS')
/

****************************************************

File Name : perf_viv_delete.sql

****************************************************

select /*+ORDERED FIRST_ROWS*/to_char(measured_date,’MM-DD-YYYY HH24:MI:SS’),a.actual_user,a.active_users,a.total_users,b.user_cpu,

b.system_cpu,b.idle_cpu,b.wait_cpu, tot_orders

from stats$totalusers a,stats$vmstat2 b ,STATS$USERSESSION c

where b.start_date = a.measured_date

and c.start_date = a.measured_date

and a.measured_Date >= trunc(sysdate)

— and a.measured_date >=to_date(‘20020502000000′,’YYYYMMDDHH24MISS’)

— and a.measured_date <=to_date('20020512235959','YYYYMMDDHH24MISS')
/

****************************************************

File Name : perfstat.sql

****************************************************

execute perfstat.statspack.snap;

exit;

****************************************************

File Name : phone_ext.sql

****************************************************

alter table ats.ats_phone_Extensions drop constraint ATS_PHONE_EXTENSIONS_PK;

alter table ats.ats_phone_Extensions add (CONSTRAINT ATS_PHONE_EXTENSIONS_PK

PRIMARY KEY ( PHONE_EXTENSION,ACD_NUMBER )

USING INDEX

TABLESPACE MISC_INDEX PCTFREE 10

STORAGE ( INITIAL 1024K NEXT 1024K PCTINCREASE 0 ));

****************************************************

File Name : pid.sql

****************************************************

select spid from v$session a ,v$process b where a.paddr=b.addr and SID = &1

/

****************************************************

File Name : pid_kill.sql

****************************************************

select ‘kill -9 ‘||b.spid from v$session a,v$process b

where a.paddr=b.addr

and a.username = ‘9999’ and a.LAST_CALL_ET >7200

and a.status = ‘INACTIVE’

/

select ‘alter system kill session ‘||””||sid||’,’||serial#||””||’ ;’

from v$session a

where a.username = ‘9999’ and a.LAST_CALL_ET >7200

and a.status = ‘INACTIVE’;

****************************************************

File Name : pin_sga_viv.sql

****************************************************

execute dbms_shared_pool.keep(‘”ATS”.ATS_F_IS_CONROYS’,’p’);

execute dbms_shared_pool.keep(‘”ATS”.TRIG_ORD_ACT_CR_LIMIT’,’r’);

****************************************************

File Name : pinsize.sql

****************************************************

set term off echo off pagesize 60

col Owner format a10

col Name format a40

col Type format a12

col Total_Bytes format 999,999,999

spool pinsize.log

select Owner,

Name,

Type,

Source_Size+Code_Size+Parsed_Size+Error_Size Total_Bytes

from DBA_OBJECT_SIZE

where Type = ‘PACKAGE BODY’

and Owner not in (‘SYS’,’SYSTEM’)

order by Total_Bytes desc

/

spool off

****************************************************

File Name : pkg_order_save1.sql

****************************************************

SQL> @gen_obj_comp

Enter value for 1: pkg_order_save1

old 7: where referenced_name = UPPER(‘&1’)

new 7: where referenced_name = UPPER(‘pkg_order_save1’)

‘PROMPT’||A.OWNER||’.’||A.NAME||’-‘||A.TYPE||CHR(10)||’ALTER’||DECODE(A.TYPE,’PA

——————————————————————————–

prompt 1193.P_INT_ORDER_PROCESS_1 – PROCEDURE

alter PROCEDURE “1193”.P_INT_ORDER_PROCESS_1 compile ;

SQL> spool off

****************************************************

File Name : pq.sql

****************************************************

— The details of a session for a given system process id (spid)

DEFINE spid=’&1′

column spid format 999999

column machine format a16

column osuser format a16

column sid format 9999

column sql_address format a10

column sql_hash_value format 9999999999

column serial# format 999999

column sql_text format a64

select b.spid,

a.machine,

a.process,

a.osuser,

a.sid,

a.serial#,

a.sql_address,

a.sql_hash_value

from v$session a, v$process b

where b.spid = ‘&spid’ and

a.paddr=b.addr

/

select sql_text from v$sqltext c,v$session a, v$process b

where b.spid = ‘&spid’

and a.paddr=b.addr

and hash_value = a.sql_hash_value

and address = a.sql_address

order by piece

/

****************************************************

File Name : pre_ins.sql

****************************************************

CREATE OR REPLACE TRIGGER ACCOUNT_PAYMENTS_PRE_INS_DBT

BEFORE INSERT

ON ATS_ACCOUNT_PAYMENTS

FOR EACH ROW

DECLARE

BEGIN

BEGIN

set_audit_proc(‘I’, :new.usr_crtd, :new.dt_crtd,

:new.usr_mdfd, :new.dt_mdfd);

END;

END;

/

****************************************************

File Name : pre_ins_trig_miss.sql

****************************************************

select table_name from dba_tab_columns where column_name = ‘DT_CRTD’ and owner = ‘ATS’

minus

select distinct table_name from dba_triggers where trigger_name like ‘%PRE_INS%’ and owner = ‘ATS’

order by 1

/

****************************************************

File Name : pre_upd.sql

****************************************************

CREATE OR REPLACE TRIGGER ACCOUNT_PAYMENTS_PRE_UPD_DBT

BEFORE UPDATE

ON ATS_ACCOUNT_PAYMENTS

FOR EACH ROW

DECLARE

BEGIN

BEGIN

set_audit_proc(‘U’, :new.usr_crtd, :new.dt_crtd,

:new.usr_mdfd, :new.dt_mdfd);

END;

END;

/

****************************************************

File Name : proc.sql

****************************************************

— The details of a session for a given system process id (spid)

DEFINE spid=’&1′

column spid format 999999

column machine format a16

column osuser format a16

column sid format 9999

column sql_address format a10

column sql_hash_value format 9999999999

column serial# format 999999

column sql_text format a64

select b.spid,

a.machine,

a.process,

a.osuser,

a.sid,

a.serial#

from v$session a, v$process b

where b.spid = ‘&spid’ and

a.paddr=b.addr

/

****************************************************

File Name : procc.sql

****************************************************

— The details of a session for a given system process id (spid)

DEFINE spid=’&1′

column spid format 999999

column machine format a16

column osuser format a16

column sid format 9999

column sql_address format a10

column sql_hash_value format 9999999999

column serial# format 999999

column sql_text format a64

select b.spid,

a.machine,

a.process,

a.osuser,

a.sid,

a.serial#,

a.sql_address,

a.sql_hash_value

from v$session a, v$process b

where b.spid = ‘&spid’ and

a.paddr=b.addr

/

****************************************************

File Name : procid_kill.sql

****************************************************

select ‘kill -9 ‘||spid from v$session a , v$process b where a.paddr = b.addr and a.status = ‘KILLED’

and a.username <> ‘ ‘;

****************************************************

File Name : psid.sql

****************************************************

— The details of a session for a given system process id (spid)

DEFINE spid=’&1′

column spid format 999999

column machine format a16

column osuser format a16

column sid format 9999

column sql_address format a10

column sql_hash_value format 9999999999

column serial# format 999999

column sql_text format a64

select b.spid,

a.machine,

a.process,

a.osuser,

a.sid,

a.serial#,

a.sql_address,

a.sql_hash_value,

a.program

from v$session a, v$process b

where b.spid = ‘&spid’ and

a.paddr=b.addr

/

****************************************************

File Name : public_synonym_users.sql

****************************************************

select

so.kglnaobj public_synonym,

count(distinct no.kglnaown) users

from

sys.x$kglob so, — synonym object

sys.x$kgldp sd, — synonym dependency

sys.x$kgldp nd, — non-existent dependency

sys.x$kglob no — non-existent object

where

so.inst_id = userenv(‘Instance’) and

sd.inst_id = userenv(‘Instance’) and

nd.inst_id = userenv(‘Instance’) and

no.inst_id = userenv(‘Instance’) and

so.kglnaown = ‘PUBLIC’ and

so.kglobtyp = 5 and — synonym

sd.kglrfhdl = so.kglhdadr and

nd.kglhdadr = sd.kglhdadr and

nd.kglrfhdl = no.kglhdadr and

no.kglobtyp = 0 and — non-existent

no.kglnaobj = so.kglnaobj — same name

group by

so.kglnaobj

order by 2

/

****************************************************

File Name : purge_Tab_lst.sql

****************************************************

column owner format a10 heading ‘Owner’

column table_name format a30 heading ‘Table Name’

column num_rows heading ‘No. of Rows(>1 Mil)’ format 999,999,999,999

column chain_cnt heading ‘Chained Rows’ format 999,999,999,999

select owner,table_name,num_rows,chain_cnt from dba_Tables

where owner in (‘ATS’,’6344′,’5336′)

and num_rows > 1000000

order by 3 desc,4,1,2

/

****************************************************

File Name : qdbadrop.sql

****************************************************

drop TABLE qdba.EVT_CARRIER_CONFIGURATION;

****************************************************

File Name : r.sql

****************************************************

alter rollback segment R26 online;

****************************************************

File Name : ratio.sql

****************************************************

set pages 2000

set lines 132

set head off

select ‘buffer cache hit ratio’,

round((congets.value+dbgets.value-physreads.value)*100/

(congets.value+dbgets.value),4) “HIT RATE”,1

from v$sysstat congets,

v$sysstat dbgets,

v$sysstat physreads

where congets.name=’consistent gets’

and dbgets.name = ‘db block gets’

and physreads.name = ‘physical reads’

/

select ‘recursive calls/total calls’,

(rc.value/(rc.value+uc.value))*100,10

from v$sysstat rc,

v$sysstat uc

where rc.name=’recursive calls’

and uc.name=’user calls’

/

select ‘dictionary cache hit rate’,

sum(gets-getmisses)*100/sum(gets),1

from v$rowcache

/

select ‘short/total table scan ratio’,sc.value/(sc.value+ls.value)*100,

12

from v$sysstat ls,

v$sysstat sc

where sc.name=’table scans (short tables)’

and ls.name=’table scans (long tables)’

/

select ‘disk sort ratio’,ds.value/

decode( (ds.value+ms.value) ,0,1,(ds.value+ms.value))*100

,10

from v$sysstat ds,

v$sysstat ms

where ms.name=’sorts (memory)’

and ds.name=’sorts (disk)’

/

select ‘buffer busy wait ratio’,

(bbw.total_waits*100/(cg.value+dbg.value)),5

from v$system_event bbw,

v$sysstat cg,

v$sysstat dbg

where bbw.event=’buffer busy waits’

and cg.name =’consistent gets’

and dbg.name=’db block gets’

/

select ‘free buffer wait ratio’,

(bbw.total_waits*100/(cg.value+dbg.value)),5

from v$system_event bbw,

v$sysstat cg,

v$sysstat dbg

where bbw.event=’free buffer waits’

and cg.name =’consistent gets’

and dbg.name=’db block gets’

/

select ‘library cache get hit ratio’,

sum(gethits)*100/sum(gets),1

from v$librarycache

/

select ‘library cache pin hit ratio’,

sum(pinhits)*100/sum(pins),1

from v$librarycache

/

select ‘cached cursor efficiency’,(1-(l.gets/s.value))*100,9

from v$librarycache l,

v$sysstat s,

v$parameter p

where l.namespace=’SQL AREA’

and s.name=’parse count’

and p.name=’session_cached_cursors’

and p.value != ‘0’

/

select ‘redo space wait ratio’,

(sw.value)*100/lw.value,9.2

from v$sysstat sw,

v$sysstat lw

where sw.name=’redo log space requests’

and lw.name=’redo writes’

/

select ‘chained fetch ratio’,

rfcr.value*100/(tsrg.value+tfbr.value),6

from v$sysstat rfcr,

v$sysstat tsrg,

v$sysstat tfbr

where rfcr.name=’table fetch continued row’

and tsrg.name=’table scan rows gotten’

and tfbr.name=’table fetch by rowid’

/

select ‘parse/execute’,

pc.value*100/decode(ec.value,0,1,ec.value),9

from v$sysstat ec,

v$sysstat pc

where ec.name=’execute count’

and pc.name=’parse count’;

select ‘CPU parse overhead’,

pc.value*100/decode(ec.value,0,1,ec.value),9

from v$sysstat ec,

v$sysstat pc

where ec.name=’CPU used by this session’

and pc.name=’parse time cpu’;

select ‘Willing to wait latch get rate’,

(sum(gets)-sum(misses))*100/sum(gets),4

from v$latch;

select ‘Immediate latch get rate’,

(sum(immediate_gets)-sum(immediate_misses))*100/

sum(immediate_gets),4

from v$latch;

select ‘rows from idx/total rows’,

(r.value/(r.value+s.value))*100,12

from v$sysstat r,

v$sysstat s

where r.name=’table fetch by rowid’

and s.name=’table scan rows gotten’

;

select ‘blk changes per transctn’,bc.value/t.value,99

from v$sysstat bc,

v$sysstat t

where bc.name=’db block changes’

and t.name=’user commits’

/

select ‘calls per transctn’,c.value/t.value,99

from v$sysstat c,

v$sysstat t

where c.name=’user calls’

and t.name=’user commits’

/

select ‘rows per sort’,r.value/

decode( (d.value+m.value) ,0,1, (d.value+m.value) ) ,99

from v$sysstat r,

v$sysstat d,

v$sysstat m

where r.name=’sorts (rows)’

and d.name=’sorts (disk)’

and m.name=’sorts (memory)’;

select ‘DBWR Avg scan depth’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR summed scan depth’

and dls.name=’DBWR lru scans’

/

select ‘DBWR Avg buffers scanned’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR buffers scanned’

and dls.name=’DBWR lru scans’

/

select ‘DBWR LRU free buffers’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR free buffers found’

and dls.name=’DBWR lru scans’

/

select ‘DBWR summed scan/buffer scan’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’DBWR summed scan depth’

and dls.name=’DBWR buffers scanned’

/

select ‘Dirty list after DBWR write’,

dbs.value/dls.value,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’summed dirty queue length’

and dls.name=’write requests’

/

select ‘Dirty buffers/free buf req %’,

dbs.value/dls.value*100,13

from v$sysstat dbs,

v$sysstat dls

where dbs.name=’dirty buffers inspected’

and dls.name=’free buffer requested’

/

select ‘consistent change ratio’,

(cg.value-cc.value)*100/cg.value,99

from v$sysstat cg,

v$sysstat cc

where cg.name=’consistent gets’

and cc.name=’consistent changes’

/

select ‘enqueue success (no wait)’,

100-(ew.value*100/er.value),8

from v$sysstat ew,

v$sysstat er

where ew.name=’enqueue waits’

and er.name=’enqueue requests’;

select ‘enqueue success (no timeout)’,

100-(ew.value*100/er.value),8

from v$sysstat ew,

v$sysstat er

where ew.name=’enqueue timeouts’

and er.name=’enqueue requests’;

select ‘commits/(commits+rollbacks)’,

(c.value/(r.value+c.value))*100,99

from v$sysstat r,

v$sysstat c

where r.name=’user rollbacks’

and c.name=’user commits’;

select ‘cursors/transaction’,

oc.value/(r.value+c.value),99

from v$sysstat c,

v$sysstat r,

v$sysstat oc

where c.name=’user commits’

and r.name=’user rollbacks’

and oc.name=’cumulative open cursors’;

select ‘free buffer inspects/scan’,

i.value/s.value,7

from v$sysstat s,

v$sysstat i

where i.name=’free buffer inspected’

and r.name=’user rollbacks’

set head on

****************************************************

File Name : ray.sql

****************************************************

set head off feed off

select ‘alter system kill session ‘|| ””||SID||’,’||serial#||””||’ ;’ from v$session

where username = ‘8574’ and status = ‘INACTIVE’

/

set head on feed on

****************************************************

File Name : rbs.sql

****************************************************

alter rollback segment R01 shrink;

****************************************************

File Name : rbssize.sql

****************************************************

set linesize 132

col name format a10

col status format a10

select name, extents, rssize,xacts, gets, waits, optsize, hwmsize,

shrinks, wraps, status from v$rollname a, v$rollstat b

where a.usn=b.usn

/

****************************************************

File Name : real_space.sql

****************************************************

declare

total_blocks number;

total_bytes number;

unused_blocks number;

unused_bytes number;

lue_file_id number;

lue_block_id number;

last_used_block number;

t_name varchar2(30);

ts_name varchar2(50);

hwm number;

n_exts number;

t_free number;

n_ext_bytes number;

l_chunk number;

cursor c is select table_name, tablespace_name, next_extent

from dba_tables

where table_name in (‘ATS_ORDERS’, ‘ATS_MESSAGES’);

cursor d is select index_name, tablespace_name, next_extent

from dba_indexes

where table_name in (‘ATS_ORDERS’, ‘ATS_MESSAGES’);

begin

dbms_output.enable(1000000);

open c;

dbms_output.put_line(‘TABLE_NAME HWM TOTAL_BYTES USED_BYTES NEXT_EXTENT LARGEST_CHUNK TABLESPACE_NAME TS_FREE_SPACE % FREE’);

dbms_output.put_line(‘—————————— ————— ————— ————— ————— ————— —————————– —————– ——-‘);

loop

fetch c into t_name, ts_name, n_ext_bytes;

exit when c%NOTFOUND;

dbms_space.unused_space(‘ATS’,t_name,’TABLE’,total_blocks, total_bytes, unused_blocks, unused_bytes, lue_file_id,

lue_block_id, last_used_block);

select blocks*8192 into hwm

from dba_tables

where table_name = t_name;

select count(*), sum(bytes), max(bytes) into n_exts, t_free, l_chunk

from dba_free_space

where tablespace_name = ts_name;

dbms_output.put_line(rpad(t_name,30, ‘ ‘)||to_char(hwm, ‘999,999,999,999’)||to_char(total_bytes,’999,999,999,999′)

||to_char(total_bytes-unused_bytes,’999,999,999,999′)||to_char(n_ext_bytes, ‘999,999,999,999’)||to_char(l_chunk, ‘999,999,999,999’)

||’ ‘||rpad(ts_name, 30, ‘ ‘)||’ ‘||to_char(t_free, ‘999,999,999,999’)||

to_char((unused_bytes/total_bytes)*100, ‘99.99’));

end loop;

open d;

dbms_output.put_line(chr(0));

dbms_output.put_line(‘INDEX_NAME TOTAL_BYTES USED_BYTES NEXT_EXTENT LARGEST_CHUNK TABLESPACE_NAME TS_FREE_SPACE % FREE’);

dbms_output.put_line(‘—————————— ————— ————— ————— ————— —————————— ————— ——‘);

loop

fetch d into t_name, ts_name, n_ext_bytes;

exit when d%NOTFOUND;

select count(*), sum(bytes), max(bytes) into n_exts, t_free, l_chunk

from dba_free_space

where tablespace_name = ts_name;

dbms_space.unused_space(‘ATS’,t_name,’INDEX’,total_blocks, total_bytes, unused_blocks, unused_bytes, lue_file_id,

lue_block_id, last_used_block);

dbms_output.put_line(rpad(t_name,30, ‘ ‘)||to_char(total_bytes,’999,999,999,999’)

||to_char(total_bytes-unused_bytes,’999,999,999,999′)||to_char(n_ext_bytes, ‘999,999,999,999’)||to_char(l_chunk, ‘999,999,999,999’)||

‘ ‘||rpad(ts_name, 30, ‘ ‘)||to_char(t_free, ‘999,999,999,999’)||to_char((unused_bytes/total_bytes)*100, ‘99.99’));

end loop;

close c;

close d;

end;

/

****************************************************

File Name : real_space3.sql

****************************************************

declare

total_blocks number;

total_bytes number;

unused_blocks number;

unused_bytes number;

lue_file_id number;

lue_block_id number;

last_used_block number;

t_name extgrow.segname%type;

ts_name extgrow.segtbs%type;

hwm number;

t_exts number;

t_own extgrow.segown%type;

n_exts number;

t_free number;

n_ext_bytes number;

l_chunk number;

cursor c is select table_name, dt.owner, dt.tablespace_name, dt.next_extent, extents, dt.blocks

from dba_tables dt, dba_segments ds

where segment_type = ‘TABLE’

and ds.segment_name = dt.table_name

and ds.owner = dt.owner

and dt.owner in (‘ATS’,’1193′,’SHISHIR’,’SATISH’,’BLOOMORA’,’EXPUSER’,’6344′,’NAVEEN’,’CHANDRA’,’BKGR’,’MERCORA’);

cursor d is select index_name, di.owner, di.tablespace_name, di.next_extent, extents

from dba_indexes di, dba_segments ds

where segment_type = ‘INDEX’

and ds.segment_name = di.index_name

and ds.owner = di.owner

and di.owner in (‘ATS’,’1193′,’SHISHIR’,’SATISH’,’BLOOMORA’,’EXPUSER’,’6344′,’NAVEEN’,’CHANDRA’,’BKGR’,’MERCORA’);

begin

open c;

loop

fetch c into t_name, t_own, ts_name, n_ext_bytes, t_exts, hwm;

exit when c%NOTFOUND;

dbms_space.unused_space(t_own,t_name,’TABLE’,total_blocks, total_bytes, unused_blocks, unused_bytes, lue_file_id,

lue_block_id, last_used_block);

hwm := hwm*8192;

select count(*), sum(bytes), max(bytes) into n_exts, t_free, l_chunk

from dba_free_space

where tablespace_name = ts_name;

insert into extgrow (segname, segown, growdate, segtype, segtbs, exts, nextext, tbsfree,

hwm, totbytes, usedbytes, contigfree, freepct, tbsexts)

values (t_name, t_own, to_date(‘&1′,’YYYYMMDD’), ‘TABLE’,ts_name, t_exts, n_ext_bytes, t_free, hwm,

total_bytes, (total_bytes-unused_bytes), l_chunk, (unused_bytes/total_bytes)*100, n_exts);

commit;

end loop;

close c;

open d;

loop

fetch d into t_name, t_own, ts_name, n_ext_bytes, t_exts;

exit when d%NOTFOUND;

select count(*), sum(bytes), max(bytes) into n_exts, t_free, l_chunk

from dba_free_space

where tablespace_name = ts_name;

dbms_space.unused_space(t_own,t_name,’INDEX’,total_blocks, total_bytes, unused_blocks, unused_bytes, lue_file_id,

lue_block_id, last_used_block);

insert into extgrow (segname, segown, growdate, segtype, segtbs, exts, nextext, tbsfree,

hwm, totbytes, usedbytes, contigfree, freepct, tbsexts)

values (t_name, t_own, to_date(‘&1′,’YYYYMMDD’), ‘INDEX’,ts_name, t_exts, n_ext_bytes, t_free, null,

total_bytes, (total_bytes-unused_bytes), l_chunk, (unused_bytes/total_bytes)*100, n_exts);

commit;

end loop;

close d;

end;

/

****************************************************

File Name : rec_idx.sql

****************************************************

select table_name,index_name,tablespace_name,num_rows

from dba_indexes where

(index_name) in

(‘A1_PK’,

‘XPKATS_MERCH_VEND_PDT’)

and owner = ‘ATS’

order by 1,2;

— ‘CRAIG’,’GIFT_GCE_ODR_NUM_IDX’,

— ‘SPLEX’,’SHAREPLEX_ROWIDMAP_I1′,

— ‘SPLEX’,’SHAREPLEX_ROWIDMAP_I2′);

****************************************************

File Name : recent_index.sql

****************************************************

set lines 132

column owner format a10

column segment_name format a50

select distinct b.owner, b.segment_name

from x$bh a, dba_extents b

where

b.file_id=a.dbarfil and

a.dbablk between b.block_id and b.block_id+blocks-1 and

segment_type=’INDEX’ and

b.owner not in (‘SYS’,’SYSTEM’);

****************************************************

File Name : recent_sql.sql

****************************************************

/* Vijay Fernando INTEL CORPORATION */

/* 7th June 2002 */

/* Recent full table scan */

/* Should be run as SYS user */

set serverout on size 1000000

set verify off

col object_name form a30

PROMPT Column flag in x$bh table is set to value 0x80000, when

PROMPT block was read by a sequential scan.

spool recentfulltablescan.lst

SELECT o.object_name,o.object_type,o.owner

FROM dba_objects o,x$bh x

WHERE x.obj=o.object_id

AND o.object_type=’TABLE’

AND standard.bitand(x.flag,524288)>0

AND o.owner<>‘SYS’;

spool off

—————————————

/* Vijay Fernando INTEL CORPORATION */

/* 7th June 2002 */

/* Recently used indexes */

/* Should be run as SYS user */

set serverout on size 1000000

set verify off

column owner format a20 trunc

column segment_name format a30 trunc

spool indexused.lst

select distinct b.owner, b.segment_name

from x$bh a, dba_extents b

where b.file_id=a.dbarfil

and a.dbablk between b.block_id

and b.block_id+blocks-1

and segment_type=’INDEX’ and b.owner not in (‘SYS’,’SYSTEM’)

/

spool off

****************************************************

File Name : reload_pin.sql

****************************************************

select sum(reloads) “Reloads”,

sum(pins) “Executions”,

sum(reloads)*100/sum(pins) “Reload Hit Ratio”

from v$librarycache;

****************************************************

File Name : remove_trace.sh

****************************************************

#!/bin/sh

rm /oracle/app/oracle/admin/800P2/bdump/*.trc 2>/dev/null

****************************************************

File Name : rename_file.sh

****************************************************

#!/bin/sh

# g is the file containing file_name from v$datafile of the source

# 800Lfil is ls -latr /db*/oradata/800L/* |awk ‘{print “$9}’ output

while read line

do

a=`echo $line|awk -F/ ‘{print $4}’`

b=`egrep -i $a 800Lfil`

echo “alter database rename file “”‘”$line”‘” ” to ‘”$b”‘;”

b=” ”

done <"./g" ****************************************************
File Name : rename_file.sql

****************************************************

alter database rename file ‘/ORADATA1/800P/800P_ord_data9.dbf’ to ‘/ORADATA8/800P/800P_ord_data9.dbf’;

****************************************************

File Name : rename_file1.sql

****************************************************

alter database rename file ‘/ORADATA12/800P/800P_temp1_1.dbf’ to ‘/ORADATA1/800P/800P_temp1_1.dbf’;

****************************************************

File Name : renamefile.sql

****************************************************

alter database rename file /ORADATA20/800P/800P_users01.dbf to /ORADATA20/800P/800P_users01.dbf

****************************************************

File Name : renfil.sh

****************************************************

#!/bin/sh

# g is the file containing file_name from v$datafile of the source

# 800Lfil is ls -latr /db*/oradata/800L/* |awk ‘{print “$9}’ output

while read line

do

a=`echo $line|awk -F/ ‘{print $4}’`

b=`egrep -i $a 800Lfil`

echo “alter database rename file “”‘”$line”‘” ” to ‘”$b”‘;”

b=” ”

done <"./g" ****************************************************
File Name : report_run.sql

****************************************************

select sid,username,osuser from v$session where program like ‘%C:ORANTBINR25SRV32.exe%’

and status = ‘ACTIVE’

/

****************************************************

File Name : reserved_pool_hwm.sql

****************************************************

define stopper = 48 — for 7.3

prompt Reserved Pool High-Water-Mark Since Instance Startup

prompt ====================================================

select

sum(r.ksmchsiz) – &stopper reserved_size,

sum(

r.ksmchsiz –

decode(h.kghlunfu, 0, decode(r.indx, 1, r.ksmchsiz, 0), 0)

) – &stopper high_water_mark,

to_char(

100 * (sum(

r.ksmchsiz –

decode(h.kghlunfu, 0, decode(r.indx, 1, r.ksmchsiz, 0), 0)

) – 48

) / (sum(r.ksmchsiz) – &stopper),

‘99999’

) || ‘%’ ” USAGE”

from

sys.x$kghlu h,

sys.x$ksmspr r

/

****************************************************

File Name : reset_password.sql

****************************************************

set term off echo off feedback off verify off

alter user &1 identified by &2

/

exit

****************************************************

File Name : resource_waits.sql

****************************************************

column average_wait format 9999990.00

select

substr(e.event, 1, 40) event,

e.time_waited,

e.time_waited / (

e.total_waits – decode(e.event, ‘latch free’, 0, e.total_timeouts)

) average_wait

from

sys.v$system_event e

where

e.event = ‘buffer busy waits’ or

e.event = ‘enqueue’ or

e.event = ‘free buffer waits’ or

e.event = ‘latch free’ or

e.event = ‘log buffer space’ or

e.event = ‘parallel query qref latch’ or

e.event = ‘pipe put’ or

e.event = ‘write complete waits’ or

e.event like ‘library cache%’ or

e.event like ‘log file switch%’ or

e.event = ‘row cache lock’

union all

select

‘non-routine log file syncs’,

round(e.average_wait * greatest(e.total_waits – s.value, 0)),

e.average_wait

from

sys.v$system_event e,

sys.v$sysstat s

where

e.event = ‘log file sync’ and

s.name = ‘user commits’

order by

2 desc

/

****************************************************

File Name : response.sql

****************************************************

set pages 20000

set lines 132

column “Response” format 999,999,999.99;

column nl newline;

ttitle ‘List Statements in Shared Pool with the Most Disk Reads’

select sql_text nl, ‘Executions=’|| executions nl,

‘Expected Response Time in Seconds= ‘,

disk_reads / decode(executions, 0, 1, executions) / 50 “Response”

from v$sqlarea

where disk_reads / decode(executions,0,1, executions) / 50 > 50

order by executions desc;

****************************************************

File Name : response_time_break.sql

****************************************************

column major format a8

column wait_event format a40 trunc

column seconds format 9999999

column pct justify right

break on major skip 1 on minor

select

substr(n_major, 3) major,

substr(n_minor, 3) minor,

wait_event,

round(time/100) seconds

—- substr(to_char(100 * ratio_to_report(time) over (), ‘99.00’), 2) || ‘%’ pct

from

(

select /*+ ordered use_hash(b) */

‘1 CPU time’ n_major,

decode(t.ksusdnam,

‘redo size’, ‘2 reloads’,

‘parse time cpu’, ‘1 parsing’,

‘3 execution’

) n_minor,

‘n/a’ wait_event,

decode(t.ksusdnam,

‘redo size’, nvl(r.time, 0),

‘parse time cpu’, t.ksusgstv – nvl(b.time, 0),

t.ksusgstv – nvl(b.time, 0) – nvl(r.time, 0)

) time

from

sys.x$ksusgsta t,

(

select /*+ ordered use_nl(s) */ — star query: few rows from d and b

s.ksusestn, — statistic#

sum(s.ksusestv) time — time used by backgrounds

from

sys.x$ksusd d, — statname

sys.x$ksuse b, — session

sys.x$ksbdp p, — background process

sys.x$ksusesta s — sesstat

where

d.ksusdnam in (

‘parse time cpu’,

‘CPU used when call started’) and

b.ksspaown = p.ksbdppro and

s.ksusestn = d.indx and

s.indx = b.indx

group by

s.ksusestn

) b,

(

select /*+ no_merge */

ksusgstv * — parse cpu time *

kglstrld / — SQL AREA reloads /

(1 + kglstget – kglstght) — SQL AREA misses

time

from

sys.x$kglst k,

sys.x$ksusgsta g

where

k.indx = 0 and

g.ksusdnam = ‘parse time cpu’

) r

where

t.ksusdnam in (

‘redo size’, — arbitrary: to get a row to replace

‘parse time cpu’, — with the ‘reload cpu time’

‘CPU used when call started’) and

b.ksusestn (+) = t.indx

union all

select

decode(n_minor,

‘1 normal I/O’, ‘2 disk I/O’,

‘2 full scans’, ‘2 disk I/O’,

‘3 direct I/O’, ‘2 disk I/O’,

‘4 BFILE reads’, ‘2 disk I/O’,

‘5 other I/O’, ‘2 disk I/O’,

‘1 DBWn writes’, ‘3 waits’,

‘2 LGWR writes’, ‘3 waits’,

‘3 ARCn writes’, ‘3 waits’,

‘4 enqueue locks’, ‘3 waits’,

‘5 PCM locks’, ‘3 waits’,

‘6 other locks’, ‘3 waits’,

‘1 commits’, ‘4 latency’,

‘2 network’, ‘4 latency’,

‘3 file ops’, ‘4 latency’,

‘4 process ctl’, ‘4 latency’,

‘5 global locks’, ‘4 latency’,

‘6 misc’, ‘4 latency’

) n_major,

n_minor,

wait_event,

time

from

(

select /*+ ordered use_hash(b) use_nl(d) */

decode(

d.kslednam,

— disk I/O

‘db file sequential read’, ‘1 normal I/O’,

‘db file scattered read’, ‘2 full scans’,

‘BFILE read’, ‘4 BFILE reads’,

‘KOLF: Register LFI read’, ‘4 BFILE reads’,

‘log file sequential read’, ‘5 other I/O’,

‘log file single write’, ‘5 other I/O’,

— resource waits

‘checkpoint completed’, ‘1 DBWn writes’,

‘free buffer waits’, ‘1 DBWn writes’,

‘write complete waits’, ‘1 DBWn writes’,

‘local write wait’, ‘1 DBWn writes’,

‘log file switch (checkpoint incomplete)’, ‘1 DBWn writes’,

‘rdbms ipc reply’, ‘1 DBWn writes’,

‘log file switch (archiving needed)’, ‘3 ARCn writes’,

‘enqueue’, ‘4 enqueue locks’,

‘buffer busy due to global cache’, ‘5 PCM locks’,

‘global cache cr request’, ‘5 PCM locks’,

‘global cache lock cleanup’, ‘5 PCM locks’,

‘global cache lock null to s’, ‘5 PCM locks’,

‘global cache lock null to x’, ‘5 PCM locks’,

‘global cache lock s to x’, ‘5 PCM locks’,

‘lock element cleanup’, ‘5 PCM locks’,

‘checkpoint range buffer not saved’, ‘6 other locks’,

‘dupl. cluster key’, ‘6 other locks’,

‘PX Deq Credit: free buffer’, ‘6 other locks’,

‘PX Deq Credit: need buffer’, ‘6 other locks’,

‘PX Deq Credit: send blkd’, ‘6 other locks’,

‘PX qref latch’, ‘6 other locks’,

‘Wait for credit – free buffer’, ‘6 other locks’,

‘Wait for credit – need buffer to send’, ‘6 other locks’,

‘Wait for credit – send blocked’, ‘6 other locks’,

‘global cache freelist wait’, ‘6 other locks’,

‘global cache lock busy’, ‘6 other locks’,

‘index block split’, ‘6 other locks’,

‘lock element waits’, ‘6 other locks’,

‘parallel query qref latch’, ‘6 other locks’,

‘pipe put’, ‘6 other locks’,

‘rdbms ipc message block’, ‘6 other locks’,

‘row cache lock’, ‘6 other locks’,

‘sort segment request’, ‘6 other locks’,

‘transaction’, ‘6 other locks’,

‘unbound tx’, ‘6 other locks’,

— routine waits

‘log file sync’, ‘1 commits’,

‘name-service call wait’, ‘2 network’,

‘Test if message present’, ‘4 process ctl’,

‘process startup’, ‘4 process ctl’,

‘read SCN lock’, ‘5 global locks’,

decode(substr(d.kslednam, 1, instr(d.kslednam, ‘ ‘)),

— disk I/O

‘direct ‘, ‘3 direct I/O’,

‘control ‘, ‘5 other I/O’,

‘db ‘, ‘5 other I/O’,

— resource waits

‘log ‘, ‘2 LGWR writes’,

‘buffer ‘, ‘6 other locks’,

‘free ‘, ‘6 other locks’,

‘latch ‘, ‘6 other locks’,

‘library ‘, ‘6 other locks’,

‘undo ‘, ‘6 other locks’,

— routine waits

‘SQL*Net ‘, ‘2 network’,

‘BFILE ‘, ‘3 file ops’,

‘KOLF: ‘, ‘3 file ops’,

‘file ‘, ‘3 file ops’,

‘KXFQ: ‘, ‘4 process ctl’,

‘KXFX: ‘, ‘4 process ctl’,

‘PX ‘, ‘4 process ctl’,

‘Wait ‘, ‘4 process ctl’,

‘inactive ‘, ‘4 process ctl’,

‘multiple ‘, ‘4 process ctl’,

‘parallel ‘, ‘4 process ctl’,

‘DFS ‘, ‘5 global locks’,

‘batched ‘, ‘5 global locks’,

‘on-going ‘, ‘5 global locks’,

‘global ‘, ‘5 global locks’,

‘wait ‘, ‘5 global locks’,

‘writes ‘, ‘5 global locks’,

‘6 misc’

)

) n_minor,

d.kslednam wait_event, — event name

i.kslestim – nvl(b.time, 0) time — non-background time

from

sys.x$kslei i, — system events

(

select /*+ ordered use_hash(e) */ — no fixed index on e

e.kslesenm, — event number

sum(e.kslestim) time — time waited by backgrounds

from

sys.x$ksuse s, — sessions

sys.x$ksbdp b, — backgrounds

sys.x$ksles e — session events

where

s.ksspaown = b.ksbdppro and — background session

e.kslessid = s.indx

group by

e.kslesenm

having

sum(e.kslestim) > 0

) b,

sys.x$ksled d

where

i.kslestim > 0 and

b.kslesenm (+) = i.indx and

nvl(b.time, 0) < i.kslestim and
d.indx = i.indx and

d.kslednam not in (

‘Null event’,

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘KXFX: Reply Message Dequeue – Query Coord’,

‘PAR RECOV : Dequeue msg – Slave’,

‘PAR RECOV : Wait for reply – Query Coord’,

‘Parallel Query Idle Wait – Slaves’,

‘PL/SQL lock timer’,

‘PX Deq: Execute Reply’,

‘PX Deq: Execution Msg’,

‘PX Deq: Index Merge Execute’,

‘PX Deq: Index Merge Reply’,

‘PX Deq: Par Recov Change Vector’,

‘PX Deq: Par Recov Execute’,

‘PX Deq: Par Recov Reply’,

‘PX Deq: Parse Reply’,

‘PX Deq: Table Q Get Keys’,

‘PX Deq: Table Q Normal’,

‘PX Deq: Table Q Sample’,

‘PX Deq: Table Q qref’,

‘PX Deq: Txn Recovery Reply’,

‘PX Deq: Txn Recovery Start’,

‘PX Deque wait’,

‘PX Idle Wait’,

‘Replication Dequeue’,

‘Replication Dequeue ‘,

‘SQL*Net message from client’,

‘SQL*Net message from dblink’,

‘debugger command’,

‘parallel query dequeue wait’,

‘pipe get’,

‘queue messages’,

‘secondary event’,

‘single-task message’,

‘slave wait’

) and

d.kslednam not like ‘resmgr:%’

)

)

order by

n_major,

n_minor,

time desc

/

****************************************************

File Name : response_time_breakdown.sql

****************************************************

column major format a8

column minor format a13

column wait_event format a40 trunc

column seconds format 9999999

column pct format a6 justify right

break on major skip 1 on minor

select

substr(n_major, 3) major,

substr(n_minor, 3) minor,

wait_event,

round(time/100) seconds,

substr(to_char(100 * ratio_to_report(time) over (), ‘99.00’), 2) || ‘%’ pct

from

(

select /*+ ordered use_hash(b) */

‘1 CPU time’ n_major,

decode(t.ksusdnam,

‘redo size’, ‘2 reloads’,

‘parse time cpu’, ‘1 parsing’,

‘3 execution’

) n_minor,

‘n/a’ wait_event,

decode(t.ksusdnam,

‘redo size’, nvl(r.time, 0),

‘parse time cpu’, t.ksusgstv – nvl(b.time, 0),

t.ksusgstv – nvl(b.time, 0) – nvl(r.time, 0)

) time

from

sys.x$ksusgsta t,

(

select /*+ ordered use_nl(s) */ — star query: few rows from d and b

s.ksusestn, — statistic#

sum(s.ksusestv) time — time used by backgrounds

from

sys.x$ksusd d, — statname

sys.x$ksuse b, — session

sys.x$ksbdp p, — background process

sys.x$ksusesta s — sesstat

where

d.ksusdnam in (

‘parse time cpu’,

‘CPU used when call started’) and

b.ksspaown = p.ksbdppro and

s.ksusestn = d.indx and

s.indx = b.indx

group by

s.ksusestn

) b,

(

select /*+ no_merge */

ksusgstv * — parse cpu time *

kglstrld / — SQL AREA reloads /

(1 + kglstget – kglstght) — SQL AREA misses

time

from

sys.x$kglst k,

sys.x$ksusgsta g

where

k.indx = 0 and

g.ksusdnam = ‘parse time cpu’

) r

where

t.ksusdnam in (

‘redo size’, — arbitrary: to get a row to replace

‘parse time cpu’, — with the ‘reload cpu time’

‘CPU used when call started’) and

b.ksusestn (+) = t.indx

union all

select

decode(n_minor,

‘1 normal I/O’, ‘2 disk I/O’,

‘2 full scans’, ‘2 disk I/O’,

‘3 direct I/O’, ‘2 disk I/O’,

‘4 BFILE reads’, ‘2 disk I/O’,

‘5 other I/O’, ‘2 disk I/O’,

‘1 DBWn writes’, ‘3 waits’,

‘2 LGWR writes’, ‘3 waits’,

‘3 ARCn writes’, ‘3 waits’,

‘4 enqueue locks’, ‘3 waits’,

‘5 PCM locks’, ‘3 waits’,

‘6 other locks’, ‘3 waits’,

‘1 commits’, ‘4 latency’,

‘2 network’, ‘4 latency’,

‘3 file ops’, ‘4 latency’,

‘4 process ctl’, ‘4 latency’,

‘5 global locks’, ‘4 latency’,

‘6 misc’, ‘4 latency’

) n_major,

n_minor,

wait_event,

time

from

(

select /*+ ordered use_hash(b) use_nl(d) */

decode(

d.kslednam,

— disk I/O

‘db file sequential read’, ‘1 normal I/O’,

‘db file scattered read’, ‘2 full scans’,

‘BFILE read’, ‘4 BFILE reads’,

‘KOLF: Register LFI read’, ‘4 BFILE reads’,

‘log file sequential read’, ‘5 other I/O’,

‘log file single write’, ‘5 other I/O’,

— resource waits

‘checkpoint completed’, ‘1 DBWn writes’,

‘free buffer waits’, ‘1 DBWn writes’,

‘write complete waits’, ‘1 DBWn writes’,

‘local write wait’, ‘1 DBWn writes’,

‘log file switch (checkpoint incomplete)’, ‘1 DBWn writes’,

‘rdbms ipc reply’, ‘1 DBWn writes’,

‘log file switch (archiving needed)’, ‘3 ARCn writes’,

‘enqueue’, ‘4 enqueue locks’,

‘buffer busy due to global cache’, ‘5 PCM locks’,

‘global cache cr request’, ‘5 PCM locks’,

‘global cache lock cleanup’, ‘5 PCM locks’,

‘global cache lock null to s’, ‘5 PCM locks’,

‘global cache lock null to x’, ‘5 PCM locks’,

‘global cache lock s to x’, ‘5 PCM locks’,

‘lock element cleanup’, ‘5 PCM locks’,

‘checkpoint range buffer not saved’, ‘6 other locks’,

‘dupl. cluster key’, ‘6 other locks’,

‘PX Deq Credit: free buffer’, ‘6 other locks’,

‘PX Deq Credit: need buffer’, ‘6 other locks’,

‘PX Deq Credit: send blkd’, ‘6 other locks’,

‘PX qref latch’, ‘6 other locks’,

‘Wait for credit – free buffer’, ‘6 other locks’,

‘Wait for credit – need buffer to send’, ‘6 other locks’,

‘Wait for credit – send blocked’, ‘6 other locks’,

‘global cache freelist wait’, ‘6 other locks’,

‘global cache lock busy’, ‘6 other locks’,

‘index block split’, ‘6 other locks’,

‘lock element waits’, ‘6 other locks’,

‘parallel query qref latch’, ‘6 other locks’,

‘pipe put’, ‘6 other locks’,

‘rdbms ipc message block’, ‘6 other locks’,

‘row cache lock’, ‘6 other locks’,

‘sort segment request’, ‘6 other locks’,

‘transaction’, ‘6 other locks’,

‘unbound tx’, ‘6 other locks’,

— routine waits

‘log file sync’, ‘1 commits’,

‘name-service call wait’, ‘2 network’,

‘Test if message present’, ‘4 process ctl’,

‘process startup’, ‘4 process ctl’,

‘read SCN lock’, ‘5 global locks’,

decode(substr(d.kslednam, 1, instr(d.kslednam, ‘ ‘)),

— disk I/O

‘direct ‘, ‘3 direct I/O’,

‘control ‘, ‘5 other I/O’,

‘db ‘, ‘5 other I/O’,

— resource waits

‘log ‘, ‘2 LGWR writes’,

‘buffer ‘, ‘6 other locks’,

‘free ‘, ‘6 other locks’,

‘latch ‘, ‘6 other locks’,

‘library ‘, ‘6 other locks’,

‘undo ‘, ‘6 other locks’,

— routine waits

‘SQL*Net ‘, ‘2 network’,

‘BFILE ‘, ‘3 file ops’,

‘KOLF: ‘, ‘3 file ops’,

‘file ‘, ‘3 file ops’,

‘KXFQ: ‘, ‘4 process ctl’,

‘KXFX: ‘, ‘4 process ctl’,

‘PX ‘, ‘4 process ctl’,

‘Wait ‘, ‘4 process ctl’,

‘inactive ‘, ‘4 process ctl’,

‘multiple ‘, ‘4 process ctl’,

‘parallel ‘, ‘4 process ctl’,

‘DFS ‘, ‘5 global locks’,

‘batched ‘, ‘5 global locks’,

‘on-going ‘, ‘5 global locks’,

‘global ‘, ‘5 global locks’,

‘wait ‘, ‘5 global locks’,

‘writes ‘, ‘5 global locks’,

‘6 misc’

)

) n_minor,

d.kslednam wait_event, — event name

i.kslestim – nvl(b.time, 0) time — non-background time

from

sys.x$kslei i, — system events

(

select /*+ ordered use_hash(e) */ — no fixed index on e

e.kslesenm, — event number

sum(e.kslestim) time — time waited by backgrounds

from

sys.x$ksuse s, — sessions

sys.x$ksbdp b, — backgrounds

sys.x$ksles e — session events

where

s.ksspaown = b.ksbdppro and — background session

e.kslessid = s.indx

group by

e.kslesenm

having

sum(e.kslestim) > 0

) b,

sys.x$ksled d

where

i.kslestim > 0 and

b.kslesenm (+) = i.indx and

nvl(b.time, 0) < i.kslestim and
d.indx = i.indx and

d.kslednam not in (

‘Null event’,

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘KXFX: Reply Message Dequeue – Query Coord’,

‘PAR RECOV : Dequeue msg – Slave’,

‘PAR RECOV : Wait for reply – Query Coord’,

‘Parallel Query Idle Wait – Slaves’,

‘PL/SQL lock timer’,

‘PX Deq: Execute Reply’,

‘PX Deq: Execution Msg’,

‘PX Deq: Index Merge Execute’,

‘PX Deq: Index Merge Reply’,

‘PX Deq: Par Recov Change Vector’,

‘PX Deq: Par Recov Execute’,

‘PX Deq: Par Recov Reply’,

‘PX Deq: Parse Reply’,

‘PX Deq: Table Q Get Keys’,

‘PX Deq: Table Q Normal’,

‘PX Deq: Table Q Sample’,

‘PX Deq: Table Q qref’,

‘PX Deq: Txn Recovery Reply’,

‘PX Deq: Txn Recovery Start’,

‘PX Deque wait’,

‘PX Idle Wait’,

‘Replication Dequeue’,

‘Replication Dequeue ‘,

‘SQL*Net message from client’,

‘SQL*Net message from dblink’,

‘debugger command’,

‘dispatcher timer’,

‘parallel query dequeue wait’,

‘pipe get’,

‘queue messages’,

‘rdbms ipc message’,

‘secondary event’,

‘single-task message’,

‘slave wait’,

‘virtual circuit status’

) and

d.kslednam not like ‘resmgr:%’

)

)

order by

n_major,

n_minor,

time desc

/

****************************************************

File Name : reval.sql

****************************************************

ttitle off

set pagesize 0 feedback off verify off heading off term off echo off

spool revaldte.sql

select ‘alter ‘||

DECODE(Object_Type,’PACKAGE BODY’,’PACKAGE’,Object_Type)||

‘ ‘||Owner ||’.’|| Object_Name ||’ compile ‘||

DECODE(Object_Type,’PACKAGE BODY’,’BODY’,null)||’;’

from DBA_OBJECTS

where Object_Type in

(‘PROCEDURE’,’PACKAGE’,’FUNCTION’,’TRIGGER’,

‘VIEW’,’PACKAGE BODY’)

and Owner = ‘QDBA’

and Status != ‘VALID’

order by Owner, Object_Type, Object_Name

/

spool off

****************************************************

File Name : revaldte2.sql

****************************************************

alter PACKAGE ATS.ATS_ALL_TELECENTER_MESSAGE_PKG compile BODY;

****************************************************

File Name : revalobj.sql

****************************************************

ttitle off

set pagesize 0 feedback off verify off heading off term off echo off

spool revaldte.sql

select ‘alter ‘||

DECODE(Object_Type,’PACKAGE BODY’,’PACKAGE’,Object_Type)||

‘ ‘||Owner ||’.’|| Object_Name ||’ compile ‘||

DECODE(Object_Type,’PACKAGE BODY’,’BODY’,null)||’;’

from DBA_OBJECTS

where Object_Type in

(‘PROCEDURE’,’PACKAGE’,’FUNCTION’,’TRIGGER’,

‘VIEW’,’PACKAGE BODY’)

and Owner = ‘ATS’

and Status != ‘VALID’

order by Owner, Object_Type, Object_Name

/

spool off

****************************************************

File Name : revalobj2.sql

****************************************************

ttitle off

set pagesize 0 feedback off verify off heading off term off echo off

spool revaldte.sql

select ‘alter ‘||

DECODE(Object_Type,’PACKAGE BODY’,’PACKAGE’,Object_Type)||

‘ ‘||Owner ||’.’|| Object_Name ||’ compile ‘||

DECODE(Object_Type,’PACKAGE BODY’,’BODY’,null)||’;’

from DBA_OBJECTS

where Object_Type in

(‘PROCEDURE’,’PACKAGE’,’FUNCTION’,’TRIGGER’,

‘VIEW’,’PACKAGE BODY’)

and Owner not in (‘SYS,’SYSTEM’)

and Status != ‘VALID’

order by Owner, Object_Type, Object_Name

/

spool off

****************************************************

File Name : rol.sql

****************************************************

select r.name “RBS NAME”,p.pid “Oracle Pid”, p.spid “OS PID”,nvl(p.username,’NO TRansaction’), p.terminal

from v$lock l,v$process p,v$rollname r

where l.sid=p.pid(+)

and trunc(l.id1(+)/65536) = r.usn

and l.type(+) = ‘TX’

and l.lmode(+) = 6

order by r.name

/

****************************************************

File Name : roll_sess.sql

****************************************************

set pages 2000

set linesize 120

set feedback 1

column “RB NAME ” format a10

column “SESSION ID” format 999999

column “USERNAME ” format a10

column “MACHINE ” format a10

SELECT r.name “RB NAME “, s.sid “SESSION ID”,

NVL (s.username, ‘NO TRANSACTION’) “USERNAME”,s.machine “MACHINE”

FROM v$lock l, v$session s, v$rollname r

WHERE l.sid = s.sid(+)

AND TRUNC (l.id1(+)/65536) = r.usn

AND l.type(+) = ‘TX’

AND l.lmode(+) = 6

ORDER BY r.name;

****************************************************

File Name : roll_user.sql

****************************************************

column “RB NAME ” format a10

SELECT r.name “RB NAME “, p.pid “ORACLE PID”,

p.spid “SYSTEM PID “, NVL (p.username, ‘NO TRANSACTION’), p.terminal

FROM v$lock l, v$process p, v$rollname r

WHERE l.sid = p.pid(+)

AND TRUNC (l.id1(+)/65536) = r.usn

AND l.type(+) = ‘TX’

AND l.lmode(+) = 6

ORDER BY r.name;

****************************************************

File Name : rollback_usg.sql

****************************************************

set lines 132

set pages 200

SELECT

E.SID,

substr (A.os_user_name, 1, 8) “OS User”

,substr (A.oracle_username, 1, 8) “Ora User”

,substr (B.owner, 1, 8) “Schema”

,substr (B.object_name, 1, 20) “Object Name”

,substr (B.object_type, 1, 10) “Type”

,substr (C.segment_name, 1, 5) “RBS”

,substr (D.used_urec, 1, 12) “# of Records”

,C.FILE_ID “File #”

,C.BLOCK_ID “Block #”

FROM

v$locked_object A

,dba_objects B

,dba_rollback_segs C

,v$transaction D

,v$session E

WHERE

A.object_id = B.object_id

AND A.xidusn = C.segment_id

AND A.xidusn = D.xidusn

AND A.xidslot = D.xidslot

AND D.addr = E.taddr

–order by 6

order by 7

/

****************************************************

File Name : row.sql

****************************************************

select ‘prompt ‘||a.table_name||’ = ‘ ||Chr(10)||’select count(*) from ‘||a.table_name||’;’

from dba_tables a

where table_name in

(

‘ATS_DAY_END_EXCEPTIONS’,

‘INT_ORDER_ITEMS’

)

order by 1

/

****************************************************

File Name : rpt_file_io.sql

****************************************************

set lines 132

set pages 2000

select

old.tsname,

sum(new.phyrds-old.phyrds) phy_rds,

sum(new.phywrts-old.phywrts) phy_wrts,

sum(new.PHYBLKRD-old.PHYBLKRD) phy_blk_rd,

sum(new.PHYBLKWRT-old.PHYBLKWRT) phy_blk_wrt,

(sum(new.PHYBLKRD-old.PHYBLKRD) + sum(new.PHYBLKWRT-old.PHYBLKWRT)) TOT_IO_BLK

from

perfstat.stats$filestatxs old,

perfstat.stats$filestatxs new

where old.snap_id = 1029

and new.snap_id = 1147

and old.filename = new.filename

and (new.phyrds-old.phyrds) > 0

group by old.tsname

order by 6

;

****************************************************

File Name : runstats.sh

****************************************************

#!/bin/sh

. /oracle/app/oracle/ora800P2.env

echo `date` >>/oracle/app/oracle/admin/logs/runstats.log

sqlplus -s “perfstat/perfstat” << ! >>/oracle/app/oracle/admin/logs/runstats.log

exec statspack.snap

exit

!

****************************************************

File Name : s.sql

****************************************************

SELECT /*+ ORDERED */

rawtohex(b.address) address,

b.sql_text,

b.piece,

a.sid

FROM v$open_cursor a,

v$sqltext_with_newlines b

where a.hash_value= b.hash_value

and a.address=b.address

and a.sid=57

/

****************************************************

File Name : scat_read.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_WHICH_DOING_SCATTERED_READ,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’db file scattered read’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : scat_read_test.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SCATTERED_READ format a110

col Orauser format a10

col Machine format a10

break on Orauser on Machine on KSUSETID on KSUSEPNM

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

c.ksuudlna “Orauser” ,c.KSUSEMNM “Machine”,

c.ksusetid,c.ksusepnm,

b.KGLNAOBJ SQL_WHICH_DOING_SCATTERED_READ

from

x$ksusecst s,

x$ksled e,

x$kglob b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’db file scattered read’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx

/

****************************************************

File Name : scatter_read.sql

****************************************************

select sid, substr(event,1,30),p1,p2,p3 from v$session_wait where event = ‘db file scattered read’

/

****************************************************

File Name : segment_header_summary.sql

****************************************************

set verify off

def ownr = &&1

def segt = &&2

ttitle –

center ‘Segment Extent Summary’ skip 2

col ownr format a8 heading ‘Owner’ justify c

col type format a8 heading ‘Type’ justify c trunc

col name format a28 heading ‘Segment Name’ justify c

col exid format 990 heading ‘Extent#’ justify c

col fiid format 9,990 heading ‘File#’ justify c

col blid format 99,990 heading ‘Block#’ justify c

col blks format 999,990 heading ‘Blocks’ justify c

break on owner –

on segment_name –

on segment_type –

skip 1

select

owner ownr,

segment_name name,

segment_type type,

extent_id exid,

file_id fiid,

block_id blid,

blocks blks

from

dba_extents

where

owner like upper(‘&ownr’)

and

segment_name like upper(‘&segt’)

order by

owner,

segment_name,

extent_id

/

undef ownr

undef segt

set verify on

****************************************************

File Name : seq_read.sql

****************************************************

set lines 132

set pages 2000

col SQL_WHICH_DOING_SEQ_READ format a64 word_wrapped

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

col INDX format 9999 heading “SID”

break on KSUUDLNA on KSUSEUNM on KSUSEMNM on INDX

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */

b.name SQL_WHICH_DOING_SEQ_READ,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM,c.INDX

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’db file sequential read’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : ser.sql

****************************************************

select serial# from V$session where sid = &1

/

****************************************************

File Name : serial.sql

****************************************************

select serial# from v$session where sid=&1

/

****************************************************

File Name : ses.sql

****************************************************

select * from v$session where sid=&1;

****************************************************

File Name : sess_cache_cursor.sql

****************************************************

select

‘session_cached_cursors’ parameter,

lpad(value, 5) value,

decode(value, 0, ‘ n/a’, to_char(100 * used / value, ‘990’) || ‘%’) usage

from

( select

max(s.value) used

from

sys.v$statname n,

sys.v$sesstat s

where

n.name = ‘session cursor cache count’ and

s.statistic# = n.statistic#

),

( select

value

from

sys.v$parameter

where

name = ‘session_cached_cursors’

)

union all

select

‘open_cursors’,

lpad(value, 5),

to_char(100 * used / value, ‘990’) || ‘%’

from

( select

max(sum(s.value)) used

from

sys.v$statname n,

sys.v$sesstat s

where

n.name in (‘opened cursors current’, ‘session cursor cache count’) and

s.statistic# = n.statistic#

group by

s.sid

),

( select

value

from

sys.v$parameter

where

name = ‘open_cursors’

)

/

column cursor_cache_hits format a17

column soft_parses format a11

column hard_parses format a11

select

to_char(100 * sess / calls, ‘999999999990.00’) || ‘%’ cursor_cache_hits,

to_char(100 * (calls – sess – hard) / calls, ‘999990.00’) || ‘%’ soft_parses,

to_char(100 * hard / calls, ‘999990.00’) || ‘%’ hard_parses

from

( select value calls from sys.v$sysstat where name = ‘parse count (total)’ ),

( select value hard from sys.v$sysstat where name = ‘parse count (hard)’ ),

( select value sess from sys.v$sysstat where name = ‘session cursor cache hits’ )

/

****************************************************

File Name : sess_wait_sql.sql

****************************************************

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */ s.indx SID,

e.kslednam EVENT,

b.name SQL_BEING_RUN

/*e.ksledp1 P1TEXT,

s.ksussp1 P1 ,

s.ksussp1r P1RAW,

e.ksledp2 P2TEXT,

s.ksussp2 P2,

s.ksussp2r P2RAW,

e.ksledp3 P3TEXT,

s.ksussp3 P3 ,

s.ksussp3r P3RAW,

s.ksusstim TIME,

s.ksusewtm TIME_WAITED,

decode(s.ksusstim,0,’WAITING’,-2,’WAITED UNKNOWN TIME’,-1,’WAITED SHORT TIME’,’WAITED KNOWN TIME’) STATUS

*/

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam =’enqueue’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : sess_waits.sql

****************************************************

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */ b.name,e.kslednam||'(‘||s.indx||’),(‘||c.KSUUDLNA||’,’||c.KSUSEUNM||’,’||KSUSEMNM||’)’

from x$ksusecst s,x$ksled e,x$kglna b,x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam not like ‘SQL%’ AND E.KSLEDNAM NOT LIKE ‘rdbms%’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : session_cached_cursor.sql

****************************************************

select

‘session_cached_cursors’ parameter,

lpad(value, 5) value,

decode(value, 0, ‘ n/a’, to_char(100 * used / value, ‘990’) || ‘%’) usage

from

( select

max(s.value) used

from

sys.v$statname n,

sys.v$sesstat s

where

n.name = ‘session cursor cache count’ and

s.statistic# = n.statistic#

),

( select

value

from

sys.v$parameter

where

name = ‘session_cached_cursors’

)

union all

select

‘open_cursors’,

lpad(value, 5),

to_char(100 * used / value, ‘990’) || ‘%’

from

( select

max(sum(s.value)) used

from

sys.v$statname n,

sys.v$sesstat s

where

n.name in (‘opened cursors current’, ‘session cursor cache count’) and

s.statistic# = n.statistic#

group by

s.sid

),

( select

value

from

sys.v$parameter

where

name = ‘open_cursors’

)

/

column cursor_cache_hits format a17

column soft_parses format a11

column hard_parses format a11

select

to_char(100 * sess / calls, ‘999999999990.00’) || ‘%’ cursor_cache_hits,

to_char(100 * (calls – sess – hard) / calls, ‘999990.00’) || ‘%’ soft_parses,

to_char(100 * hard / calls, ‘999990.00’) || ‘%’ hard_parses

from

( select value calls from sys.v$sysstat where name = ‘parse count (total)’ ),

( select value hard from sys.v$sysstat where name = ‘parse count (hard)’ ),

( select value sess from sys.v$sysstat where name = ‘session cursor cache hits’ )

/

****************************************************

File Name : session_cursor_cache.sql

****************************************************

column parameter format a29

column value format a5

column usage format a5

select

‘session_cached_cursors’ parameter,

lpad(value, 5) value,

decode(value, 0, ‘ n/a’, to_char(100 * used / value, ‘990’) || ‘%’) usage

from

( select

max(s.value) used

from

sys.v$statname n,

sys.v$sesstat s

where

n.name = ‘session cursor cache count’ and

s.statistic# = n.statistic#

),

( select

value

from

sys.v$parameter

where

name = ‘session_cached_cursors’

)

union all

select

‘open_cursors’,

lpad(value, 5),

to_char(100 * used / value, ‘990’) || ‘%’

from

( select

max(sum(s.value)) used

from

sys.v$statname n,

sys.v$sesstat s

where

n.name in (‘opened cursors current’, ‘session cursor cache count’) and

s.statistic# = n.statistic#

group by

s.sid

),

( select

value

from

sys.v$parameter

where

name = ‘open_cursors’

)

/

column cursor_cache_hits format a17

column soft_parses format a11

column hard_parses format a11

select

to_char(100 * sess / calls, ‘999999999990.00’) || ‘%’ cursor_cache_hits,

to_char(100 * (calls – sess – hard) / calls, ‘999990.00’) || ‘%’ soft_parses,

to_char(100 * hard / calls, ‘999990.00’) || ‘%’ hard_parses

from

( select value calls from sys.v$sysstat where name = ‘parse count (total)’ ),

( select value hard from sys.v$sysstat where name = ‘parse count (hard)’ ),

( select value sess from sys.v$sysstat where name = ‘session cursor cache hits’ )

/

column max_cacheable_cursors format 99999999999999999999

select

max(count(*)) max_cacheable_cursors

from

( select

p.kglobt18 schema# — parsing schema number

from

sys.x$kglcursor p

where

p.kglobt12 > 2 — enough parse_calls

union all

select

s.kglntsnm schema# — authorized schema number

from

sys.x$kglcursor c,

sys.x$kglsn s

where

c.kglobt12 > 2 and

s.kglhdadr = c.kglhdadr

)

group by

schema#

/

****************************************************

File Name : sga_break.sql

****************************************************

select decode(name,’db_block_buffers’,’buffer cache’,

‘sql area’,’sql area’,

‘library cache’,’library cache’,

‘log_buffer’,’log buffer’,

‘fixed_sga’,’fixed sga’,

‘free memory’, ‘free memory’,

‘sessions’,’session memory’,

‘session heap’,’session memory’,

‘dictionary cache’,’dictionary cache’,

‘other shared pool’) name, round(sum(bytes/1024)) kb

from v$sgastat

group by decode(name,’db_block_buffers’,’buffer cache’,

‘sql area’,’sql area’,

‘library cache’,’library cache’,

‘log_buffer’,’log buffer’,

‘fixed_sga’,’fixed sga’,

‘free memory’, ‘free memory’,

‘sessions’,’session memory’,

‘session heap’,’session memory’,

‘dictionary cache’,’dictionary cache’,

‘other shared pool’)

order by decode(name,’free memory’,1,0) , 1

/

****************************************************

File Name : sga_summ.sql

****************************************************

select decode(name,’db_block_buffers’,’buffer cache’,

‘sql area’,’sql area’,

‘library cache’,’library cache’,

‘log_buffer’,’log buffer’,

‘fixed_sga’,’fixed sga’,

‘free memory’, ‘free memory’,

‘sessions’,’session memory’,

‘session heap’,’session memory’,

‘dictionary cache’,’dictionary cache’,

‘other shared pool’) name, round(sum(bytes/1024)) kb

from v$sgastat

group by decode(name,’db_block_buffers’,’buffer cache’,

‘sql area’,’sql area’,

‘library cache’,’library cache’,

‘log_buffer’,’log buffer’,

‘fixed_sga’,’fixed sga’,

‘free memory’, ‘free memory’,

‘sessions’,’session memory’,

‘session heap’,’session memory’,

‘dictionary cache’,’dictionary cache’,

‘other shared pool’)

order by decode(name,’free memory’,1,0) , 1

/

****************************************************

File Name : sh3.sql

****************************************************

alter table ats.ats_int_head_tmp modify (referral_code varchar2(20));

****************************************************

File Name : sh4.sql

****************************************************

alter table ats.ats_int_det_tmp modify (gift varchar2(50), UAMILEAGE varchar2(20));

****************************************************

File Name : shared_lru_stats.sql

****************************************************

column kghlurcr heading “RECURRENT|CHUNKS”

column kghlutrn heading “TRANSIENT|CHUNKS”

column kghlufsh heading “FLUSHED|CHUNKS”

column kghluops heading “PINS AND|RELEASES”

column kghlunfu heading “ORA-4031|ERRORS”

column kghlunfs heading “LAST ERROR|SIZE”

select

kghlurcr,

kghlutrn,

kghlufsh,

kghluops,

kghlunfu,

kghlunfs

from

sys.x$kghlu

/

****************************************************

File Name : shared_pool.sql

****************************************************

SELECT substr(sql_text,1,40) “SQL”,

count(*) , sum(executions) “TotExecs”

FROM v$sqlarea

WHERE executions < 5 GROUP BY substr(sql_text,1,40)
HAVING count(*) > 30 ORDER BY 2 ;

****************************************************

File Name : shared_pool_frag.sql

****************************************************

SET ECHO off TERMOUT off TRIMSPOOL on VERIFY off

col instance new_value V_INSTANCE noprint

select lower(replace(t.instance,chr(0),”)) instance

from v$thread t,

v$parameter p

where p.name = ‘thread’

and t.thread# = to_number(decode(p.value,’0′,’1′,p.value));

spool shared_pool_frag_&&V_INSTANCE

REM ————————————————————————

REM REQUIREMENTS:

REM Must be run as SYS

REM ————————————————————————

REM EXAMPLE:

REM —————————————————-

REM —————————————————-

REM Tuning and Monitoring The Shared Pool

REM —————————————————-

REM —————————————————-

REM

REM —————————————————-

REM Tuning the library cache

REM —————————————————-

REM

REM GetHit PinHit

REM Namespace Gets Ratio Pins Ratio Reloads Invalid.

REM ————— ——– ——- ——- ——- ——- ——–

REM SQL AREA 101795 0.9942 218718 0.9940 116 18

REM TABLE/PROCEDURE 3110 0.8196 3390 0.7658 205 0

REM BODY 54 0.6667 54 0.5926 4 0

REM TRIGGER 1 0.0000 1 0.0000 0 0

REM INDEX 49 0.0000 49 0.0000 0 0

REM CLUSTER 27 0.4444 15 0.3333 0 0

REM OBJECT 0 1.0000 0 1.0000 0 0

REM PIPE 0 1.0000 0 1.0000 0 0

REM

REM

REM —————————————————-

REM Increase the shared_pool_size because of

REM the following:

REM ————————————————–

REM TABLE/PROCEDURE: gethitration is less

REM than 85%: –>.821

REM!!!!I suggest that you increase

REM shared_pool_size!!!!

REM You may suffer from too

REM many reloads in the following areas:

REM —————————————————–

REM TABLE/PROCEDURE: High number

REM of reloads –>.0598

REM !!!!I suggest that you increase

REM shared_pool_size!!!!

REM —————————————————-

REM

REM ————————————————————————

REM DISCLAIMER:

REM This script is provided for educational purposes only. It is NOT

REM supported by Oracle World Wide Technical Support.

REM The script has been tested and appears to work as intended.

REM You should always run new scripts on a test instance initially.

REM ————————————————————————

REM MODIFICATIONS:

REM TGorman 28feb98 some formatting corrections from the original;

REM retrieve SHARED_POOL_RESERVED_MIN_ALLOC to determine

REM the size of a “large object” in the shared pool

REM ————————————————————————

REM Main text of script follows:

set feedback off

set serveroutput on

set pagesize 60

set linesize 79

PROMPT —————————————————–

PROMPT —————————————————–

PROMPT Tuning and Monitoring The Shared Pool

PROMPT —————————————————–

PROMPT —————————————————–

PROMPT

PROMPT —————————————————–

PROMPT Tuning the library cache

PROMPT —————————————————–

column NAMESPACE heading Namespace

column GETS heading Gets

column GETHITRATIO heading GetHit|Ratio format 0.9999

column PINS heading Pins

column PINHITRATIO heading PinHit|Ratio format 0.9999

column RELOADS heading Reloads

column INVALIDATIONS heading Invalid.

select namespace, gets, gethitratio,pins,pinhitratio,reloads,invalidations

from v$librarycache

/

PROMPT

PROMPT

PROMPT —————————————————–

DECLARE

namespace_var v$librarycache.namespace%TYPE;

get_var v$librarycache.gets%TYPE;

pin_var v$librarycache.pins%TYPE;

gethitratio_var v$librarycache.gethitratio%TYPE;

pinhitratio_var v$librarycache.pinhitratio%TYPE;

reloads_var v$librarycache.reloads%TYPE;

printyes BOOLEAN := TRUE;

no_problem_with_libs EXCEPTION;

increase_shared_pool EXCEPTION;

CURSOR lowratio IS

SELECT namespace,gets,pins,gethitratio,pinhitratio

FROM v$librarycache

WHERE gets >1000 AND

pins >1000 AND

gethitratio < 0.85 AND
pinhitratio < 0.85;
BEGIN

OPEN lowratio;

LOOP

FETCH lowratio

INTO namespace_var,get_var,pin_var,

gethitratio_var,pinhitratio_var;

IF (lowratio%NOTFOUND AND (printyes = TRUE)) THEN

RAISE no_problem_with_libs;

ELSIF (lowratio%NOTFOUND AND (printyes = FALSE)) THEN

RAISE increase_shared_pool;

END IF;

/* Print the different fetched values */

IF printyes = TRUE THEN

DBMS_OUTPUT.PUT_LINE(‘Increase the shared_pool_size because of the following:’);

DBMS_OUTPUT.PUT_LINE(‘————————————————–‘);

printyes := FALSE;

END IF;

IF gethitratio_var < 0.85 THEN
DBMS_OUTPUT.PUT_LINE(namespace_var || ‘: gethitration is less than 85%: –>’ || trunc(gethitratio_var,3));

ELSIF pinhitratio_var < 0.85 THEN
DBMS_OUTPUT.PUT_LINE(namespace_var || ‘: pinhitration is less than 85%: –>’ || trunc(pinhitratio_var,3));

END IF;

END LOOP;

CLOSE lowratio;

DBMS_OUTPUT.PUT(‘————————————————–‘);

EXCEPTION

WHEN no_problem_with_libs

THEN

DBMS_OUTPUT.PUT_LINE(‘No problem here with library cache’);

WHEN increase_shared_pool

THEN

DBMS_OUTPUT.PUT_LINE(‘!!!!I suggest that you increase shared_pool_size!!!!’);

END;

/

DECLARE

namespace_var v$librarycache.namespace%TYPE;

pin_var v$librarycache.pins%TYPE;

reloads_var v$librarycache.reloads%TYPE;

printyes BOOLEAN := TRUE;

no_problem_with_reloads EXCEPTION;

increase_shared_pool EXCEPTION;

CURSOR highreloads IS

SELECT namespace,pins,reloads FROM v$librarycache

WHERE pins > 1000;

BEGIN

OPEN highreloads;

printyes := TRUE;

LOOP

FETCH highreloads INTO namespace_var,pin_var,reloads_var;

IF highreloads%NOTFOUND AND (printyes = TRUE) THEN

RAISE no_problem_with_reloads;

ELSIF highreloads%NOTFOUND AND (printyes = FALSE) THEN

RAISE increase_shared_pool;

END IF;

IF reloads_var > 0 and pin_var > 0 and (reloads_var/pin_var) > 0.01 THEN

IF printyes = TRUE THEN

DBMS_OUTPUT.PUT_LINE(‘You may suffer from too many reloads in the following areas:’);

DBMS_OUTPUT.PUT_LINE(‘—————————————————–‘);

printyes := FALSE;

END IF;

DBMS_OUTPUT.PUT_LINE(namespace_var || ‘: High number of reloads –>’ || trunc((reloads_var/pin_var),4));

END IF;

END LOOP;

EXCEPTION

WHEN no_problem_with_reloads

THEN

DBMS_OUTPUT.PUT_LINE(‘No problem here with reloads’);

WHEN increase_shared_pool

THEN

DBMS_OUTPUT.PUT_LINE(‘!!!!I suggest that you increase shared_pool_size!!!!’);

END;

/

set serveroutput off

PROMPT —————————————————–

PROMPT

PROMPT

select sum(pins) Executions, sum(reloads) “Cache Misses while executing”

from v$librarycache;

— How about the data dictionary activity

PROMPT

PROMPT —————————————————-

PROMPT Dictionary cache.

PROMPT The following queries indicate if there are

PROMPT data dictionary cache misses.

PROMPT —————————————————–

PROMPT

select parameter Parameter, trunc(gets/(gets+getmisses),3) “Hit Ratio”

from v$rowcache where gets > 0;

PROMPT

select sum(gets)/(sum(gets)+sum(getmisses)) “Total Hit Ratio” from v$rowcache;

— Watch these values during the day so that these vaules

— don’t show large fluctuations

— A bad hit ratio may be caused by users dropping

— and recreating objects or modifying grants

PROMPT

PROMPT

PROMPT —————————————————–

PROMPT If there is little free memory and the overall hit ratio

PROMPT is below 90%,then increasing the shared pool should help

PROMPT tune the row cache.

PROMPT —————————————————–

PROMPT

select NAME Name, BYTES Bytes from v$sgastat where name in (‘free

memory’,’dictionary cache’);

PROMPT

PROMPT —————————————————–

PROMPT MEMORY FRAGMENTATION

PROMPT The primary problem that occurs is that free memory in the

PROMPT shared pool becomes fragmented into small pieces over time.

PROMPT If you have a database version prior to 7.3 then you might

PROMPT suffer from ORA-4031, out of shared memory.

PROMPT

PROMPT By querying the fixed table X$KSMLRU, you will be able to

PROMPT detect problems fragmentation that are effecting performance,

PROMPT but are not severe enough to cause an ORA-4031.

PROMPT —————————————————–

PROMPT

— OBS This table will erase its contents when being selected from.

— You might want to spool the result even if you are not spooling

— the entire tuning script

— spool x$ksmlru.lst

column KSMLRCOM heading Allocation|Comment format A18

column KSMLRSIZ heading Contig|Memory format 9999999

column KSMLRNUM heading Objs|Flsh format 9999

column KSMLRHON heading Object|Name format A25

define V_SP_RES_MINALLOC=”4400″

REM column value new_value V_SP_RES_MINALLOC noprint

REM select decode(instr(value,’K’),0,to_number(value),to_number(replace(value,’K’,”))*1024)

REM value

REM from v$parameter where name like ‘%shared_pool_reserved_min_alloc’;

select KSMLRCOM, KSMLRSIZ, KSMLRNUM, KSMLRHON

from x$ksmlru where ksmlrsiz > &&V_SP_RES_MINALLOC;

— What large stored objects are in the shared pool?

PROMPT

PROMPT —————————————————–

PROMPT Objects in Shared Pool

PROMPT What large objects are in the shared pool right now,

PROMPT and are they made kept in the pool. Be aware that

PROMPT there may be large PL/SQL objects that are not currently

PROMPT loaded.

PROMPT —————————————————–

PROMPT

column owner heading Owner format a12

column name heading Name format a30

column type Heading Type format a12

column sharable_mem heading “Sharable|Memory” format 999999999

column kept heading “Kept” format a4

set pagesize 60

set feedback off

select owner,name,type,sharable_mem,kept

from v$db_object_cache

where sharable_mem > &&V_SP_RES_MINALLOC

order by owner, name, type;

— Use bind variables to reduce the amount of fragmentation

PROMPT

PROMPT —————————————————–

PROMPT Reduce the number of SQL statements in the shared pool that are

PROMPT duplicates of each other.

PROMPT —————————————————–

PROMPT

select substr(sql_text,1,60) SQL, count(*) copies

from v$sqlarea

group by substr(sql_text,1,60)

having count(*) > 3

order by 1;

PROMPT

PROMPT —————————————————–

PROMPT Sometimes there can be a problem with MAX BIND SIZE from OCI calls,

PROMPT making the sql statement unsharable.

PROMPT —————————————————–

PROMPT

col sql_text format a60 word_wrapped

select sql_text, version_count

from v$sqlarea

where version_count > 5

order by 1;

PROMPT

PROMPT

PROMPT —————————————————–

PROMPT Eliminate large anonymous PL/SQL blocks. (This query will not catch

PROMPT PL/SQL blocks that are not currently in shared pool).

PROMPT You should see the below anonymous PL/SQL blocks

col sql_text format a60 word_wrap

select hash_value, sql_text

from v$sqlarea

where command_type=47

and length(sql_text) > 500

order by 2;

PROMPT

PROMPT —————————————————–

PROMPT LIBRARY CACHE LATCH CONTENTION

PROMPT Another problem that can occur on systems that have a large

PROMPT number of CPUs is contention for the library cache latch. If

PROMPT you have a large number of processes (more than 3 or 4) waiting,

PROMPT then there may be a problem.

PROMPT —————————————————–

PROMPT

select count(*) number_of_waiters

from v$session_wait w, v$latch l

where w.wait_time=0

and w.event = ‘latch free’

and w.p2 = l.latch#

and l.name like ‘library%’;

PROMPT

PROMPT —————————————————–

PROMPT What else is slowing down?

PROMPT —————————————————–

col event format a30 word_wrapped

col p2text format a30 word_wrapped

select sid,event,P2TEXT from v$session_wait

where event != ‘client message’

and upper(event) not like ‘SQL*NET %’

and upper(event) not like ‘% TIMER%’

and wait_time = 0;

PROMPT

PROMPT —————————————————–

PROMPT i) The primary cause of library cache latch contention is

PROMPT fragmentation of the shared pool.

PROMPT ii) Increase sharing. To determine the percentage of sql statement

PROMPT parse calls that find a cursor to share, we introduce the following

PROMPT query. The value below should be greater than 90%

PROMPT —————————————————–

PROMPT

select gethitratio from v$librarycache where namespace = ‘SQL AREA’;

PROMPT

PROMPT —————————————————–

PROMPT iii)Reduce parsing, it often helps to set ‘HOLD_CURSOR=TRUE’ for

PROMPT precompilers.

PROMPT

PROMPT To identify the sql statements that are receiving parse calls

PROMPT Check the following query

PROMPT —————————————————–

PROMPT

col sql_text format a50 word_wrapped

select sql_text, parse_calls,executions,KEPT_VERSIONS from v$sqlarea

where executions < 2* parse_calls; PROMPT
PROMPT —————————————————–

PROMPT To identify the total amount of parsing going on in the system:

PROMPT —————————————————–

PROMPT

select name,value from v$sysstat where name = ‘parse count’;

PROMPT

PROMPT —————————————————–

PROMPT If this value increases at a rate greater than about 10 per second

PROMPT Then you might have problem.

PROMPT Sleep for 10 sec…

PROMPT —————————————————–

PROMPT

execute dbms_lock.sleep(10);

select name,value from v$sysstat where name = ‘parse count’;

PROMPT

PROMPT —————————————————–

PROMPT If the two above values differ by more than 100, you may

PROMPT have a problem

PROMPT

PROMPT Some hints for solving this kind of problem are:

PROMPT 1. CURSOR_SPACE_FOR_TIME

PROMPT 2. SESSION_CACHED_CURSORS

PROMPT 3. Using fully qualified table names

PROMPT —————————————————–

PROMPT

PROMPT

PROMPT

PROMPT —————————————————–

PROMPT SIZING OF SHARED POOL

PROMPT

PROMPT —————————————————–

PROMPT The following provides some guidelines for this

PROMPT OBS These are just guidelines not hard and fast rules.

PROMPT

PROMPT This should be run in a production environment with a very

PROMPT large shared pool

PROMPT

PROMPT Object stored in the shared pool

PROMPT The amount of Shared pool for objects in the db

PROMPT —————————————————–

set serveroutput on

DECLARE

object_mem number;

shared_sql number;

cursor_mem number;

used_pool_size number;

free_mem number;

pool_size varchar2(100);

BEGIN

–Stored objects

select sum(sharable_mem) into object_mem from v$db_object_cache;

— Shared SQL –need to have additional memory if dynamic sql is used

select sum(sharable_mem) into shared_sql from v$sqlarea;

–User Cursor Usage –run this during peak usage

select sum(250*users_opening) into cursor_mem from v$sqlarea;

— Free (unused) memory in the SGA: gives an indication of how much

–is being wasted out of the total allocated

select bytes into free_mem from v$sgastat

where name = ‘free memory’ and pool = ‘shared pool’;

–Add up

used_pool_size := round(1.3*(object_mem+shared_sql+cursor_mem));

select value into pool_size from v$parameter where name = ‘shared_pool_size’;

–Display results

dbms_output.put_line(‘Obj mem: ‘|| to_char(object_mem) || ‘ bytes’);

dbms_output.put_line(‘Shared sql: ‘|| to_char(shared_sql) || ‘ bytes’);

dbms_output.put_line(‘Cursor: ‘|| to_char(cursor_mem) || ‘ bytes’);

dbms_output.put_line(‘Free memory: ‘|| to_char(free_mem) || ‘ bytes ‘ || ‘(‘ || to_char(round(free_mem/1024/1024,2)) || ‘M)’);

dbms_output.put_line(‘Shared pool utilization (total): ‘||

to_char(used_pool_size) || ‘ bytes ‘ || ‘(‘ ||

to_char(round(used_pool_size/1024/1024,2)) || ‘M)’);

dbms_output.put_line(‘Share pool allocation (actual): ‘||

pool_size || ‘ bytes ‘ || ‘(‘ || to_char(round(pool_size/1024/1024,2)) ||

‘M)’);

dbms_output.put_line(‘Percentage Utilized: ‘||

to_char(round(used_pool_size/pool_size*100)) || ‘%’);

END;

/

set serveroutput off

PROMPT —————————————————–

PROMPT —————————————————–

PROMPT The free memory reported in this table is not like free memory reported

PROMPT by O/S statitics. Free memory is more properly thought as ‘waste memory’.

PROMPT You would rather see this value be low than high. In fact, a high value

PROMPT for free memory is sometimes a symptom that a lot of objects been aged

PROMPT out of the shared pool.

PROMPT —————————————————–

PROMPT —————————————————–

spool off

set termout on verify on

****************************************************

File Name : shared_pool_free_lists.sql

****************************************************

select

decode(sign(ksmchsiz – 80), -1, 0, trunc(1/log(ksmchsiz – 15, 2)) – 5)

bucket,

sum(ksmchsiz) free_space,

count(*) free_chunks,

trunc(avg(ksmchsiz)) average_size,

max(ksmchsiz) biggest

from

sys.x$ksmsp

where

ksmchcls = ‘free’

group by

decode(sign(ksmchsiz – 80), -1, 0, trunc(1/log(ksmchsiz – 15, 2)) – 5)

/

****************************************************

File Name : shared_pool_hash.sql

****************************************************

SELECT hash_value, count(*) FROM v$sqlarea GROUP BY hash_value

HAVING count(*) > 5 ;

****************************************************

File Name : shared_pool_lru_stats.sql

****************************************************

column kghlurcr heading “RECURRENT|CHUNKS”

column kghlutrn heading “TRANSIENT|CHUNKS”

column kghlufsh heading “FLUSHED|CHUNKS”

column kghluops heading “PINS AND|RELEASES”

column kghlunfu heading “ORA-4031|ERRORS”

column kghlunfs heading “LAST ERROR|SIZE”

select kghlurcr, kghlutrn, kghlufsh,

kghluops, kghlunfu, kghlunfs

from sys.x$kghlu

where

inst_id = userenv(‘Instance’)

/

****************************************************

File Name : show_depen.sql

****************************************************

set verify offset feed offset lines 200

PROMPT

PROMPT name of object:

ACCEPT name

PROMPT

set termout off

—create table all_dep_tmp AS select * from all_dependencies;

set termout on

spool deps_&name..txt

PROMPT

PROMPT

PROMPT objects referencing &name

PROMPT ===================

SELECT SUBSTR(LPAD(‘ ‘,2*(LEVEL-1))||name,1,50) AS object,type,

owner FROM all_dep_tmp

START WITH referenced_name = REPLACE(UPPER(‘&name’),’ ‘)

CONNECT BY PRIOR name = referenced_name ;

PROMPT

PROMPT

PROMPT objects being referenced by &name

PROMPT ===========================

SELECT SUBSTR(LPAD(‘ ‘,2*(LEVEL-1))||referenced_name,1,50) AS object,

referenced_type AS type,referenced_owner AS owner FROM all_dep_tmp

START WITH name = REPLACE(UPPER(‘&name’),’ ‘)

CONNECT BY PRIOR referenced_name = name ;

PROMPT

PROMPT

spool offset termout off

set termout onset verify onset feed on

/

****************************************************

File Name : shrink.sql

****************************************************

alter rollback segment R01 shrink;

****************************************************

File Name : shutdown_800B.sql

****************************************************

connect internal

spool $ORA_BDUMP/shutdown_800B.log

rem @$SCRIPTS/stopq.sql

shutdown

****************************************************

File Name : shutdown_800P.sql

****************************************************

connect internal

spool $ORA_BDUMP/shutdown_800P.log

@$SCRIPTS/stopq.sql

shutdown

****************************************************

File Name : shutdown_immediate_800B.sql

****************************************************

connect internal

spool $ORA_BDUMP/shutdown_immed_800B.log

rem @$SCRIPTS/stopq.sql

shutdown immediate

****************************************************

File Name : shutdown_immediate_800P.sql

****************************************************

connect internal

spool $ORA_BDUMP/shutdown_immed_800P.log

@$SCRIPTS/stopq.sql

shutdown immediate

****************************************************

File Name : sid.sql

****************************************************

select ‘exec dbms_system.set_ev(‘||SID||’,’||SERIAL#||’,10046,8,’||””||’ ‘||””||’);’

from v$session where sid = &1

/

****************************************************

File Name : sor.sql

****************************************************

—select sid,value from V$sesstat where STATISTIC# in(139,140) and value <> 0

—-order by 2

—/

select sid,value from V$sesstat where STATISTIC# = 163 and value <> 0

order by 2

/

****************************************************

File Name : sort.sql

****************************************************

select v$session.username,sql_text

sid from v$session,v$sort_usage,V$sql c where v$session.SADDR = v$SORT_USAGE.SESSION_ADDR

and v$sort_usage.SQLADDR= c.address

and c.hash_value = v$sort_usage.sqlhash

/

****************************************************

File Name : sort_usage.sql

****************************************************

create or replace view v$_sort_usage_2 (

username,

sid,

session_addr,

session_num,

sqladdr,

sqlhash,

tablespace,

contents,

extents,

blocks,

segfile#,

segblk#,

segrfno#)

as

select username,

sid,

ktssoses,

ktssosno,

prev_sql_addr,

prev_hash_value,

ktssotsn,

decode(ktssocnt,0, ‘PERMANENT’, 1, ‘TEMPORARY’ ),

ktssoexts,

ktssoblks,

KTSSOFNO,

ktssobno,

ktssorfno

from x$ktsso,v$session

where x$ktsso.ktssoses = v$session.saddr

and x$ktsso.ktssosno = v$session.serial#

— and x$ktsso.inst_id = sys_context(‘userenv’,’instance’);

/

rem

rem Could make this v$sort_usage to hide the erroneous view completely

rem

create or replace view v$sort_usage_2 as select * from V$_sort_usage_2;

grant select on v$_sort_usage_2 to public;

create public synonym v$sort_usage_2 for v$sort_usage_2;

****************************************************

File Name : sortsql.sql

****************************************************

select sql_text,(executions-sorts) “Diff” from v$sqlarea where (executions-sorts) < 20 order by 2 ;
****************************************************

File Name : sp_4031.sql

****************************************************

column kghlurcr heading “RECURRENT|CHUNKS”

column kghlutrn heading “TRANSIENT|CHUNKS”

column kghlufsh heading “FLUSHED|CHUNKS”

column kghluops heading “PINS AND|RELEASES”

column kghlunfu heading “ORA-4031|ERRORS”

column kghlunfs heading “LAST ERROR|SIZE”

select

kghlurcr,

kghlutrn,

kghlufsh,

kghluops,

kghlunfu,

kghlunfs

from

sys.x$kghlu

where

inst_id = userenv(‘Instance’)

/

****************************************************

File Name : space_avail.sql

****************************************************

–/*________________________________________________________________________

—

–MODULE NAME : avlspc.sql

—

–SYNOPSIS : sqlplus / @avlspc.sql

—

–DESCRIPTION : This script will produce a report (avlspc.dbname.dt) listing

— of available space in all tablspaces.

—

–Limitations : MUST BE RUN FROM ORACLE DBA ACCOUNT

–_________________________________________________________________________*/

set pages 2000

column Tablespace heading ‘Tablespace|Name’ format a30

column sumb format 999,999,999,999

column extents format 9999

column bytes format 99,999,999,999

column largest format 99,999,999,999

column Tot_Size heading ‘Total|Bytes’ format 999,999,999,999

column Tot_Free heading ‘Free|Bytes’ format 999,999,999,999

column Pct_Free heading ‘Pct|Free’ format 999

column Chunks_Free heading ‘Chunks’ format 99999

column Max_Free heading ‘Biggest|Chunk’ format 9,999,999,999

compute sum of Tot_Free on report

compute sum of Tot_Size on report

column dbname noprint new_value DBName

column dt noprint new_value Dt

set feedback off

select name dbname from v$database;

select to_char(sysdate, ‘MMDDYY’) dt from dual;

set echo off linesize 132

spool /home/oracle/scripts/space_avail.&DBName

PROMPT SPACE AVIALABLE IN TABLESPACES

select a.tablespace_name Tablespace,

sum(a.tots) Tot_Size,

sum(a.sumb) Tot_Free,

sum(a.sumb)*100/sum(a.tots) Pct_Free,

sum(a.largest) Max_Free,

sum(a.chunks) Chunks_Free

from

(

select tablespace_name,

0 tots,sum(bytes) sumb,

max(bytes) largest,

count(*) chunks

from sys.dba_free_space

group by tablespace_name

union

select tablespace_name,

sum(bytes) tots,

0,

0,

0

from sys.dba_data_files

group by tablespace_name) a

group by tablespace_name

having (sum(a.sumb)*100/sum(a.tots)) <25
order by 4 desc

/

PROMPT

PROMPT

PROMPT

spool off

clear breaks

set pagesize 24 feedback on linesize 80 pause off

clear breaks columns

****************************************************

File Name : space_needed.sql

****************************************************

set feedback off

set term off

set pagesize 100

column “Total megs needed” format 999,999.99

column tbs_free format 999,999,999.99

spool $RPT/space_needed.log

select segtbs, in1.tbs_free , sum(nextext)/1024/1024 “Total megs needed”

from ops$oracle.extgrow, (select tablespace_name, sum(bytes)/1024/1024 tbs_free

from dba_free_space

group by tablespace_name) in1

where growdate = (select max(growdate) from ops$oracle.extgrow)

and (totbytes-usedbytes)/(totbytes)*100 < 5
and in1.tablespace_name = segtbs

and totbytes != 0

group by segtbs, tbs_free

order by 3 desc;

spool off

set term on

set feedback on

set pages 80

****************************************************

File Name : space_needed_old.sql

****************************************************

column “Free space” format 999,999,999.99

column “Total megs needed” format 999,999.99

set pagesize 1000

spool $RPT/space_needed.log

select segtbs, tbsfree/1024/1024 “Free space”, sum(nextext)/1024/1024 “Total megs needed”

from ops$oracle.extgrow

where growdate = (select max(growdate) from ops$oracle.extgrow)

and (totbytes-usedbytes)/(totbytes)*100 < 5
group by segtbs, tbsfree

order by 2 desc;

exit;

****************************************************

File Name : spacerpt.sql

****************************************************

set pagesize 50 trimspool on linesize 250 verify off feedback off term off echo off

col segname format a30 heading ‘OBJECT’

col segown format a10 heading ‘OWNER’

col segtype format a5 heading ‘TYPE’

col segtbs format a15 heading ‘TABLESPACE’

col exts format 9999 heading ‘OBJEXTS’

col nextext format 9,999,999,999 heading ‘NEXT EXTENT’

col tbsfree format 9,999,999,999 heading ‘TOTAL TBS FREE’

col hwm format 9,999,999,999 heading ‘HIGHWATER MARK’

col totbytes format 9,999,999,999 heading ‘TOT ALLOC SPC’

col usedbytes format 9,999,999,999 heading ‘USED SPACE’

col contigfree format 9,999,999,999 heading ‘LARGEST FREE’

col freepct format 999.99 heading ‘% FREE’

col tbsexts format 9999 heading ‘TBSEXTS’

compute sum of nextext on segtbs

break on report on segtbs skip 1 on tbsfree on contigfree on tbsexts on segown

select segtbs, tbsfree, contigfree, tbsexts,segown, segname,segtype, hwm, totbytes, usedbytes,

exts, nextext, freepct

from extgrow

where freepct <= &1
and growdate = to_date(‘&2′,’YYYYMMDD’)

and segown like upper(‘%&3%’)

order by segtbs, segown, segname

spool $RPT/spacerpt.log

/

exit

****************************************************

File Name : spacerpt1.sql

****************************************************

set pagesize 50 trimspool on linesize 250 verify off feedback off term off echo off

col segname format a30 heading ‘OBJECT’

col segown format a10 heading ‘OWNER’

col segtype format a5 heading ‘TYPE’

col segtbs format a15 heading ‘TABLESPACE’

col exts format 9999 heading ‘OBJEXTS’

col nextext format 9,999,999,999 heading ‘NEXT EXTENT’

col tbsfree format 9,999,999,999 heading ‘TOTAL TBS FREE’

col hwm format 9,999,999,999 heading ‘HIGHWATER MARK’

col totbytes format 9,999,999,999 heading ‘TOT ALLOC SPC’

col usedbytes format 9,999,999,999 heading ‘USED SPACE’

col contigfree format 9,999,999,999 heading ‘LARGEST FREE’

col freepct format 999.99 heading ‘% FREE’

col tbsexts format 9999 heading ‘TBSEXTS’

compute sum of nextext on segtbs

break on report on segtbs skip 1

select segtbs, segown, segname,totbytes, usedbytes,

nextext, freepct

from extgrow

where freepct <= &1
and growdate = to_date(‘&2′,’YYYYMMDD’)

and segtbs like upper(‘%&3%’)

order by segtbs, segown, segname

spool $RPT/spacerpt.log

/

exit

****************************************************

File Name : spacesum.sql

****************************************************

set pagesize 50 trimspool on linesize 250 verify off feedback off term off echo off

col segtbs format a15 heading ‘TABLESPACE’

col tbsfree format 9,999,999,999 heading ‘TOTAL TBS FREE’

col tbsexts format 9999 heading ‘TBSEXTS’

col totextension format 9,999,999,999 heading ‘TOTAL EXTENSION’

select segtbs, tbsfree, sum(nextext) totextension

from extgrow

where

growdate = to_date(‘&1′,’YYYYMMDD’)

group by segtbs, tbsfree

order by segtbs

spool $RPT/spacesum.log

/

rem exit

****************************************************

File Name : spacesum1.sql

****************************************************

set pagesize 50 trimspool on linesize 250 verify off feedback off term off echo off

set term on echo on

col segtbs format a15 heading ‘TABLESPACE’

col tbsfree format 9,999,999,999 heading ‘TOTAL TBS FREE’

col tbsexts format 9999 heading ‘TBSEXTS’

col totextension format 9,999,999,999 heading ‘TOTAL EXTENSION’

select segtbs, tbsfree, sum(nextext) totextension, (sum(nextext) – tbsfree)

from extgrow

where

growdate = to_date(‘&1′,’YYYYMMDD’)

group by 1, 2, 4

order by segtbs

spool $RPT/spacesum.log

/

rem exit

****************************************************

File Name : spfl.sql

****************************************************

select

decode(

sign(ksmchsiz – 812),

-1, (ksmchsiz – 16) / 4,

decode(

sign(ksmchsiz – 4012),

-1, trunc((ksmchsiz + 11924) / 64),

decode(

sign(ksmchsiz – 65548),

-1, trunc(1/log(ksmchsiz – 11, 2)) + 238,

254

)

)

) bucket,

sum(ksmchsiz) free_space,

count(*) free_chunks,

trunc(avg(ksmchsiz)) average_size,

max(ksmchsiz) biggest

from

sys.x_$ksmsp

where

inst_id = userenv(‘Instance’) and

ksmchcls = ‘free’

group by

decode(

sign(ksmchsiz – 812),

-1, (ksmchsiz – 16) / 4,

decode(

sign(ksmchsiz – 4012),

-1, trunc((ksmchsiz + 11924) / 64),

decode(

sign(ksmchsiz – 65548),

-1, trunc(1/log(ksmchsiz – 11, 2)) + 238,

254

)

)

)

/

****************************************************

File Name : spid.sql

****************************************************

col username format a30

col machine format a20

col program format a40

select a.sid,a.username,a.program,a.machine

from v$session a,V$process b

where a.paddr = b.addr

and b.spid = &1

/

****************************************************

File Name : sq.sql

****************************************************

— The details of a session for a given system process id (sid)

DEFINE sid=’&1′

column machine format a16

column osuser format a16

column sid format 9999

column sql_address format a10

column sql_hash_value format 9999999999

column serial# format 999999

column sql_text format a64

select a.sid,

a.serial#,

a.machine,

a.osuser,

a.sql_address,

a.sql_hash_value

from v$session a

where sid =’&sid’

/

select sql_text from v$sqltext c,v$session a

where a.sid =’&sid’

and hash_value = a.sql_hash_value

and address = a.sql_address

order by piece

/

****************************************************

File Name : sql_by_session.sql

****************************************************

break on address on hashvalue

SELECT /*+ ORDERED */

rawtohex(b.address) address,

b.hash_value hashvalue,

b.sql_text,

b.piece,

a.sid

FROM v$open_cursor a,

v$sqltext_with_newlines b

where a.hash_value= b.hash_value

and a.address=b.address

and a.sid=&1

order by 1,2,4

/

****************************************************

File Name : sql_doing_ft.sql

****************************************************

select sql_text

from V$sql a,

v$sql_plan b

where a.address = b.address

and a.hash_value = b.hash_value

and b.operation = ‘TABLE ACCESS’

and b.options = ‘FULL’

/

****************************************************

File Name : sql_text.sql

****************************************************

select sql_text from v$sql where address = ‘&1’

/

****************************************************

File Name : sqltxt.sql

****************************************************

select sql_text from v$sqltext where address = ‘&1’ order by piece

/

****************************************************

File Name : sread.sql

****************************************************

select /*+ USE_NL(s) use_nl(e) use_nl(b) use_nl(c) */ s.indx SID,

decode(e.kslednam,’enqueue’,’enqueue on object_id (‘||c.KSUSEOBJ||’)of block(‘||c.KSUSEBLK||’)of rowid(‘||c.KSUSESLT||’)’,e.kslednam),

b.name SQL_BEING_RUN,

e.ksledp1 P1TEXT,

s.ksussp1 P1 ,

s.ksussp1r P1RAW,

e.ksledp2 P2TEXT,

s.ksussp2 P2,

s.ksussp2r P2RAW,

e.ksledp3 P3TEXT,

s.ksussp3 P3 ,

s.ksussp3r P3RAW,

s.ksusstim TIME,

s.ksusewtm TIME_WAITED,

decode(s.ksusstim,0,’WAITING’,-2,’WAITED UNKNOWN TIME’,-1,’WAITED SHORT TIME’,’WAITED KNOWN TIME’) STATUS

from

x$ksusecst s,

x$ksled e,

x$kglna b,

x$ksuse c

where bitand(s.ksspaflg,1)!=0 and bitand(s.ksuseflg,1)!=0

and s.ksussseq!=0

and s.ksussopc=e.indx

and e.kslednam not like ‘SQL%’ AND E.KSLEDNAM NOT LIKE ‘rdbms%’

and s.indx=c.indx

and b.KGLHDADR=c.ksusesql

and s.indx=c.indx

order by s.indx,b.piece

/

****************************************************

File Name : startq.sql

****************************************************

execute qdba.q$bgproc.start_driver;

****************************************************

File Name : startup_800B.sql

****************************************************

connect internal

spool $ORA_BDUMP/startup_800B.log

startup

rem @$SCRIPTS/startq.sql

****************************************************

File Name : startup_800P.sql

****************************************************

connect internal

startup mount

@$SCRIPTS/check_backup_mode.sql

@$SCRIPTS/end_backup_mode.sql

alter database open;

@$SCRIPTS/startq.sql

****************************************************

File Name : statsrep.sql

****************************************************

Rem

Rem $Header: statsrep.sql 01-nov-99.14:39:59 cdialeri Exp $

Rem

Rem statsrep.sql

Rem

Rem Copyright (c) Oracle Corporation 1999. All Rights Reserved.

Rem

Rem NAME

Rem statsrep.sql

Rem

Rem DESCRIPTION

Rem SQL*Plus command file to report on differences between

Rem values recorded in two snapshots.

Rem

Rem NOTES

Rem Usually run as the STATSPACK owner, PERFSTAT

Rem

Rem MODIFIED (MM/DD/YY)

Rem cdialeri 11/01/99 – Enhance, 1059172

Rem cgervasi 06/16/98 – Remove references to wrqs

Rem cmlim 07/30/97 – Modified system events

Rem gwood.uk 02/30/94 – Modified

Rem densor.uk 03/31/93 – Modified

Rem cellis.uk 11/15/89 – Created

Rem

clear break compute;

repfooter off;

ttitle off;

btitle off;

set timing off veri off space 1 flush on pause off termout on numwidth 10;

set echo off feedback off pagesize 60 linesize 78 newpage 2;

—

— Get the current database/instance information – this will be used

— later in the report along with bid, eid to lookup snapshots

column inst_num heading “Inst Num” new_value inst_num format 99999;

column inst_name heading “Instance” new_value inst_name format a10;

column db_name heading “DB Name” new_value db_name format a10;

column dbid heading “DB Id” new_value dbid format 9999999999 just c;

select d.dbid dbid

, d.name db_name

, i.instance_number inst_num

, i.instance_name inst_name

from v$database d,

v$instance i;

variable dbid number;

variable inst_num number;

variable inst_name varchar2(20);

variable db_name varchar2(20);

begin

:dbid := &dbid;

:inst_num := &inst_num;

:inst_name := ‘&inst_name’;

:db_name := ‘&db_name’;

end;

/

—

— Ask for the snapshots Id’s which are to be compared

set termout on;

column instart_fmt noprint;

column versn noprint heading ‘Release’ new_value versn;

column host_name noprint heading ‘Host’ new_value host_name;

column para noprint heading ‘OPS’ new_value para;

column level heading ‘Snap Level’;

column snap_id heading ‘SnapId’ format 99999;

column snapdat heading ‘Snap Started’ just c format a22;

column comment heading ‘Comment’ format a60;

break on inst_name on db_name on instart_fmt skip 1;

ttitle lef ‘Completed Snapshots’ skip 2;

accept bid number prompt “Enter beginning Snap Id: “;

accept eid number prompt “Enter ending Snap Id: “;

set termout on;

variable bid number;

variable eid number;

variable versn varchar2(10);

variable para varchar2(9);

variable host_name varchar2(64);

begin

:bid := &bid;

:eid := &eid;

:versn := ‘&versn’;

:para := ‘&para’;

:host_name := ‘&host_name’;

end;

/

—

— Request output file name, or use default and begin spooling

column sp_fil new_value sp_fil noprint;

select ‘st_’||:bid||’_’||:eid sp_fil from dual;

set termout on;

accept spool char prompt “Enter name of output file [&sp_fil] : “;

set termout off;

col spool new_value spool;

select nvl(‘&spool’,’&sp_fil’) spool from dual;

spool &spool;

set termout on;

—

— Verify begin and end snapshot Ids exist for the database, and that

— there wasn’t an instance shutdown in between the two snapshots

— being taken.

set heading off;

select ‘ERROR: Database/Instance does not exist in STATS$DATABASE_INSTANCE’

from dual

where not exists

(select null

from stats$database_instance

where instance_number = :inst_num

and dbid = :dbid);

select ‘ERROR: Begin Snapshot Id specified does not exist for this database/instance’

from dual

where not exists

(select null

from stats$snapshot b

where b.snap_id = :bid

and b.dbid = :dbid

and b.instance_number = :inst_num);

select ‘ERROR: End Snapshot Id specified does not exist for this database/instance’

from dual

where not exists

(select null

from stats$snapshot e

where e.snap_id = :eid

and e.dbid = :dbid

and e.instance_number = :inst_num);

select ‘WARNING: timed_statitics setting changed between begin/end snaps: TIMINGS ARE INVALID’

from dual

where not exists

(select null

from stats$parameter b

, stats$parameter e

where b.snap_id = :bid

and e.snap_id = :eid

and b.dbid = :dbid

and e.dbid = :dbid

and b.instance_number = :inst_num

and e.instance_number = :inst_num

and b.name = e.name

and b.name = ‘timed_statistics’

and b.value = e.value);

select ‘ERROR: Snaps chosen spanned an instance shutdown: RESULTS ARE INVALID’

from dual

where not exists

(select null

from stats$snapshot b

, stats$snapshot e

where b.snap_id = :bid

and e.snap_id = :eid

and b.dbid = :dbid

and e.dbid = :dbid

and b.instance_number = :inst_num

and e.instance_number = :inst_num

and b.startup_time = e.startup_time);

select ‘ERROR: Session statistics are for different sessions: RESULTS ARE INVALID’

from dual

where not exists

(select null

from stats$snapshot b

, stats$snapshot e

where b.snap_id = :bid

and e.snap_id = :eid

and b.dbid = :dbid

and e.dbid = :dbid

and b.instance_number = :inst_num

and e.instance_number = :inst_num

and b.session_id = e.session_id

and b.serial# = e.serial#);

set heading on;

—

—

set newpage 1 space 2 heading on;

—

— Summary Statistics

—

—

— Print database, instance, parallel, release, host and snapshot

— information

prompt

prompt STATSPACK report for

set heading on;

column host_name heading “Host” format a10 print;

column para heading “OPS” format a4 print;

column versn heading “Release” format a10 print;

select :db_name db_name

, :dbid dbid

, :inst_name inst_name

, :inst_num inst_num

, :versn versn

, :para para

, :host_name host_name

from sys.dual;

—

— Print snapshot information

column inst_num noprint

column instart_fmt new_value INSTART_FMT noprint;

column instart new_value instart noprint;

column session_id new_value SESSION noprint;

column ela new_value ELA noprint;

column btim new_value btim heading ‘Start Time’ format a20 just c;

column etim new_value etim heading ‘End Time’ format a20 just c;

column bid heading ‘Start Id’ format 9999990;

column eid heading ‘ End Id’ format 9999990;

column dur heading ‘Snap Length|(Minutes)’ format 999,990.00 just c;

select b.instance_number inst_num

, to_char(b.startup_time, ‘dd-Mon-yy hh24:mi:ss’) instart_fmt

, b.session_id

, round(((e.snap_time – b.snap_time) * 1440 * 60), 0) ela — secs

, b.snap_id bid

, e.snap_id eid

, to_char(b.snap_time, ‘dd-Mon-yy hh24:mi:ss’) btim

, to_char(e.snap_time, ‘dd-Mon-yy hh24:mi:ss’) etim

, round(((e.snap_time – b.snap_time) * 1440 * 60), 0)/60 dur — mins

, to_char(b.startup_time,’YYYYMMDD HH24:MI:SS’) instart

from stats$snapshot b

, stats$snapshot e

where b.snap_id = :bid

and e.snap_id = :eid

and b.dbid = :dbid

and e.dbid = :dbid

and b.instance_number = :inst_num

and e.instance_number = :inst_num

and b.startup_time = e.startup_time

and b.snap_time < e.snap_time;
variable btim varchar2 (20);

variable etim varchar2 (20);

variable ela number;

variable instart varchar2 (18);

begin

:btim := ‘&btim’;

:etim := ‘&etim’;

:ela := &ela;

:instart := ‘&instart’;

end;

/

—

— Call statspack to calculate certain statistics

set heading off;

variable lhtr number;

variable bfwt number;

variable tran number;

variable chng number;

variable ucal number;

variable urol number;

variable rsiz number;

variable phyr number;

variable phyw number;

variable prse number;

variable hprs number;

variable recr number;

variable gets number;

variable rlsr number;

variable rent number;

variable srtm number;

variable srtd number;

variable srtr number;

variable strn number;

variable call number;

variable lhr number;

variable sp varchar2(512);

variable bc varchar2(512);

variable lb varchar2(512);

variable bs varchar2(512);

variable twt number;

begin STATSPACK.STAT_CHANGES

( :bid, :eid — IN arguments

, :lhtr, :bfwt, :tran, :chng, :ucal, :urol, :rsiz, :phyr, :phyw

, :prse, :hprs

, :recr, :gets, :rlsr, :rent, :srtm, :srtd, :srtr, :strn

, :lhr, :bc, :sp, :lb, :bs, :twt

);

:call := :ucal + :recr;

end;

/

—

—

set heading off;

—

— Cache Sizes

prompt

column dscr format a28 newline;

column val format a10 just r;

select ‘Cache Sizes’ dscr

,’~~~~~~~~~~~’ dscr

,’ db_block_buffers:’ dscr, lpad(:bc,10) val

,’ db_block_size:’ dscr, lpad(:bs,10) val

,’ log_buffer:’ dscr, lpad(:lb,10) val

,’ shared_pool_size:’ dscr, lpad(:sp,10) val

from sys.dual;

—

— Load Profile

column dscr format a28 newline;

column val format 999,999,999,990.99;

column sval format 99,990.99;

column totcalls new_value totcalls noprint

select ‘Load Profile’

,’~~~~~~~~~~~~’ dscr

,’ Per Second Per Transaction’

,’ ————— —————‘

,’ Redo size:’ dscr, round(:rsiz/&ela,2) val

, round(:rsiz/:tran,2) val

,’ Logical reads:’ dscr, round(:gets/&ela,2) val

, round(:gets/:tran,2) val

,’ Block changes:’ dscr, round(:chng/&ela,2) val

, round(:chng/:tran,2) val

,’ Physical reads:’ dscr, round(:phyr/&ela,2) val

, round(:phyr/:tran,2) val

,’ Physical writes:’ dscr, round(:phyw/&ela,2) val

, round(:phyw/:tran,2) val

,’ User calls:’ dscr, round(:ucal/&ela,2) val

, round(:ucal/:tran,2) val

,’ Parses:’ dscr, round(:prse/&ela,2) val

, round(:prse/:tran,2) val

,’ Hard parses:’ dscr, round(:hprs/&ela,2) val

, round(:hprs/:tran,2) val

,’ Sorts:’ dscr, round((:srtm+:srtd)/&ela,2) val

, round((:srtm+:srtd)/:tran,2) val

,’ Transactions:’ dscr, round(:tran/&ela,2) val

, ‘ ‘ dscr

,’ Rows per Sort:’ dscr, decode((:srtm+:srtd)

,0,to_number(null)

,round(:srtr/(:srtm+:srtd),2)) sval

,’ Pct Blocks changed / Read:’ dscr, round(100*:chng/:gets,2) sval

,’ Recursive Call Pct:’ dscr, round(100*:recr/:call,2) sval

,’ Rollback / transaction Pct:’ dscr, round(100*:urol/:tran,2) sval

from dual;

—

— Instance Efficiency Percentages

column ldscr format a50

column pctval format 99,990.99;

select ‘Instance Efficiency Percentages (Target 100%)’ ldscr

,’~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~’ ldscr

,’ Buffer Nowait Ratio:’ dscr, round(100*(1-:bfwt/:gets),2) pctval

,’ Buffer Hit Ratio:’ dscr, round(100*(1-:phyr/:gets),2) pctval

,’ Library Hit Ratio:’ dscr, round(100*:lhtr,2) pctval

,’ Redo NoWait Ratio:’ dscr, decode(:rent,0,to_number(null),

round(100*(1-:rlsr/:rent),2)) pctval

,’ In-memory Sort Ratio:’ dscr, decode((:srtm+:srtd),0,to_number(null),

round(100*:srtm/(:srtd+:srtm),2)) pctval

,’ Soft Parse Ratio:’ dscr, round(100*(1-:hprs/:prse),2) pctval

,’ Latch Hit Ratio:’ dscr, round(100*(1-:lhr),2) pctval

from dual;

—

—

set heading on space 1;

repfooter center –

‘————————————————————-‘;

—

— Top Wait Events

col idle noprint;

col event format a44 heading ‘Top 5 Wait Events|~~~~~~~~~~~~~~~~~|Event’;

col waits format 999,999,990 heading ‘Waits’;

col time format 999,999,990 heading ‘Wait|Time (cs)’ just c;

col pctwtt format 999.99 heading ‘% Total|Wt Time’;

select event

, waits

, time

, pctwtt

from (select e.event event

, e.total_waits – nvl(b.total_waits,0) waits

, e.time_waited – nvl(b.time_waited,0) time

, decode(:twt, 0, 0,

100*((e.time_waited – nvl(b.time_waited,0))/:twt)) pctwtt

from stats$system_event b

, stats$system_event e

where b.snap_id = :bid

and e.snap_id = :eid

and b.dbid(+) = :dbid

and e.dbid = :dbid

and b.instance_number (+) = :inst_num

and e.instance_number = :inst_num

and b.event(+) = e.event

and e.total_waits > nvl(b.total_waits,0)

and e.event not in

( select event

from stats$idle_event

)

order by time desc, waits desc

)

where rownum < 6; —
—

prompt

prompt End of Report

prompt

spool off;

set termout off;

clear columns sql;

ttitle off;

btitle off;

repfooter off;

set linesize 78 termout on feedback 6;

—

— End of script file;

****************************************************

File Name : stext.sql

****************************************************

accept val1 prompt “Enter Hash Value:”

select sql_text from v$SQLTEXT_WITH_NEWLINES where hash_value=&val1

order by piece;

****************************************************

File Name : stopq.sql

****************************************************

execute qdba.q$bgproc.stop_driver;

****************************************************

File Name : switch_logfile.sql

****************************************************

alter system switch logfile;

exit

****************************************************

File Name : syn_info.sql

****************************************************

select owner,table_owner from dba_synonyms where synonym_name = upper(‘&1’)

/

****************************************************

File Name : system_event.sql

****************************************************

col CATEGORY format a25

col event format a30

SELECT /*+ ORDERED USE_HASH(EC) CACHE(EC) */

ec.category,

sum(se.total_waits) total_waits,

sum(se.total_timeouts) total_timeouts,

sum(se.time_waited*10) time_waited,

sum(se. average_wait) average_wait

FROM v$system_event se,

iw3_event_categories ec

WHERE se.event=ec.name

AND ec.category<>‘Idle’

GROUP BY ec.category

/

select event,category,total_waits,time_waited,average_wait

from v$system_event a, iw3_event_categories b

where a.event = b.name

and b.category != ‘Idle’

order by 3,2

/

****************************************************

File Name : t.sql

****************************************************

spool t.lst

alter rollback segment R78 storage (optimal 40M);

****************************************************

File Name : t5.sql

****************************************************

select /*+ INDEX (a I_OBJ1) */ name from sys.obj$ a,v$lock b where obj#=id1 and b.type = ‘TM’ ;

****************************************************

File Name : tab.sql

****************************************************

set lines 132

column FREELISTS format 999999

column ma format 9999

column tabl format a30

column owner format a6

select owner,table_name tabl,FREELISTS,INI_TRANS,MAX_TRANS ma,PCT_FREE,BLOCKS,NUM_ROWS

from dba_Tables where table_name = UPPER(‘&1’)

/

****************************************************

File Name : tab_info.sql

****************************************************

column owner format a5

column ini_trans format 999

column freelists format 999

select table_name,TABLESPACE_NAME,owner,BUFFER_POOL,AVG_ROW_LEN,FREELISTS,INI_TRANS

from dba_tables where table_name like upper(‘&1’);

****************************************************

File Name : tabfile.sql

****************************************************

select a.name

from v$datafile a, v$tablespace b

where a.ts# = b.ts# and

b.name = upper(‘&1’)

/

****************************************************

File Name : table_info.sql

****************************************************

select table_name,num_rows,INI_TRANS,FREELISTS,TABLESPACE_NAME from dba_tables where table_name = upper(‘&1’)

/

****************************************************

File Name : table_miss_pre_trig.sql

****************************************************

select table_name from dba_tables where table_name in (select distinct table_name from dba_tab_columns

where owner = ‘ATS’ and (column_name in (‘DT_CRTD’, ‘DT_MDFD’)))

minus

select table_name from dba_triggers where

(owner,trigger_name) in (

select a.owner,a.name

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘SET_AUDIT_PROC’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

and b.objecT_type = ‘TRIGGER’

and b.owner = ‘ATS’

)

group by table_name

order by 1

/

****************************************************

File Name : tar.sql

****************************************************

select version_count,loads,executions,address,hash_value,sql_text

from v$sqlarea where address=’C9054F84′;

select * from

v$sql_shared_cursor where address=’C9054F84′;

select a.address,a.position,a.datatype,a.max_length,a.array_len,a.bind_name

from v$sql_bind_metadata a,

v$sql_Shared_cursor b

where a.address = b.address and KGLHDPAR = ‘C9054F84’ order by 2,3,4;

select * from v$sql

where address=’C9054F84′;

****************************************************

File Name : tbs_info.sql

****************************************************

select substr(file_name,1,50),bytes from dba_data_files where tablespace_name = upper(‘&1’);

****************************************************

File Name : tbsmap.sql

****************************************************

set term on echo off verify off

col blksize new_value blksz noprint

col bytes format 999,999,999,999 heading ‘BYTES’

col blks format 999,999,999,999 heading ‘END BLOCK’

col segname format a30 heading ‘SEGMENT NAME’

select value blksize from v$parameter

where name like (‘%db_block_size%’)

/

undefine tablespace_name

col segment_name format a25

select segment_name segname, file_id, block_id, block_id+blocks-1 blks, blocks*&blksz bytes

from dba_extents

where tablespace_name = upper(‘&&tablespace_name’)

union

select ‘****FREE****’ segname, file_id, block_id, block_id+blocks-1 blks, blocks*&blksz bytes

from dba_free_space

where tablespace_name = upper(‘&tablespace_name’)

order by 2,3

/

undefine tablespace_name

****************************************************

File Name : tc.sql

****************************************************

select c.name, count(*)

from v$session a, ats_employees b, ats_telecenters c

where username not in (‘5269′,’5336′,’SHISHIR’,’1193′,’SATISH’,’6344′,’8574′,’CCUSER’,’SUBBU’,’BLOOMORA’,’EXPUSER’,’BKGR’,’ASHISH’,

‘6315’,’9999′,’ATS’)

and a.username = b.epe_Code

and b.tlr_code = c.code

group by c.name

/

****************************************************

File Name : tech.sql

****************************************************

SET ECHO off TERMOUT off TRIMSPOOL on VERIFY off

col instance new_value V_INSTANCE noprint

select lower(replace(t.instance,chr(0),”)) instance

from v$thread t,

v$parameter p

where p.name = ‘thread’

and t.thread# = to_number(decode(p.value,’0′,’1′,p.value));

spool tfsjstat_&&V_INSTANCE

REM NAME: TFSJSTAT.SQL

REM USAGE:”@path/tfsjstat”

REM ————————————————————————

REM REQUIREMENTS:

REM Must be run as SYS

REM ————————————————————————

REM AUTHOR:

REM Mikael Johansson

REM Copyright 1996, Oracle Corporation

REM ————————————————————————

REM PURPOSE:

REM The purpose of this script is to simplify the tuning process

REM of an Oracle7 Database.

REM ————————————————————————

REM EXAMPLE:

REM —————————————————-

REM —————————————————-

REM Tuning and Monitoring The Shared Pool

REM —————————————————-

REM —————————————————-

REM

REM —————————————————-

REM Tuning the library cache

REM —————————————————-

REM

REM GetHit PinHit

REM Namespace Gets Ratio Pins Ratio Reloads Invalid.

REM ————— ——– ——- ——- ——- ——- ——–

REM SQL AREA 101795 0.9942 218718 0.9940 116 18

REM TABLE/PROCEDURE 3110 0.8196 3390 0.7658 205 0

REM BODY 54 0.6667 54 0.5926 4 0

REM TRIGGER 1 0.0000 1 0.0000 0 0

REM INDEX 49 0.0000 49 0.0000 0 0

REM CLUSTER 27 0.4444 15 0.3333 0 0

REM OBJECT 0 1.0000 0 1.0000 0 0

REM PIPE 0 1.0000 0 1.0000 0 0

REM

REM

REM —————————————————-

REM Increase the shared_pool_size because of

REM the following:

REM ————————————————–

REM TABLE/PROCEDURE: gethitration is less

REM than 85%: –>.821

REM!!!!I suggest that you increase

REM shared_pool_size!!!!

REM You may suffer from too

REM many reloads in the following areas:

REM —————————————————–

REM TABLE/PROCEDURE: High number

REM of reloads –>.0598

REM !!!!I suggest that you increase

REM shared_pool_size!!!!

REM —————————————————-

REM

REM ————————————————————————

REM DISCLAIMER:

REM This script is provided for educational purposes only. It is NOT

REM supported by Oracle World Wide Technical Support.

REM The script has been tested and appears to work as intended.

REM You should always run new scripts on a test instance initially.

REM ————————————————————————

REM MODIFICATIONS:

REM TGorman 28feb98 some formatting corrections from the original;

REM retrieve SHARED_POOL_RESERVED_MIN_ALLOC to determine

REM the size of a “large object” in the shared pool

REM ————————————————————————

REM Main text of script follows:

set feedback off

set serveroutput on

set pagesize 60

set linesize 79

PROMPT —————————————————–

PROMPT —————————————————–

PROMPT Tuning and Monitoring The Shared Pool

PROMPT —————————————————–

PROMPT —————————————————–

PROMPT

PROMPT —————————————————–

PROMPT Tuning the library cache

PROMPT —————————————————–

column NAMESPACE heading Namespace

column GETS heading Gets

column GETHITRATIO heading GetHit|Ratio format 0.9999

column PINS heading Pins

column PINHITRATIO heading PinHit|Ratio format 0.9999

column RELOADS heading Reloads

column INVALIDATIONS heading Invalid.

select namespace, gets, gethitratio,pins,pinhitratio,reloads,invalidations

from v$librarycache

/

PROMPT

PROMPT

PROMPT —————————————————–

DECLARE

namespace_var v$librarycache.namespace%TYPE;

get_var v$librarycache.gets%TYPE;

pin_var v$librarycache.pins%TYPE;

gethitratio_var v$librarycache.gethitratio%TYPE;

pinhitratio_var v$librarycache.pinhitratio%TYPE;

reloads_var v$librarycache.reloads%TYPE;

printyes BOOLEAN := TRUE;

no_problem_with_libs EXCEPTION;

increase_shared_pool EXCEPTION;

CURSOR lowratio IS

SELECT namespace,gets,pins,gethitratio,pinhitratio

FROM v$librarycache

WHERE gets >1000 AND

pins >1000 AND

gethitratio < 0.85 AND
pinhitratio < 0.85;
BEGIN

OPEN lowratio;

LOOP

FETCH lowratio

INTO namespace_var,get_var,pin_var,

gethitratio_var,pinhitratio_var;

IF (lowratio%NOTFOUND AND (printyes = TRUE)) THEN

RAISE no_problem_with_libs;

ELSIF (lowratio%NOTFOUND AND (printyes = FALSE)) THEN

RAISE increase_shared_pool;

END IF;

/* Print the different fetched values */

IF printyes = TRUE THEN

DBMS_OUTPUT.PUT_LINE(‘Increase the shared_pool_size because of the following:’);

DBMS_OUTPUT.PUT_LINE(‘————————————————–‘);

printyes := FALSE;

END IF;

IF gethitratio_var < 0.85 THEN
DBMS_OUTPUT.PUT_LINE(namespace_var || ‘: gethitration is less than 85%: –>’ || trunc(gethitratio_var,3));

ELSIF pinhitratio_var < 0.85 THEN
DBMS_OUTPUT.PUT_LINE(namespace_var || ‘: pinhitration is less than 85%: –>’ || trunc(pinhitratio_var,3));

END IF;

END LOOP;

CLOSE lowratio;

DBMS_OUTPUT.PUT(‘————————————————–‘);

EXCEPTION

WHEN no_problem_with_libs

THEN

DBMS_OUTPUT.PUT_LINE(‘No problem here with library cache’);

WHEN increase_shared_pool

THEN

DBMS_OUTPUT.PUT_LINE(‘!!!!I suggest that you increase shared_pool_size!!!!’);

END;

/

DECLARE

namespace_var v$librarycache.namespace%TYPE;

pin_var v$librarycache.pins%TYPE;

reloads_var v$librarycache.reloads%TYPE;

printyes BOOLEAN := TRUE;

no_problem_with_reloads EXCEPTION;

increase_shared_pool EXCEPTION;

CURSOR highreloads IS

SELECT namespace,pins,reloads FROM v$librarycache

WHERE pins > 1000;

BEGIN

OPEN highreloads;

printyes := TRUE;

LOOP

FETCH highreloads INTO namespace_var,pin_var,reloads_var;

IF highreloads%NOTFOUND AND (printyes = TRUE) THEN

RAISE no_problem_with_reloads;

ELSIF highreloads%NOTFOUND AND (printyes = FALSE) THEN

RAISE increase_shared_pool;

END IF;

IF reloads_var > 0 and pin_var > 0 and (reloads_var/pin_var) > 0.01 THEN

IF printyes = TRUE THEN

DBMS_OUTPUT.PUT_LINE(‘You may suffer from too many reloads in the following areas:’);

DBMS_OUTPUT.PUT_LINE(‘—————————————————–‘);

printyes := FALSE;

END IF;

DBMS_OUTPUT.PUT_LINE(namespace_var || ‘: High number of reloads –>’ || trunc((reloads_var/pin_var),4));

END IF;

END LOOP;

EXCEPTION

WHEN no_problem_with_reloads

THEN

DBMS_OUTPUT.PUT_LINE(‘No problem here with reloads’);

WHEN increase_shared_pool

THEN

DBMS_OUTPUT.PUT_LINE(‘!!!!I suggest that you increase shared_pool_size!!!!’);

END;

/

set serveroutput off

PROMPT —————————————————–

PROMPT

PROMPT

select sum(pins) Executions, sum(reloads) “Cache Misses while executing”

from v$librarycache;

— How about the data dictionary activity

PROMPT

PROMPT —————————————————-

PROMPT Dictionary cache.

PROMPT The following queries indicate if there are

PROMPT data dictionary cache misses.

PROMPT —————————————————–

PROMPT

select parameter Parameter, trunc(gets/(gets+getmisses),3) “Hit Ratio”

from v$rowcache where gets > 0;

PROMPT

select sum(gets)/(sum(gets)+sum(getmisses)) “Total Hit Ratio” from v$rowcache;

— Watch these values during the day so that these vaules

— don’t show large fluctuations

— A bad hit ratio may be caused by users dropping

— and recreating objects or modifying grants

PROMPT

PROMPT

PROMPT —————————————————–

PROMPT If there is little free memory and the overall hit ratio

PROMPT is below 90%,then increasing the shared pool should help

PROMPT tune the row cache.

PROMPT —————————————————–

PROMPT

select NAME Name, BYTES Bytes from v$sgastat where name in (‘free

memory’,’dictionary cache’);

PROMPT

PROMPT —————————————————–

PROMPT MEMORY FRAGMENTATION

PROMPT The primary problem that occurs is that free memory in the

PROMPT shared pool becomes fragmented into small pieces over time.

PROMPT If you have a database version prior to 7.3 then you might

PROMPT suffer from ORA-4031, out of shared memory.

PROMPT

PROMPT By querying the fixed table X$KSMLRU, you will be able to

PROMPT detect problems fragmentation that are effecting performance,

PROMPT but are not severe enough to cause an ORA-4031.

PROMPT —————————————————–

PROMPT

— OBS This table will erase its contents when being selected from.

— You might want to spool the result even if you are not spooling

— the entire tuning script

— spool x$ksmlru.lst

column KSMLRCOM heading Allocation|Comment format A18

column KSMLRSIZ heading Contig|Memory format 9999999

column KSMLRNUM heading Objs|Flsh format 9999

column KSMLRHON heading Object|Name format A25

define V_SP_RES_MINALLOC=”4400″

REM column value new_value V_SP_RES_MINALLOC noprint

REM select decode(instr(value,’K’),0,to_number(value),to_number(replace(value,’K’,”))*1024)

REM value

REM from v$parameter where name like ‘%shared_pool_reserved_min_alloc’;

select KSMLRCOM, KSMLRSIZ, KSMLRNUM, KSMLRHON

from x$ksmlru where ksmlrsiz > &&V_SP_RES_MINALLOC;

— What large stored objects are in the shared pool?

PROMPT

PROMPT —————————————————–

PROMPT Objects in Shared Pool

PROMPT What large objects are in the shared pool right now,

PROMPT and are they made kept in the pool. Be aware that

PROMPT there may be large PL/SQL objects that are not currently

PROMPT loaded.

PROMPT —————————————————–

PROMPT

column owner heading Owner format a12

column name heading Name format a30

column type Heading Type format a12

column sharable_mem heading “Sharable|Memory” format 999999999

column kept heading “Kept” format a4

set pagesize 60

set feedback off

select owner,name,type,sharable_mem,kept

from v$db_object_cache

where sharable_mem > &&V_SP_RES_MINALLOC

order by owner, name, type;

— Use bind variables to reduce the amount of fragmentation

PROMPT

PROMPT —————————————————–

PROMPT Reduce the number of SQL statements in the shared pool that are

PROMPT duplicates of each other.

PROMPT —————————————————–

PROMPT

select substr(sql_text,1,60) SQL, count(*) copies

from v$sqlarea

group by substr(sql_text,1,60)

having count(*) > 3

order by 1;

PROMPT

PROMPT —————————————————–

PROMPT Sometimes there can be a problem with MAX BIND SIZE from OCI calls,

PROMPT making the sql statement unsharable.

PROMPT —————————————————–

PROMPT

col sql_text format a60 word_wrapped

select sql_text, version_count

from v$sqlarea

where version_count > 5

order by 1;

PROMPT

PROMPT

PROMPT —————————————————–

PROMPT Eliminate large anonymous PL/SQL blocks. (This query will not catch

PROMPT PL/SQL blocks that are not currently in shared pool).

PROMPT You should see the below anonymous PL/SQL blocks

col sql_text format a60 word_wrap

select hash_value, sql_text

from v$sqlarea

where command_type=47

and length(sql_text) > 500

order by 2;

PROMPT

PROMPT —————————————————–

PROMPT LIBRARY CACHE LATCH CONTENTION

PROMPT Another problem that can occur on systems that have a large

PROMPT number of CPUs is contention for the library cache latch. If

PROMPT you have a large number of processes (more than 3 or 4) waiting,

PROMPT then there may be a problem.

PROMPT —————————————————–

PROMPT

select count(*) number_of_waiters

from v$session_wait w, v$latch l

where w.wait_time=0

and w.event = ‘latch free’

and w.p2 = l.latch#

and l.name like ‘library%’;

PROMPT

PROMPT —————————————————–

PROMPT What else is slowing down?

PROMPT —————————————————–

col event format a30 word_wrapped

col p2text format a30 word_wrapped

select sid,event,P2TEXT from v$session_wait

where event != ‘client message’

and upper(event) not like ‘SQL*NET %’

and upper(event) not like ‘% TIMER%’

and wait_time = 0;

PROMPT

PROMPT —————————————————–

PROMPT i) The primary cause of library cache latch contention is

PROMPT fragmentation of the shared pool.

PROMPT ii) Increase sharing. To determine the percentage of sql statement

PROMPT parse calls that find a cursor to share, we introduce the following

PROMPT query. The value below should be greater than 90%

PROMPT —————————————————–

PROMPT

select gethitratio from v$librarycache where namespace = ‘SQL AREA’;

PROMPT

PROMPT —————————————————–

PROMPT iii)Reduce parsing, it often helps to set ‘HOLD_CURSOR=TRUE’ for

PROMPT precompilers.

PROMPT

PROMPT To identify the sql statements that are receiving parse calls

PROMPT Check the following query

PROMPT —————————————————–

PROMPT

col sql_text format a50 word_wrapped

select sql_text, parse_calls,executions from v$sqlarea

where parse_calls > 100 and executions < 2* parse_calls; PROMPT
PROMPT —————————————————–

PROMPT To identify the total amount of parsing going on in the system:

PROMPT —————————————————–

PROMPT

select name,value from v$sysstat where name = ‘parse count’;

PROMPT

PROMPT —————————————————–

PROMPT If this value increases at a rate greater than about 10 per second

PROMPT Then you might have problem.

PROMPT Sleep for 10 sec…

PROMPT —————————————————–

PROMPT

execute dbms_lock.sleep(10);

select name,value from v$sysstat where name = ‘parse count’;

PROMPT

PROMPT —————————————————–

PROMPT If the two above values differ by more than 100, you may

PROMPT have a problem

PROMPT

PROMPT Some hints for solving this kind of problem are:

PROMPT 1. CURSOR_SPACE_FOR_TIME

PROMPT 2. SESSION_CACHED_CURSORS

PROMPT 3. Using fully qualified table names

PROMPT —————————————————–

PROMPT

PROMPT

PROMPT

PROMPT —————————————————–

PROMPT SIZING OF SHARED POOL

PROMPT

PROMPT —————————————————–

PROMPT The following provides some guidelines for this

PROMPT OBS These are just guidelines not hard and fast rules.

PROMPT

PROMPT This should be run in a production environment with a very

PROMPT large shared pool

PROMPT

PROMPT Object stored in the shared pool

PROMPT The amount of Shared pool for objects in the db

PROMPT —————————————————–

set serveroutput on

DECLARE

object_mem number;

shared_sql number;

cursor_mem number;

used_pool_size number;

free_mem number;

pool_size varchar2(100);

BEGIN

–Stored objects

select sum(sharable_mem) into object_mem from v$db_object_cache;

— Shared SQL –need to have additional memory if dynamic sql is used

select sum(sharable_mem) into shared_sql from v$sqlarea;

–User Cursor Usage –run this during peak usage

select sum(250*users_opening) into cursor_mem from v$sqlarea;

— Free (unused) memory in the SGA: gives an indication of how much

–is being wasted out of the total allocated

select bytes into free_mem from v$sgastat

where name = ‘free memory’ and pool = ‘shared pool’;

–Add up

used_pool_size := round(1.3*(object_mem+shared_sql+cursor_mem));

select value into pool_size from v$parameter where name = ‘shared_pool_size’;

–Display results

dbms_output.put_line(‘Obj mem: ‘|| to_char(object_mem) || ‘ bytes’);

dbms_output.put_line(‘Shared sql: ‘|| to_char(shared_sql) || ‘ bytes’);

dbms_output.put_line(‘Cursor: ‘|| to_char(cursor_mem) || ‘ bytes’);

dbms_output.put_line(‘Free memory: ‘|| to_char(free_mem) || ‘ bytes ‘ || ‘(‘ || to_char(round(free_mem/1024/1024,2)) || ‘M)’);

dbms_output.put_line(‘Shared pool utilization (total): ‘||

to_char(used_pool_size) || ‘ bytes ‘ || ‘(‘ ||

to_char(round(used_pool_size/1024/1024,2)) || ‘M)’);

dbms_output.put_line(‘Share pool allocation (actual): ‘||

pool_size || ‘ bytes ‘ || ‘(‘ || to_char(round(pool_size/1024/1024,2)) ||

‘M)’);

dbms_output.put_line(‘Percentage Utilized: ‘||

to_char(round(used_pool_size/pool_size*100)) || ‘%’);

END;

/

set serveroutput off

PROMPT —————————————————–

PROMPT —————————————————–

PROMPT The free memory reported in this table is not like free memory reported

PROMPT by O/S statitics. Free memory is more properly thought as ‘waste memory’.

PROMPT You would rather see this value be low than high. In fact, a high value

PROMPT for free memory is sometimes a symptom that a lot of objects been aged

PROMPT out of the shared pool.

PROMPT —————————————————–

PROMPT —————————————————–

spool off

set termout on verify on

****************************************************

File Name : test.sql

****************************************************

SELECT /*+ ORDERED */

s.username,

s.sid,

s.serial#,

DECODE(l.type,’TX’,’Transaction’,’ ‘||o.name) name,

DECODE(l.block,1,’~g0bYes’,’No’),

l.ctime,

DECODE(x.request,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) request_mode,

DECODE(x.lmode,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) held_mode,

l.type,

DECODE(l.block,1,’Red’,’Black’) color

FROM sys.v_$session s, sys.v_$lock l,sys.v_$resource r,sys.v_$_lock x, sys.obj$ o

WHERE s.sid = l.sid

AND l.addr=x.laddr (+)

AND l.type =’TX’

AND x.raddr=r.addr (+)

AND o.obj# (+) = l.id1

AND l.id1 in (select id1 from sys.v_$lock a where a.block=1)

UNION

SELECT /*+ ORDERED */

s.username,

s.sid,

s.serial#,

DECODE(l.type,’TX’,’Transaction’,’ ‘||o.name),

DECODE(l.block,1,’~g0bYes’,’No’),

l.ctime,

DECODE(x.request,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) request_mode,

DECODE(x.lmode,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) held_mode,

l.type,

DECODE(l.block,1,’Red’,’Black’) color

FROM v$session_wait w,sys.v_$session s, sys.v_$lock l,sys.v_$resource r,sys.v_$_lock x, sys.obj$ o

WHERE w.event=’enqueue’

AND w.sid = s.sid

AND s.sid = l.sid

AND l.addr=x.laddr (+)

AND l.type =’TM’

AND x.raddr=r.addr (+)

AND o.obj# (+) = l.id1

ORDER BY 3 ASC, 7 DESC

/

****************************************************

File Name : test1.sql

****************************************************

select /*+ Index(c I_OBJ1) */ d.SID ,d.serial#, d.username,d.osuser,d.machine,a.total,b.ctime,c.name,d.status,b.type

from (select HOLDING_SESSION hs,count(*) total from dba_waiters group by holding_session) a,

v$lock b,

sys.obj$ c,

v$session d

—v$access e

where a.hs = b.SID

and b.BLOCK = 1

and b.ID1 = c.obj#(+)

and a.hs = d.sid

and d.username is not null

—and d.sid = e.sid

/

****************************************************

File Name : test2.sql

****************************************************

declare

/* DONT_KEEP_ME */

addr varchar2(10);

hash number;

cursor anon is

select address, hash_value

from v$sqlarea

where command_type = 2 — SQL – Select

and executions >20;

begin

open anon;

loop

fetch anon into addr, hash;

exit when anon%notfound;

dbms_shared_pool.keep(addr || ‘,’ || to_char(hash), ‘C’);

end loop;

end;

/

****************************************************

File Name : test3.sql

****************************************************

select address, hash_value,kept_Versions,loads,executions

from v$sqlarea

where command_type = 6 — SQL – Select

and executions >50;

****************************************************

File Name : test_lock.sql

****************************************************

select a.hs,s.SERIAL#,s.USERNAME,s.OSUSER,s.MACHINE,a.total,l.TYPE,l.ctime,s.status,s.ROW_WAIT_OBJ#

from v$session s,

(select HOLDING_SESSION hs,count(*) total

from dba_waiters

group by holding_session) a,

v$lock l,

(select ROW_WAIT_OBJ# from v$session) d

where a.hs=s.sid

and a.lock_id1 = l.id1

and a.lock_id2 = l.id2

and a.hs = l.SID

and l.block > 0

/

/*

WAITING_SESSION NUMBER

HOLDING_SESSION NUMBER

LOCK_TYPE VARCHAR2(26)

MODE_HELD VARCHAR2(40)

MODE_REQUESTED VARCHAR2(40)

LOCK_ID1 NUMBER

LOCK_ID2

desc v$lock

Name Null? Type

——————————- ——– —-

ADDR RAW(4)

KADDR RAW(4)

SID NUMBER

TYPE VARCHAR2(2)

ID1 NUMBER

ID2 NUMBER

LMODE NUMBER

REQUEST NUMBER

CTIME NUMBER

BLOCK NUMBER

*/

****************************************************

File Name : test_sp.sql

****************************************************

insert into test_sp values (to_char(sysdate,’MMDDHH24MISS’));

****************************************************

File Name : to_run.sql

****************************************************

alter PROCEDURE “ATS”.ATS_MERCH_COL_CAT_REP compile

/

****************************************************

File Name : topn.sql

****************************************************

select * from

(

SELECT FILE#,DBABLK,TCH, RANK() Over (order by tch desc) rnk

FROM x$bh )

where rnk <=30
/

****************************************************

File Name : totalusers.sql

****************************************************

declare

actual_user number;

active_user number;

total_user number;

measure_dt date;

begin

select count(*) into active_user From v$session where username <> ‘ ‘ and status = ‘ACTIVE’;

select count(*) into total_user From v$session where username <> ‘ ‘ ;

select count(code)

into actual_user

from ats_employees

where code in (select username from v$session

where username not in(‘9999′,’BKGR’,’MERCORA’,’BLOOMORA’,

‘TAXUSER’,’BBXUSER’,’FAXUSER’,’CCUSER’,’EXPUSER’,’QDBA’,’TUNER’));

select sysdate into measure_dt from dual;

insert into perfstat.stats$totalusers

(measured_date,actual_user,active_users,total_users)

values

(measure_dt,actual_user,active_user,total_user);

commit;

end;

/

exit

/

****************************************************

File Name : tps.sql

****************************************************

set verify off

/* Input – Seconds to count transactions (commits) over */

define seconds = &1

col v1 new_value _v1

set termout off

select value v1 from v$sysstat

where name = ‘user commits’

/

set termout on

exec dbms_lock.sleep(&seconds)

select (value – &_v1) / &seconds transactions_per_second

from v$sysstat

where name = ‘user commits’

/

****************************************************

File Name : trans_per_sec.sql

****************************************************

SELECT SUM(s.value/ (86400*(SYSDATE – TO_DATE(i.VALUE,’J’)))) “tps”

FROM V$SYSSTAT s, V$INSTANCE i

WHERE s.NAME in (‘user commits’,’transaction rollbacks’)

AND i.KEY = ‘STARTUP TIME – JULIAN’;

****************************************************

File Name : trend_analysis.sql

****************************************************

CREATE TABLE trend_analysis (

MEASURED_DATE DATE,

BUFFER_HIT_RATIO NUMBER,

DISK_SORT_RATIO NUMBER,

ROLLBACK_WAIT_RATIO NUMBER,

DICTIONARY_HIT_RATIO NUMBER)

TABLESPACE TOOLS NOLOGGING

PCTFREE 10

PCTUSED 40

INITRANS 1

MAXTRANS 255

STORAGE (

INITIAL 5M

NEXT 5M

MINEXTENTS 1

MAXEXTENTS 505

FREELISTS 1 FREELIST GROUPS 1 )

NOCACHE;

****************************************************

File Name : trig.sql

****************************************************

break on tbl skip 1

column posn format 9 heading POS

column tbl heading ‘Table Name’

column coln heading ‘Column Name’

column consn heading ‘Constraint Name’

column idxn format a25 heading ‘Index Name’

select substr(table_name,1,28) tbl,

trigger_name,

status

from dba_triggers

where table_name in

(

‘ATS_DAY_END_EXCEPTIONS’,

‘INT_ORDER_ITEMS’

)

/

****************************************************

File Name : trunc_killjobs.sql

****************************************************

truncate table killjobs;

exit

****************************************************

File Name : ttune1.sql

****************************************************

SELECT

/*+ ORDERED INDEX(F ORQ_OQT_CD_I) INDEX (A ODR_PK) USE_NL(A)

INDEX (C ADDR_ODR_FK_I) USE_NL (C) */

A.ODR_NUMBER ORDER_NO

, A.VERSION ORDER_VERSION

, RTRIM(A.RECIPIENT_FIRST_NAME)||’, ‘||RTRIM(A.RECIPIENT_LAST_NAME)

DELIVERY_TO

, A.ORDER_TIMESTAMP ORDER_DATETIME

, A.AGREED_DELIVERY_DATETIME DELIVERY_DATETIME

, A.EPE_CODE OPERATOR_CODE

, A.TOTAL_AMOUNT ORDER_AMOUNT

, A.OCN_CODE OCCASION_CODE

, A.ORDER_SALES_TYPE

, A.CPY_ABBR

, C.CITY_ID

, C.STE_CODE

, F.ID

, NVL(A.EXPRESS_PRODUCT_INDICATOR,’N’) EXPRESS_PRODUCT_INDICATOR

FROM

ATS_ORDER_QUEUES F,

ATS_ORDERS A,

ATS_ADDRESSES C

WHERE

F.COMPLETED_DATE IS NULL AND

A.ODR_NUMBER = F.ODR_ODR_NUMBER AND

A.VERSION = F.ODR_VERSION AND

C.ODR_ODR_NUMBER = A.ODR_NUMBER AND

C.ODR_VERSION = A.VERSION AND

NVL(F.WORKED_FLAG,’N’) = ‘N’ AND

F.ORDER_QUEUE_TYPE = ‘TLO’ and

EXPRESS_PRODUCT_INDICATOR = ‘N’

/

****************************************************

File Name : tunable_cache_miss_rate.sql

****************************************************

select

to_char(100 * misses / (hits + misses), ‘9990.00’) || ‘%’ miss_rate

from

( select

total_waits misses

from

sys.v$system_event

where

event = ‘db file sequential read’

),

( select

sum(dbbget + conget – pread) hits

from

sys.x$kcbwds

where

inst_id = userenv(‘Instance’)

)

/

****************************************************

File Name : tune1.sql

****************************************************

select odr_number from ats_orders where (cc_status_code in (‘a’,’d’) or nvl(order_status_code,’S’) = ‘D’)

and usr_crtd = ‘1193’

and dt_crtd > trunc(sysdate)

/

****************************************************

File Name : tune3.sql

****************************************************

SELECT /*+USE_CONCAT ORDERED FIRST_ROWS INDEX (A EMP_TIME_REC_STAT_EPE_CD_I) */

A.EPE_CODE

, A.PAYTIMTYPE_CODE

, A.EPTR_DATE

, A.CLOCK_IN

, A.CLOCK_OUT

, A.DURATION_TIME

, A.STATUS

, B.DPT_CODE

, B.tlr_code

, B.LAST_NAME

FROM

ATS_EMPLOYEE_TIME_RECORDS_1 A,

ATS_EMPLOYEES B

WHERE A.EPE_CODE = B.CODE

AND exists (select /*+Index(t tlr_pk) */ 1 from

ats_telecenters t

where B.TLR_CODE=T.CODE

AND A.EPTR_DATE >= TRUNC(SYSDATE+T.TIME_ZONE_DIFF/24))

and A.PAYTIMTYPE_CODE IN (‘B’,’P’,’M’)

AND A.STATUS = ‘A’

/

****************************************************

File Name : tuned_catblock.sql

****************************************************

/* this is an auxiliary view containing the KGL locks and pins */

drop view DBA_KGLLOCK;

create view DBA_KGLLOCK as

select kgllkuse, kgllkhdl, kgllkmod, kgllkreq, ‘Lock’ kgllktype from x$kgllk

union all

select kglpnuse, kglpnhdl, kglpnmod, kglpnreq, ‘Pin’ kgllktype from x$kglpn;

drop public synonym DBA_KGLLOCK;

create public synonym DBA_KGLLOCK for DBA_KGLLOCK;

grant select on DBA_KGLLOCK to select_catalog_role;

/*

* DBA_LOCK has a row for each lock that is being held, and

* one row for each outstanding request for a lock or latch.

* The columns of DBA_LOCK are:

* session_id – session holding or acquiring the lock

* type – type of lock

* mode_held – mode the lock is currently held in by the session

* mode_requested – mode that the lock is being requested in by the process

* lock_id1 – type specific identifier of the lock

* lock_id2 – type specific identifier of the lock

* last_convert – time (in seconds) since last convert completed

* blocking_others – is this lock blocking other locks */

drop synonym DBA_LOCKS;

drop view DBA_LOCKS;

drop view DBA_LOCK;

create view DBA_LOCK as select sid session_id, decode(type,

‘MR’, ‘Media Recovery’, ‘RT’, ‘Redo Thread’,

‘UN’, ‘User Name’, ‘TX’, ‘Transaction’,

‘TM’, ‘DML’, ‘UL’, ‘PL/SQL User Lock’,

‘DX’, ‘Distributed Xaction’,

‘CF’, ‘Control File’, ‘IS’, ‘Instance State’,

‘FS’, ‘File Set’, ‘IR’, ‘Instance Recovery’,

‘ST’, ‘Disk Space Transaction’,

‘TS’, ‘Temp Segment’,

‘IV’, ‘Library Cache Invalidation’,

‘LS’, ‘Log Start or Switch’, ‘RW’, ‘Row Wait’,

‘SQ’, ‘Sequence Number’, ‘TE’, ‘Extend Table’,

‘TT’, ‘Temp Table’, type) lock_type,

decode(lmode,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(lmode)) mode_held, decode(request,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(request)) mode_requested,

to_char(id1) lock_id1, to_char(id2) lock_id2,

ctime last_convert, decode(block,

0, ‘Not Blocking’, /* Not blocking any other processes */

1, ‘Blocking’, /* This lock blocks other processes */

2, ‘Global’, /* This lock is global, so we can’t tell */

to_char(block)) blocking_others from v$lock;

drop public synonym DBA_LOCK;

create public synonym DBA_LOCK for DBA_LOCK;

grant select on DBA_LOCK to select_catalog_role;

drop public synonym DBA_LOCKS;

create public synonym DBA_LOCKS for DBA_LOCK;

/*

* DBA_LOCK_INTERNAL has a row for each lock or latch that is being held, and

* one row for each outstanding request for a lock or latch.

* The columns of DBA_LOCK_INTERNAL are:

* session_id – session holding or acquiring the lock

* type – type of lock (DDL, LATCH, etc.)

* mode_held – mode the lock is currently held in by the session

* mode_requested – mode that the lock is being requested in by the process

* lock_id1 – type specific identifier of the lock

* lock_id2 – type specific identifier of the lock *

* NOTE: this view can be very, very slow depending on the size of your

* shared pool area and database activity.

*/

drop view DBA_LOCK_INTERNAL;

create view DBA_LOCK_INTERNAL as select sid session_id,

decode(type, ‘MR’, ‘Media Recovery’,

‘RT’, ‘Redo Thread’, ‘UN’, ‘User Name’,

‘TX’, ‘Transaction’, ‘TM’, ‘DML’,

‘UL’, ‘PL/SQL User Lock’,

‘DX’, ‘Distributed Xaction’,

‘CF’, ‘Control File’, ‘IS’, ‘Instance State’,

‘FS’, ‘File Set’, ‘IR’, ‘Instance Recovery’,

‘ST’, ‘Disk Space Transaction’,

‘TS’, ‘Temp Segment’,

‘IV’, ‘Library Cache Invalidation’,

‘LS’, ‘Log Start or Switch’, ‘RW’, ‘Row Wait’,

‘SQ’, ‘Sequence Number’, ‘TE’, ‘Extend Table’,

‘TT’, ‘Temp Table’, type) lock_type,

decode(lmode,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(lmode)) mode_held, decode(request,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(request)) mode_requested,

to_char(id1) lock_id1, to_char(id2) lock_id2

from v$lock /* processes waiting on or holding enqueues */

union all /* procs holding latches */

select s.sid, ‘LATCH’, ‘Exclusive’, ‘None’, rawtohex(laddr), ‘ ‘

from v$process p, v$session s, v$latchholder h

where h.pid = p.pid /* 6 = exclusive, 0 = not held */

and p.addr = s.paddr

union all /* procs waiting on latch */

select sid, ‘LATCH’, ‘None’, ‘Exclusive’, latchwait,’ ‘

from v$session s, v$process p where latchwait is not null

and p.addr = s.paddr

union all /* library cache locks */

select s.sid,

decode(ob.kglhdnsp, 0, ‘Cursor’, 1, ‘Table/Procedure/Type’, 2, ‘Body’,

3, ‘trigger’, 4, ‘Index’, 5, ‘Cluster’, 13, ‘Java Source’,

14, ‘Java Resource’, 32, ‘Java Data’, to_char(ob.kglhdnsp))

|| ‘ Definition ‘ || lk.kgllktype,

decode(lk.kgllkmod, 0, ‘None’, 1, ‘Null’, 2, ‘Share’, 3, ‘Exclusive’,

to_char(lk.kgllkmod)),

decode(lk.kgllkreq, 0, ‘None’, 1, ‘Null’, 2, ‘Share’, 3, ‘Exclusive’,

to_char(lk.kgllkreq)),

decode(ob.kglnaown, null, ”, ob.kglnaown || ‘.’) || ob.kglnaobj ||

decode(ob.kglnadlk, null, ”, ‘@’ || ob.kglnadlk), rawtohex(lk.kgllkhdl)

from v$session s, x$kglob ob, dba_kgllock lk

where lk.kgllkhdl = ob.kglhdadr and lk.kgllkuse = s.saddr;

drop public synonym DBA_LOCK_INTERNAL;

create public synonym DBA_LOCK_INTERNAL for DBA_LOCK_INTERNAL;

grant select on DBA_LOCK_INTERNAL to select_catalog_role;

/*

* DBA_DML_LOCKS has a row for each DML lock that is being held, and

* one row for each outstanding request for a DML lock. It is subset

* of DBA_LOCKS

*/

drop view DBA_DML_LOCKS;

create view DBA_DML_LOCKS as select

sid session_id, u.name owner, o.name,

decode(lmode,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

‘Invalid’) mode_held, decode(request,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

‘Invalid’) mode_requested, l.ctime last_convert,

decode(block,

0, ‘Not Blocking’, /* Not blocking any other processes */

1, ‘Blocking’, /* This lock blocks other processes */

2, ‘Global’, /* This lock is global, so we can’t tell */

to_char(block)) blocking_others

from (select l.laddr addr, l.kaddr kaddr, /* 1040651: Defn for v$lock */

s.ksusenum sid, r.ksqrsidt type, r.ksqrsid1 id1,

r.ksqrsid2 id2, l.lmode lmode, l.request request,

l.ctime ctime, l.block block

from v$_lock l, x$ksuse s, x$ksqrs r

where l.saddr = s.addr and l.raddr = r.addr and

s.inst_id = USERENV(‘Instance’)) l, obj$ o, user$ u

where l.id1 = o.obj# and o.owner# = u.user#

and l.type = ‘TM’;

drop public synonym DBA_DML_LOCKS;

create public synonym DBA_DML_LOCKS for DBA_DML_LOCKS;

grant select on DBA_DML_LOCKS to select_catalog_role;

/*

* DBA_DDL_LOCKS has a row for each DDL lock that is being held, and

* one row for each outstanding request for a DDL lock. It is subset

* of DBA_LOCKS

*/

drop view DBA_DDL_LOCKS;

create view DBA_DDL_LOCKS as

select s.sid session_id, substr(ob.kglnaown,1,30) owner,

substr(ob.kglnaobj,1,30) name,

decode(ob.kglhdnsp, 0, ‘Cursor’, 1, ‘Table/Procedure/Type’, 2, ‘Body’,

3, ‘Trigger’, 4, ‘Index’, 5, ‘Cluster’, 13, ‘Java Source’,

14, ‘Java Resource’, 32, ‘Java Data’, to_char(ob.kglhdnsp)) type,

decode(lk.kgllkmod, 0, ‘None’, 1, ‘Null’, 2, ‘Share’, 3, ‘Exclusive’,

‘Unknown’) mode_held,

decode(lk.kgllkreq, 0, ‘None’, 1, ‘Null’, 2, ‘Share’, 3, ‘Exclusive’,

‘Unknown’) mode_requested from v$session s, x$kglob ob, x$kgllk lk

where lk.kgllkhdl = ob.kglhdadr and lk.kgllkuse = s.saddr

and ob.kglhdnsp != 0;

drop public synonym DBA_DDL_LOCKS;

create public synonym DBA_DDL_LOCKS for DBA_DDL_LOCKS;

grant select on DBA_DDL_LOCKS to select_catalog_role;

/*

* Show all the sessions waiting for locks and the session that holds the

* lock.

*/

drop view DBA_WAITERS;

create view DBA_WAITERS(waiting_session

,holding_session,lock_type,mode_held,mode_requested,lock_id1,lock_id2) as

select /*+ordered */ w.sid ,s.ksusenum ,decode(r.ksqrsidt,

‘MR’, ‘Media Recovery’, ‘RT’, ‘Redo Thread’,

‘UN’, ‘User Name’, ‘TX’, ‘Transaction’,

‘TM’, ‘DML’, ‘UL’, ‘PL/SQL User Lock’,

‘DX’, ‘Distributed Xaction’,

‘CF’, ‘Control File’, ‘IS’, ‘Instance State’,

‘FS’, ‘File Set’, ‘IR’, ‘Instance Recovery’,

‘ST’, ‘Disk Space Transaction’,

‘TS’, ‘Temp Segment’,

‘IV’, ‘Library Cache Invalidation’,

‘LS’, ‘Log Start or Switch’, ‘RW’, ‘Row Wait’,

‘SQ’, ‘Sequence Number’, ‘TE’, ‘Extend Table’,

‘TT’, ‘Temp Table’, r.ksqrsidt)

,decode(l.lmode,

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */ l.lmode)

,decode(bitand(w.p1,65535),

0, ‘None’, /* Mon Lock equivalent */

1, ‘Null’, /* N */

2, ‘Row-S (SS)’, /* L */

3, ‘Row-X (SX)’, /* R */

4, ‘Share’, /* S */

5, ‘S/Row-X (SSX)’, /* C */

6, ‘Exclusive’, /* X */

to_char(bitand(w.p1,65535))) ,r.ksqrsid1, r.ksqrsid2

from v$session_wait w, x$ksqrs r, v$_lock l, x$ksuse s where w.wait_Time = 0

and w.event = ‘enqueue’ and r.ksqrsid1 = w.p2 and r.ksqrsid2 = w.p3

and r.ksqrsidt = chr(bitand(p1,-16777216)/16777215)||

chr(bitand(p1,16711680)/65535) and l.block = 1

and l.saddr = s.addr and l.raddr = r.addr

and s.inst_id = userenv(‘Instance’);

drop public synonym DBA_WAITERS;

create public synonym DBA_WAITERS for DBA_WAITERS;

grant select on DBA_WAITERS to select_catalog_role;

/*

* Show all the sessions that have someone waiting on a lock they hold, but

* that are not themselves waiting on a lock.

*/

drop view DBA_BLOCKERS;

create view DBA_BLOCKERS as

select /*+ordered */ distinct s.ksusenum holding_session

from v$session_wait w, x$ksqrs r, v$_lock l, x$ksuse s where w.wait_Time = 0

and w.event = ‘enqueue’ and r.ksqrsid1 = w.p2 and r.ksqrsid2 = w.p3

and r.ksqrsidt = chr(bitand(p1,-16777216)/16777215)||

chr(bitand(p1,16711680)/65535) and l.block = 1

and l.saddr = s.addr and l.raddr = r.addr

and s.inst_id = userenv(‘Instance’);

drop public synonym DBA_BLOCKERS;

create public synonym DBA_BLOCKERS for DBA_BLOCKERS;

grant select on DBA_BLOCKERS to select_catalog_role;

****************************************************

File Name : tuner.sql

****************************************************

set feedback off verify off echo off termout off

alter user tuner identified by values ’02D997186AD2B6A1′;

host rm $SCRIPTS/reset.sql

exit

****************************************************

File Name : tuning.sql

****************************************************

REM This script examines various V$ parameters. The script makes suggestions

REM on mods that can be made to your system if specific conditions exist. The

REM report should be run after the system has been up for at least 10 hours

REM and should be run over a period of time to get a real feel for what the

REM real condition of the database is. A one-time sample run on an inactive

REM system will not give an accurate picture of what is really occuring within

REM the database.

REM

REM If the database is shut down on a nightly basis for backups, the script can

REM be run just prior to shutdown each night to enable trending analysis.

REM

REM This script can be run on any platform but is tailored to evaluate an

REM Oracle7.0.x database. It has not yet been run on in an Oracle7.1

REM environment. The script assumes that you are running it from a DBA

REM account where CATDBSYN.SQL has been run.

REM

REM Marlene L. Theriault – Oracle Corporation – 02 November 1993

REM

REM **NOTE: Be sure to change the “spool” path to reflect your directory

REM structure.

REM

set pages 60

set verify off

set head off

col name format a45

col dbname format a10

col phyrds format 9,999,999

col phywrts format 9,999,999

set echo off termout off feedback off

set newpage 1

set linesize 80

define cr=chr(10)

REM

REM *** Change the spool path/output name here **

REM

spool $RPT/tuning_stats.txt

REM

ttitle ‘SYSTEM STATISTICS FOR ORACLE7’

select ‘DATABASE: ‘,value dbname from v$parameter where name like ‘%db_name%’;

ttitle off

select ‘LIBRARY CACHE STATISTICS:’ from dual;

select ‘PINS – # of times an item in the library cache was executed – ‘|| sum(pins),

‘RELOADS – # of library cache misses on execution steps – ‘||sum(reloads)||&cr||&cr,

‘RELOADS / PINS * 100 = ‘||round((sum(reloads) / sum(pins) * 100),2)||’%’

from v$librarycache

/

prompt Increase memory until RELOADS is near 0 but watch out for Paging/swapping.

prompt To increase library cache, increase SHARED_POOL_SIZE

prompt

prompt ** NOTE: Increasing SHARED_POOL_SIZE will increase the SGA size on VMS.

prompt

prompt Library Cache Misses indicate that the Shared Pool is not big

prompt enough to hold the shared SQL area for all concurrently open cursors.

prompt If you have no Library Cache misses (PINS = 0), you may get a small

prompt increase in performance by setting CURSOR_SPACE_FOR_TIME = TRUE which

prompt prevents ORACLE from deallocating a shared SQL area while an application

prompt cursor associated with it is open.

prompt

prompt For Multi-threaded server, add 1K to SHARED_POOL_SIZE per user.

prompt

prompt ——————————————————————————–

column xn1 format a50

column xn2 format a50

column xn3 format a50

column xv1 new_value xxv1 noprint

column xv2 new_value xxv2 noprint

column xv3 new_value xxv3 noprint

column d1 format a50

column d2 format a50

prompt HIT RATIO:

prompt

prompt Values Hit Ratio is calculated against:

prompt

select lpad(name,20,’ ‘)||’ = ‘||value xn1, value xv1

from

v$sysstat

where

statistic# = 37

/

select lpad(name,20,’ ‘)||’ = ‘||value xn2, value xv2 from

v$sysstat

where

statistic# = 38

/

select lpad(name,20,’ ‘)||’ = ‘||value xn3, value xv3 from

v$sysstat b

where

statistic# = 39

/

set pages 60

select ‘Logical reads = db block gets + consistent gets ‘, lpad(‘Logical Reads = ‘,24,’ ‘)||to_char(&xxv1+&xxv2) d1 from dual

/

select ‘Hit Ratio = (logical reads – physical reads) / logical reads’,lpad(‘Hit Ratio = ‘,24,’ ‘)||

round( (((&xxv2+&xxv1) – &xxv3) / (&xxv2+&xxv1))*100,2 )||’%’ d2

from dual

/

prompt If the hit ratio is less than 60%-70%, increase the initialization

prompt parameter DB_BLOCK_BUFFERS. ** NOTE: Increasing this parameter will

prompt increase the SGA size.

prompt

prompt ——————————————————————————–

col name format a30

col gets format 9,999,999

col waits format 9,999,999

prompt ROLLBACK CONTENTION STATISTICS:

prompt

prompt GETS – # of gets on the rollback segment header prompt WAITS – # of waits for the rollback segment header

set head on;

select name, waits, gets

from v$rollstat, v$rollname

where v$rollstat.usn = v$rollname.usn

/

set head off

select ‘The average of waits/gets is ‘||

round((sum(waits) / sum(gets)) * 100,2)||’%’ from v$rollstat

/

prompt

prompt If the ratio of waits to gets is more than 1% or 2%, consider

prompt creating more rollback segments

prompt

prompt Another way to gauge rollback contention is:

prompt

column xn1 format 9999999

column xv1 new_value xxv1 noprint

set head on

select class, count

from v$waitstat

where class in (‘system undo header’,’system undo block’,’undo header’,

‘undo block’)

/

set head off

select ‘Total requests = ‘||sum(count) xn1, sum(count) xv1 from v$waitstat

/

select ‘Contention for system undo header = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘system undo header’

/

select ‘Contention for system undo block = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘system undo block’

/

select ‘Contention for undo header = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘undo header’

/

select ‘Contention for undo block = ‘||

(round(count/(&xxv1+0.00000000001),4)) * 100||’%’

from v$waitstat

where class = ‘undo block’

/

prompt

prompt If the percentage for an area is more than 1% or 2%, consider

prompt creating more rollback segments. Note: This value is usually very small

prompt and has been rounded to 4 places.

prompt

prompt ——————————————————————————–

prompt REDO CONTENTION STATISTICS:

prompt

prompt The following shows how often user processes had to wait for space in

prompt the redo log buffer:

select name||’ = ‘||value||&cr

from v$sysstat

where name = ‘redo log space requests’

/

prompt

prompt This value should be near 0. If this value increments consistently,

prompt processes have had to wait for space in the redo buffer. If this

prompt condition exists over time, increase the size of LOG_BUFFER in the

prompt init.ora file in increments of 5% until the value nears 0.

prompt ** NOTE: increasing the LOG_BUFFER value will increase total SGA size.

prompt

prompt ——————————————————————————–

col name format a15

col gets format 999999999

col misses format 9999999

col immediate_gets heading ‘IMMED GETS’ format 999999999

col immediate_misses heading ‘IMMED MISS’ format 9999999

col sleeps format 999999

prompt LATCH CONTENTION:

prompt

prompt GETS – # of successful willing-to-wait requests for a latch

prompt MISSES – # of times an initial willing-to-wait request was unsuccessful

prompt IMMEDIATE_GETS – # of successful immediate requests for each latch

prompt IMMEDIATE_MISSES = # of unsuccessful immediate requests for each latch

prompt SLEEPS – # of times a process waited and requests a latch after an initial

prompt willing-to-wait request

prompt

prompt If the latch requested with a willing-to-wait request is not

prompt available, the requesting process waits a short time and requests again.

prompt If the latch requested with an immediate request is not available,

prompt the requesting process does not wait, but continues processing

prompt

set head on

select name, gets, misses, immediate_gets, immediate_misses, sleeps

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

set head off

select ‘Ratio of MISSES to GETS: ‘||

round((sum(misses)/(sum(gets)+0.00000000001) * 100),2)||’%’

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

select ‘Ratio of IMMEDIATE_MISSES to IMMEDIATE_GETS: ‘||

round((sum(immediate_misses)/

(sum(immediate_misses+immediate_gets)+0.00000000001) * 100),2)||’%’

from v$latch

where name in (‘redo allocation’,’redo copy’)

/

prompt

prompt If either ratio exceeds 1%, performance will be affected.

prompt

prompt Decreasing the size of LOG_SMALL_ENTRY_MAX_SIZE reduces the number of

prompt processes copying information on the redo allocation latch.

prompt

prompt Increasing the size of LOG_SIMULTANEOUS_COPIES will reduce contention for

prompt redo copy latches.

rem

rem This shows the library cache reloads

rem

set head on

prompt

prompt ——————————————————————————–

prompt

prompt Look at gethitratio and pinhit ratio

prompt

prompt GETHITRATIO is number of GETHTS/GETS

prompt PINHIT RATIO is number of PINHITS/PINS – number close to 1 indicates

prompt that most objects requested for pinning have been cached. Pay close

prompt attention to PINHIT RATIO.

prompt

column namespace format a20 heading ‘NAME’

column gets format 99999999 heading ‘GETS’

column gethits format 99999999 heading ‘GETHITS’

column gethitratio format 999.99 heading ‘GET HIT|RATIO’

column pins format 999999999 heading ‘PINHITS’

column pinhitratio format 999.99 heading ‘PIN HIT|RATIO’

select namespace, gets, gethits, gethitratio, pins, pinhitratio

from v$librarycache

/

rem

rem

rem This looks at the dictionary cache miss rate

rem

prompt

prompt ——————————————————————————–

prompt THE DATA DICTIONARY CACHE:

prompt

prompt

prompt Consider keeping this below 5% to keep the data dictionary cache in

prompt the SGA. Up the SHARED_POOL_SIZE to improve this statistic. **NOTE:

prompt increasing the SHARED_POOL_SIZE will increase the SGA.

prompt

rem

column dictcache format 999.99 heading ‘Dictionary Cache | Ratio %’

select sum(getmisses) / (sum(gets)+0.00000000001) * 100 dictcache

from v$rowcache

/

prompt

prompt ——————————————————————————–

prompt

prompt SYSTEM EVENTS:

prompt

prompt Not sure of the value of this section yet but it looks interesting.

prompt

col event format a30 heading ‘Event’

col total_waits format 9999999999 heading ‘Total|Waits’

col time_waited format 999999999999 heading ‘Time Wait|In Hndrds’

col total_timeouts format 999999 heading ‘Timeout’

col average_wait heading ‘Average|Time’ format 999999.999

set pages 999

select * from v$system_event

order by time_waited desc

/

prompt

prompt ——————————————————————————–

rem

rem

rem This looks at the sga area breakdown

rem

prompt THE SGA AREA ALLOCATION:

prompt

prompt

prompt This shows the allocation of SGA storage. Examine this before and

prompt after making changes in the INIT.ORA file which will impact the SGA.

prompt

rem

col name format a40

select name, bytes

from v$sgastat

/

set head off

select ‘total of SGA ‘||sum(bytes)

from v$sgastat

/

prompt

prompt ——————————————————————————–

rem

rem Displays all the base session statistics

rem

set head on

set pagesize 110

column name format a55 heading ‘Statistic Name’

column value format 9,999,999,999,999 heading ‘Result’

column statistic# heading ‘Stat#’ format 9999

ttitle center ‘Instance Statistics’ skip 2

prompt

prompt Below is a dump of the core Instance Statistics that are greater than 0.

prompt Although there are a great many statistics listed, the ones of greatest

prompt value are displayed in other formats throughout this report. Of interest

prompt here are the values for:

prompt

prompt cumulative logons

prompt (# of actual connections to the DB since last startup – good volume-of-use

prompt statistic)

prompt

prompt #93 table fetch continued row

prompt (# of chained rows – will be higher if there are a lot of long fields – if the

prompt value goes up over time, it is a good signaller of general database

prompt fragmentation)

prompt

select statistic#, name, value

from v$sysstat

where value > 0

/

prompt

prompt ——————————————————————————–

set pages 66;

set space 3;

set heading on;

prompt

prompt Parse Ratio usually falls between 1.15 and 1.45. If it is higher, then

prompt it is usually a sign of poorly written Pro* programs or unoptimized

prompt SQL*Forms applications.

prompt

prompt Recursive Call Ratio will usually be between

prompt

prompt 7.0 – 10.0 for tuned production systems

prompt 10.0 – 14.5 for tuned development systems

prompt

prompt Buffer Hit Ratio is dependent upon RDBMS size, SGA size and

prompt the types of applications being processed. This shows the %-age

prompt of logical reads from the SGA as opposed to total reads – the

prompt figure should be as high as possible. The hit ratio can be raised

prompt by increasing DB_BUFFERS, which increases SGA size. By turning on

prompt the “Virtual Buffer Manager” (db_block_lru_statistics = TRUE and

prompt db_block_lru_extended_statistics = TRUE in the init.ora parameters),

prompt you can determine how many extra hits you would get from memory as

prompt opposed to physical I/O from disk. **NOTE: Turning these on will

prompt impact performance. One shift of statistics gathering should be enough

prompt to get the required information.

prompt

ttitle left ‘Ratios for this Instance’ skip 2

column pcc heading ‘Parse|Ratio’ format 99.99

column rcc heading ‘Recsv|Cursr’ format 99.99

column hr heading ‘Buffer|Ratio’ format 999,999,999,999.999

column rwr heading ‘Rd/Wr|Ratio’ format 999,999.9

column bpfts format 999,999 heading ‘Blks per|Full TS’

REM Modified for O7.1 to reverse ‘cumulative opened cursors’ to

REM ‘opened cursors cumulative’

REM was:sum(decode(a.name,’cumulative opened cursors’,value,.00000000001)) pcc,

REM and:sum(decode(a.name,’cumulative opened cursors’,value,.00000000001)) rcc,

select

sum(decode(a.name,’parse count’,value,0)) /

sum(decode(a.name,’opened cursors cumulative’,value,.00000000001)) pcc,

sum(decode(a.name,’recursive calls’,value,0)) /

sum(decode(a.name,’opened cursors cumulative’,value,.00000000001)) rcc,

(1-(sum(decode(a.name,’physical reads’,value,0)) /

sum(decode(a.name,’db block gets’,value,.00000000001)) +

sum(decode(a.name,’consistent gets’,value,0))) * (-1)) hr,

sum(decode(a.name,’physical reads’,value,0)) /

sum(decode(a.name,’physical writes’,value,.00000000001)) rwr,

(sum(decode(a.name,’table scan blocks gotten’,value,0)) –

sum(decode(a.name,’table scans (short tables)’,value,0)) * 4) /

sum(decode(a.name,’table scans (long tables)’,value,.00000000001)) bpfts

from v$sysstat a

/

prompt

prompt ——————————————————————————–

prompt This looks at overall i/o activity against individual files within a

prompt tablespace

prompt

prompt Look for a mismatch across disk drives in terms of I/O

prompt

prompt Also, examine the Blocks per Read Ratio for heavily accessed

prompt TSs – if this value is significantly above 1 then you may have

prompt full tablescans occurring (with multi-block I/O)

prompt

prompt If activity on the files is unbalanced, move files around to balance

prompt the load. Should see an approximately even set of numbers across files.

prompt

set pagesize 100;

set space 1

column pbr format 99999999999 heading ‘Physical|Blk Read’

column pbw format 999999999 heading ‘Physical|Blks Wrtn’

column pyr format 999999 heading ‘Physical|Reads’

column readtim format 99999999 heading ‘Read|Time’

column name format a35 heading ‘DataFile Name’

column writetim format 99999999 heading ‘Write|Time’

ttitle center ‘Tablespace Report’ skip 2

compute sum of f.phyblkrd, f.phyblkwrt on report

rem

select fs.name name,f.phyblkrd pbr,f.phyblkwrt pbw,f.readtim, f.writetim

from v$filestat f, v$datafile fs

where f.file# = fs.file#

order by fs.name

/

prompt

prompt ——————————————————————————–

prompt GENERATING WAIT STATISTICS:

prompt

prompt This will show wait stats for certain kernel instances. This may show

prompt the need for additional rbs, wait lists, db_buffers

prompt

ttitle center ‘Wait Statistics for the Instance’ skip 2

column class heading ‘Class Type’

column count format 99,999,999 heading ‘Times Waited’

column time heading ‘Total Times’ format 99,999,999

select class, count, time

from v$waitstat

where count > 0

order by class

/

prompt

prompt Look at the wait statistics generated above (if any). They will

prompt tell you where there is contention in the system. There will

prompt usually be some contention in any system – but if the ratio of

prompt waits for a particular operation starts to rise, you may need to

prompt add additional resource, such as more database buffers, log buffers,

prompt or rollback segments

prompt

prompt ——————————————————————————–

prompt ROLLBACK STATISTICS:

prompt

ttitle off;

set linesize 132

column extents format 999 heading ‘Extents’

column rssize format 999,999,999 heading ‘Size in|Bytes’

column optsize format 999,999,999 heading ‘Optimal|Size’

column hwmsize format 99,999,999 heading ‘High Water|Mark’

column shrinks format 9,999 heading ‘Number of|Shrinks’

column wraps format 9,999 heading ‘Number of|Wraps’

column extends format 999,999 heading ‘Number of|Extends’

column aveactive format 999,999,999 heading ‘Average size|Active Extents’

column rownum noprint

select rssize, optsize, hwmsize, shrinks, wraps, extends, aveactive

from v$rollstat

order by rownum

/

rem

prompt

prompt ——————————————————————————–

set linesize 80

break on report

compute sum of gets waits writes on report

ttitle center ‘Rollback Statistics’ skip 2

select rownum, extents, rssize, xacts, gets, waits, writes

from v$rollstat

order by rownum

/

ttitle off

set heading off

ttitle off

prompt

prompt ——————————————————————————–

prompt

prompt SORT AREA SIZE VALUES:

prompt

prompt To make best use of sort memory, the initial extent of your Users

prompt sort-work Tablespace should be sufficient to hold at least one sort

prompt run from memory to reduce dynamic space allocation. If you are getting

prompt a high ratio of disk sorts as opposed to memory sorts, setting

prompt sort_area_retained_size = 0 in init.ora will force the sort area to be

prompt released immediately after a sort finishes.

prompt

column value format 999,999,999,999

select ‘INIT.ORA sort_area_size: ‘||value

from v$parameter where name like ‘sort_area_size’;

select a.name, value

from v$statname a, v$sysstat

where a.statistic# = v$sysstat.statistic#

and a.name in (‘sorts (disk)’,’sorts (memory)’,’sorts (rows)’)

/

prompt

prompt ——————————————————————————–

set heading on

set space 2

prompt

prompt This looks at Tablespace Sizing – Total bytes and free bytes

prompt

ttitle center ‘Tablespace Sizing Information’ Skip 2

column tablespace_name format a30 heading ‘TS Name’

column sbytes format 999,999,999,999 heading ‘Total Bytes’

column fbytes format 9,999,999,999 heading ‘Free Bytes’

column kount format 999 heading ‘Ext’

compute sum of fbytes on tablespace_name

compute sum of sbytes on tablespace_name

compute sum of sbytes on report

compute sum of fbytes on report

break on report

rem Here must grant select on DBA_FREE_SPACE directly to the

rem creator of this view, else error occurs indicating that you cannot create

rem view using role privs

create or replace view sum_tbsp_free as

select sum(bytes) bytes, count(bytes) num_chks, tablespace_name

from sys.dba_free_space

group by tablespace_name

/

rem kept Marlene’s query, just substituted the view for DBA_FREE_SPACE and

rem removed SUMS/COUNT verb from associated attributes

rem group by using “b” items works because of 1-to-1 relationship

select a.tablespace_name, sum(a.bytes) sbytes, b.bytes fbytes,

b.num_chks kount

from dba_data_files a, sum_tbsp_free b

where a.tablespace_name = b.tablespace_name

group by a.tablespace_name, b.bytes,b.num_chks

order by a.tablespace_name

/

set linesize 80

prompt

prompt A large number of Free Chunks indicates that the tablespace may need

prompt to be defragmented and compressed.

prompt

prompt ——————————————————————————–

set heading off

ttitle off

column value format 99,999,999,999

select ‘Total Physical Reads’, value

from v$sysstat

where statistic# = 39

/

prompt

prompt If you can significantly reduce physical reads by adding incremental

prompt data buffers…do it. To determine whether adding data buffers will

prompt help, set db_block_lru_statistics = TRUE and

prompt db_block_lru_extended_statistics = TRUE in the init.ora parameters.

prompt You can determine how many extra hits you would get from memory as

prompt opposed to physical I/O from disk. **NOTE: Turning these on will

prompt impact performance. One shift of statistics gathering should be enough

prompt to get the required information.

prompt

set heading on

clear computes

ttitle off

prompt

prompt ——————————————————————————–

prompt CHECKING FOR FRAGMENTED DATABASE OBJECTS:

prompt

prompt Fragmentation report – If number of extents is approaching Maxextents,

prompt it is time to defragment the table.

prompt

column owner noprint new_value owner_var

column segment_name format a30 heading ‘Object Name’

column segment_type format a9 heading ‘Table/Indx’

column sum(bytes) format 999,999,999 heading ‘Bytes Used’

column count(*) format 999 heading ‘No.’

break on owner skip page 2

ttitle center ‘Table Fragmentation Report’ skip 2 –

left ‘creator: ‘ owner_var skip 2

select a.owner, segment_name, segment_type, sum(bytes), max_extents, count(*)

from dba_extents a, dba_tables b

where segment_name = b.table_name

having count(*) > 3

group by a.owner, segment_name, segment_type, max_extents

order by a.owner, segment_name, segment_type, max_extents

/

ttitle center ‘Index Fragmentation Report’ skip 2 –

left ‘creator: ‘ owner_var skip 2

select a.owner, segment_name, segment_type, sum(bytes), max_extents, count(*)

from dba_extents a, dba_indexes b

where segment_name = index_name

having count(*) > 3

group by a.owner, segment_name, segment_type, max_extents

order by a.owner, segment_name, segment_type, max_extents

/

prompt

prompt ——————————————————————————–

spool off

exit

****************************************************

File Name : tx_lock.sql

****************************************************

accept val1 number prompt “VALUE of P2(session_wait) Id1(v$lock):”

select trunc(&val1/65536) “Rollback Seg#”, (&val1 – (trunc(&val1/65536)*65536)) “Wrap”

from dual

/

****************************************************

File Name : unable_to_alloc_next.sql

****************************************************

set pagesize 50 trimspool on linesize 250 verify off feedback off term on echo on

col segname format a30 heading ‘OBJECT’

col segown format a10 heading ‘OWNER’

col segtype format a5 heading ‘TYPE’

col segtbs format a15 heading ‘TABLESPACE’

col nextext format 9,999,999,999 heading ‘NEXT EXTENT’

col contigfree format 9,999,999,999 heading ‘CONTIG FREE SPACE’

col freepct format 999 heading ‘FREE PCT%’

break on report on segtbs skip 1

select segtbs, segown, segname, contigfree, nextext,freepct

from extgrow

where growdate = to_date(‘&1′,’YYYYMMDD’)

and nextext > contigfree

order by segtbs, segown, segname

spool $RPT/unable_to_extend.log

/

—exit

****************************************************

File Name : upd_growth_table.sql

****************************************************

set term off echo off

execute update_growth_table(‘ATS’);

exit

****************************************************

File Name : us.sql

****************************************************

select count(*) From v$session where username <> ‘ ‘;

****************************************************

File Name : used_space.sql

****************************************************

set heading on pagesize 25 feedback off echo off

set space 2

ttitle center ‘Tablespace Sizing Information’ Skip 2

column tablespace_name format a15 heading ‘TS Name’

column sbytes format 999,999,999,999 heading ‘Total Bytes’

column fbytes format 999,999,999,999 heading ‘Free Bytes’

column used format 999,999,999,999 heading ‘Used Bytes’

column kount format 9999 heading ‘Ext’

column pct format 999.9 heading ‘PCT’

compute sum of used on tablespace_name

compute sum of fbytes on tablespace_name

compute sum of sbytes on tablespace_name

compute sum of used on report

compute sum of sbytes on report

compute sum of fbytes on report

break on report

rem Here must grant select on DBA_FREE_SPACE directly to the

rem creator of this view, else error occurs indicating that you cannot create

rem view using role privs

rem create or replace view sum_tbsp_free as

rem select sum(bytes) bytes, count(bytes) num_chks, tablespace_name

rem from sys.dba_free_space

rem group by tablespace_name

rem /

rem kept Marlene’s query, just substituted the view for DBA_FREE_SPACE and

rem removed SUMS/COUNT verb from associated attributes

rem group by using “b” items works because of 1-to-1 relationship

set term off echo off

spool $RPT/used_space.log

select a.tablespace_name, sum(a.bytes) sbytes, b.bytes fbytes,

(sum(a.bytes)-b.bytes) used

from dba_data_files a, sum_tbsp_free b

where a.tablespace_name = b.tablespace_name

group by a.tablespace_name, b.bytes

order by a.tablespace_name

/

set linesize 80

ttitle off

spool off

exit

****************************************************

File Name : user.sql

****************************************************

col osuser format a14

select sid,serial#,SQL_HASH_VALUE,sql_address,PREV_HASH_VALUE,PREV_SQL_ADDR,

program,osuser,machine,username,status,to_char(logon_time,’DD-MON-YY HH24:MI:SS’) from v$session where SID = &1

/

****************************************************

File Name : user_cpu_cmp.sql

****************************************************

select actual_user,total_users,USER_CPU ,SYSTEM_CPU ,RUNQUE_WAITS,

to_char(start_Date,’DD-MON-YYYY HH24:MI:SS’) from stats$vmstat,stats$totalusers

where measured_date = start_date and measured_date >= to_date(‘11212001000000′,’MMDDRRRRHH24MISS’)

/

****************************************************

File Name : user_info.sql

****************************************************

accept UNM char prompt “Username :”

select program,osuser,machine,username,status,to_char(logon_time,’DD-MON-YY HH24:MI:SS’)

from v$session

where username = upper(‘&UNM’)

/

****************************************************

File Name : user_on_dblink.sql

****************************************************

select b.sid,b.serial#,b.username,b.machine,b.program

from v$session_wait a,V$session b

where a.sid=b.sid

and a.event=’SQL*Net message from dblink’

/

****************************************************

File Name : user_status.sql

****************************************************

select sid,serial#,status from v$session where username = ‘&1’

/

****************************************************

File Name : users_ts_xref.sql

****************************************************

set pagesize 60

set term off

set echo off

break on owner on tablespace_name

column owner format a20

column tablespace_name format a30

column objects format a20

select

substr(owner,1,20) owner,

substr(tablespace_name,1,30) ts_name,

count(*)||’ tables’ objects

from dba_tables

group by

substr(owner,1,20),

substr(tablespace_name,1,30)

union

select

substr(owner,1,20) owner,

substr(tablespace_name,1,30) ts_name,

count(*)||’ indexes’ objects

from dba_indexes

group by

substr(owner,1,20),

substr(tablespace_name,1,30)

spool $RPT/user_locs_$ORACLE_SID.rpt

/

spool off

rem user list by tablespace for export reference

rem uses the column and pagesize already set

clear breaks

break on tablespace_name on owner

select

substr(tablespace_name,1,30) ts_name,

substr(owner,1,20) owner,

count(*)||’ tables’ objects

from dba_tables

group by

substr(tablespace_name,1,30),

substr(owner,1,20)

union

select

substr(tablespace_name,1,30) ts_name,

substr(owner,1,20) owner,

count(*)||’ indexes’ objects

from dba_indexes

group by

substr(tablespace_name,1,30),

substr(owner,1,20)

spool $RPT/ts_users_$ORACLE_SID.rpt

/

spool off

exit

****************************************************

File Name : usn.sql

****************************************************

col osuser format a14

col machine format a12

accept usn prompt “Enter User Name:”

select sid,serial#,SQL_HASH_VALUE,sql_address,PREV_HASH_VALUE,PREV_SQL_ADDR,

program,osuser,machine,username,status,to_char(logon_time,’DD-MON-YY HH24:MI:SS’) from v$session where username=upper(‘&usn’)

/

****************************************************

File Name : ussql.sql

****************************************************

select sql_text from v$sqlarea c,v$session a, v$process b

where a.sid = ‘&spid’

and a.paddr=b.addr

and hash_value = a.sql_hash_value

and c.address = a.sql_address

/

****************************************************

File Name : v.sql

****************************************************

select a.tablespace_name Tablespace,

sum(a.tots) Tot_Size,

sum(a.sumb) Tot_Free,

sum(a.sumb)*100/sum(a.tots) Pct_Free,

sum(a.largest) Max_Free,

sum(a.chunks) Chunks_Free

from

(

select tablespace_name,

0 tots,sum(bytes) sumb,

max(bytes) largest,

count(*) chunks

from sys.dba_free_space

group by tablespace_name

union

select tablespace_name,

sum(bytes) tots,

0,

0,

0

from sys.dba_data_files

group by tablespace_name) a

group by tablespace_name

/

****************************************************

File Name : v1.sql

****************************************************

Declare

l_ZIP_ZIP_CODE VARCHAR2(10);

l_NAME VARCHAR2(30);

l_CTY_CODE VARCHAR2(3);

l_STE_CODE VARCHAR2(2);

l_STREET_ADDRESS_1 VARCHAR2(50);

l_STREET_ADDRESS2 VARCHAR2(50);

l_UOR_ID NUMBER(10) := 102269520;

BEGIN

SELECT /*+ USE_NL(A B) */ ZIP_ZIP_CODE,NAME,A.CTY_CODE,A.STE_CODE,

STREET_ADDRESS_1,STREET_ADDRESS2

into

l_ZIP_ZIP_CODE,l_NAME,l_CTY_CODE,l_STE_CODE,l_STREET_ADDRESS_1,l_STREET_ADDRESS2

FROM ATS_ADDRESSES A,ATS_CITIES B

WHERE UOR_ID = l_uor_id

AND B.ID = A.CITY_ID AND ROWNUM = 1;

END ;

/

****************************************************

File Name : v_depen1.sql

****************************************************

REM depends.sql Try to determine what objects an objects depends on

REM Oracle 8 version.

REM

REM Usage: Connect to SQL*Plus as a DBA user and run this script.

REM When prompted for ‘OWNER’ enter the owner or a pattern

REM Eg: sco%

REM When prompted for the ‘OBJECT’ enter its name or a pattern.

REM The relevant objects should be listed.

REM Select the object ID of the required object to check.

REM

REM A immediate dependency chart should be shown.

REM

REM

set echo off

set feedback off

set ver off

set pages 10000

column Owner format “A10”

column Obj# format “99999”

column Object format “A42”

rem

ACCEPT OWN CHAR PROMPT “Enter OWNER pattern: ”

ACCEPT NAM CHAR PROMPT “Enter OBJECT NAME pattern: ”

prompt

prompt “Objects matching &&OWN..&&NAM”

prompt “~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

select o.obj# “Obj#”,

decode(o.linkname, null,

u.name||’.’||o.name,

o.remoteowner||’.’||o.name||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’,

13, ‘TYPE’, 14,’TYPE BODY’,

19,’TABLE PARTITION’, 20,’INDEX PARTITION’,

21,’LOB’,22,’LIBRARY’,

23,’DIRECTORY’, ‘UNDEFINED’) “Type”,

decode(o.status,0,’N/A’,1,’VALID’, ‘INVALID’) “Status”

from sys.obj$ o, sys.user$ u

where owner#=user#

and u.name like upper(‘&&OWN’) and o.name like upper(‘&&NAM’)

;

prompt

ACCEPT OBJID CHAR PROMPT “Enter Object ID required: ”

prompt

prompt

prompt “Object &&OBJID is:”

prompt “~~~~~~~~~~~~~~~~~~~”

select o.obj# “Obj#”,

decode(o.linkname, null,

u.name||’.’||o.name,

o.remoteowner||’.’||o.name||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’,

13, ‘TYPE’, 14,’TYPE BODY’,

19,’TABLE PARTITION’, 20,’INDEX PARTITION’,

21,’LOB’,22,’LIBRARY’,

23,’DIRECTORY’, ‘UNDEFINED’) “Type”,

decode(o.status,0,’N/A’,1,’VALID’, ‘INVALID’) “Status”,

substr(to_char(stime,’DD-MON-YYYY HH24:MI:SS’),1,20) “S-Time”

from sys.obj$ o, sys.user$ u

where owner#=user# and o.obj#=’&&OBJID’

;

prompt

prompt “Depends on:”

prompt “~~~~~~~~~~~”

select o.obj# “Obj#”,

decode(o.linkname, null,

nvl(u.name,’Unknown’)||’.’||nvl(o.name,’Dropped?’),

o.remoteowner||’.’||nvl(o.name,’Dropped?’)||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’,

13, ‘TYPE’, 14,’TYPE BODY’,

19,’TABLE PARTITION’, 20,’INDEX PARTITION’,

21,’LOB’,22,’LIBRARY’,

23,’DIRECTORY’, ‘UNDEFINED’) “Type”,

decode(sign(stime-P_TIMESTAMP),

1,’*NEWER*’,-1,’*?OLDER?*’,null,’-‘,’-SAME-‘) “TimeStamp”,

decode(o.status,0,’N/A’,1,’VALID’,’INVALID’) “Status”

from sys.dependency$ d, sys.obj$ o, sys.user$ u

where P_OBJ#=obj#(+) and o.owner#=u.user#(+) and D_OBJ#=’&&OBJID’

;

prompt

prompt “Direct Dependants:”

prompt “~~~~~~~~~~~~~~~~~~”

select o.obj# “Obj#”,

decode(o.linkname, null,

nvl(u.name,’Unknown’)||’.’||nvl(o.name,’Dropped?’),

o.remoteowner||’.’||nvl(o.name,’Dropped?’)||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’,

13, ‘TYPE’, 14,’TYPE BODY’,

19,’TABLE PARTITION’, 20,’INDEX PARTITION’,

21,’LOB’,22,’LIBRARY’,

23,’DIRECTORY’, ‘UNDEFINED’) “Type”,

decode(sign(stime-D_TIMESTAMP),

1,’*NEWER*’,-1,’*?OLDER?*’,null,’-‘,’-SAME-‘) “TimeStamp”,

decode(o.status,0,’N/A’,1,’VALID’,’INVALID’) “Status”

from sys.dependency$ d, sys.obj$ o, sys.user$ u

where D_OBJ#=obj#(+) and o.owner#=u.user#(+) and P_OBJ#=’&&OBJID’

;

****************************************************

File Name : verify_user.sql

****************************************************

select table_name from dba_Tables where table_name in

(select table_name from dba_tab_columns

where owner = ‘ATS’

and column_name in (‘DT_CRTD’,’DT_MDFD’,’USR_MDFD’,’USR_CRTD’)

group by table_name having count(*) =4)

minus

select table_name from dba_triggers where

(owner,trigger_name) in (

select a.owner,a.name

from

(select distinct owner,name,type from dba_dependencies

where referenced_name = UPPER(‘SET_AUDIT_PROC’)

) a,

dba_objects b

where a.name=b.object_name

and a.owner=b.owner

and a.type = b.object_type

and b.objecT_type = ‘TRIGGER’

and b.owner = ‘ATS’

)

/

****************************************************

File Name : verindex.sql

****************************************************

select index_name, status

from dba_indexes a

where index_name in

( ‘FLPRD_PDT_FK_I’,

‘ATS_SCP_2ND_CHOICE_FK_I’

);

****************************************************

File Name : version.sql

****************************************************

select

to_char(min(v)) ||

decode(

max(v) – min(v),

0, null,

‘ to ‘ || to_char(max(v))

) version_count,

count(*) cursors

from

(

select

count(*) v

from

sys.x$kglcursor

where

kglhdadr != kglhdpar

group by

kglhdpar,

kglnahsh

)

group by

trunc(round(log(2, v), 37))

/

****************************************************

File Name : version_sql.sql

****************************************************

select SQL_TEXT,OUTLINE_MISMATCH ,EXPLAIN_PLAN_CURSOR, BUFFERED_DML_MISMATCH , BIND_MISMATCH

from V$SQL_SHARED_CURSOR a, v$sqlarea b

where a.KGLHDPAR = b.address

and b.version_count >6

/

****************************************************

File Name : viv_depen.sql

****************************************************

set feedback off

set ver off

set pages 10000

column Owner format “A10”

column Obj# format “99999”

column Object format “A42”

rem

ACCEPT OWN CHAR PROMPT “Enter OWNER pattern: ”

ACCEPT NAM CHAR PROMPT “Enter OBJECT NAME pattern: ”

prompt

prompt “Objects matching &&OWN..&&NAM”

prompt “~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

select o.obj# “Obj#”,

decode(o.linkname, null,

u.name||’.’||o.name,

o.remoteowner||’.’||o.name||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’, ‘UNDEFINED’) “Type”,

decode(o.status,0,’N/A’,1,’VALID’, ‘INVALID’) “Status”

from sys.obj$ o, sys.user$ u

where owner#=user#

and u.name like upper(‘&&OWN’) and o.name like upper(‘&&NAM’)

;

prompt

ACCEPT OBJID CHAR PROMPT “Enter Object ID required: ”

prompt

prompt

prompt “Object &&OBJID is:”

prompt “~~~~~~~~~~~~~~~~~~~”

select o.obj# “Obj#”,

decode(o.linkname, null,

u.name||’.’||o.name,

o.remoteowner||’.’||o.name||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’, ‘UNDEFINED’) “Type”,

decode(o.status,0,’N/A’,1,’VALID’, ‘INVALID’) “Status”,

substr(to_char(stime,’DD-MON-YYYY HH24:MI:SS’),1,20) “S-Time”

from sys.obj$ o, sys.user$ u

where owner#=user# and o.obj#=’&&OBJID’

;

prompt

prompt “Depends on:”

prompt “~~~~~~~~~~~”

select o.obj# “Obj#”,

decode(o.linkname, null,

nvl(u.name,’Unknown’)||’.’||nvl(o.name,’Dropped?’),

o.remoteowner||’.’||nvl(o.name,’Dropped?’)||’@’||o.linkname) “Object”,

decode(o.type#, 0, ‘NEXT OBJECT’, 1, ‘INDEX’, 2, ‘TABLE’, 3, ‘CLUSTER’,

4, ‘VIEW’, 5, ‘SYNONYM’, 6, ‘SEQUENCE’,

7, ‘PROCEDURE’, 8, ‘FUNCTION’, 9, ‘PACKAGE’,

10, ‘*Not Exist*’,

11, ‘PKG BODY’, 12, ‘TRIGGER’, ‘UNDEFINED’) “Type”,

decode(sign(stime-P_TIMESTAMP),

1,’*NEWER*’,-1,’*?OLDER?*’,null,’-‘,’-SAME-‘)

“TimeStamp”,

decode(o.status,0,’N/A’,1,’VALID’,’INVALID’) “Status”

from sys.dependency$ d, sys.obj$ o, sys.user$ u

where P_OBJ#=obj#(+) and o.owner#=u.user#(+) and D_OBJ#=’&&OBJID’

/

****************************************************

File Name : vivek_pin.sql

****************************************************

set pagesize 0 feedback off

spool ./pin_sga_viv.sql

select ‘execute dbms_shared_pool.keep(”’||'”‘||owner||'”‘||’.’||name||”’,”’||decode(type,’PACKAGE’,’p’,’SEQUENCE’,’q’,’TRIGGER’,’r’,’PROCEDURE’,’p’,’FUNCTION’,’p’)||”’);’

from v$db_object_cache

WHERE

type in (‘PACKAGE’,’SEQUENCE’,’TRIGGER’,’PROCEDURE’,’FUNCTION’)

and kept=’NO’

/

spool off

exit

–owner in (‘ATS’,’SYS’,’1193′,’6344′,’5336′,’ASHISH’,’BLOOMORA’,’EXPUSER’,’SHISHIR’,’SYSMON’) and

****************************************************

File Name : vivek_pin_cp.sql

****************************************************

set pagesize 0 feedback off

spool ./pin_sga_viv.sql

select ‘execute dbms_shared_pool.keep(”’||'”‘||owner||'”‘||’.’||name||”’,”’||decode(type,’PACKAGE’,’p’,’SEQUENCE’,’q’,’TRIGGER’,’r’,’PROCEDURE’,’p’,’FUNCTION’,’p’)||”’);’

from v$db_object_cache

WHERE

owner in (‘ATS’,’SYS’,’1193′,’6344′,’5336′,’ASHISH’,’BLOOMORA’,’EXPUSER’,’SHISHIR’,’SYSMON’) and

type in (‘PACKAGE’,’SEQUENCE’,’TRIGGER’,’PROCEDURE’,’FUNCTION’)

and kept = ‘NO’

/

spool off

exit

****************************************************

File Name : vivlock.sql

****************************************************

SELECT /*+ ORDERED */

s.username,

s.sid,

s.serial#,

DECODE(l.type,’TX’,’Transaction’,’ ‘||o.name) name,

DECODE(l.block,1,’~g0bYes’,’No’),

l.ctime,

DECODE(x.request,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) request_mode,

DECODE(x.lmode,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) held_mode,

l.type,

DECODE(l.block,1,’Red’,’Black’) color

FROM sys.v_$session s, sys.v_$lock l,sys.v_$resource r,sys.v_$_lock x, sys.obj$ o

WHERE s.sid = l.sid

AND l.addr=x.laddr (+)

AND l.type =’TX’

AND x.raddr=r.addr (+)

AND o.obj# (+) = l.id1

AND l.id1 in (select id1 from sys.v_$lock a where a.block=1)

UNION

SELECT /*+ ORDERED */

s.username,

s.sid,

s.serial#,

DECODE(l.type,’TX’,’Transaction’,’ ‘||o.name),

DECODE(l.block,1,’~g0bYes’,’No’),

l.ctime,

DECODE(x.request,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) request_mode,

DECODE(x.lmode,0,’ ‘,

1,’Null’,

2,’Row-S’,

3,’Row-X’,

4,’Share’,

5,’S/Row-X’,

6,’Exclusive’) held_mode,

l.type,

DECODE(l.block,1,’Red’,’Black’) color

FROM sys.v_$session s, sys.v_$lock l,sys.v_$resource r,sys.v_$_lock x, sys.obj$ o

WHERE s.sid = l.sid

AND l.addr=x.laddr (+)

AND l.type =’TM’

AND x.raddr=r.addr (+)

AND o.obj# (+) = l.id1

ORDER BY 3 ASC, 7 DESC

/

****************************************************

File Name : w.sql

****************************************************

set pages 2000

set lines 132

column event format a25

column p1text format a20

column p2text format a20

column p3text format a10

column p3 format 999

select event,p1text,p1,p2text,p2,p3text,p3 from v$session_wait

where event not in

(‘SQL*Net message from client’,’SQL*Net message from dblink’,’SQL*Net message to client’,

‘SQL*Net more data to client’,’pipe get’,’pmon timer’,’rdbms ipc message’,’smon timer’)

/

****************************************************

File Name : w1.sql

****************************************************

set pages 2000

set lines 132

column event format a25

column p1text format a20

column p2text format a20

column p3text format a10

select sid,event,p1text,p1,p2text,p2,p3text,p3 from v$session_wait

where event not in

(‘SQL*Net message from client’,’SQL*Net message from dblink’,’SQL*Net message to client’,

‘SQL*Net more data to client’,’pipe get’,’pmon timer’,’rdbms ipc message’,’smon timer’)

/

****************************************************

File Name : wa.sql

****************************************************

select p1,p2,p3 from v$session_wait where sid = &1

/

–select TYPE, ID1, ID2, LMODE, REQUEST, CTIME from v$lock where sid = &&1

–/

****************************************************

File Name : wait.sql

****************************************************

set pages 2000

set lines 132

column p1text format a18

column event format a35

column WT format 9999

column SW format 9999

select sid, event,p1text,p1raw,p1,p2,p3,seconds_in_Wait “SW”,Wait_time “WT”

from v$session_wait

where event not in(

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqcls – consumer closing TQ’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Message Fragment Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘Null event’,

‘PL/SQL lock timer’,

‘Parallel Query Idle Wait – Slaves’,

‘Replication Dequeue’,

‘SQL*Net message from client’,

‘buffer deadlock’,

‘dispatcher timer’,

‘io done’,

‘pipe get’,

‘pmon timer’,

‘rdbms ipc message’,

‘rdbms ipc message block’,

‘rdbms ipc reply’,

‘slave wait’,

‘smon timer’,

‘virtual circuit status’)

/

****************************************************

File Name : wait1.sql

****************************************************

set pages 2000

set lines 132

column p1text format a18

column event format a35

column WT format 9999

column SW format 9999

select sid, event,p1text,p1raw,p1,p2

from v$session_wait

where event not in(

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqcls – consumer closing TQ’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Message Fragment Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘Null event’,

‘PL/SQL lock timer’,

‘Parallel Query Idle Wait – Slaves’,

‘Replication Dequeue’,

‘SQL*Net message from client’,

‘buffer deadlock’,

‘dispatcher timer’,

‘io done’,

‘pipe get’,

‘pmon timer’,

‘rdbms ipc message’,

‘rdbms ipc message block’,

‘rdbms ipc reply’,

‘slave wait’,

‘smon timer’,

‘virtual circuit status’)

/

****************************************************

File Name : wait2.sql

****************************************************

set pages 2000

set lines 132

column p1text format a18

column event format a30

column WT format 9999

column SW format 9999

col ksuudlna format a10 heading “ORA User”

col KSUSEUNM format a10 heading “OS User”

col KSUSEMNM format a10 heading “Machine”

select sid, event,p1text,p1raw,p1,p2,p3,seconds_in_Wait “SW”,Wait_time “WT”,c.ksuudlna,c.KSUSEUNM,c.KSUSEMNM

from v$session_wait,

x$ksuse c

where event not in(

‘KXFQ: Dequeue Range Keys – Slave’,

‘KXFQ: Dequeuing samples’,

‘KXFQ: kxfqcls – consumer closing TQ’,

‘KXFQ: kxfqdeq – dequeue from specific qref’,

‘KXFQ: kxfqdeq – normal deqeue’,

‘KXFX: Execution Message Dequeue – Slave’,

‘KXFX: Message Fragment Dequeue – Slave’,

‘KXFX: Parse Reply Dequeue – Query Coord’,

‘Null event’,

‘PL/SQL lock timer’,

‘Parallel Query Idle Wait – Slaves’,

‘Replication Dequeue’,

‘SQL*Net message from client’,

‘buffer deadlock’,

‘dispatcher timer’,

‘io done’,

‘pipe get’,

‘pmon timer’,

‘rdbms ipc message’,

‘rdbms ipc message block’,

‘rdbms ipc reply’,

‘slave wait’,

‘smon timer’,

‘virtual circuit status’)

and c.indx = v$session_wait.SID

/

****************************************************

File Name : waiters.sql

****************************************************

column event format a29

column t0 format 999

column t1 format 999

column t2 format 999

column t3 format 999

column t4 format 999

column t5 format 999

column t6 format 999

column t7 format 999

column t8 format 999

column t9 format 999

select /*+ ordered */

substr(n.name, 1, 29) event,

t0,

t1,

t2,

t3,

t4,

t5,

t6,

t7,

t8,

t9

from

sys.v$event_name n,

(select event e0, count(*) t0 from sys.v_$session_wait group by event),

(select event e1, count(*) t1 from sys.v_$session_wait group by event),

(select event e2, count(*) t2 from sys.v_$session_wait group by event),

(select event e3, count(*) t3 from sys.v_$session_wait group by event),

(select event e4, count(*) t4 from sys.v_$session_wait group by event),

(select event e5, count(*) t5 from sys.v_$session_wait group by event),

(select event e6, count(*) t6 from sys.v_$session_wait group by event),

(select event e7, count(*) t7 from sys.v_$session_wait group by event),

(select event e8, count(*) t8 from sys.v_$session_wait group by event),

(select event e9, count(*) t9 from sys.v_$session_wait group by event)

where

n.name != ‘Null event’ and

n.name != ‘rdbms ipc message’ and

n.name != ‘pipe get’ and

n.name != ‘virtual circuit status’ and

n.name not like ‘%timer%’ and

n.name not like ‘SQL*Net message from %’ and

e0 (+) = n.name and

e1 (+) = n.name and

e2 (+) = n.name and

e3 (+) = n.name and

e4 (+) = n.name and

e5 (+) = n.name and

e6 (+) = n.name and

e7 (+) = n.name and

e8 (+) = n.name and

e9 (+) = n.name and

nvl(t0, 0) + nvl(t1, 0) + nvl(t2, 0) + nvl(t3, 0) + nvl(t4, 0) +

nvl(t5, 0) + nvl(t6, 0) + nvl(t7, 0) + nvl(t8, 0) + nvl(t9, 0) > 0

order by

nvl(t0, 0) + nvl(t1, 0) + nvl(t2, 0) + nvl(t3, 0) + nvl(t4, 0) +

nvl(t5, 0) + nvl(t6, 0) + nvl(t7, 0) + nvl(t8, 0) + nvl(t9, 0)

/

****************************************************

File Name : whence.sql

****************************************************

column object_owner format a10

column object_name format a50

select /*+ ordered use_hash(d) use_hash(o) */

o.kglnaown object_owner,

o.kglnaobj object_name,

sum(o.kglhdldc – decode(o.kglhdobj, hextoraw(’00’), 0, 1)) unloads,

sum(decode(bad_deps, 1, invalids, 0)) invalidations,

sum(decode(bad_deps, 1, 0, invalids)) and_maybe

from

(

select /*+ ordered use_hash(d) use_hash(o) */

c.kglhdadr,

sum(c.kglhdivc) invalids,

count(*) bad_deps

from

sys.x$kglcursor c,

sys.x$kgldp d,

sys.x$kglob o

where

c.inst_id = userenv(‘Instance’) and

d.inst_id = userenv(‘Instance’) and

o.inst_id = userenv(‘Instance’) and

c.kglhdivc > 0 and

d.kglhdadr = c.kglhdadr and

o.kglhdadr = d.kglrfhdl and

o.kglhdnsp = 1 and

(

o.kglhdldc > 1 or

o.kglhdobj = hextoraw(’00’)

)

group by

c.kglhdadr

) c,

sys.x$kgldp d,

sys.x$kglob o

where

d.inst_id = userenv(‘Instance’) and

o.inst_id = userenv(‘Instance’) and

d.kglhdadr = c.kglhdadr and

o.kglhdadr = d.kglrfhdl and

o.kglhdnsp = 1 and

(

o.kglhdldc > 1 or

o.kglhdobj = hextoraw(’00’)

)

group by

o.kglnaown,

o.kglnaobj

order by

sum(invalids / bad_deps)

/

****************************************************

File Name : where_sid_wait.sql

****************************************************

select event,p1,p2,p3 from v$session_wait where sid = &1

/

****************************************************

File Name : which_buff_obj.sql

****************************************************

select ‘KEEP’ POOL, o.name, count(buf#) BLOCKS

from obj$ o, x$bh x

where o.dataobj# = x.obj

and x.state !=0

and o.owner# !=0

and buf# >= (select lo_bnum from v$buffer_pool where name=’KEEP’

and buffers > 0)

and buf# <= (select hi_bnum from v$buffer_pool where name='KEEP'
and buffers > 0)

group by ‘KEEP’,o.name

union all

select ‘DEFAULT’ POOL, o.name, count(buf#) BLOCKS

from obj$ o, x$bh x

where o.dataobj# = x.obj

and x.state !=0

and o.owner# !=0

and buf# >= (select lo_bnum from v$buffer_pool where name=’DEFAULT’

and buffers > 0)

and buf# <= (select hi_bnum from v$buffer_pool where name='DEFAULT'
and buffers > 0)

group by ‘DEFAULT’,o.name

union all

select ‘RECYCLE’ POOL, o.name, count(buf#) BLOCKS

from obj$ o, x$bh x

where o.dataobj# = x.obj

and buf# >= (select lo_bnum from v$buffer_pool where name=’RECYCLE’

and buffers > 0)

and x.state !=0

and o.owner# !=0

and buf# <= (select hi_bnum from v$buffer_pool where name='RECYCLE'
and buffers > 0)

group by ‘RECYCLE’,o.name

order by 2

/

****************************************************

File Name : who_user.sql

****************************************************

select first_name,last_name from ats_employees where code = upper(‘&1’);

****************************************************

File Name : xview.sql

****************************************************

—

— Special purpose script to create view

— for later rapidly surfing exclusive locks ( held and requested)

—

— ( Internal tables and hints used due to extremely poor

— performance of v$lock and v$session views. )

—

— view v$ross ( named to indicate alterability! )

— will return only:

—

— * Exclusive lock holders more than 15 minutes old

— * Exclusive lock requesters more than 60 seconds old

— * Lock blockers at any time

—

— Script is intended to be run as part of automailing

— system. See LOOK_LONGLOCKS.SQL.

—

— Created and tested 7 Oct 98 RM/Greencastle Database Systems

—

–create or replace view V$ROSS as

create or replace view V$longlocks as

SELECT /*+ ordered use_nl(l), use_nl(s) +*/

a.first_name,

a.last_name,

s.indx “SID”,

r.ksqrsidt “TYPE”,

l.request “REQ”,

l.lmode “HLD”,

l.ctime “HELD_SEC”,

s.ksuudsna “OSUSER”,

s.ksuseunm “PROCESS”,

s.ksusemnm “TERMINAL”,

decode(l.block,1,’**BLOCKING**’,l.block) “BLOCKER”

FROM

v$_lock l,x$ksuse s, x$ksqrs r,ats.ats_employees a

WHERE

l.saddr=s.addr and

l.raddr=r.addr and

a.code(+)=s.ksuudsna and

r.ksqrsidt not in (‘MR’,’UL’,’RT’,’JQ’) and

(

((l.lmode=4 or l.lmode=6) and l.ctime>900) or

((l.request=4 or l.request=6) and l.ctime>60) or

(l.block!=0 )

)

/

=============== END OF MYFILE ======================

Oracle, SQL scripts

Post navigation

Previous Post: ORACLE_SID in sqlplus
Next Post: dbinv.sql

Related Posts

  • 556976.1 Oracle Clusterware: Components installed Oracle
  • FRA Information. Oracle
  • How to find pinned objects from shared pool. (pinned via dbms_shared_pool.keep) Oracle
  • Generating XML from SQLPLUS Oracle
  • Creating never expiring DB user accounts in Oracle Oracle
  • Finding locked objects Oracle

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • AWS (2)
  • Azure (1)
  • Linux/Unix (149)
  • Oracle (388)
  • PHP/MYSQL/Wordpress (10)
  • Power-BI (0)
  • Python/PySpark (7)
  • RAC (17)
  • rman-dataguard (26)
  • shell (149)
  • SQL scripts (337)
  • Uncategorized (0)
  • Videos (0)

Recent Posts

  • findinfo.sql (SQL for getting CPU and Active session info)27-May-2025
  • SQL Tracker by SID sqltrackerbysid.sql22-Apr-2025
  • How to connect to Oracle Database with Wallet with Python.21-Mar-2025
  • JSON/XML Types in Oracle18-Mar-2025
  • CPU Core related projections12-Mar-2025
  • Exadata Basics10-Dec-2024
  • Reading config file from other folder inside class24-Sep-2024
  • Python class import from different folders22-Sep-2024
  • Transfer SQL Profiles from One database to other database.05-Sep-2024
  • Load testing on Oracle 19C RAC with HammerDB18-Jan-2024

Archives

  • 2025
  • 2024
  • 2023
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006
  • 2005
  • 284785.1 How to check RAC Option is currently linked into the Oracle Binary Oracle
  • Some OS level threshold for performance. Linux/Unix
  • SQL Tracker by SID sqltrackerbysid.sql Oracle
  • Unix split command to split files Linux/Unix
  • How to check current redo log progress redo_progress.sql Oracle
  • Good notes on Oracle Events Oracle
  • switchover for primary database Oracle
  • Changing default shell Linux/Unix

Copyright © 2025 pvmehta.com.

Powered by PressBook News WordPress theme