32
Oracle --> BigData --> Cloud My Journey towards Cloud ... Scripts related to TEMP Tablespace To see Temp Space: ------------------- SELECT a.tablespace_name,RO!"##c.total_bloc$s%b.bloc$_s&'e()*+ )*+ )*+ ,( Total S&'e /012 ,RO!"##a.used_bloc$s%b.bloc$_s&'e()*+ )*+ )*+ ,( sed_s&'e RO!"###c.total_bloc$s-a.used_bloc$s(%b.bloc$_s&'e()*+ )*+ )*+ ,( 3ree_s&'e/0 RO!"##a.ma4_bloc$s%b.bloc$_s&'e()*+ )*+ )*+ ,( Ma4_S&'e_E5er_sed/012 , RO!"##a.ma4_used_bloc$s%b.bloc$_s&'e()*+ )*+ )*+ ,( Ma4S&'e_e5er_sed_by_Sorts/012 , RO!"##a.used_bloc$s)c.total_bloc$s(%*++, ( sed 6ercenta7e 3ROM 89sort_se7ment a,dba_tablespaces b,#SELECT tablespace_name,SM#bloc$s( total_bloc$s 3ROM dba_temp_ &les 0RO6 by tablespace_name( c ;<ERE a.tablespace_name=b.tablespace_name >!" a.tablespace_name=c.tablespace_name? ======================================================================== ====================== To see top *+ consum&n7 process : --------------------------------- select % rom #SELECT d.tablespace_name,a.s&d,a.ser&al@,a.pro7ram,a.module,a.act&on,a.username sername ,a.osuser,RO!"##b.bloc$s%d.bloc$_s&'e()*+ )*+ ,( sed M1 ,c.sAl_te4 3ROM 59sess&on a, 59tempse7_usa7e b, 59sAlarea c,dba_tablespaces d ;<ERE a.saddr = b.sess&on_addr >!" c.address= a.sAl_address >!" c.BasB_5alue = a.sAl_BasB_5alue >!" d.tablespace_name=b.tablespace OR"ER 1 b.tablespace, b.bloc$ "ESC( wBere rownum D=*+ ======================================================================== ======================

Script Comands All DBA

Embed Size (px)

DESCRIPTION

script comands all dba.docx

Citation preview

Oracle --> BigData --> CloudMy Journey towards Cloud ...Scripts related to TEMP Tablespace

To see Temp Space:-------------------

SELECT a.tablespace_name,ROUND((c.total_blocks*b.block_size)/1024/1024/1024,2)"Total Size [GB]",ROUND((a.used_blocks*b.block_size)/1024/1024/1024,2) "Used_size[GB]",ROUND(((c.total_blocks-a.used_blocks)*b.block_size)/1024/1024/1024,2) "Free_size[GB]",ROUND((a.max_blocks*b.block_size)/1024/1024/1024,2) "Max_Size_Ever_Used[GB]", ROUND((a.max_used_blocks*b.block_size)/1024/1024/1024,2) "MaxSize_ever_Used_by_Sorts[GB]" ,ROUND((a.used_blocks/c.total_blocks)*100,2) "Used Percentage"FROM V$sort_segment a,dba_tablespaces b,(SELECT tablespace_name,SUM(blocks)total_blocks FROM dba_temp_files GROUP by tablespace_name) cWHERE a.tablespace_name=b.tablespace_name AND a.tablespace_name=c.tablespace_name;

==============================================================================================To see top 10 consuming process :---------------------------------

select * from(SELECT d.tablespace_name,a.sid,a.serial#,a.program,a.module,a.action,a.username "DB Username",a.osuser,ROUND((b.blocks*d.block_size)/1024/1024,2) "Used MB",c.sql_textFROM v$session a, v$tempseg_usage b, v$sqlarea c,dba_tablespaces dWHERE a.saddr = b.session_addr AND c.address= a.sql_address AND c.hash_value = a.sql_hash_value AND d.tablespace_name=b.tablespace ORDER BY b.tablespace, b.blocks DESC)where rownum 1024 ORDER BY b.tablespace, 6 desc;

=============================================================================================

No comments:Tracking Oracle database growth

To calculate the Datafile Growth on a yearly basis:===================================================select to_char(CREATION_TIME,'RRRR') year,to_char(CREATION_TIME,'MM') month,round(sum(bytes)/1024/1024/1024) gbfrom v$datafile group by to_char(CREATION_TIME,'RRRR'),to_char(CREATION_TIME,'MM') order by 1,2;

YEAR MO GB---- -- ----------2000 04 92004 06 52004 11 52005 01 22005 02 42005 06 42005 09 202005 10 22005 11 122006 01 82007 01 12007 06 82007 08 14902008 01 82008 02 92008 03 442008 04 222008 07 162008 09 102008 10 572009 01 142009 02 362009 04 372009 05 262009 06 232009 07 822009 08 02009 09 182009 11 362009 12 162010 01 392010 02 802010 03 62010 04 562010 05 802010 06 4712010 07 362010 08 752010 09 1602010 10 42010 12 382011 02 592011 04 522011 05 162011 07 782011 08 402011 09 92011 10 782011 11 572011 12 82012 01 1102012 02 1342012 06 62012 08 14

Through OEM :===========

Here are the steps to know Database growth pattern for last one month/year using OEM

1) Login to OEM and Click on the Reports Tab2) Navigate to Reports>Storage>Oracle Database Space Usage path and Click on Oracle Database Space Usage link.3) Select the Target database and here we are getting Oracle Database space usage for last one Month.4) Also we can get one year Database growth by setting Set Time Period Button.5) Also we can find Oracle Database Tablespace Monthly Space Usage by Navigating Reports>Storage>Oracle Database Space Usage path and click on Oracle Database Tablespace Monthly Space Usage link.1 comment:AWR Reports

AWR FEATURESThe AWR is used to collect performance statistics including: Wait events used to identify performance problems. Time model statistics indicating the amount of DB time associated with a process from theV$SESS_TIME_MODELandV$SYS_TIME_MODELviews. Active Session History (ASH) statistics from theV$ACTIVE_SESSION_HISTORYview. Some system and session statistics from theV$SYSSTATandV$SESSTATviews. Object usage statistics.

WORKLOAD REPOSITORY REPORTSOracle provide two scripts to produce workload repository reports (awrrpt.sql and awrrpti.sql). They are similar in format to the statspack reports and give the option of HTML or plain text formats. The two reports give essential the same output but the awrrpti.sql allows you to select a single instance. The reports can be generated as follows.@$ORACLE_HOME/rdbms/admin/awrrpt.sql@$ORACLE_HOME/rdbms/admin/awrrpti.sqlThe scripts prompt you to enter the report format (html or text), the start snapshot id, the end snapshot id and the reportfile name. The resulting report can beopenedin a browser or text editor accordingly.

ENTERPRISE MANAGERThe automated workload repository administration tasks have been included in Enterprise Manager. The "Automatic Workload Repository" page is accessed from the main page by clicking on the "Administration" link, then the "Workload Repository" link under the "Workload" section. The page allows you to modify AWR settings or manage snapshots without using the PL/SQL APIs.No comments:Long running Concurrent Requests1.How to Determine Which Manager Ran a Specific Concurrent Request?

col USER_CONCURRENT_QUEUE_NAME for a100select b.USER_CONCURRENT_QUEUE_NAME from fnd_concurrent_processes a,fnd_concurrent_queues_vl b, fnd_concurrent_requests cwhere a.CONCURRENT_QUEUE_ID = b.CONCURRENT_QUEUE_IDand a.CONCURRENT_PROCESS_ID = c.controlling_managerand c.request_id = '&conc_reqid';

2.Concurrent manager status for a given sid?

col MODULE for a20col OSUSER for a10col USERNAME for a10set num 10col MACHINE for a20set lines 200col SCHEMANAME for a10select s.sid,s.serial#,p.spid os_pid,s.status, s.osuser,s.username, s.MACHINE,s.MODULE,s.SCHEMANAME,s.action from gv$session s, gv$process p WHERE s.paddr = p.addr and s.sid = '&oracle_sid';

3. Find out request id from Oracle_Process Id:

select REQUEST_ID,ORACLE_PROCESS_ID,OS_PROCESS_Id from apps.fnd_concurrent_requests whereORACLE_PROCESS_ID='&a';

4.To find sid,serial# for a given concurrent request id?

set lines 200SELECT a.request_id, d.sid, d.serial# ,d.osuser,d.process , c.SPID ,d.inst_idFROM apps.fnd_concurrent_requests a,apps.fnd_concurrent_processes b,gv$process c,gv$session dWHERE a.controlling_manager = b.concurrent_process_idAND c.pid = b.oracle_process_idAND b.session_id=d.audsidAND a.request_id = &Request_IDAND a.phase_code = 'R';

5.To find concurrent program name,phase code,status code for a given request id?

SELECT request_id, user_concurrent_program_name, DECODE(phase_code,'C','Completed',phase_code)phase_code, DECODE(status_code,'D', 'Cancelled' ,'E', 'Error' , 'G', 'Warning', 'H','On Hold' , 'T', 'Terminating', 'M', 'No Manager' , 'X','Terminated', 'C', 'Normal', status_code) status_code, to_char(actual_start_date,'dd-mon-yy:hh24:mi:ss') Start_Date, to_char(actual_completion_date,'dd-mon-yy:hh24:mi:ss'),completion_text FROM apps.fnd_conc_req_summary_v WHERE request_id = '&req_id' ORDER BY 6 DESC;

6.To find the sql query for a given concurrent request sid?

select sid,sql_text from gv$session ses, gv$sqlarea sql whereses.sql_hash_value = sql.hash_value(+) and ses.sql_address = sql.address(+) andses.sid='&oracle_sid'/

7. To find child requests

set lines 200col USER_CONCURRENT_PROGRAM_NAME for a40col PHASE_CODE for a10col STATUS_CODE for a10col COMPLETION_TEXT for a20SELECT sum.request_id,req.PARENT_REQUEST_ID,sum.user_concurrent_program_name, DECODE(sum.phase_code,'C','Completed',sum.phase_code) phase_code, DECODE(sum.status_code,'D','Cancelled' ,'E', 'Error' , 'G', 'Warning', 'H','On Hold' , 'T', 'Terminating', 'M', 'No Manager' , 'X','Terminated', 'C', 'Normal', sum.status_code) status_code, sum.actual_start_date,sum.actual_completion_date, sum.completion_text FROM apps.fnd_conc_req_summary_v sum,apps.fnd_concurrent_requests req where req.request_id=sum.request_id and req.PARENT_REQUEST_ID ='&parent_concurrent_request_id';

8. Cancelling Concurrent request :

update fnd_concurrent_requestsset status_code='D', phase_code='C'where request_id=&req_id;

9. Kill sessions program wise

select 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' immediate;' from v$session whereMODULE like '';

10 .Concurrent Request running by SID

SELECT a.request_id,d.sid as Oracle_SID,d.serial#,d.osuser,d.process,c.SPID as OS_Process_IDFROM apps.fnd_concurrent_requests a,apps.fnd_concurrent_processes b,gv$process c,gv$session dWHERE a.controlling_manager = b.concurrent_process_idAND c.pid = b.oracle_process_idAND b.session_id=d.audsidAND d.sid = &SID;

11. Find out request id from Oracle_Process Id:

select REQUEST_ID,ORACLE_PROCESS_ID,OS_PROCESS_Id from fnd_concurrent_requests whereORACLE_PROCESS_ID='&a';

12. Oracle Concurrent Request Error Script (requests which were error ed out)

SELECT a.request_id "Req Id",a.phase_code,a.status_code, actual_start_date, actual_completion_date,c.concurrent_program_name || ': ' || ctl.user_concurrent_program_name "program"FROM APPLSYS.fnd_Concurrent_requests a,APPLSYS.fnd_concurrent_processes b,applsys.fnd_concurrent_queues q,APPLSYS.fnd_concurrent_programs c,APPLSYS.fnd_concurrent_programs_tl ctlWHERE a.controlling_manager = b.concurrent_process_idAND a.concurrent_program_id = c.concurrent_program_idAND a.program_application_id = c.application_idAND a.status_code = 'E'AND a.phase_code = 'C'AND actual_start_date > sysdate - 2AND b.queue_application_id = q.application_idAND b.concurrent_queue_id = q.concurrent_queue_idAND ctl.concurrent_program_id = c.concurrent_program_idAND ctl.LANGUAGE = 'US'ORDER BY 5 DESC;

13. Request submitted by User

SELECTuser_concurrent_program_name,request_date,request_id,phase_code,status_codeFROMfnd_concurrent_requests fcr,fnd_concurrent_programs_tl fcp,fnd_responsibility_tl fr,fnd_user fuWHEREfcr.CONCURRENT_PROGRAM_ID = fcp.concurrent_program_idand fcr.responsibility_id = fr.responsibility_idand fcr.requested_by = fu.user_idand user_name = '&user'AND actual_start_date > sysdate - 1ORDER BY REQUEST_DATE Asc;

14.Concurrent Program enable with trace

col User_Program_Name for a40col Last_Updated_By for a30col DESCRIPTION for a30SELECT A.CONCURRENT_PROGRAM_NAME "Program_Name",SUBSTR(A.USER_CONCURRENT_PROGRAM_NAME,1,40) "User_Program_Name",SUBSTR(B.USER_NAME,1,15) "Last_Updated_By",SUBSTR(B.DESCRIPTION,1,25) DESCRIPTIONFROM APPS.FND_CONCURRENT_PROGRAMS_VL A, APPLSYS.FND_USER BWHERE A.ENABLE_TRACE='Y'AND A.LAST_UPDATED_BY=B.USER_ID

How to monitor RMAN Backups ?

RMAN Backups Monitoring

select count(*) from v$backup_async_io where status='IN PROGRESS';

Session information on backups

SELECT s.sid, username AS "User", program, module, action, logon_time "Logon", l.*FROM v$session s, v$enqueue_lock lWHERE l.sid = s.sid and l.type = 'CF' AND l.id1 = 0 and l.id2 = 2;

RMAN backup overall progress status

SELECT decode(context,1,'This Task:',2,'Agregate:','?') Context, sofar, totalwork, round(sofar/totalwork*100,2) "% Complete"FROM v$session_longopsWHERE opname LIKE 'RMAN%'AND opname LIKE '%aggregate%'AND totalwork != 0AND sofar totalworkUNIONSELECT decode(context,1,'This Task:',2,'Agregate:','?') Context, sofar, totalwork, round(sofar/totalwork*100,2) "% Complete"FROM v$session_longopsWHERE opname LIKE 'RMAN%'AND opname NOT LIKE '%aggregate%'AND totalwork != 0AND sofar totalwork;No comments:

The simplest query for checking whats happening in a database

When someone asks you to take a quick look into database performance and for whatever reason you cant run your usual scripts or performance tools on there, ), then what query would you run first?Yeah sometimes Ive been not allowed to run custom scripts nor even touch the keyboard due security policies in effect.Whenever youre in such situation you want to be the command both short and effective for showing the database state.The simplest query for determining database state performance wise would be this:SQL> select event, state, count(*) from v$session_wait group by event, state order by 3 desc;

EVENT STATE COUNT(*)---------------------------------------------------------------- ------------------- ----------rdbms ipc message WAITING 9SQL*Net message from client WAITING 8log file sync WAITING 6gcs remote message WAITING 2PL/SQL lock timer WAITING 2PL/SQL lock timer WAITED KNOWN TIME 2Streams AQ: qmn coordinator idle wait WAITING 1smon timer WAITING 1log file parallel write WAITING 1ges remote message WAITING 1SQL*Net message to client WAITED SHORT TIME 1DIAG idle wait WAITING 1pmon timer WAITING 1db file sequential read WAITING 1Streams AQ: waiting for messages in the queue WAITING 1rdbms ipc message WAITED KNOWN TIME 1jobq slave wait WAITING 1Streams AQ: qmn slave idle wait WAITING 1Streams AQ: waiting for time management or cleanup tasks WAITING 1

19 rows selected.

It uses the Oracle wait interface to report what all database sessions are currently doing wait/CPU usage wise. Whenever theres a systemic issue (like extremely slow log file writes) this query will give good hint towards the cause of problem. Of course just running couple of queries against wait interface doesnt give you the full picture (as these kinds of database wide healthchecks can be misleading as we should be really measuring end user response time breakdown at session level and asking questions like what throughput/response time do you normally get) but nevertheless, if you want to see an instance sessions state overview, this is the simplest query I know.Interpreting this query output should be combined with reading some OS performance tool output (like vmstat or perfmon), in order to determine whether the problem is induced by CPU overload. For example, if someone is running a parallel backup compression job on the server which is eating all CPU time, some of these waits may be just a side-effect of CPU overload).Below is a cosmetically enhanced version of this command, as one thing I decode the WAITED FOR xyz TIME wait states to WORKING and On CPU / runqueue as event name as otherwise its easy to miss by accident that some sessions are not actually waiting on previous event anymore:SQL> select 2 count(*), 3 CASE WHEN state != 'WAITING' THEN 'WORKING' 4 ELSE 'WAITING' 5 END AS state, 6 CASE WHEN state != 'WAITING' THEN 'On CPU / runqueue' 7 ELSE event 8 END AS sw_event 9 FROM 10 v$session_wait 11 GROUP BY 12 CASE WHEN state != 'WAITING' THEN 'WORKING' 13 ELSE 'WAITING' 14 END, 15 CASE WHEN state != 'WAITING' THEN 'On CPU / runqueue' 16 ELSE event 17 END 18 ORDER BY 19 1 DESC, 2 DESC 20 /

COUNT(*) STATE EVENT---------- ------- ---------------------------------------- 11 WAITING log file sync 9 WAITING rdbms ipc message 4 WAITING SQL*Net message from client 3 WAITING PL/SQL lock timer 2 WORKING On CPU / runqueue 2 WAITING gcs remote message 1 WAITING ges remote message 1 WAITING pmon timer 1 WAITING smon timer 1 WAITING jobq slave wait 1 WAITING Streams AQ: waiting for messages in the 1 WAITING DIAG idle wait 1 WAITING Streams AQ: qmn slave idle wait 1 WAITING Streams AQ: waiting for time management 1 WAITING db file sequential read 1 WAITING log file parallel write 1 WAITING Streams AQ: qmn coordinator idle wait

17 rows selected.

SQL>

Also, sometimes you might want to exclude the background processes and idle sessions from the picture:SQL> select 2 count(*), 3 CASE WHEN state != 'WAITING' THEN 'WORKING' 4 ELSE 'WAITING' 5 END AS state, 6 CASE WHEN state != 'WAITING' THEN 'On CPU / runqueue' 7 ELSE event 8 END AS sw_event 9 FROM 10 v$session 11 WHERE 12 type = 'USER' 13 AND status = 'ACTIVE' 14 GROUP BY 15 CASE WHEN state != 'WAITING' THEN 'WORKING' 16 ELSE 'WAITING' 17 END, 18 CASE WHEN state != 'WAITING' THEN 'On CPU / runqueue' 19 ELSE event 20 END 21 ORDER BY 22 1 DESC, 2 DESC 23 /

COUNT(*) STATE EVENT---------- ------- ---------------------------------------- 6 WAITING PL/SQL lock timer 4 WORKING On CPU / runqueue 3 WAITING db file sequential read 1 WAITING read by other session 1 WAITING Streams AQ: waiting for messages in the 1 WAITING jobq slave wait

6 rows selected.

By the way, the above scripts report quite similar data what ASH is actually using (especially the instance performance graph which shows you the instance wait summary). ASH nicely puts the CPU count of server into the graph as well (that you would be able to put the number of On CPU sessions into perspective), so another useful command to run after this script is show parameter cpu_count or better yet, check at OS level to be sure :)Note that you can use similar technique for easily viewing the instance activity from other perspectives/dimensions, like which SQL is being executed:SQL> select sql_hash_value, count(*) from v$session 2 where status = 'ACTIVE' group by sql_hash_value order by 2 desc;

SQL_HASH_VALUE COUNT(*)-------------- ---------- 0 20 966758382 8 2346103937 2 3393152264 1 3349907142 1 2863564559 1 4030344732 1 1631089791 1

8 rows selected.

SQL> select sql_text,users_executing from v$sql where hash_value = 966758382;

SQL_TEXT USERS_EXECUTING------------------------------------------------------------ ---------------BEGIN :1 := orderentry.neworder(:2,:3,:4); END; 10

No comments:

How to recover Applications context file if it is corrupted or deleted accidentally?

The Applications context file can be retrieved by running the adclonectx.pl script.To retrieve the Applications tier context file, perl /clone/bin/adclonectx.pl retrieve On being prompted for the context file to be retrieved, select the option of retrieving the Applications tier context file that has been lost and retrieve it to the default location specified by the script.The above command can be used only when INST_TOP the is still intact. In case that has also been lostaccidentally, the Applications tier context file may be retrieved as follows: Execute the following command on the Database tier:perl /appsutil/clone/bin/adclonectx.pl retrieve On being prompted for the context file to be retrieved, select the option of retrieving the Applications tier context file that has been lost. While confirming the location for the context file, set it to any existing directory with write permission. Once the context file has been generated in the specified location, move it to the location specified for the context file in the context variable 's_contextfile'.To retrieve the Database tier context file, Execute the following command on the Database tier:perl /appsutil/clone/bin/adclonectx.pl retrieve On being prompted for the context file to be retrieved, select the Database tier context file and retrieve it to the default location specified by the script.No comments:

How to compile invalid objects in an APPS Environment

Applying Patches can create invalid objects. To get a quick count of the number of existing invalids (if any), use the following select statement :

SELECT COUNT(*)FROM DBA_OBJECTSWHERE STATUS = 'INVALID';

For a more detailed query, use the following script :

SELECT OWNER, OBJECT_TYPE, COUNT(*)FROM DBA_OBJECTSWHERE STATUS = 'INVALID'GROUP BY OWNER, OBJECT_TYPE;

To recompile an individual object, connect to SQL*PLUS as the owner of the object (generally apps) and use one of the following depending on the object type :

alter package compile; (package specification)alter package compile body; (package body)alter view compile; (view)

If the object compiles with warnings, use either of the following to see the errors that caused the warnings :

show errorsORselect * from user_errors where name = '';

Another way to correct invalid objects is to run the adadmin utility as follows:

UNIX OPERATING PLATFORM

1. Log in as APPS User : /

2. Start the adadmin-Utility from the Unix prompt with this command :

adadmin

The utility will then ask you a series of questions.

3. Under the Maintain Applications Database Objects Menu, select Compile APPS schema(s)

This task spawns parallel workers to compile invalid database objects in your APPS schema(s). It uses the same parallel phases as AutoInstall.

Also try running $ORACLE_HOME/rdbms/admin/utlrp.sql ( as sysdba )

Within Applications, there is a script to compile INVALID objects - called ADCOMPSC.pls

Arguments for ADCOMPSC.pls :

1 - Schema to run in2 - Password for schema3 - Check errors for objects starting with #3

NOTE: The order in which to compile Invalid Objects in schemas is SYS, SYSTEM, APPS and then all others. APPS_DDL and APPS_ARRAY_DDL should exist in all schema's. In case of an ORA-1555 error while running adcompsc.pls, restart the script.

The script can be run as followed :

cd $AD_TOP/sqlsqlplus @adcompsc.pls SCHEMA_NAME SCHEMA_PASSWORD %

Example : SQL> @adcompsc.pls apps apps %

After the script completes, check for invalid objects again. If the number has decreased, but invalid objects still exist, run adcompsc.pls again. Keep running adcompsc.pls until number of invalid objects stops decreasing.

If there are any objects still left INVALID, verify them by using the script 'aderrchk.sql' to record the remaining INVALID objects. 'Aderrchk.sql' uses the same syntax as 'adcompsc.pls'. This script is also supplied with the Applications. Send the aderrchk.sql to a file using the spool command in sqlplus.

e.g. sqlplus x/y @aderrchk.sql SCHEMA_NAME SCHEMA_PASSWORD %

For objects which will not compile, try the following :

select textfrom user_sourcewhere name = 'OBJECTNAME'and text like '%Header%';

This script will provide the script that creates the packages/recreates the packages.SQL>@packageheaderSQL>@packagebodyIf recreating the package does not make the package valid, analyze the user_errors table to determine the cause of the invalid package :

select textfrom user_errorswhere name = '';No comments:

Undo Related Queries

To check retention guarantee for undo tablespace

select tablespace_name,status,contents,logging,retention from dba_tablespaces where tablespace_name like '%UNDO%';

To show ACTIVE/EXPIRED/UNEXPIRED Extents of Undo Tablespace

selecttablespace_name,status,count(extent_id) "Extent Count",sum(blocks) "Total Blocks",sum(blocks)*8/(1024*1024) total_spacefromdba_undo_extentsgroup bytablespace_name, status;

Extent Count and Total Blocks

set linesize 152col tablespace_name for a20col status for a10

select tablespace_name,status,count(extent_id) "Extent Count",sum(blocks) "Total Blocks",sum(bytes)/(1024*1024*1024) spaceInGBfromdba_undo_extentswheretablespace_name in ('&undotbsp')group bytablespace_name,status;

To show UndoRetention Value

Show parameter undo_retention;

Undo retention in hours

col "Retention" for a30col name for a30col value for a50select name "Retention",value/60/60 "Hours" from v$parameter where name like '%undo_retention%';

To check space related statistics ofUndoTablespace from stats$undostat of 90 days

