QUERIES STATUS Startup time select to_char(startup_time, 'HH24:MI DD-MON-YY') "Startup time" from v$instance / How large is the database col "Database Size" format a20 col "Free space" format a20 col "Used space" format a20 select round(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 (select bytes from v$datafile union all select bytes from v$tempfile union all select bytes 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 space set pages 999 col "size MB" format 999,999,999 col "Objects" format 999,999,999 select obj.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(+) order by 3 desc ,2 desc, 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
col "Database Size" format a20col "Free space" format a20col "Used space" format a20select round(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 union all
select bytes from v$tempfile union all select bytes 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 999col "size MB" format 999,999,999col "Objects" format 999,999,999select obj.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_sizefrom dba_segments group by owner) segwhere obj.owner = seg.owner(+)order by 3 desc ,2 desc, 1/
Show the ten largest objects in the database
Col owner format a15Col segment_name format a30Col segment_type format a15Col mb format 999,999,999select owner,segment_name,segment_type,mbfrom(select owner,segment_name,segment_type,bytes / 1024 / 1024 "MB"from dba_segmentsorder by bytes desc)where rownum < 11/
Is java installed in the database?
This will return 9000'ish if it is...select count(*)from all_objectswhere object_type like '%JAVA%'and owner = 'SYS'/
set lines 100 pages 999col ID format a15select username,sid || ',' || serial# "ID",status,last_call_et "Last Activity"from v$sessionwhere username is not nullorder by status desc,last_call_et desc
/
Time since last user activity
set lines 100 pages 999select username, floor(last_call_et / 60) "Minutes", statusfrom v$sessionwhere username is not nullorder by last_call_et
/
Sessions sorted by logon time
set lines 100 pages 999col ID format a15col osuser format a15col login_time format a14select username, osuser, sid || ',' || serial# "ID", status, to_char(logon_time, 'hh24:mi dd/mm/yy') login_time, last_call_etfrom v$sessionwhere username is not nullorder by login_time
/
Show user info including os pid
col "SID/SERIAL" format a10col username format a15col osuser format a15col program format a40select s.sid || ',' || s.serial# "SID/SERIAL", s.username, s.osuser, p.spid "OS PID", s.program
from v$session s, v$process pWhere s.paddr = p.addrorder by to_number(p.spid)
/
Show a users current sql
Select sql_textfrom v$sqlareawhere (address, hash_value) in(select sql_address, sql_hash_value from v$session where username like '&username')
/
Session status associated with the specified os process id
set feedback offset serveroutput on size 9999column username format a20column sql_text format a55 word_wrappedbegin 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;
/
Display any long operations
set lines 100 pages 999col username format a15col message format a40col remaining format 9999select username, to_char(start_time, 'hh24:mi:ss dd/mm/yy') started, time_remaining remaining, messagefrom v$session_longopswhere time_remaining = 0order by time_remaining desc/
List open cursors per user
set pages 999select sess.username, sess.sid, sess.serial#, stat.value cursorsfrom v$sesstat stat, v$statname sn, v$session sesswhere sess.username is not nulland sess.sid = stat.sidand stat.statistic# = sn.statistic#and sn.name = 'opened cursors current'order by value
/
Or alternatively... set lines 100 pages 999select count(hash_value) cursors, sid, user_namefrom v$open_cursorgroup by sid, user_nameorder by cursors/
set pages 999 lines 100col name format a30col value format a50select name, valuefrom v$parameterwhere isdefault = 'FALSE'and value is not nullorder by name
/
or for name='parameter' style...set pages 999 lines 100select name || '=' || decode(type, 2, '''') || value
|| decode(type, 2, '''') parameterfrom v$parameterwhere isdefault = 'FALSE'and value is not nullorder by name
/
Reset/Unset a spfile parameter
Setting a parameter to =' ' often isn't enough. Do this instead...alter system reset <parameter> scope=spfile sid='*'
/
The sid='*' bit is always necessary, even in non RAC database.
USER
List users
set pages 999 lines 100col username format a20col status format a8col tablespace format a20
col temp_ts format a20select username, account_status status, created, default_tablespace tablespace, temporary_tablespace temp_tsfrom dba_usersorder by username/
Lock or unlock a user
alter user <username> account lock;
And to unlock...
alter user <username> account unlock;
ROLEFind a role
select *from dba_roleswhere role like '&role'
/
Show what roles are granted to a user
select grantee, granted_role, admin_optionfrom dba_role_privswhere grantee like upper('&username')
/
Show what system privileges are granted to a role
select privilege, admin_optionfrom role_sys_privswhere role 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 diskgroup
Check if css is running/working
crsctl check cssd
Display disk-groups
set lines 100col name format a10col path format a30select name, group_number, disk_number, mount_status, state, pathfrom v$asm_diskorder by group_number
/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_mbfrom v$asm_diskorder by group_number
or with multiple raw partitions...multiple diskscreate diskgroup data2external redundancydisk '/dev/raw/raw2', '/dev/raw/raw3'
/
or with multiple fail groups...create diskgroup data3normal redundancyfailgroup controller1 disk '/dev/raw/raw4'failgroup controller2 disk '/dev/raw/raw6'
/
Add a disk to a group
alter diskgroup data1add disk '/dev/raw/raw4'
/
Wildcards can be used for raw device names (eg. raw*)
Drop a disk group
drop diskgroup '<name>'
/
Is ASM performing a balancing operation
select *from v$asm_operation
/
Mount/dismount disk groupsalter diskgroup all mount
alter diskgroup data1 mount
alter diskgroup all dismount
alter diskgroup data1 dismount
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 subnet
Start, stop and check CRS (Cluster Ready Services)
Note. Start/stop need to be run as root from the CRS home.
First find the interface which is in use as the interconnect - run as root from the crs home:oifcfg getif
Make a note of the interface name (eth1 in the following example), thenrun the following:oifcfg delif -global eth1oifcfg setif -global eth1/<your new subnet>: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 job
List scheduled jobs
set lines 100 pages 999col schema_user format a15col fails format 999select job, 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) whatfrom dba_jobsorder by 4/
Drop an object with out putting it in the recycle bin
drop <object_type> <object_name> 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 999col tablespace_name format a40col "size MB" format 999,999,999col "free MB" format 99,999,999col "% Used" format 999select 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 allselect tablespace_name || ' **TEMP**', sum(bytes)/1024/1024 used_mbfrom dba_temp_files group by tablespace_name) tsu
, (select tablespace_name, sum(bytes)/1024/1024 free_mbfrom dba_free_space group by tablespace_name) tsf
where tsu.tablespace_name = tsf.tablespace_name (+)order by 4/
set lines 100col file_name format a70select file_name, ceil(bytes / 1024 / 1024) "size MB"from dba_data_fileswhere tablespace_name like '&TSNAME'/
Tablespaces >80% full
set pages 999 lines 100col tablespace_name format a40col "size MB" format 999999999col "% Used" format 999col "80%" format 999999col "75%" format 999999select 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) tsfwhere tsu.tablespace_name = tsf.tablespace_name (+)and 100 - floor(tsf.free_mb/tsu.used_mb*100) >= 80order by 3,4,5/
User quotas on all tablespaces
col quota format a10select username, tablespace_name, decode(max_bytes, -1, 'unlimited' , ceil(max_bytes / 1024 / 1024) || 'M' ) "QUOTA"from dba_ts_quotaswhere tablespace_name not in ('TEMP')/
List all objects in a tablespace
set pages 999col owner format a15col segment_name format a40col segment_type format a20select owner, segment_name, segment_typefrom dba_segmentswhere lower(tablespace_name) like lower('%&tablespace%')order by owner, segment_name/
Show all tablespaces used by a user
select tablespace_name, ceil(sum(bytes) / 1024 / 1024) "MB"from dba_extentswhere owner like '&user_id'group by tablespace_nameorder by tablespace_name/
col segment_name format a40select owner, segment_type, segment_name, max_extents - extents as "spare", max_extentsfrom dba_segmentswhere owner not in ('SYS','SYSTEM')and (max_extents - extents) < 10order by 4/
To change maxextentsalter <segment_type> <segment_name> storage(maxextents 150);
List the contents of the temporary tablespace(s)
set pages 999 lines 100col username format a15col mb format 999,999select su.username, ses.sid , ses.serial#, su.tablespace, ceil((su.blocks * dt.block_size) / 1048576) MBfrom v$sort_usage su, dba_tablespaces dt, v$session seswhere su.tablespace = dt.tablespace_nameand 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 size
Find an object
set pages 999col owner format a15col object_name format a40col object_type format a20select owner, object_name, object_typefrom dba_objectswhere lower(object_name) like lower('%&object%')order by owner, object_type, object_name/
Invalid objects
List invalid objects... set lines 200 pages 999col "obj" format a40select owner || '.' || object_name "obj", object_typefrom dba_objectswhere status = 'INVALID'/
Recompile all invalid objects...@?/rdbms/admin/utlrp.sql
Show the size of an object
col segment_name format a20select segment_name, bytes "SIZE_BYTES", ceil(bytes / 1024 / 1024) "SIZE_MB"from dba_segmentswhere segment_name like '&obj_name'/
All objects owned by a user
col object_name format a40select object_name, object_typefrom dba_objectswhere owner = '&user'order by object_type, object_name/
Source code of a procedure
select textfrom dba_sourcewhere owner = 'ANDY'and name = 'FILE_TEST'and type = 'PACKAGE BODY'order by line/
Get an objects ddl (9i onwards)
Note. Works for 9i and newer.Parameters: OBJECT_TYPE, OBJECT_NAME, SCHEMAset pagesize 0set long 90000select dbms_metadata.get_ddl('TABLE','TABLE_A','ANDY') from dual;
Display compilation errors and warnings
show errors
show errors view <veiw_name>show errors procedure <proc_name>
select * from dba_errors;
Find all tables containing the specified column
set pages 999 lines 100col tab format a60col column_name format a20select owner || '.' || table_name as tab, column_namefrom dba_tab_columnswhere column_name like upper('&col')/
List all tables owned by a user sorted by size
set lines 100 pages 999col segment_name format a40col mb format 999,999,999select segment_name, ceil(sum(bytes) / 1024 / 1024) "MB"
from dba_segmentswhere owner like '&user'and segment_type = 'TABLE'group by segment_nameorder by ceil(sum(bytes) / 1024 / 1024) desc/
Structure - Indexes Index info by table Show indexed columns
Index info by table
select i.index_name, i.tablespace_name, ceil(s.bytes / 1048576) "Size MB"from dba_indexes i, dba_segments swhere i.index_name = s.segment_nameand table_name like '&table'order by 2, 1
/
Show indexed columns
select column_namefrom dba_ind_columnswhere 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 mode
set trimspool on wrap offset heading offset verify offset 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
List controlfiles
select namefrom v$controlfile/
Create an OS command for every file in the database
The example deletes all filesselect 'rm ' || namefrom (select name
from v$datafileunion allselect namefrom v$tempfileunion allselect memberfrom v$logfile
union all select name from v$controlfile
)/
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/
List files that are in hot-backup mode
set lines 100 pages 999col name format a60select df.name, b.status, to_char(time, 'hh24:mi:ss dd/mm/yyyy') timefrom v$datafile df, v$backup bwhere df.file# = b.file#and b.status = 'ACTIVE'order by b.file#
/
Structure - Redo Logs Remove drop add logfile members List members and sizes
Remove drop
alter database drop logfile member '<filename>';
add logfile members
alter database add logfile member '<filename>' to group <group>;
List members and sizes
col member format a60col "Size MB" format 9,999,999select lf.member, ceil(lg.bytes / 1024 / 1024) "Size MB"from v$logfile lf, v$log lgwhere lg.group# = lf.group#order by 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?
select tablespace_name, status, count(*) as HOW_MANYfrom dba_undo_extentsgroup by tablespace_name, status/
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 999col username format a15
col command format a20select ses.username, substr(ses.program, 1, 19) command, tra.used_ublkfrom v$session ses, v$transaction trawhere ses.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 user
Show all constraints on a table
col type format a10col cons_name format a30select decode(constraint_type,
'C', 'Check','O', 'R/O View','P', 'Primary','R', 'Foreign','U', 'Unique','V', 'Check view') type
, constraint_name cons_name, status, last_changefrom dba_constraintswhere owner like '&owner'and table_name like '&table_name'order by 1/
List tables that are using the specified table as a foreign key
Same as above, but produces 'disable constraint' statementsset lines 100 pages 999col discon format a100 select 'alter table '||a.owner||'.'||a.table_name||' disable constraint'||a.constraint_name||';' disconfrom dba_constraints a, dba_constraints bwhere a.constraint_type = 'R'and a.r_constraint_name = b.constraint_nameand a.r_owner = b.ownerand b.owner = '&table_owner'and b.table_name = '&table_name'/
Produce a list of disabled fk constraints
set lines 100 pages 999col table format a60col constraint_name format a30select owner||'.'||table_name "table", constraint_namefrom dba_constraintswhere status = 'DISABLED'and constraint_type = 'R'
and owner not in ('SYS','SYSTEM')order by 1,2/
Produce enable statements all disabled fk constraints
set lines 100 pages 999select 'alter table '||owner||'.'||table_name||' enable constraint'||constraint_name||';' "enable"from dba_constraintswhere status = 'DISABLED'and constraint_type = 'R'and owner not in ('SYS','SYSTEM')order by 1/
List parent tables that may need fixing/re-importing
select distinct r.owner || '.' || r.table_name "exp"from dba_constraints c, dba_constraints rwhere c.status = 'DISABLED'and c.constraint_type = 'R'and c.r_owner = r.ownerand c.r_constraint_name = r.constraint_nameand c.owner not in ('SYS','SYSTEM')order by 1/
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 rcwhere c.constraint_type = 'R'and c.owner not in ('SYS','SYSTEM')and c.r_owner = r.ownerand c.owner = cc.ownerand r.owner = rc.ownerand c.constraint_name = cc.constraint_nameand r.constraint_name = rc.constraint_nameand c.r_constraint_name = r.constraint_nameand cc.position = rc.positionand 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/
Show all table constraints for a user
Note. This still needs some work...set lines 100 pages 999break on table_name
, nvl(index_name, R_CONSTRAINT_NAME) "IDX"from dba_constraintswhere owner like '&user'order by 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 refresh
Create a view log for the master table
This is required for fast refreshcreate materialized view log on <table>/
or...create materialized view log on <table>tablespace <tablespace_name>/
create materialized view andy_mviewrefresh [fast | complete | force]start with sysdatenext sysdate + 1/24with primary keyas select * from test_table/
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 999col last_refresh format a20select owner, mview_name, to_char(last_refresh_date, 'dd/mm/yy hh24:mi') last_refreshfrom dba_mviewsorder by owner, last_refresh/
Show materialized view tables and masters
set lines 100col mview format a40col master format a40select owner || '.' || name mview, master_owner || '.' || master masterfrom dba_mview_refresh_times/
Show refresh jobs in dba_jobs
This is useful for spotting failuresset lines 100col job format 9999col log_user format a15col last format a15col next format a15col fail format 9999col what format a20select job, 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, '"') whatfrom dba_jobswhere what like '%dbms_refresh.refresh%'/
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 partition
List partitioned tables
set pages 999 lines 100col table_name format a40select table_name, partitioning_type type
alter table <table_name>split partition <partition_name> at (<value>)into (partition <partition_name>, partition <partition_name>)update global indexes/
Drop a partition
alter table <table_name> drop partition <partition_name>/
Truncate a partition
alter table <table_name> truncate partition <partition_name>/
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 advisory
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_idfrom v$sqlareawhere executions > 10order by 6 desc/
File io stats
Requires timed_statistics=trueset lines 80 pages 999col fname heading "File Name" format a60col sizemb heading "Size(Mb)" format 99,999col phyrds heading "Reads" format 999,999,999col readtim heading "Time" format 99.999col phywrts heading "Writes" format 9,999,999col writetim heading "Time" format 99.999select lower(name) fname, (bytes / 1048576) sizemb, phyrds, readtim, phywrts, writetimfrom v$datafile df, v$filestat fswhere df.file# = fs.file#order by 1/
In session tracing
To switch it on:exec dbms_system.set_sql_trace_in_session (<sid>, <serial#>, true);
To switch it off:exec dbms_system.set_sql_trace_in_session (<sid>, <serial#>, false);
switch on event 10046
To switch it on:alter session set events '10046 trace name context forever, level 8';
To switch it off:alter session set events '10046 trace name context off';
Note. use tkprof to interpret the results.
Rows per block
select avg(row_count) avg, max(row_count) max, min(row_count) minfrom ( select count(*) row_count from &table_name group by substr(rowid, 1, 15) )/
Show the buffer cache advisory
Note. The current setting is halfway down and has a read factor of one.set lines 100 pages 999col est_mb format 99,999col estd_physical_reads format 999,999,999,999,999
select size_for_estimate est_mb, estd_physical_read_factor, estd_physical_readsfrom v$db_cache_advicewhere name = 'DEFAULT'order by size_for_estimate/
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 locks
Then select the row with that rowid...select * from <table> where rowid=<rowid>;
List locks
column lock_type format a12column mode_held format a10column mode_requested format a10column blocking_others format a20column username format a10SELECT session_id, lock_type, mode_held, mode_requested, blocking_others, lock_id1FROM dba_lock lWHERE 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 sessions
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 instance
Top ten hotest objects by touch count
col owner format a20 trunccol object_nameformat a30col touches format 9,999,999select *from (
col name format a60select name, count from x$kcbfwait, v$datafilewhere indx + 1 = file#order by 2/
Segment Waits
select object_name, obj#, statistic_name, valuefrom v$segment_statisticswhere owner like '&owner'and statistic_name like '%waits%'and value > 0order by statistic_name, value desc/
Time waited for latches
col event format a30select event, time_waited, round(time_waited*100/ SUM (time_waited) OVER(),2) wait_pctfrom (
select event, time_waitedfrom v$system_eventwhere event not in (
union(select name, valuefrom v$sysstatwhere name like 'CPU used when call started')
)order by 2 desc/
Identify hot blocks
Look at all waits for the instancecol event format a30select event, total_waits, time_waitedfrom v$system_event where event like '%wait%'order by 2,3/
If there are lots of 'data block' waits, get a break-down of themselect *from v$waitstat/
Then run this to identify the file, block and reason code...select p1 "File #", p2 "Block #", p3 "Reason Code"from v$session_waitwhere event = 'buffer busy waits'/
Note. You might need to run this a few times before anything is displayed.
Look at the performance stats for the instance
select n.name, s.valuefrom v$statname n, v$sysstat swhere n.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 today
Gather database statistics
Gather stats on the entire database...execute dbms_stats.gather_database_stats;
Wait for a while - idealy with the database under a typical workloadexecute dbms_stats.gather_system_stats('Stop');
To see the current system statisticsselect pname, pval1 from sys.aux_stats$
where sname = 'SYSSTATS_MAIN'/
Export/Import optimizer statistics
Create a table to hold the statistics... exec dbms_stats.create_stat_table(ownname => 'SYS',-stattab => 'prod_stats', tblspace => 'USERS');
Populate the table with the current stats... exec dbms_stats.export_schema_stats(ownname => 'SCOTT',-statown=>'SYS', stattab=>'prod_stats');
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');
, count(*) total_tablesfrom dba_tablesgroup by owner) a
, (select owner, count(last_analyzed) analyzed_tablesfrom dba_tableswhere last_analyzed is not nullgroup by owner) b
where a.owner = b.owner (+)and a.owner not in ('SYS', 'SYSTEM')order by a.total_tables - nvl(b.analyzed_tables,0) desc/
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 doselect count(last_analyzed) left_to_dofrom dba_tableswhere owner = '&schema'and trunc(last_analyzed) < trunc(sysdate)order by 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 area
Create a plan table
@?/rdbms/admin/utlxplan.sql
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 queryset 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
set lines 100 pages 999col bytes format 999,999,999compute sum of bytes on poolbreak on pool skip 1select pool, name, bytesfrom v$sgastatorder by pool, name/
Performance - Statspack Take a snapshot Delete one or more snapshots Generate a report List snapshots Install statspack Uninstall statspack Schedule and hourly snapshot
Take a snapshot
exec statspack.snap;
Or to specify a level...exec statspack.snap(i_snap_level => 6, i_modify_parameter => 'true');
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.
col "Date/Time" format a30select snap_id, snap_level, to_char(snap_time,'HH24:MI:SS DD-MM-YYYY') "Date/Time"from stats$snapshot, v$databaseorder by snap_id/
Install statspack
1. Create a tablespace (minimum size 100MB)2. Run...@?/rdbms/admin/spcreate
Uninstall statspack
@?/rdbms/admin/spdrop
Schedule and hourly snapshot
@?/rdbms/admin/spauto.sql
Note. This uses dbms_job, so job_queue_processes needs to be set greater than 0.
To see the job: select job, whatfrom dba_jobs/
To delete the job:exec dbms_job.remove(<job number>);
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) report
Display a list of snapshots
set lines 100 pages 999select snap_id, snap_level, to_char(begin_interval_time, 'dd/mm/yy hh24:mi:ss') beginfrom dba_hist_snapshot order by 1/
Note. This job is enabled by defaultexec dbms_scheduler.enable('GATHER_STATS_JOB')
and to disable...exec dbms_scheduler.disable('GATHER_STATS_JOB')
Time model queries
System time modelset lines 100 pages 999select stat_name, valuefrom v$sys_time_modelorder by value desc/
Session time modelset lines 100 pages 999select stat_name, valuefrom v$sess_time_modelwhere sid = '&sid'order by value desc/
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 logs
alter database register physical logfile '<fullpath/filename>';
If FAL doesn't work and it says the log is already registered
alter database register or replace physical logfile '<fullpath/filename>';
If that doesn't work, try this...shutdown immediatestartup nomountalter database mount standby database;alter database recover automatic standby database;
wait for the recovery to finish - then cancelshutdown immediatestartup nomountalter database mount standby database;alter database recover managed standby database disconnect;
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#)/
Disable/Enable archive log destinations
alter system set log_archive_dest_state_2 = 'defer';alter system set log_archive_dest_state_2 = 'enable';
To be run on the primaryset numwidth 8 lines 100column id format 99 select dest_id id, archiver, transmit_mode, affirm, async_blocks async, net_timeout net_time, delay_mins delay, reopen_secs reopen, register,binding from v$archive_destorder by
dest_id/
List any standby redo logs
set lines 100 pages 999col member format a70select st.group#, st.sequence#, ceil(st.bytes / 1048576) mb, lf.memberfrom v$standby_log st, v$logfile lfwhere st.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 back
To 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'));
To disable flashback run...exec dbms_flashback.disable;
Copy old data into a new table
First, create an empty copy of the source table...create table old_test_tabletablespace andyas select *
set pages 999select scn, to_char(time_dp, 'hh24:mi:ss dd/mm/yyyy') timefrom smon_scn_timeorder by scn/
Flash the database back
shutdown immediatestartup mount exclusive
flashback database to scn <scn>;
or...flashback database to timestamp to_timestamp('22/04/2007 19:30:00','dd/mm/yyyy hh24:mi:ss');
alter database open resetlogs;
Manual upgrade from 9i to 10g Release 2This 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 tablespace
Having a sysaux tablespace is a requirement in 10g. So, if you haven't already got one, create one now.create tablespace sysauxdatafile '<file_name>' size 512Mextent management localsegment space management auto/
3. Run utlu102i.sql
This 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.
Alter /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 parameters
Temporarily 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
startupThat's it!
Capture all SQL run between two points in timetnsManager - 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:
create table sql_exec_before as select executions , hash_value from v$sqlarea /
2. Get the user to perform their task within the application 3. Take the second snapshot select aft.hash_value from sql_exec_before bef , sql_exec_after aft where aft.executions > bef.executions and aft.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: select aft.hash_value from sql_exec_before bef , sql_exec_after aft where aft.executions > bef.executions and aft.hash_value = bef.hash_value (+) /
This one will display the hash and the SQL itself: