important oracle query & script

Upload: biswajit-das

Post on 29-Oct-2015

89 views

Category:

Documents


1 download

DESCRIPTION

SQL queries you should know during monitoring of oracle databases

TRANSCRIPT

QUERIES

STATUS

Startup time

selectto_char(startup_time, 'HH24:MI DD-MON-YY') "Startup time"

fromv$instance

/

How large is the database

col "Database Size" format a20

col "Free space" format a20

col "Used space" format a20

selectround(sum(used.bytes) / 1024 / 1024 / 1024 ) || ' GB' "Database Size"

,round(sum(used.bytes) / 1024 / 1024 / 1024 ) -

round(free.p / 1024 / 1024 / 1024) || ' GB' "Used space"

,round(free.p / 1024 / 1024 / 1024) || ' GB' "Free space"

from (selectbytes from v$datafile

unionall

selectbytes from v$tempfile

union all

selectbytes from v$log) used, (select sum(bytes) as p from dba_free_space) free

group by free.p

/

Distribution of objects and data

Which schemas are taking up all of the spaceset pages 999

col "size MB" format 999,999,999

col "Objects" format 999,999,999

selectobj.owner "Owner",obj_cnt "Objects",decode(seg_size, NULL, 0, seg_size) "size MB"

from (select owner, count(*) obj_cnt from dba_objects group by owner) obj,(select owner, ceil(sum(bytes)/1024/1024) seg_size

from dba_segments group by owner) seg

where obj.owner = seg.owner(+)

orderby 3 desc ,2 desc, 1

/

Show the ten largest objects in the database

Col owner format a15

Col segment_name format a30

Col segment_type format a15

Col mb format 999,999,999

select owner,segment_name,segment_type,mb

from(select owner,segment_name,segment_type,bytes / 1024 / 1024 "MB"

from dba_segments

order by bytes desc

)

whererownum < 11

/

Is java installed in the database?

This will return 9000'ish if it is...select count(*)

from all_objects

where object_type like '%JAVA%'

and owner = 'SYS'

/

Display character set information

select * from nls_database_parameters

/

Show all used features

selectname

,detected_usages

fromdba_feature_usage_statistics

where detected_usages > 0

/

SESSION

Show all connected users

set lines 100 pages 999

col ID format a15

select username,sid || ',' || serial# "ID",status,last_call_et "Last Activity"

from v$session

where username is not null

order by status desc,last_call_et desc

/

Bottom of Form

Time since last user activity

set lines 100 pages 999

select username

, floor(last_call_et / 60) "Minutes"

, status

from v$session

where username is not null

order by last_call_et

/

Bottom of Form

Sessions sorted by logon time

set lines 100 pages 999

col ID

format a15

col osuserformat a15

col login_timeformat a14

select username

,osuser

,sid || ',' || serial# "ID"

,status

,to_char(logon_time, 'hh24:mi dd/mm/yy') login_time

,last_call_et

fromv$session

whereusername is not null

orderby login_time

/

Bottom of Form

Show user info including os pid

col "SID/SERIAL" format a10

col username format a15

col osuser format a15

col program format a40

selects.sid || ',' || s.serial# "SID/SERIAL"

,s.username

,s.osuser

,p.spid "OS PID"

,s.program

fromv$session s

,v$process p

Wheres.paddr = p.addr

order by to_number(p.spid)

/

Bottom of Form

Show a users current sql

Select sql_text

from v$sqlarea

where (address, hash_value) in

(select sql_address, sql_hash_value

from v$session

where username like '&username')

/

Bottom of Form

Session status associated with the specified os process id

selects.username

,s.sid

,s.serial#

,p.spid

,last_call_et

,status

from V$SESSION s

,V$PROCESS p

wheres.PADDR = p.ADDR

andp.spid='&pid'

/

Bottom of Form

All active sql

set feedback off

set serveroutput on size 9999

column username format a20

column sql_text format a55 word_wrapped

begin

for x in

(select username||'('||sid||','||serial#||') ospid = '|| process ||

' program = ' || program username,

to_char(LOGON_TIME,' Day HH24:MI') logon_time,

to_char(sysdate,' Day HH24:MI') current_time,

sql_address,

sql_hash_value

from v$session

where status = 'ACTIVE'

and rawtohex(sql_address) '00'

and username is not null ) loop

for y in (select sql_text

from v$sqlarea

where address = x.sql_address ) loop

if ( y.sql_text not like '%listener.get_cmd%' and

y.sql_text not like '%RAWTOHEX(SQL_ADDRESS)%' ) then

dbms_output.put_line( '--------------------' );

dbms_output.put_line( x.username );

dbms_output.put_line( x.logon_time || ' ' || x.current_time || ' SQL#=' || x.sql_hash_value);

dbms_output.put_line( substr( y.sql_text, 1, 250 ) );

end if;

end loop;

end loop;

end;

/

Bottom of Form

Display any long operations

set lines 100 pages 999

col username format a15

col message format a40

col remaining format 9999

selectusername

,to_char(start_time, 'hh24:mi:ss dd/mm/yy') started

,time_remaining remaining

,message

fromv$session_longops

wheretime_remaining = 0

order by time_remaining desc

/

Top of Form

Bottom of Form

List open cursors per user

set pages 999

select sess.username

,sess.sid

,sess.serial#

,stat.value cursors

fromv$sesstat stat

,v$statname sn

,v$session sess

wheresess.username is not null

andsess.sid = stat.sid

andstat.statistic# = sn.statistic#

andsn.name = 'opened cursors current'

order by value

/

Bottom of Form

Or alternatively... set lines 100 pages 999

select count(hash_value) cursors

, sid

, user_name

from v$open_cursor

group by

sid

, user_name

order by

cursors

/

INIT PARAMETERSShow latent parameter changes

select name

, value

from v$parameter

where ismodified != 'FALSE'

/

Bottom of Form

Show non-default parameters

set pages 999 lines 100

col name format a30

col value format a50

select name

,value

fromv$parameter

whereisdefault = 'FALSE'

andvalue is not null

orderby name

/

Bottom of Form

or for name='parameter' style...set pages 999 lines 100

select name || '=' || decode(type, 2, '''') || value

|| decode(type, 2, '''') parameter

fromv$parameter

whereisdefault = 'FALSE'

andvalue is not null

orderby name

/

Bottom of Form

Reset/Unset a spfile parameter

Setting a parameter to =' ' often isn't enough. Do this instead...alter system reset scope=spfile sid='*'

/

Bottom of Form

The sid='*' bit is always necessary, even in non RAC database.USER

List users

set pages 999 lines 100

col usernameformat a20

col statusformat a8

col tablespaceformat a20

col temp_tsformat a20

selectusername

,account_status status

,created

,default_tablespace tablespace

,temporary_tablespace temp_ts

fromdba_users

orderby username

/

Top of Form

Bottom of Form

Lock or unlock a user

alter user account lock;

Top of Form

Bottom of Form

And to unlock...alter user account unlock;

ROLEFind a role

select*

from dba_roles

whererole like '&role'

/

Bottom of Form

Show what roles are granted to a user

selectgrantee

,granted_role

,admin_option

fromdba_role_privs

wheregrantee like upper('&username')

/

Bottom of Form

Show what system privileges are granted to a role

selectprivilege

,admin_option

fromrole_sys_privs

whererole like '&role'

/

Bottom of Form

Show what table privileges are granted to a role

selectowner || '.' || table_name "TABLE"

,column_name

,privilege

,grantable

fromrole_tab_privs

whererole like '&role'

/

Administration - ASM

Check if css is running/working Display disk-groups Show disk space usage Create a disk group Add a disk to a group Drop a disk group Is ASM performing a balancing operation Check the internal consistency of a diskgroupCheck if css is running/working

crsctl check cssd

Bottom of Form

Display disk-groups

set lines 100

col nameformat a10

col path format a30

selectname

,group_number

,disk_number

,mount_status

,state

,path

from v$asm_disk

order by group_number

/

Bottom of Form

note. A group number of zero his indicates that a disk is available but hasn't yet been assigned to a disk group.Show disk space usage

select name

, group_number

, disk_number

, total_mb

, free_mb

from v$asm_disk

order by group_number

/

Bottom of Form

Create a disk group

create diskgroup data1

external redundancy

disk '/dev/raw/raw1'

/

Bottom of Form

or with multiple raw partitions...multiple disks

create diskgroup data2

external redundancy

disk'/dev/raw/raw2'

,'/dev/raw/raw3'

/

Bottom of Form

or with multiple fail groups...create diskgroup data3

normal redundancy

failgroup controller1 disk '/dev/raw/raw4'

failgroup controller2 disk '/dev/raw/raw6'

/

Bottom of Form

Add a disk to a group

alter diskgroup data1

add disk '/dev/raw/raw4'

/

Bottom of Form

Wildcards can be used for raw device names (eg. raw*)Drop a disk group

drop diskgroup ''

/

Bottom of Form

Is ASM performing a balancing operation

select *

from v$asm_operation

/

Bottom of Form

Mount/dismount disk groupsalter diskgroup all mount

/Bottom of Form

alter diskgroup data1 mount

/Bottom of Form

alter diskgroup all dismount

/Bottom of Form

alter diskgroup data1 dismount

/Bottom of Form

Check the internal consistency of a diskgroup

alter diskgroup data1 check all

/

Administration - RAC 10gR2

Start, stop and check CRS (Cluster Ready Services) Start/stop nodeapps Start/stop asm Start/stop a database (all nodes) Start/stop an individual instance Check the VIP config Change the VIP address, subnetmask or interface Locate the voting disk Retrive OCR (Oracle Cluster Registry) information To prevent a database starting at boot time Change the private interconnect subnetStart, stop and check CRS (Cluster Ready Services)

Note. Start/stop need to be run as root from the CRS home.

Start CRScrsctl start crs

Top of Form

Bottom of Form

Stop CRScrsctl stop crs

Top of Form

Bottom of Form

Check CRS's statuscrsctl check crs

Top of Form

Bottom of Form

See the status of the various servicescrs_stat -t

Top of Form

Bottom of Form

Start/stop nodeapps

srvctl start nodeapps -n

Top of Form

Bottom of Form

srvctl stop nodeapps -n

Top of Form

Bottom of Form

Start/stop asm

srvctl start asm -n

Top of Form

Bottom of Form

srvctl stop asm -n

Top of Form

Bottom of Form

Start/stop a database (all nodes)

srvctl start database -d

Top of Form

Bottom of Form

srvctl stop database -d

Top of Form

Bottom of Form

Start/stop an individual instance

srvctl start instance -d -i

Top of Form

Bottom of Form

srvctl stop instance -d -i

Top of Form

Bottom of Form

Check the VIP config

srvctl config nodeapps -n -a -g -s -l

Top of Form

Bottom of Form

Change the VIP address, subnetmask or interface

srvctl stop nodeapps -n

srvctl stop nodeapps -n

srvctl modify nodeapps -n -A //

srvctl modify nodeapps -n -A //

srvctl start nodeapps -n

srvctl start nodeapps -n

Top of Form

Bottom of Form

Locate the voting disk

crsctl query css votedisk

Top of Form

Bottom of Form

Retrive OCR (Oracle Cluster Registry) information

ocrcheck

Top of Form

Bottom of Form

To prevent a database starting at boot time

srvctl disable database -d

Top of Form

Bottom of Form

Change the private interconnect subnet

First find the interface which is in use as the interconnect - run as root from the crs home:oifcfg getif

Top of Form

Bottom of Form

Make a note of the interface name (eth1 in the following example), thenrun the following:oifcfg delif -global eth1

oifcfg setif -global eth1/:cluster_interconnect

Administration - Job Scheduler

List scheduled jobs Submit a job Remove a job Reset a broken job Add a program to the 10g scheduler (os program) Add a program to the 10g scheduler (stored procedure) Schedule a 10g jobList scheduled jobs

set lines 100 pages 999

colschema_user format a15

colfails format 999

selectjob

,schema_user

,to_char(last_date, 'hh24:mi dd/mm/yy') last_run

,to_char(next_date, 'hh24:mi dd/mm/yy') next_run

,failures fails

,broken

,substr(what, 1, 15) what

fromdba_jobs

order by 4

/

Top of Form

Bottom of Form

Submit a job

dbms_job.submit('', , , TRUE);

Top of Form

Bottom of Form

For example:declare

job_id number;

begin

dbms_job.submit(

job_id

,'andy.daily_data_clense'

,trunc(sysdate+1)+22/24

,'sysdate+1'

,true);

end;

/

Top of Form

Bottom of Form

This will run a stored procedure called 'daily_data_clense' each day at 10pm.Remove a job

You need to be connected as the user who owns the jobexec dbms_job.remove();

Top of Form

Bottom of Form

Reset a broken job

You need to be connected as the user who owns the jobexec dbms_job.broken(, FALSE);

Top of Form

Bottom of Form

Add a program to the 10g scheduler (os program)

begin

dbms_scheduler.create_program(

program_name=>'ANDY.job_test',

program_action=>'/home/oracle/andyb/job_test.sh',

program_type=>'EXECUTABLE',

comments=>'test job',

enabled=>TRUE);

end;

/

Top of Form

Bottom of Form

Add a program to the 10g scheduler (stored procedure)

begin

dbms_scheduler.create_program(

program_name=>'ANDY.job_test',

program_action=>'andy.job_test',

program_type=>'STORED_PROCEDURE',

comments=>'test program',

enabled=>TRUE);

end;

/

Top of Form

Bottom of Form

Schedule a 10g job

begin

dbms_sheduler.create_job(

job_name=>'andy.andy_job_test',

program_name=>'andy.job_test',

start_date=>

)

Administration - Recycle bin

Display the contents of the recycle bin Empty the recycle bin Drop an object with out putting it in the recycle binDisplay the contents of the recycle bin

show recyclebin

Top of Form

Bottom of Form

Empty the recycle bin

purge recyclebin

Top of Form

Bottom of Form

Drop an object with out putting it in the recycle bin

drop purge;

Structure - Tablespace

Tablespace usage Show the files that comprise a tablespace Tablespaces >80% full User quotas on all tablespaces List all objects in a tablespace Show all tablespaces used by a user Create a temporary tablespace Alter a databases default temporary tablespace Show segments that are approaching max_extents List the contents of the temporary tablespace(s)Tablespace usage

set pages 999

col tablespace_name format a40

col "size MB" format 999,999,999

col "free MB" format 99,999,999

col "% Used" format 999

select tsu.tablespace_name, ceil(tsu.used_mb) "size MB"

,decode(ceil(tsf.free_mb), NULL,0,ceil(tsf.free_mb)) "free MB"

,decode(100 - ceil(tsf.free_mb/tsu.used_mb*100), NULL, 100,

100 - ceil(tsf.free_mb/tsu.used_mb*100)) "% used"

from(select tablespace_name, sum(bytes)/1024/1024 used_mb

from dba_data_files group by tablespace_name union all

select tablespace_name || ' **TEMP**'

,sum(bytes)/1024/1024 used_mb

from dba_temp_files group by tablespace_name) tsu

,(select tablespace_name, sum(bytes)/1024/1024 free_mb

from dba_free_space group by tablespace_name) tsf

wheretsu.tablespace_name = tsf.tablespace_name (+)

orderby 4

/

Top of Form

Bottom of Form

Show the files that comprise a tablespace

set lines 100

col file_name format a70

select file_name

, ceil(bytes / 1024 / 1024) "size MB"

from dba_data_files

where tablespace_name like '&TSNAME'

/

Top of Form

Bottom of Form

Tablespaces >80% full

set pages 999 lines 100

col tablespace_name format a40

col "size MB" format 999999999

col "% Used" format 999

col "80%" format 999999

col "75%" format 999999

select tsu.tablespace_name

, ceil(tsu.used_mb) "size MB"

, 100 - floor(tsf.free_mb/tsu.used_mb*100) "% Used"

, (tsu.used_mb / 100) * (20 - floor(tsf.free_mb/tsu.used_mb*100)) "80%"

, (tsu.used_mb / 100) * (25 - floor(tsf.free_mb/tsu.used_mb*100)) "75%"

from (select tablespace_name, sum(bytes)/1024/1024 used_mb

from dba_data_files group by tablespace_name) tsu

, (select tablespace_name, sum(bytes)/1024/1024 free_mb

from dba_free_space group by tablespace_name) tsf

where tsu.tablespace_name = tsf.tablespace_name (+)

and 100 - floor(tsf.free_mb/tsu.used_mb*100) >= 80

order by 3,4,5

/

Top of Form

Bottom of Form

User quotas on all tablespaces

col quota format a10

select username

, tablespace_name

, decode(max_bytes, -1, 'unlimited'

, ceil(max_bytes / 1024 / 1024) || 'M' ) "QUOTA"

from dba_ts_quotas

where tablespace_name not in ('TEMP')

/

Top of Form

Bottom of Form

List all objects in a tablespace

set pages 999

col owner format a15

col segment_name format a40

col segment_type format a20

select owner

, segment_name

, segment_type

from dba_segments

where lower(tablespace_name) like lower('%&tablespace%')

order by owner, segment_name

/

Top of Form

Bottom of Form

Show all tablespaces used by a user

selecttablespace_name

,ceil(sum(bytes) / 1024 / 1024) "MB"

fromdba_extents

whereowner like '&user_id'

group by tablespace_name

order by tablespace_name

/

Top of Form

Bottom of Form

Create a temporary tablespace

create temporary tablespace temp

tempfile '' size 500M

/

Top of Form

Bottom of Form

Alter a databases default temporary tablespace

alter database default temporary tablespace temp

/

Top of Form

Bottom of Form

Show segments that are approaching max_extents

colsegment_name format a40

selectowner

,segment_type

,segment_name

,max_extents - extents as "spare"

,max_extents

fromdba_segments

whereowner not in ('SYS','SYSTEM')

and(max_extents - extents) < 10

order by 4

/

Top of Form

Bottom of Form

To change maxextentsalter storage(maxextents 150);

Top of Form

Bottom of Form

List the contents of the temporary tablespace(s)

set pages 999 lines 100

col username format a15

col mb format 999,999

select su.username

, ses.sid

, ses.serial#

, su.tablespace

, ceil((su.blocks * dt.block_size) / 1048576) MB

from v$sort_usage su

, dba_tablespaces dt

, v$session ses

where su.tablespace = dt.tablespace_name

and su.session_addr = ses.saddr

/

Structure - Objects

Find an object Invalid objects Show the size of an object All objects owned by a user Source code of a procedure Get an objects ddl (9i onwards) Display compilation errors and warnings Find all tables containing the specified column List all tables owned by a user sorted by sizeFind an object

set pages 999

col owner format a15

col object_name format a40

col object_type format a20

select owner

, object_name

, object_type

from dba_objects

where lower(object_name) like lower('%&object%')

order by owner, object_type, object_name

/

Top of Form

Bottom of Form

Invalid objects

List invalid objects... set lines 200 pages 999

col "obj" format a40

select owner || '.' || object_name "obj",

object_type

from dba_objects

where status = 'INVALID'

/

Top of Form

Bottom of Form

Recompile all invalid objects...@?/rdbms/admin/utlrp.sql

Top of Form

Bottom of Form

Show the size of an object

col segment_name format a20

select segment_name

, bytes "SIZE_BYTES"

, ceil(bytes / 1024 / 1024) "SIZE_MB"

from dba_segments

where segment_name like '&obj_name'

/

Top of Form

Bottom of Form

All objects owned by a user

col object_name format a40

select object_name

, object_type

from dba_objects

where owner = '&user'

order by object_type, object_name

/

Top of Form

Bottom of Form

Source code of a procedure

select text

from dba_source

where owner = 'ANDY'

and name = 'FILE_TEST'

and type = 'PACKAGE BODY'

order by line

/

Top of Form

Bottom of Form

Get an objects ddl (9i onwards)

Note. Works for 9i and newer.Parameters: OBJECT_TYPE, OBJECT_NAME, SCHEMAset pagesize 0

set long 90000

select dbms_metadata.get_ddl('TABLE','TABLE_A','ANDY') from dual;

Top of Form

Bottom of Form

Display compilation errors and warnings

show errors

show errors view

show errors procedure

Top of Form

Bottom of Form

select * from dba_errors;

Top of Form

Bottom of Form

Find all tables containing the specified column

set pages 999 lines 100

col tabformat a60

col column_name format a20

selectowner || '.' || table_name as tab

,column_name

fromdba_tab_columns

wherecolumn_name like upper('&col')

/

Top of Form

Bottom of Form

List all tables owned by a user sorted by size

set lines 100 pages 999

colsegment_nameformat a40

col mb

format 999,999,999

selectsegment_name

,ceil(sum(bytes) / 1024 / 1024) "MB"

fromdba_segments

whereowner like '&user'

andsegment_type = 'TABLE'

groupby segment_name

order by ceil(sum(bytes) / 1024 / 1024) desc

/

Structure - Indexes

Index info by table Show indexed columnsIndex info by table

selecti.index_name

,i.tablespace_name

,ceil(s.bytes / 1048576) "Size MB"

from dba_indexes i

,dba_segments s

where i.index_name = s.segment_name

and table_name like '&table'

order by 2, 1

/

Bottom of Form

Show indexed columns

select column_name

from dba_ind_columns

where index_name = '&index'

order by column_position

/

Structure - Files

Display all datafiles, tempfiles and logfiles (and their sizes) Quick datafile health check Show directories that contain datafiles List autoextensible datafiles Turn autoextend off for all datafiles Move files between disks List controlfiles Create an OS command for every file in the database Find duplicate filenames List files that are in hot-backup modeDisplay all datafiles, tempfiles and logfiles (and their sizes)

set lines 100 pages 999

col name format a50

selectname, bytes

from (selectname, bytes

fromv$datafile

unionall

selectname, bytes

from v$tempfile

union all

select lf.member "name", l.bytes

fromv$logfile lf

,v$log l

wherelf.group# = l.group#

union all

selectname, 0

fromv$controlfile) used

,(select sum(bytes) as p

from dba_free_space) free

/

Top of Form

Bottom of Form

Quick datafile health check

You should only see online and system (maybe read-only too)select distinct status from v$datafile

/

Top of Form

Bottom of Form

Show directories that contain datafiles

selectdistinct substr(name, 1, instr(name, '/', -1)) DIR

fromv$datafile

order by 1

/

Top of Form

Bottom of Form

List autoextensible datafiles

selectfile_name

fromdba_data_files

whereautoextensible = 'YES'

/

Top of Form

Bottom of Form

Turn autoextend off for all datafiles

select 'alter database datafile ''' || file_name || ''' autoextend off;'

from dba_data_files

/

Top of Form

Bottom of Form

Move files between disks

set trimspool on wrap off

set heading off

set verify off

set pages 1000 lines 100

spool rename.sql

select 'alter database rename file ''' ||

name || ''' to ''' ||

replace(name || ''';', '/u01', '/u02')

from v$datafile

/

select 'alter database rename file ''' ||

member || ''' to ''' ||

replace(member || ''';', '/u01', '/u02')

from v$logfile

/

spool off

Top of Form

Bottom of Form

List controlfiles

selectname

fromv$controlfile

/

Top of Form

Bottom of Form

Create an OS command for every file in the database

The example deletes all filesselect'rm ' || name

from(selectname

fromv$datafile

unionall

selectname

from v$tempfile

union all

select member

from v$logfile

union all

select name

from v$controlfile

)

/

Top of Form

Bottom of Form

Find duplicate filenames

Searches for files with the same name in all directoriesselect count(substr(name, instr(name, '/', -1) + 1, 999)) "total"

,count(distinct substr(name, instr(name, '/', -1) + 1, 999)) "distinct"

from v$datafile

/

Top of Form

Bottom of Form

List files that are in hot-backup mode

set lines 100 pages 999

col name format a60

selectdf.name

,b.status

,to_char(time, 'hh24:mi:ss dd/mm/yyyy') time

fromv$datafiledf

,v$backupb

wheredf.file# = b.file#

andb.status = 'ACTIVE'

order by b.file#

/

Structure - Redo Logs

Remove drop add logfile members List members and sizesRemove drop

alter database drop logfile member '';

Bottom of Form

add logfile members

alter database add logfile member '' to group ;

Bottom of Form

List members and sizes

col memberformat a60

col "Size MB"format 9,999,999

selectlf.member

,ceil(lg.bytes / 1024 / 1024) "Size MB"

fromv$logfile lf

,v$log lg

wherelg.group# = lf.group#

orderby 1

/

Structure - Undo

Converting from Rollback to Undo Display the rollback segments Alter undo retention What's in undo Is anything rolling back at the moment?Display the rollback segments

selectsegment_name

,status

fromdba_rollback_segs

/

Top of Form

Bottom of Form

Alter undo retention

alter system set undo_retention=500 scope=memory;

Top of Form

Bottom of Form

Note. This is in seconds What's in undo

selecttablespace_name

,status

,count(*) as HOW_MANY

fromdba_undo_extents

groupby tablespace_name

,status

/

Top of Form

Bottom of Form

Is anything rolling back at the moment?

Look for the used_ublk value decreasing. If it is, the session connected with it is rolling back. When it reaches zero, rollback is complete.set lines 100 pages 999

col username format a15

col command format a20

selectses.username

,substr(ses.program, 1, 19) command

,tra.used_ublk

fromv$session ses

,v$transaction tra

whereses.saddr = tra.ses_addr

/

Structure - Constraints

Show all constraints on a table List tables that are using the specified table as a foreign key Produce a list of disabled fk constraints Produce enable statements all disabled fk constraints List parent tables that may need fixing/re-importing List missing foriegn key values Show all table constraints for a userShow all constraints on a table

col type format a10

col cons_name format a30

selectdecode(constraint_type,

'C', 'Check',

'O', 'R/O View',

'P', 'Primary',

'R', 'Foreign',

'U', 'Unique',

'V', 'Check view') type

,constraint_name cons_name

,status

,last_change

fromdba_constraints

whereowner like '&owner'

andtable_name like '&table_name'

order by 1

/

Top of Form

Bottom of Form

List tables that are using the specified table as a foreign key

set lines 100 pages 999

selecta.owner

,a.table_name

,a.constraint_name

fromdba_constraints a

,dba_constraints b

wherea.constraint_type = 'R'

and a.r_constraint_name = b.constraint_name

and a.r_owner = b.owner

and b.owner = '&table_owner'

andb.table_name = '&table_name'

/

Top of Form

Bottom of Form

Same as above, but produces 'disable constraint' statementsset lines 100 pages 999

col discon format a100

select 'alter table '||a.owner||'.'||a.table_name||' disable constraint

'||a.constraint_name||';' discon

fromdba_constraints a

,dba_constraints b

wherea.constraint_type = 'R'

and a.r_constraint_name = b.constraint_name

anda.r_owner = b.owner

and b.owner = '&table_owner'

andb.table_name = '&table_name'

/

Top of Form

Bottom of Form

Produce a list of disabled fk constraints

set lines 100 pages 999

coltable format a60

colconstraint_name format a30

selectowner||'.'||table_name "table"

,constraint_name

fromdba_constraints

wherestatus = 'DISABLED'

andconstraint_type = 'R'

andowner not in ('SYS','SYSTEM')

order by 1,2

/

Top of Form

Bottom of Form

Produce enable statements all disabled fk constraints

set lines 100 pages 999

select'alter table '||owner||'.'||table_name||' enable constraint

'||constraint_name||';' "enable"

fromdba_constraints

wherestatus = 'DISABLED'

andconstraint_type = 'R'

andowner not in ('SYS','SYSTEM')

order by 1

/

Top of Form

Bottom of Form

List parent tables that may need fixing/re-importing

selectdistinct r.owner || '.' || r.table_name "exp"

fromdba_constraints c

,dba_constraints r

wherec.status = 'DISABLED'

andc.constraint_type = 'R'

andc.r_owner = r.owner

andc.r_constraint_name = r.constraint_name

andc.owner not in ('SYS','SYSTEM')

order by 1

/

Top of Form

Bottom of Form

List missing foriegn key values

Note. Useful for resolving ORA-02298select 'select '||cc.column_name-

||' from '||c.owner||'.'||c.table_name-

||' a where not exists (select ''x'' from '-

||r.owner||'.'||r.table_name-

||' where '||rc.column_name||' = a.'||cc.column_name||')'

from dba_constraints c,

dba_constraints r,

dba_cons_columns cc,

dba_cons_columns rc

where c.constraint_type = 'R'

and c.owner not in ('SYS','SYSTEM')

and c.r_owner = r.owner

and c.owner = cc.owner

and r.owner = rc.owner

and c.constraint_name = cc.constraint_name

and r.constraint_name = rc.constraint_name

and c.r_constraint_name = r.constraint_name

and cc.position = rc.position

and c.owner = '&table_owner'

and c.table_name = '&table_name'

and c.constraint_name = '&constraint_name'

order by c.owner, c.table_name, c.constraint_name, cc.position

/

Top of Form

Bottom of Form

Show all table constraints for a user

Note. This still needs some work...set lines 100 pages 999

break on table_name

select table_name

,decode(constraint_type,

'C', 'Check',

'O', 'R/O View',

'P', 'Primary',

'R', 'Foreign',

'U', 'Unique',

'V', 'Check view') type

,nvl(index_name, R_CONSTRAINT_NAME) "IDX"

from dba_constraints

whereowner like '&user'

orderby table_name

,decode(constraint_type,

'P','0','R','1','U','2','C','3','O','4','V','5')

/

Structure - Materialized view

Create a view log for the master table List all materialized view logs Create a simple materialized view Show all materialized and resfresh times Show materialized view tables and masters Show refresh jobs in dba_jobs Manually start a refresh Force a complete refreshCreate a view log for the master table

This is required for fast refreshcreate materialized view log on

/

Top of Form

Bottom of Form

or...create materialized view log on

tablespace

/

Top of Form

Bottom of Form

List all materialized view logs

select log_owner

,log_table

fromdba_mview_logs

/

Top of Form

Bottom of Form

Create a simple materialized view

create materialized view andy_mview

refresh [fast | complete | force]

start with sysdate

next sysdate + 1/24

with primary key

as select * from test_table

/

Top of Form

Bottom of Form

Fast = update changes onlyComplete = wipe and repopulate the mviewForce = fast if possible, complete if not.Show all materialized and resfresh times

set lines 100 pages 999

col last_refresh format a20

selectowner

,mview_name

,to_char(last_refresh_date, 'dd/mm/yy hh24:mi') last_refresh

fromdba_mviews

order by owner, last_refresh

/

Top of Form

Bottom of Form

Show materialized view tables and masters

set lines 100

col mview format a40

col master format a40

selectowner || '.' || name mview

,master_owner || '.' || master master

fromdba_mview_refresh_times

/

Top of Form

Bottom of Form

Show refresh jobs in dba_jobs

This is useful for spotting failuresset lines 100

col job format 9999

col log_user format a15

col last format a15

col next format a15

col fail format 9999

col what format a20

selectjob

,log_user

,to_char(last_date, 'dd/mm/yy hh24:mi') last

,to_char(next_date, 'dd/mm/yy hh24:mi') next

,failures fail

,replace(what, '"') what

fromdba_jobs

wherewhat like '%dbms_refresh.refresh%'

/

Top of Form

Bottom of Form

Manually start a refresh

execute dbms_mview.refresh ('');

Top of Form

Bottom of Form

Force a complete refresh

execute dbms_mview.refresh ('','C');

Structure - Partitions

List partitioned tables List a tables partitions Show partition sizes for the specified table Move a partition to a new tablespace Add a partition Split a partition Drop a partition Truncate a partitionList partitioned tables

set pages 999 lines 100

col table_name format a40

selecttable_name

,partitioning_type type

,partition_count partitions

fromdba_part_tables

whereowner = '&owner'

order by 1

/

Top of Form

Bottom of Form

List a tables partitions

set pages 999 lines 100

col high_value format a20

col tablespace_name format a20

selectpartition_name

,tablespace_name

,high_value

fromdba_tab_partitions

wheretable_owner = '&owner'

andtable_name = '&table_name'

order by partition_position

/

Top of Form

Bottom of Form

Show partition sizes for the specified table

set pages 999 lines 100

col tablespace_name format a20

col num_rows format 999,999,999

selectp.partition_name

,p.tablespace_name

,p.num_rows

,ceil(s.bytes / 1024 / 1204) mb

fromdba_tab_partitions p

,dba_segments s

wherep.table_owner = s.owner

andp.partition_name = s.partition_name

and p.table_name = s.segment_name

andp.table_owner = '&owner'

andp.table_name = '&table_name'

order by partition_position

/

Top of Form

Bottom of Form

Move a partition to a new tablespace

alter table

move partition

tablespace

nologging

/

Top of Form

Bottom of Form

Add a partition

alter table

add partition values less than ()

tablespace

/

Top of Form

Bottom of Form

or...alter table

add partition values ()

tablespace

/

Top of Form

Bottom of Form

Split a partition

alter table

split partition at ()

into (partition , partition )

update global indexes

/

Top of Form

Bottom of Form

Drop a partition

alter table drop partition

/

Top of Form

Bottom of Form

Truncate a partition

alter table truncate partition

/

Performance - General

Show currently exectuing sql Session statistics Resource intensive sql File io stats In session tracing switch on event 10046 Rows per block Show the buffer cache advisoryShow currently exectuing sql

select sql_text

from v$sqlarea

where users_executing > 0

/

Top of Form

Bottom of Form

Session statistics

selectsn.name

,st.value

fromv$sesstat st

,v$statname sn

wherest.STATISTIC# = sn.STATISTIC#

andst.VALUE > 0

andst.SID = &SID

order by value desc

/

Top of Form

Bottom of Form

Resource intensive sql

change 8192 to match block size select sql_text

, executions

, to_char((((disk_reads+buffer_gets)/executions) * 8192)/1048576, '9,999,999,990.00')

as total_gets_per_exec_mb

, to_char((( disk_reads /executions) * 8192)/1048576, '9,999,999,990.00')

as disk_reads_per_exec_mb

, to_char((( buffer_gets /executions) * 8192)/1048576, '9,999,999,990.00')

as buffer_gets_per_exec_mb

, parsing_user_id

from v$sqlarea

where executions > 10

order by 6 desc

/

Top of Form

Bottom of Form

File io stats

Requires timed_statistics=trueset lines 80 pages 999

col fname heading "File Name" format a60

col sizemb heading "Size(Mb)" format 99,999

col phyrds heading "Reads" format 999,999,999

col readtim heading "Time" format 99.999

col phywrts heading "Writes" format 9,999,999

col writetim heading "Time" format 99.999

select lower(name) fname

, (bytes / 1048576) sizemb

, phyrds

,readtim

, phywrts

,writetim

from v$datafile df

, v$filestat fs

where df.file# = fs.file#

order by 1

/

Top of Form

Bottom of Form

In session tracing

To switch it on:exec dbms_system.set_sql_trace_in_session (, , true);

Top of Form

Bottom of Form

To switch it off:exec dbms_system.set_sql_trace_in_session (, , false);

Top of Form

Bottom of Form

switch on event 10046

To switch it on:alter session set events '10046 trace name context forever, level 8';

Top of Form

Bottom of Form

To switch it off:alter session set events '10046 trace name context off';

Top of Form

Bottom of Form

Note. use tkprof to interpret the results. Rows per block

select avg(row_count) avg

, max(row_count) max

, min(row_count) min

from (

select count(*) row_count

from &table_name

group by substr(rowid, 1, 15)

)

/

Top of Form

Bottom of Form

Show the buffer cache advisory

Note. The current setting is halfway down and has a read factor of one.set lines 100 pages 999

col est_mb format 99,999

col estd_physical_reads format 999,999,999,999,999

selectsize_for_estimate est_mb

,estd_physical_read_factor

,estd_physical_reads

fromv$db_cache_advice

wherename = 'DEFAULT'

order by size_for_estimate

/

Top of Form

Bottom of Form

db_cache_advice needs to be on for the above to workalter system set db_cache_advice=on;

Performance - Locks DML

Show sessions that are blocking each other Show locked objects Show which row is locked List locksShow sessions that are blocking each other

select'SID ' || l1.sid ||' is blocking ' || l2.sid blocking

fromv$lock l1, v$lock l2

wherel1.block =1 and l2.request > 0

andl1.id1=l2.id1

andl1.id2=l2.id2

/

Top of Form

Bottom of Form

Show locked objects

set lines 100 pages 999

col username format a20

col sess_id format a10

col objectformat a25

col mode_heldformat a10

selectoracle_username || ' (' || s.osuser || ')' username

,s.sid || ',' || s.serial# sess_id

,owner || '.' ||object_name object

,object_type

,decode(l.block

,0, 'Not Blocking'

,1, 'Blocking'

,2, 'Global') status

,decode(v.locked_mode

,0, 'None'

,1, 'Null'

,2, 'Row-S (SS)'

,3, 'Row-X (SX)'

,4, 'Share'

,5, 'S/Row-X (SSX)'

,6, 'Exclusive', TO_CHAR(lmode)) mode_held

fromv$locked_object v

,dba_objects d

,v$lock l

,v$session s

where v.object_id = d.object_id

and v.object_id = l.id1

and v.session_id = s.sid

order by oracle_username

,session_id

/

Top of Form

Bottom of Form

Show which row is locked

selectdo.object_name

,row_wait_obj#

,row_wait_file#

,row_wait_block#

,row_wait_row#

,dbms_rowid.rowid_create (1, ROW_WAIT_OBJ#, ROW_WAIT_FILE#,

ROW_WAIT_BLOCK#, ROW_WAIT_ROW#)

fromv$session s

,dba_objects do

wheresid=&sid

and s.ROW_WAIT_OBJ# = do.OBJECT_ID

/

Top of Form

Bottom of Form

Then select the row with that rowid...select * from where rowid=;

Top of Form

Bottom of Form

List locks

column lock_type format a12

column mode_held format a10

column mode_requested format a10

column blocking_others format a20

column username format a10

SELECTsession_id

,lock_type

,mode_held

,mode_requested

,blocking_others

,lock_id1

FROMdba_lock l

WHERE lock_type NOT IN ('Media Recovery', 'Redo Thread')

/

Performance - Locks DDL

Show all ddl locks in the system Slightly more simple version of the above Generate kill statement for ddl locking sessionsShow all ddl locks in the system

selectdecode(lob.kglobtyp,

0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',

4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',

7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',

11, 'PACKAGE BODY', 12, 'TRIGGER',

13, 'TYPE', 14, 'TYPE BODY',

19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',

22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',

28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',

32, 'INDEXTYPE', 33, 'OPERATOR',

34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',

40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',

42, 'MATERIALIZED VIEW',

43, 'DIMENSION',

44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',

48, 'CONSUMER GROUP',

51, 'SUBSCRIPTION', 52, 'LOCATION',

55, 'XML SCHEMA', 56, 'JAVA DATA',

57, 'SECURITY PROFILE', 59, 'RULE',

62, 'EVALUATION CONTEXT','UNDEFINED'

) object_type

,lob.kglnaobj object_name

,pn.kglpnmod lock_mode_held

,pn.kglpnreq lock_mode_requested

,ses.sid

,ses.serial#

,ses.username

fromv$session_waitvsw

,x$kglob

lob

,x$kglpn

pn

,v$sessionses

wherevsw.event = 'library cache lock'

andvsw.p1raw = lob.kglhdadr

andlob.kglhdadr = pn.kglpnhdl

andpn.kglpnmod != 0

andpn.kglpnuse = ses.saddr

/

Top of Form

Bottom of Form

Slightly more simple version of the above

selectses.username

,ddl.session_id

,ses.serial#

,owner || '.' || ddl.name object

,ddl.type

,ddl.mode_held

fromdba_ddl_locks ddl

,v$session ses

whereowner like '%userid%'

andddl.session_id = ses.sid

/

Top of Form

Bottom of Form

Generate kill statement for ddl locking sessions

select'alter system kill session ''' || ddl.session_id || ',' || ses.serial# || ''' immediate;'

fromdba_ddl_locks ddl

,v$session ses

whereowner like '%userid%'

andddl.session_id = ses.sid

/

Performance - Waits

Top ten hotest objects by touch count Waits by file Segment Waits Time waited for latches Identify hot blocks Look at the performance stats for the instanceTop ten hotest objects by touch count

col owner format a20 trunc

col object_nameformat a30

col touches format 9,999,999

select*

from(

selectcount(*)

,sum(tch) TOUCHES

,u.name OWNER

,o.name OBJECT_NAME

from x$bh x

,obj$ o

,user$ u

wherex.obj = o.obj#

ando.owner# = u.user#

group by u.name, o.name

order by 2 desc

)

whererownum < 11

/

Top of Form

Bottom of Form

Waits by file

col name format a60

selectname

,count

fromx$kcbfwait

,v$datafile

whereindx + 1 = file#

orderby 2

/

Top of Form

Bottom of Form

Segment Waits

selectobject_name

,obj#

,statistic_name

,value

fromv$segment_statistics

whereowner like '&owner'

andstatistic_name like '%waits%'

andvalue > 0

orderby statistic_name

, value desc

/

Top of Form

Bottom of Form

Time waited for latches

col event format a30

selectevent

,time_waited

,round(time_waited*100/ SUM (time_waited) OVER(),2) wait_pct

from(

selectevent

,time_waited

fromv$system_event

whereevent not in (

'Null event'

,'client message'

,'rdbms ipc reply'

,'smon timer'

,'rdbms ipc message'

,'PX Idle Wait'

,'PL/SQL lock timer'

,'file open'

,'pmon timer'

,'WMON goes to sleep'

,'virtual circuit status'

,'dispatcher timer'

,'SQL*Net message from client'

,'parallel query dequeue wait'

,'pipe get')

union

(

selectname

,

value

fromv$sysstat

where name like 'CPU used when call started'

)

)

order by 2 desc

/

Top of Form

Bottom of Form

Identify hot blocks

Look at all waits for the instancecol event format a30

select event

,total_waits

,time_waited

fromv$system_event

whereevent like '%wait%'

order by 2,3

/

Top of Form

Bottom of Form

If there are lots of 'data block' waits, get a break-down of themselect*

fromv$waitstat

/

Top of Form

Bottom of Form

Then run this to identify the file, block and reason code...selectp1 "File #"

,p2 "Block #"

,p3 "Reason Code"

fromv$session_wait

whereevent = 'buffer busy waits'

/

Top of Form

Bottom of Form

Note. You might need to run this a few times before anything is displayed.Look at the performance stats for the instance

selectn.name

,s.value

fromv$statname n

,v$sysstat s

wheren.statistic# = s.statistic#

order by n.class

,n.name

/

Performance - Statistics

Gather database statistics Gather stats for a single schema... Delete stats Gather system stats Export/Import optimizer statistics Old style analyze Show a count of analyezed tables broken down by schema Show tables that have analyze dates older than todayGather database statistics

Gather stats on the entire database...execute dbms_stats.gather_database_stats;

Top of Form

Bottom of Form

Or...execute dbms_stats.gather_database_stats( -

estimate_percent => 1, -

method_opt => 'FOR ALL COLUMNS SIZE 1',-

cascade => TRUE);

Top of Form

Bottom of Form

Gather stats for a single schema...

execute dbms_stats.gather_schema_stats('SCOTT');

Top of Form

Bottom of Form

Or...execute dbms_stats.gather_schema_stats( -

ownname => 'SCOTT', -

estimate_percent => 1, -

method_opt => 'FOR ALL COLUMNS SIZE 1',-

cascade => TRUE);

Top of Form

Bottom of Form

You can let oracle come up with the estimate figure by using dbms_stats.auto_sample_size

or...execute dbms_stats.gather_schema_stats( -

ownname => 'SYS', -

cascade => TRUE);

Top of Form

Bottom of Form

Table statisticsexec dbms_stats.gather_table_stats('', '');

Top of Form

Bottom of Form

Delete stats

exec dbms_stats.delete_database_stats;

Top of Form

Bottom of Form

exec dbms_stats.delete_schema_stats('SCOTT');

Top of Form

Bottom of Form

exec dbms_stats.delete_table_stats('SCOTT', 'EMPLOYEES');

Top of Form

Bottom of Form

exec dbms_stats.delete_index_stats('SCOTT', 'EMPLOYEES_PK');

Top of Form

Bottom of Form

Gather system stats

execute dbms_stats.gather_system_stats('Start');

Top of Form

Bottom of Form

Wait for a while - idealy with the database under a typical workloadexecute dbms_stats.gather_system_stats('Stop');

Top of Form

Bottom of Form

To see the current system statisticsselectpname

,pval1

from sys.aux_stats$

where sname = 'SYSSTATS_MAIN'

/

Top of Form

Bottom of Form

Export/Import optimizer statistics

Create a table to hold the statistics... exec dbms_stats.create_stat_table(ownname => 'SYS',-

stattab => 'prod_stats', tblspace => 'USERS');

Top of Form

Bottom of Form

Populate the table with the current stats... exec dbms_stats.export_schema_stats(ownname => 'SCOTT',-

statown=>'SYS', stattab=>'prod_stats');

Top of Form

Bottom of Form

At this point you need to:1) take an export of the 'prod_stats' table2) import 'prod_stats' into the target database3) load the statistics using this command... exec dbms_stats.import_schema_stats(ownname => 'SCOTT',-

statown=>'SYS', stattab=>'prod_stats');

Top of Form

Bottom of Form

Old style analyze

analyze table employees compute statistics;

Top of Form

Bottom of Form

analyze table employees estimate statistics sample 100 rows;

Top of Form

Bottom of Form

analyze table employees estimate statistics sample 15 percent;

Top of Form

Bottom of Form

analyze index employees_ind compute statistics;

Top of Form

Bottom of Form

Show a count of analyezed tables broken down by schema

set pages 999 lines 100

selecta.owner

,a.total_tables tables

,nvl(b.analyzed_tables,0) analyzed

from(selectowner

,count(*) total_tables

fromdba_tables

groupby owner) a

,(selectowner

,count(last_analyzed) analyzed_tables

fromdba_tables

wherelast_analyzed is not null

groupby owner) b

wherea.owner = b.owner (+)

anda.owner not in ('SYS', 'SYSTEM')

orderby a.total_tables - nvl(b.analyzed_tables,0) desc

/

Top of Form

Bottom of Form

Show tables that have analyze dates older than today

This is useful if you are running an analyze and want to see how much is left to doselectcount(last_analyzed) left_to_do

fromdba_tables

whereowner = '&schema'

andtrunc(last_analyzed) < trunc(sysdate)

orderby 1

/

Performance - Query Tuning

Create a plan table Autotrace Explain plan Find a query's hash Grab the sql associated with a hash Look at a query's stats in the sql areaCreate a plan table

@?/rdbms/admin/utlxplan.sql

Top of Form

Bottom of Form

Autotrace

To switch it on:column plan_plus_exp format a100

set autotrace on explain # Displays the execution plan only.

set autotrace traceonly explain # dont run the query

set autotrace on # Shows the execution plan as well as statistics of the statement.

set autotrace on statistics # Displays the statistics only.

set autotrace traceonly # Displays the execution plan and the statistics

Top of Form

Bottom of Form

To switch it off:set autotrace off

Top of Form

Bottom of Form

Explain plan

explain plan for

select ...

Top of Form

Bottom of Form

or...explain plan set statement_id = 'bad1' for

select...

Top of Form

Bottom of Form

Then to see the output...set lines 100 pages 999

@?/rdbms/admin/utlxpls

Top of Form

Bottom of Form

Find a query's hash

Put something unique in the like clauseselect hash_value, sql_text

from v$sqlarea

where sql_text like '%TIMINGLINKS%FOLDERREF%'

/

Top of Form

Bottom of Form

Grab the sql associated with a hash

select sql_text

from v$sqlarea

where hash_value = '&hash'

/

Top of Form

Bottom of Form

Look at a query's stats in the sql area

selectexecutions

,cpu_time

,disk_reads

,buffer_gets

,rows_processed

,buffer_gets / executions

fromv$sqlarea

wherehash_value = '&hash'

/

Performance - Memory

SGA breakdown PGA usage by username Display pool usageSGA breakdown

set lines 100 pages 999

col bytes format 999,999,999

computesum of bytes on pool

break on pool skip 1

selectpool

,name

,bytes

from v$sgastat

order by pool

,name

/

Top of Form

Bottom of Form

PGA usage by username

selectst.sid "SID",

sn.name "TYPE",

ceil(st.value / 1024 / 1024) "MB"

fromv$sesstat st,

v$statname sn

wherest.statistic# = sn.statistic#

and sid in(select sid

from v$session

where username like '&user')

andupper(sn.name) like '%PGA%'

order by st.sid,

st.value desc

/

Bottom of Form

Display pool usage

selectname

,sum(bytes)

fromv$sgastat

wherepool like 'shared pool'

group by name

/

Performance - Statspack

Take a snapshot Delete one or more snapshots Generate a report List snapshots Install statspack Uninstall statspack Schedule and hourly snapshotTake a snapshot

exec statspack.snap;

Top of Form

Bottom of Form

Or to specify a level...exec statspack.snap(i_snap_level => 6, i_modify_parameter => 'true');

Top of Form

Bottom of Form

Level 0 - This level captures general statistics, including rollback segment, row cache, SGA, system events, background events, session events, system statistics, wait statistics, lock statistics, and Latch information.

Level 5 - This level includes capturing high resource usage SQL Statements, along with all data captured by lower levels.

Level 6 - This level includes capturing SQL plan and SQL plan usage information for high resource usage SQL Statements, along with all data captured by lower levels.

Level 7 - This level captures segment level statistics, including logical and physical reads, row lock, itl and buffer busy waits, along with all data captured by lower levels.

Level 10 - This level includes capturing Child Latch statistics, along with all data captured by lower levels. Delete one or more snapshots

@?/rdbms/admin/sppurge;

Top of Form

Bottom of Form

Generate a report

@?/rdbms/admin/spreport.sql

Top of Form

Bottom of Form

List snapshots

col "Date/Time" format a30

selectsnap_id

, snap_level

,to_char(snap_time,'HH24:MI:SS DD-MM-YYYY') "Date/Time"

fromstats$snapshot

,v$database

order by snap_id

/

Top of Form

Bottom of Form

Install statspack

1. Create a tablespace (minimum size 100MB)2. Run...@?/rdbms/admin/spcreate

Top of Form

Bottom of Form

Uninstall statspack

@?/rdbms/admin/spdrop

Top of Form

Bottom of Form

Schedule and hourly snapshot

@?/rdbms/admin/spauto.sql

Top of Form

Bottom of Form

Note. This uses dbms_job, so job_queue_processes needs to be set greater than 0.

To see the job: selectjob

,what

fromdba_jobs

/

Top of Form

Bottom of Form

To delete the job:exec dbms_job.remove();

Performance - AWR

Display a list of snapshots Produce a report To see the snapshot interval and retention period Change the snapshot interval Change the retention period Manually take a snapshot List all baselines Create a baseline Remove a baseline Enable/Disable automatic snapshots Time model queries Produce an Active Session History (ASH) reportDisplay a list of snapshots

set lines 100 pages 999

selectsnap_id

,snap_level

,to_char(begin_interval_time, 'dd/mm/yy hh24:mi:ss') begin

fromdba_hist_snapshot

order by 1

/

Top of Form

Bottom of Form

Produce a report

@?/rdbms/admin/awrrpt.sql