select UNDOBLKS,BEGIN_TIME,MAXQUERYLEN,UNXPSTEALCNT,EXPSTEALCNT,NOSPACEERRCNT from stats$undostat where BEGIN_TIME between sysdate-90 and sysdate and UNXPSTEALCNT > 0;

To check space related statistics ofUndoTablespace from v$undostat

selectsum(ssolderrcnt) "Total ORA-1555s",round(max(maxquerylen)/60/60) "Max Query HRS",sum(unxpstealcnt) "UNExpired STEALS",sum(expstealcnt) "Expired STEALS"from v$undostatorder by begin_time;Date wise occurrence of ORA-1555

select to_char(begin_time, 'mm/dd/yyyy hh24:mi') "Int. Start",ssolderrcnt "ORA-1555s", maxquerylen "Max Query",unxpstealcnt "UNExp SCnt",UNXPBLKRELCNT "UnEXPblks", expstealcnt "Exp SCnt",EXPBLKRELCNT "ExpBlks",NOSPACEERRCNT nospacefrom v$undostat where ssolderrcnt>0order by begin_time;

Total number of ORA-1555s since instance startup

select 'TOTAL # OF ORA-01555 SINCE INSTANCE STARTUP : '|| to_char(startup_time,'DD-MON-YY HH24:MI:SS')from v$instance;

To check for Active Transactions

set head onselect usn,extents,round(rssize/1048576)rssize,hwmsize,xacts,waits,optsize/1048576 optsize,shrinks,wrapsfrom v$rollstat where xacts>0order by rssize;

Undo Space Utilization by each Sessions

set lines 200col sid for 99999col username for a10col name for a15selects.sid,s.serial#,username,s.machine,t.used_ublk ,t.used_urec,rn.name,(t.used_ublk *8)/1024/1024 SizeGBfromv$transaction t,v$session s,v$rollstat rs, v$rollname rnwheret.addr=s.taddr and rs.usn=rn.usn and rs.usn=t.xidusn and rs.xacts>0;

List of long running queries since instance startup

set head offselect 'LIST OF LONG RUNNING - QUERY SINCE INSTANCE STARTUP' from dual;set head onselect*from(select to_char(begin_time, 'DD-MON-YY hh24:mi:ss') BEGIN_TIME ,round((maxquerylen/3600),1) Hoursfrom v$undostatorder by maxquerylen desc)whererownum < 11;

Undo Space used by all transactions

set lines 200col sid for 99999col username for a10col name for a15selects.sid,s.serial#,username,s.machine,t.used_ublk ,t.used_urec,rn.name,(t.used_ublk *8)/1024/1024 SizeGBfromv$transaction t,v$session s,v$rollstat rs, v$rollname rnwheret.addr=s.taddr and rs.usn=rn.usn and rs.usn=t.xidusn and rs.xacts>0;

List of All active Transactions

selectsid,username,t.used_ublk ,t.used_urecfromv$transaction t,v$session swheret.addr=s.taddr;

To list all Datafile of UndoTablespace

select tablespace_name,file_name,file_id,autoextensible,bytes/1048576Mbytes, maxbytes/1048576 maxMbytesfrom dba_data_fileswhere tablespace_name like '%UNDO%'or tablespace_name like '%RBS%'order by tablespace_name,file_name;

select tablespace_name,file_name,file_id,autoextensible,bytes/1048576Mbytes, maxbytes/1048576 maxMbytesfrom dba_data_fileswhere tablespace_name like '%UNDOTBS2%'order by tablespace_name,file_name;

col file_name for a40set pagesize 100select tablespace_name,file_name,file_id,autoextensible,bytes/1048576Mbytes, maxbytes/1048576 maxMbytesfrom dba_data_fileswhere tablespace_name like '%APPS_UNDOTS1%'order by tablespace_name,file_name;

select file_name,tablespace_name,bytes/1024/1024,maxbytes/1024/1024,autoextensiblefrom dba_data_files where file_name like '%undo%' order by file_name;

To check when a table is last analysed

select OWNER,TABLE_NAME,TABLESPACE_NAME,STATUS,LAST_ANALYZED,PARTITIONED,DEPENDENCIES,DROPPED from dba_tables where TABLE_NAME like 'MLC_PICK_LOCKS_DETAIL';

select OWNER,TABLE_NAME,TABLESPACE_NAME,LAST_ANALYZED,PARTITIONED,DEPENDENCIES,DROPPED from dba_tables where TABLE_NAME like 'APPS.XLA_AEL_GL_V';

To list all Undo datafiles with status and size

show parameter undoshow parameter db_block_sizecol tablespace_name form a20col file_name form a60set lines 120select tablespace_name, file_name, status, bytes/1024/1024 from dba_data_fileswhere tablespace_name=(select tablespace_name from dba_tablespaces where contents='UNDO');

Total undo space

selectsum(bytes)/1024/1024/1024 GB from dba_data_fileswhere tablespace_name='&Undo_TB_Name';

Undo Tablespace

select tablespace_name from dba_tablespaces where tablespace_name like '%UNDO%';

To find MaxQueryLength from stats$undostat

Select Max(MAXQUERYLEN) from stats$undostat;

*select max(maxquerylen) from v$undostat;

*select begin_date,u.maxquerylen from(select to_char(begin_time,'DD-MON-YYYY:HH24-MI-SS') begin_date,maxquerylenfrom v$undostat order by maxquerylen desc) uwhere rownum0;

* select name,extents,rssize/1048576 rssizeMB ,xacts,writes/1024/1024,optsize/1048576 optsize,shrinks,wraps,extends,aveshrink/1048576,waits,rs.status,rs.curextfrom v$rollstat rs, v$rollname rnwherern.usn=rs.usnorder by wraps;

* select name,extents,optsize/1048576 optsize,shrinks,wraps,aveshrink/1048576,aveactive,rs.status,rs.curextfrom v$rollstat rs, v$rollname rnwherern.usn=rs.usn;

* selectsum(rssize)/1024/1024/1024 sizeGB from v$rollstat;

* select sum(xacts) from v$rollstat;selectsum(rssize)/1024/1024/1024 sizeGB from v$rollstat where xacts=0;selectsum(rssize)/1024/1024/1024 sizeGB from v$rollstat where xacts>0;select sum(xacts) from v$rollstat;

* select tablespace_name,segment_name,initial_extent,next_extent,min_extents,max_extents,statusfrom dba_rollback_segswhere status='ONLINE';

* select tablespace_name,file_name,bytes/1024/1024,maxbytes/1024/1024,autoextensiblefrom dba_data_files where file_name like '%&filename%';

* select sum(bytes)/1024/1024 from dba_free_space where tablespace_name='&tbs';

Optimize Oracle UNDO Parameters

Actual Undo SizeSELECT SUM(a.bytes/1024/1024/1024) "UNDO_SIZE"FROM v$datafile a,v$tablespace b,dba_tablespaces cWHERE c.contents = 'UNDO'AND c.status = 'ONLINE'AND b.name = c.tablespace_nameAND a.ts# = b.ts#;

UNDO_SIZE----------209715200

Undo Blocks per Second

SELECT MAX(undoblks/((end_time-begin_time)*3600*24))"UNDO_BLOCK_PER_SEC"FROM v$undostat;

UNDO_BLOCK_PER_SEC------------------3.12166667

Undo Segment Summary for DB

Undo Segment Summary for DB: S901Instance: S901Snaps: 2 -3-> Undo segment block stats:-> uS - unexpired Stolen,uR - unexpired Released,uU - unexpired reUsed-> eS - expiredStolen,eR - expiredReleased,eU - expiredreUsed

UndoUndoNumMax QryMax Tx Snapshot Out of uS/uR/uU/TS#BlocksTransLen (s)ConcurcyToo OldSpace eS/eR/eU---- -------------- ---------- -------- ---------- -------- ------ -------------120,2841,96481200 0/0/0/0/0/0

Undo Segment Stats for DB

Undo Segment Stats for DB: S901Instance: S901Snaps: 2 -3-> ordered by Time desc

UndoNum Max QryMax TxSnapOut of uS/uR/uU/End TimeBlocksTrans Len (s)Concy Too OldSpace eS/eR/eU------------ ------------ -------- ------- -------- ------- ------ -------------12-Mar 16:1118,7231,75681200 0/0/0/0/0/012-Mar 16:011,56120831200 0/0/0/0/0/0

Undo Segment Space Required = (undo_retention_time * undo_blocks_per_seconds)

As an example, an UNDO_RETENTION of 5 minutes (default) with 50 undo blocks/second (8k blocksize)will generate:Undo Segment Space Required = (300 seconds * 50 blocks/ seconds * 8K/block) = 120 M

select tablespace_name,file_name,file_id,autoextensible,bytes/1048576Mbytes, maxbytes/1048576 maxMbytesfrom dba_data_fileswhere tablespace_name like '%UNDO%'or tablespace_name like '%RBS%'or tablespace_name like '%ROLLBACK%'order by tablespace_name,file_name;

select a.owner,a.tablespace_name,b.status, a.extents,a.next_extent/1024 next_extnentKB,a.max_extents,a.pct_increase from dba_segments a,dba_tablespaces bwhere segment_type='ROLLBACK' and a.tablespace_name=b.tablespace_name;

select tablespace_name,status from dba_tablespaces where tablespace_name='ROLLBACK';

Actual Undo Size

SELECT SUM(a.bytes/1024/1024) "UNDO_SIZE"FROM v$datafile a,v$tablespace b,dba_tablespaces cWHERE c.contents = 'UNDO'AND c.status = 'ONLINE'AND b.name = c.tablespace_nameAND a.ts# = b.ts#;

UNDO_SIZE----------209715200

Undo Blocks per Second

SELECT MAX(undoblks/((end_time-begin_time)*3600*24))"UNDO_BLOCK_PER_SEC"FROM v$undostat;

UNDO_BLOCK_PER_SEC------------------3.12166667

DB Block Size

SELECT TO_NUMBER(value) "DB_BLOCK_SIZE [KByte]"FROM v$parameterWHERE name = 'db_block_size';

DB_BLOCK_SIZE [Byte]--------------------4096

Optimal Undo Retention