Top of Form

Bottom of Form

To see the snapshot interval and retention period

col snap_interval format a30

col retention format a30

selectsnap_interval

,retention

fromdba_hist_wr_control

/

Top of Form

Bottom of Form

Change the snapshot interval

Note. This example changes it to 30 minutesexec dbms_workload_repository.modify_snapshot_settings (interval => 30)

Top of Form

Bottom of Form

Change the retention period

Note. This example changes it to two weeks (14 days)exec dbms_workload_repository.modify_snapshot_settings (retention => 14*24*60)

Top of Form

Bottom of Form

Manually take a snapshot

exec dbms_workload_repository.create_snapshot

Top of Form

Bottom of Form

List all baselines

set lines 100

col baseline_name format a40

selectbaseline_id

,baseline_name

,start_snap_id

,end_snap_id

fromdba_hist_baseline

order by 1

/

Top of Form

Bottom of Form

Create a baseline

exec dbms_workload_repository.create_baseline (, ,'')

Top of Form

Bottom of Form

Remove a baseline

exec dbms_workload_repository.drop_baseline('')

Top of Form

Bottom of Form

Enable/Disable automatic snapshots

Note. This job is enabled by defaultexec dbms_scheduler.enable('GATHER_STATS_JOB')

Top of Form

Bottom of Form

and to disable...exec dbms_scheduler.disable('GATHER_STATS_JOB')

Top of Form

Bottom of Form

Time model queries

System time modelset lines 100 pages 999

selectstat_name

,value

fromv$sys_time_model

order by value desc

/

Top of Form

Bottom of Form

Session time modelset lines 100 pages 999

selectstat_name

,value

fromv$sess_time_model

wheresid = '&sid'

order by value desc

/

Top of Form

Bottom of Form

Produce an Active Session History (ASH) report

@?/rdbms/admin/ashrpt.sql

Backup - DataGuard

Startup commands To remove a delay from a standby Cancel managed recovery Register a missing log file If FAL doesn't work and it says the log is already registered Check which logs are missing Disable/Enable archive log destinations Turn on fal tracing on the primary db Stop the Data Guard broker Show the current instance role Logical standby apply stop/start See how up to date a physical standby is Display info about all log destinations Display log destinations options List any standby redo logsStartup commands

startup nomount

alter database mount standby database;

alter database recover managed standby database disconnect;

Top of Form

Bottom of Form

To remove a delay from a standby

alter database recover managed standby database cancel;

alter database recover managed standby database nodelay disconnect;

Top of Form

Bottom of Form

Cancel managed recovery

alter database recover managed standby database cancel;

Top of Form

Bottom of Form

Register a missing log file

alter database register physical logfile '';

Top of Form

Bottom of Form

If FAL doesn't work and it says the log is already registered

alter database register or replace physical logfile '';

Top of Form

Bottom of Form

If that doesn't work, try this...shutdown immediate

startup nomount

alter database mount standby database;

alter database recover automatic standby database;

Top of Form

Bottom of Form

wait for the recovery to finish - then cancelshutdown immediate

startup nomount

alter database mount standby database;

alter database recover managed standby database disconnect;

Top of Form

Bottom of Form

Check which logs are missing

Run this on the standby... select local.thread#

, local.sequence# from

(select thread#

, sequence#

from v$archived_log

where dest_id=1) local

where local.sequence# not in

(select sequence#

from v$archived_log

where dest_id=2 and

thread# = local.thread#)

/

Top of Form

Bottom of Form

Disable/Enable archive log destinations

alter system set log_archive_dest_state_2 = 'defer';

alter system set log_archive_dest_state_2 = 'enable';

Top of Form

Bottom of Form

Turn on fal tracing on the primary db

alter system set LOG_ARCHIVE_TRACE = 128;

Top of Form

Bottom of Form

Stop the Data Guard broker

alter system set dg_broker_start=false

/

Top of Form

Bottom of Form

Show the current instance role

selectdatabase_role

fromv$database

/

Top of Form

Bottom of Form

Logical standby apply stop/start

Stop...alter database stop logical standby apply;

Top of Form

Bottom of Form

Start...alter database start logical standby apply;

Top of Form

Bottom of Form

See how up to date a physical standby is

Run this on the primaryset numwidth 15

selectmax(sequence#) current_seq

fromv$log

/

Top of Form

Bottom of Form

Then run this on the standbyset numwidth 15

selectmax(applied_seq#) last_seq

fromv$archive_dest_status

/

Top of Form

Bottom of Form

Display info about all log destinations

To be run on the primaryset lines 100

set numwidth 15

column ID format 99

column "SRLs" format 99

column active format 99

col type format a4

selectds.dest_id id

,ad.status

,ds.database_mode db_mode

,ad.archiver type

,ds.recovery_mode

,ds.protection_mode

,ds.standby_logfile_count "SRLs"

,ds.standby_logfile_active active

,ds.archived_seq#

fromv$archive_dest_statusds

,v$archive_dest

ad

whereds.dest_id = ad.dest_id

andad.status != 'INACTIVE'

order by

ds.dest_id

/

Top of Form

Bottom of Form

Display log destinations options

To be run on the primaryset numwidth 8 lines 100

column id format 99

selectdest_id id

,archiver

,transmit_mode

,affirm

,async_blocks async

,net_timeout net_time

,delay_mins delay

,reopen_secs reopen

,register,binding

fromv$archive_dest

order by

dest_id

/

Top of Form

Bottom of Form

List any standby redo logs

set lines 100 pages 999

col member format a70

selectst.group#

,st.sequence#

,ceil(st.bytes / 1048576) mb

,lf.member

fromv$standby_logst

,v$logfilelf

wherest.group# = lf.group#

/

Backup - Flashback

To put the session back in time Copy old data into a new table Export a database from a point in time Find the current SCN number Set the database recovery directory and size Set the flashback database retention target Turn on flashback database What is the earliest time the database can be flashed back to? Get a list of times and scn numbers Flash the database backTo put the session back in time

Note. undo_management must be autoNote. Take a look at undo_retention to get an idea of how far back you might be able to go.Note. This can't be run as sys - system works thoughexec dbms_flashback.enable_at_time(to_date('2006-AUG-24 12:00:00', 'YYYY-MON-DD HH24:MI:SS'));

Top of Form

Bottom of Form

To disable flashback run...exec dbms_flashback.disable;

Top of Form

Bottom of Form

Copy old data into a new table

First, create an empty copy of the source table...create table old_test_table

tablespace andy

as select *

from test_table

where rownum < 1

/

Top of Form

Bottom of Form

Now, insert the old data into it...insert /*+ APPEND */ old_test_table

(select * from test_table as of timestamp

to_timestamp('24-AUG-06 12:00:00','DD-MON-YY HH24:MI:SS'))

/

Top of Form

Bottom of Form

Export a database from a point in time

exp / file=full_scr9.dmp log=full_scr9.log flashback_time=TO_TIMESTAMP('10-09-2006 09:00:00', 'DD-MM-YYYY HH24:MI:SS')

Top of Form

Bottom of Form

exp / parfile=full_scr9.par

Top of Form

Bottom of Form

parfile...userid=system/******

file=full_scr9.dmp

log=full_scr9.log

flashback_time='2006-09-13 12:00:00'

Top of Form

Bottom of Form

Find the current SCN number

select dbms_flashback.get_system_change_number from dual

/

Top of Form

Bottom of Form

Set the database recovery directory and size

These settings are dynamicalter system set db_recovery_file_dest='' scope=both

/

alter system set db_recovery_file_dest_size= scope=both

/

Top of Form

Bottom of Form

Set the flashback database retention target

alter system set db_flashback_retention_target= scope=both

/

Top of Form

Bottom of Form

Turn on flashback database

shutdown immediate

startup mount

alter database flashback on;

alter database open;

Top of Form

Bottom of Form

What is the earliest time the database can be flashed back to?

selectoldest_flashback_scn scn

,to_char(oldest_flashback_time, 'hh24:mi:ss dd/mm/yyyy') oldest_time

fromv$flashback_database_log

/

Top of Form

Bottom of Form

Get a list of times and scn numbers

set pages 999

selectscn

,to_char(time_dp, 'hh24:mi:ss dd/mm/yyyy') time

fromsmon_scn_time

order by scn

/

Top of Form

Bottom of Form

Flash the database back

shutdown immediate

startup mount exclusive

Top of Form

Bottom of Form

flashback database to scn ;

Top of Form

Bottom of Form

or...flashback database to timestamp to_timestamp('22/04/2007 19:30:00','dd/mm/yyyy hh24:mi:ss');

Top of Form

Bottom of Form

alter database open resetlogs;

Manual upgrade from 9i to 10g Release 2

This procedure describes the steps necessary to manually upgrade a database from 9.2.x to 10.2.x. It assumes that you have already installed 10g onto the server. Of course, it is essential that you take a backup of your database before attempting any upgrade.

1. Compile any invalid objects@?/rdbms/admin/utlrp.sql

2. Create a sysaux tablespaceHaving a sysaux tablespace is a requirement in 10g. So, if you haven't already got one, create one now.

create tablespace sysaux

datafile '' size 512M

extent management local

segment space management auto

/

3. Run utlu102i.sqlThis utility script checks that the database is ready to be upgraded to 10g. It also identifies any actions that need to be taken. The script is located in the 10g oracle home, so you will need to specify the full path to it.

@/u01/app/oracle/product/10.2.0/db_1/rdbms/admin/utlu102i.sql

Review the output and make any necessary alterations. Make a note of how many invalid objects there are.

4. Shut the database down with either normal or immediateshutdown immediate

5. Copy the spfile (or pfile) and the password file from the existing home to the 10g one.cp ${ORACLE_HOME}/dbs/*${ORACLE_SID}* /dbs/

6. Edit oratabAlter /etc/oratab (or /var/opt/oracle/oratab) to point to the10g home. Once done, rerun oraenv to bring the alteration into effect.

7. Upgrade the database

sqlplus "/ as sysdba"

startup upgrade

This next bit is the upgrade itself. It takes roughly half an hour to complete. Spool the output to a file so that you can review it afterward.

@?/rdbms/admin/catupgrd.sql

8. Recompile any invalid objects@?/rdbms/admin/utlrp.sql

Compare the number of invalid objects with the number noted in step 3. It should hopefully be the same or less.

9. Then check the status of the upgrade@?/rdbms/admin/utlu102s.sql

10. Alter or remove initialisation parametersTemporarily creating a pfile is the easiest way.

create pfile from spfile;

shutdown immediate

vi ${ORACLE_HOME}/dbs/init${ORACLE_SID}.ora

Alter/remove parameters identified in step 9. Set compatible to 10.2.0.0.0

startup

create spfile from pfile;

shutdown immediate

startup

That's it!Capture all SQL run between two points in time

tnsManager - Distribute tnsnames the easy way and for free!

There are situations where it is useful to capture the SQL that a particular user is running in the database. Usually you would simply enable session tracing for that user, but there are two potential problems with that approach.

The first is that many web based applications maintain a pool of persistent database connections which are shared amongst multiple users. The second is that some applications connect, run some SQL and disconnect very quickly, making it tricky to enable session tracing at all (you could of course use a logon trigger to enable session tracing in this case).

A quick and dirty solution to the problem is to capture all SQL statements that are run between two points in time.

The following procedure will create two tables, each containing a snapshot of the database at a particular point. The tables will then be queried to produce a list of all SQL run during that period.

If possible, you should do this on a quiet development system - otherwise you risk getting way too much data back.

1. Take the first snapshotRun the following sql to create the first snapshot:

createtable sql_exec_before as

selectexecutions

, hash_value

fromv$sqlarea

/

2. Get the user to perform their task within the application 3. Take the second snapshot selectaft.hash_value

fromsql_exec_before bef

,sql_exec_after aft

whereaft.executions > bef.executions

andaft.hash_value = bef.hash_value (+)

/

4. Check the resultsNow that you have captured the SQL it is time to query the results.

This first query will list all query hashes that have been executed:

selectaft.hash_value

fromsql_exec_before bef

,sql_exec_after aft

whereaft.executions > bef.executions

andaft.hash_value = bef.hash_value (+)

/

This one will display the hash and the SQL itself:

set pages 999 lines 100

break on hash_value

selecthash_value

,sql_text

from v$sqltext

wherehash_value in (

selectaft.hash_value

fromsql_exec_before bef

,sql_exec_after aft

whereaft.executions > bef.executions

andaft.hash_value = bef.hash_value (+)

)

order by

hash_value

,piece

/

5. Tidy upDon't forget to remove the snapshot tables once you've finished:

drop table sql_exec_before

/

drop table sql_exec_after

/

Bottom of Form

_1300628673.unknown

_1300628722.unknown

_1300628750.unknown

_1300628767.unknown

_1300628771.unknown

_1300628773.unknown

_1300628774.unknown

_1300628772.unknown

_1300628769.unknown

_1300628770.unknown

_1300628768.unknown

_1300628754.unknown

_1300628763.unknown

_1300628765.unknown

_1300628766.unknown

_1300628764.unknown

_1300628757.unknown

_1300628761.unknown

_1300628762.unknown

_1300628759.unknown

_1300628760.unknown

_1300628758.unknown

_1300628755.unknown

_1300628752.unknown

_1300628753.unknown

_1300628751.unknown

_1300628735.unknown

_1300628746.unknown

_1300628748.unknown

_1300628749.unknown

_1300628747.unknown

_1300628742.unknown

_1300628744.unknown

_1300628745.unknown

_1300628743.unknown

_1300628738.unknown

_1300628740.unknown

_1300628741.unknown

_1300628739.unknown

_1300628737.unknown

_1300628731.unknown

_1300628733.unknown

_1300628734.unknown

_1300628732.unknown

_1300628727.unknown

_1300628729.unknown

_1300628730.unknown

_1300628728.unknown

_1300628724.unknown

_1300628725.unknown

_1300628726.unknown

_1300628723.unknown

_1300628699.unknown

_1300628711.unknown

_1300628717.unknown

_1300628720.unknown

_1300628721.unknown

_1300628719.unknown

_1300628718.unknown

_1300628713.unknown

_1300628714.unknown

_1300628716.unknown

_1300628712.unknown

_1300628703.unknown

_1300628705.unknown

_1300628709.unknown

_1300628710.unknown

_1300628707.unknown

_1300628708.unknown

_1300628706.unknown

_1300628704.unknown

_1300628701.unknown

_1300628702.unknown

_1300628700.unknown

_1300628690.unknown

_1300628695.unknown

_1300628697.unknown

_1300628698.unknown

_1300628696.unknown

_1300628692.unknown

_1300628693.unknown

_1300628691.unknown

_1300628681.unknown

_1300628686.unknown

_1300628688.unknown

_1300628689.unknown

_1300628687.unknown

_1300628683.unknown

_1300628684.unknown

_1300628685.unknown

_1300628682.unknown

_1300628675.unknown

_1300628679.unknown

_1300628680.unknown

_1300628677.unknown

_1300628678.unknown

_1300628674.unknown

_1300628626.unknown

_1300628648.unknown

_1300628663.unknown

_1300628667.unknown

_1300628669.unknown

_1300628671.unknown

_1300628672.unknown

_1300628670.unknown

_1300628668.unknown

_1300628665.unknown

_1300628666.unknown

_1300628664.unknown

_1300628656.unknown

_1300628659.unknown

_1300628661.unknown

_1300628662.unknown

_1300628660.unknown

_1300628658.unknown

_1300628650.unknown

_1300628654.unknown

_1300628655.unknown

_1300628652.unknown

_1300628653.unknown

_1300628651.unknown

_1300628649.unknown

_1300628634.unknown

_1300628640.unknown

_1300628642.unknown

_1300628646.unknown

_1300628647.unknown

_1300628644.unknown

_1300628645.unknown

_1300628643.unknown

_1300628641.unknown

_1300628638.unknown

_1300628639.unknown

_1300628635.unknown

_1300628637.unknown

_1300628630.unknown

_1300628632.unknown

_1300628633.unknown

_1300628631.unknown

_1300628628.unknown

_1300628629.unknown

_1300628627.unknown

_1300628598.unknown

_1300628610.unknown

_1300628620.unknown

_1300628622.unknown

_1300628624.unknown

_1300628625.unknown

_1300628623.unknown

_1300628621.unknown

_1300628616.unknown

_1300628618.unknown

_1300628619.unknown

_1300628617.unknown

_1300628612.unknown

_1300628613.unknown

_1300628614.unknown

_1300628611.unknown

_1300628602.unknown

_1300628608.unknown

_1300628609.unknown

_1300628606.unknown

_1300628607.unknown

_1300628604.unknown

_1300628605.unknown

_1300628603.unknown

_1300628600.unknown

_1300628601.unknown

_1300628599.unknown

_1300628583.unknown

_1300628590.unknown

_1300628592.unknown

_1300628596.unknown

_1300628597.unknown

_1300628594.unknown

_1300628595.unknown

_1300628591.unknown

_1300628585.unknown

_1300628587.unknown

_1300628589.unknown

_1300628588.unknown

_1300628586.unknown

_1300628584.unknown

_1300628579.unknown

_1300628581.unknown

_1300628582.unknown

_1300628580.unknown

_1300628577.unknown

_1300628578.unknown

_1300628575.unknown