209'715'200 / (3.12166667 * 4'096) = 16'401 [Sec]

Using Inline Views, you can do all in one query!

SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",SUBSTR(e.value,1,25) "UNDO RETENTION [Sec]",ROUND((d.undo_size / (to_number(f.value) *g.undo_block_per_sec))) "OPTIMAL UNDO RETENTION [Sec]"FROM (SELECT SUM(a.bytes) undo_sizeFROM v$datafile a,v$tablespace b,dba_tablespaces cWHERE c.contents = 'UNDO'AND c.status = 'ONLINE'AND b.name = c.tablespace_nameAND a.ts# = b.ts#) d,v$parameter e,v$parameter f,(SELECT MAX(undoblks/((end_time-begin_time)*3600*24))undo_block_per_secFROM v$undostat) gWHERE e.name = 'undo_retention'AND f.name = 'db_block_size'/

ACTUAL UNDO SIZE [MByte]------------------------200

UNDO RETENTION [Sec]--------------------10800

OPTIMAL UNDO RETENTION [Sec]----------------------------16401

Calculate Needed UNDO Size for given Database Activity

If you are not limited by disk space, then it would be better to choose the UNDO_RETENTION time that is best for you (for FLASHBACK, etc.). Allocate the appropriate size to the UNDO tablespace according to the database activity:

Again, all in one query:

SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",SUBSTR(e.value,1,25) "UNDO RETENTION [Sec]",(TO_NUMBER(e.value) * TO_NUMBER(f.value) *g.undo_block_per_sec) / (1024*1024)"NEEDED UNDO SIZE [MByte]"FROM (SELECT SUM(a.bytes) undo_sizeFROM v$datafile a,v$tablespace b,dba_tablespaces cWHERE c.contents = 'UNDO'AND c.status = 'ONLINE'AND b.name = c.tablespace_nameAND a.ts# = b.ts#) d,v$parameter e,v$parameter f,(SELECT MAX(undoblks/((end_time-begin_time)*3600*24))undo_block_per_secFROM v$undostat) gWHERE e.name = 'undo_retention'AND f.name = 'db_block_size'/

ACTUAL UNDO SIZE [MByte]------------------------200UNDO RETENTION [Sec]--------------------10800NEEDED UNDO SIZE [MByte]------------------------131.695313

Checking when tables are last analyzedselectOWNER,TABLE_NAME,TABLESPACE_NAME,STATUS,LAST_ANALYZED,PARTITIONED,DEPENDENCIES,DROPPED fromdba_tables where TABLE_NAME like 'MLC_END_USER_REGISTRATION';

DECLAREv_table_space_nameVARCHAR2(30);v_table_space_size_in_MBNUMBER(9);v_auto_extendBOOLEAN;v_undo_retentionNUMBER(9);v_retention_guaranteeBOOLEAN;v_undo_info_returnBOOLEAN;BEGINv_undo_info_return := dbms_undo_adv.undo_info(v_table_space_name, v_table_space_size_in_MB, v_auto_extend, v_undo_retention, v_retention_guarantee);dbms_output.put_line(UNDO Tablespace Name: || v_table_space_name);dbms_output.put_line(UNDO Tablespace size (MB) : || TO_CHAR(v_table_space_size_in_MB));dbms_output.put_line(If UNDO tablespace is auto extensible above size indicates max possible size of the undo tablespace);dbms_output.put_line(UNDO tablespace auto extensiable is : || CASE WHEN v_auto_extend THENON ELSE OFF END);dbms_output.put_line(Undo Retention (Sec): || v_undo_retention);dbms_output.put_line(Retention : ||CASE WHEN v_retention_guarantee THEN Guaranteed ELSE NOT Guaranteed END);END;

undo_autotune

This function is used to find auto tuning of undo retention is ENABLED or NOT.

Set serverout ondeclarev_autotune_return Boolean := null;v_autotune_enabled boolean := null;beginv_autotune_return:= dbms_undo_adv.undo_autotune(v_autotune_enabled);dbms_output.put_line(CASE WHEN v_autotune_return THEN 'Information is available :' ELSE 'Information is NOT available :' END||CASE WHEN v_autotune_enabled THEN 'Auto tuning of undo retention is ENABLED' ELSE 'Auto tuning of undo retention is NOT enabled' END);end;/

select dbms_undo_adv.longest_query from dual

select dbms_undo_adv.required_retention from dual

select dbms_undo_adv.best_possible_retention from dual

selectdbms_undo_adv.required_undo_size(1800) from dual

DECLAREv_undo_health_return number;v_retention number;v_utbsize number;v_problem VARCHAR2(1024);v_recommendation VARCHAR2(1024);v_rationale VARCHAR2(1024);BEGINv_undo_health_return :=dbms_undo_adv.undo_health(problem => v_problem,recommendation => v_recommendation,rationale => v_rationale,retention => v_retention,utbsize => v_utbsize);dbms_output.put_line(Problem : ||v_problem);dbms_output.put_line(Recommendation= : ||v_recommendation);dbms_output.put_line(Rationale : ||v_retention);dbms_output.put_line(Retention : ||v_retention);dbms_output.put_line(UNDO tablespace size : ||v_utbsize);END;

undo_advisor

It uses oracles advisor framework to find out problem and provide recommendations.

DECLAREv_undo_advisor_return VARCHAR2(100);BEGINv_undo_advisor_return := dbms_undo_adv.undo_advisor(instance => 1);dbms_output.put_line(v_undo_advisor_return);END;