June 22, 2014

Tablespace Utilization Script for Tablespace Space Used % more than 80 %

Oracle Tablespace Utilization Script (including AUTOEXTEND) for generating report of more than 80 % used tablespaces (IN GB)

1. Check the database details.
2. Check the tablespace Utilization.
3. Check the details of the datafiles for a particular TableSpace which needs attention.
4. Resize or Add the datafiles as per the standards of the existing datafiles on the database.

1. Check the database details.
$ sqlplus "/as sysdba"

set pages 9999 lines 300
col OPEN_MODE for a10
col HOST_NAME for a30
select name DB_NAME,HOST_NAME,DATABASE_ROLE from v$database,v$instance;

2. Check the tablespace Utilization.
Tablespace Utilization Script including AUTOEXTEND (IN GB)
----------------------------------------------------------
$ sqlplus "/as sysdba"

set pages 50000 lines 32767
col tablespace_name format a30
col TABLESPACE_NAME heading "Tablespace|Name"
col Allocated_size heading "Allocated|Size(GB)" form 99999999.99
col Current_size heading "Current|Size(GB)" form 99999999.99
col Used_size heading "Used|Size(GB)" form 99999999.99
col Available_size heading "Available|Size(GB)" form 99999999.99
col Pct_used heading "%Used (vs)|(Allocated)" form 99999999.99

select a.tablespace_name
        ,a.alloc_size/1024/1024/1024 Allocated_size
        ,a.cur_size/1024/1024/1024 Current_Size
        ,(u.used+a.file_count*65536)/1024/1024/1024 Used_size
        ,(a.alloc_size-(u.used+a.file_count*65536))/1024/1024/1024 Available_size
        ,((u.used+a.file_count*65536)*100)/a.alloc_size Pct_used
from     dba_tablespaces t
        ,(select t1.tablespace_name
        ,nvl(sum(s.bytes),0) used
        from  dba_segments s
        ,dba_tablespaces t1
         where t1.tablespace_name=s.tablespace_name(+)
         group by t1.tablespace_name) u
        ,(select d.tablespace_name
        ,sum(greatest(d.bytes,nvl(d.maxbytes,0))) alloc_size
        ,sum(d.bytes) cur_size
        ,count(*) file_count
        from dba_data_files d
        group by d.tablespace_name) a
where t.tablespace_name=u.tablespace_name
and ((u.used+a.file_count*65536)*100)/a.alloc_size>80
and t.tablespace_name=a.tablespace_name
order by t.tablespace_name
/

3. Check the details of the datafiles for a particular TableSpace which needs attention.
Datafiles of a particular TableSpace:
------------------------------------
set pages 50000 lines 32767
col tablespace_name for a30
col CREATION_TIME for a15
col file_name for a70
select dd.tablespace_name TABLESPACE_NAME,dd.file_name,dd.bytes/1024/1024 Size_MB,dd.autoextensible,dd.maxbytes/1024/1024 MAXSIZE_MB,df.CREATION_TIME
from dba_data_files dd, v$datafile df where df.name=dd.file_name and tablespace_name='&TABLESPACENAME' order by 1,2,6;

Note:- If required, can get the DDL of a tablespace as below.

TABLESPACE DDL
--------------
set pagesize 0
SET LONG 9999999
select dbms_metadata.get_ddl('TABLESPACE','&TABLESPACE_NAME') FROM DUAL;

How to generate Multiple AWR reports

Multiple AWR report generation script

The following script can be used for AWR reports generation, for specific intervals between the required Snapshots generated.


The below script (awr_report_generate.sh) is to generate AWR reports for the specific intervals between the required Snapshots generated.
Let say, there is a requirement to generate awr reports for every 2 hours of previous day from 00:00 hrs to current date 00:00 hrs ie., 24 hrs.

Reuirements:-
===========

First we need to get the Begin Snap ID and End Snap ID, in order to generate multiple awr reports using the below script.

$ sqlplus "/as sysdba"
SQL> @?/rdbms/admin/awrrpt.sql       (For RAC, SQL> @?/rdbms/admin/awrrpti.sql)
.
.
.

Specify the Report Type
~~~~~~~~~~~~~~~~~~~~~~~
Enter 'html' for an HTML report, or 'text' for plain text
Defaults to 'html'
Enter value for report_type:                    ---------------> press 'Enter' Key

Specify the number of days of snapshots to choose from
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter value for num_days:

Listing the last n days of Completed Snapshots  ---------------> here 'n' represents the number of days we have entered for generating awr reports.

NOTE:-
====
Here, for the required period, make a note of the required Begin Snap ID and End Snap ID.


Create a script awr_report_generate.sh:-
======================================
SQL> exit

$ vi awr_report_generate.sh

#!/usr/bin/sh
echo "Enter the value for Begin Snapshot Id :"
read beginid
echo "Enter the value for End Snapshot Id:"
read endid
echo "Enter the value for interval between Snapshot Id's. To generate reports between consecutive Snapshop Id's, Enter '1'. Else, enter desired value:"
read snapint
echo "Enter the value for report type: html/text"
read repfmt
echo "Enter the path for unix directory to generate the reports. Press 'Enter' to generate the reports in current working directory:"
read repdir
if [ "$repdir" = "" ]
then
repdir=$PWD
fi

while [ $beginid -lt $endid ]
do
tempid=`echo $beginid + $snapint |bc`
sqlplus -s '/as sysdba'<<EOF
set verify off
set feedback off
set pages 0
set serveroutput on
clear break compute;
repfooter off;
ttitle off;
btitle off;

set heading on;
set timing off veri off space 1 flush on pause off termout on numwidth 10;
set echo off feedback off pagesize 0 linesize 1500 newpage 1 recsep off;
set trimspool on trimout on define "&" concat "." serveroutput on;
set underline on;
col endid new_value endid;
col repname new_value repname;
col dbid new_value dbid;
col inst_num new_value inst_num;

define beginid=$beginid;
define tempid=$tempid;

variable repname varchar2(60);
variable dbid varchar2(10);
variable inst_num varchar2(2);

select dbid dbid from v\$database;
select instance_number inst_num from v\$instance ;
select '$repdir/AWR_'||(select instance_name inst_name from v\$instance)||'_'||(select to_char(END_INTERVAL_TIME,'DDMONYY_HH24MI')from dba_hist_snapshot where snap_id='$beginid' and instance_number=(select instance_number from v\$instance))||'_'||(select to_char(END_INTERVAL_TIME,'DDMONYY_HH24MI')from dba_hist_snapshot where snap_id='$tempid' and instance_number=(select instance_number from v\$instance))||'.$repfmt' repname from dual;
spool &repname
select output from table(dbms_workload_repository.awr_report_$repfmt(&dbid,&inst_num,&&beginid,&&tempid,0));
spool off
exit
EOF
beginid=`echo $beginid + $snapint |bc`
done


-- Press esc
:wq

$ ls -lrt awr_report_generate.sh

Run the script:-
==============

$ sh awr_report_generate.sh


$ ls -lrt





How to check AWR interval and retention Settings

AWR interval and retention Settings

The following query can be used to check the current settings for the AWR interval and AWR retention.
The query returns the current AWR interval values in minutes.

set pages 50000 lines 32767
col snap_interval format a20
col retention format a20
col topnsql format a20
select extract( day from snap_interval) *24*60+
       extract( hour from snap_interval) *60+
       extract( minute from snap_interval ) "Snapshot Interval",
       extract( day from retention) *24*60+
       extract( hour from retention) *60+
       extract( minute from retention ) "Retention Interval"
from dba_hist_wr_control;


Snapshot Interval Retention Interval
----------------- ------------------

Database health checks in Oracle

Performing Database health checks, when there is an issue reported by Application users.

1. Check the Database details
2. Monitor the consumption of resources
3. Check the Alert Log
4. Check Listener log
5. Check Filesystem space Usage
6. Generate AWR Report
7. Generate ADDM Report
8. Finding Locks,Blocker Session and Waiting sessions in a oracle database
9. Check for alerts in OEM

1. Check the Database details :-
=============================
set pages 9999 lines 300
col OPEN_MODE for a10
col HOST_NAME for a30
select name DB_NAME,HOST_NAME,DATABASE_ROLE,OPEN_MODE,version DB_VERSION,LOGINS,to_char(STARTUP_TIME,'DD-MON-YYYY HH24:MI:SS') "DB UP TIME" from v$database,gv$instance;

For RAC:
-------
set pages 9999 lines 300
col OPEN_MODE for a10
col HOST_NAME for a30
select INST_ID,INSTANCE_NAME, name DB_NAME,HOST_NAME,DATABASE_ROLE,OPEN_MODE,version DB_VERSION,LOGINS,to_char(STARTUP_TIME,'DD-MON-YYYY HH24:MI:SS') "DB UP TIME" from v$database,gv$instance;


2. Monitor the consumption of resources :-
=======================================
select * from v$resource_limit where resource_name in ('processes','sessions');

The v$session views shows current sessions (which change rapidly),
while the v$resource_limit shows the current and maximum global resource utilization for some system resources.


3. Check the Alert Log :-
======================
$locate alert_<ORACLE_SID>

--- OR ---

UNIX/Linux command to locate the alert log file
-----------------------------------------------

$ find / -name 'alert_*.log' 2> /dev/null

vi <alert_log_location_of_the_above_output>
shift+g
?ORA-   ---> press enter key
press 'n' to check backwards/up side and 'N' for forward/down side search.

:q! --and press enter, for exiting vi editor


--- OR ---

11G
===
$ sqlplus "/as sysdba"
set pages 9999 lines 300
col NAME for a15
col VALUE for a60
select name, value from v$diag_info where name = 'Diag Trace';

On a server with multiple instances, each instance will have it's own background_dump_dest in $ORACLE_HOME/diag/$ORACLE_SID/trace directory

Before 11G
==========
$ sqlplus "/as sysdba"
set pages 9999 lines 300
show parameter BACKGROUND_DUMP_DEST;

On a server with multiple instances, each instance will have it's own background_dump_dest in $ORACLE_HOME/admin/$ORACLE_SID/bdump directory


4. Check Listener log :-
=====================
$locate listener.log

--- OR ---

UNIX/Linux command to locate the listener log file
--------------------------------------------------
$ find / -name 'listener.log' 2> /dev/null
vi <listener.log>
shift+g
?TNS-    ---> press enter key
press 'n' to check backwords and 'N' for forword search.

AND

shift+g
?error   ---> press enter key
press 'n' to check backwords and 'N' for forword search.

:q! --and press enter, for exiting vi editor

--- OR ---

$lsnrctl status

from the output you can get the listener log location (see the value for "Listener Log File" in the output).


5. Check Filesystem space Usage :-
===============================
df -h (Linux / UNIX)

df -g (AIX)

6. Generate AWR Report :-
======================
Generate AWR report for current and before to compare

SQL> @?/rdbms/admin/awrrpt.sql        (For RAC,  @?/rdbms/admin/awrrpti.sql - for each instance)

If Required,
SQL> @?/rdbms/admin/awrddrpt.sql ---->   Produces Workload Repository Compare Periods Report


7. Generate ADDM Report :-
=======================
Generate ADDM report for current and before to compare.

ADDM report provides Findings and Recommendations to fix the issue.

SQL> @?/rdbms/admin/addmrpt.sql     (For RAC,  @?/rdbms/admin/addmrpti.sql - for each instance)


8. Finding Locks,Blocker Session and Waiting sessions in a oracle database :-
========================================================================
Select * from v$lock;

Select * from gv_$lock;  (For RAC)

A fast way to check blocking/waiting situations
-----------------------------------------------
SELECT * FROM v$lock WHERE block > 0 OR request > 0;

set pages 50000 lines 32767
select object_name,s.inst_id,s.sid,s.serial#,p.spid,s.osuser,s.program,s.server,s.machine,s.status from gv$locked_object l,gv$session s,gv$process p,dba_objects o where l.object_id=o.object_id and l.session_id=s.sid and s.paddr=p.addr;

set pages 50000 lines 32767
col OBJECT_NAME for a40
col USERNAME for a10
col LOCKED_MODE for a15
col OBJECT_OWNER for a15
col OS_USER_NAME for a12
SELECT b.inst_id,b.session_id AS sid,NVL(b.oracle_username, '(oracle)') AS username,a.owner AS object_owner,a.object_name,
Decode(b.locked_mode, 0, 'None',1, 'Null (NULL)',2, 'Row-S (SS)',3, 'Row-X (SX)',4, 'Share (S)',5, 'S/Row-X (SSX)',6, 'Exclusive (X)',
b.locked_mode) locked_mode,b.os_user_name FROM dba_objects a, gv$locked_object b WHERE a.object_id = b.object_id ORDER BY 1, 2, 3, 4;

Blocker Session and Waiting sessions
====================================
column Username format A15 column Sid format 9990 heading SID
column Type format A4 column Lmode format 990 heading 'HELD'
column Request format 990 heading 'REQ' column Id1 format 9999990
column Id2 format 9999990 break on Id1 skip 1 dup
SELECT SN.Username, M.Sid, M.Type,
DECODE(M.Lmode, 0, 'None', 1, 'Null', 2, 'Row Share', 3, 'Row
Excl.', 4, 'Share', 5, 'S/Row Excl.', 6, 'Exclusive',
LTRIM(TO_CHAR(Lmode,'990'))) Lmode,
DECODE(M.Request, 0, 'None', 1, 'Null', 2, 'Row Share', 3, 'Row
Excl.', 4, 'Share', 5, 'S/Row Excl.', 6, 'Exclusive',
LTRIM(TO_CHAR(M.Request, '990'))) Request,
M.Id1, M.Id2
FROM V$SESSION SN, V$LOCK M
WHERE (SN.Sid = M.Sid and M.Request ! = 0)
or (SN.Sid = M.Sid and M.Request = 0 and Lmode != 4 and (id1, id2)
in (select S.Id1, S.Id2 from V$LOCK S where Request != 0 and S.Id1
= M.Id1 and S.Id2 = M.Id2) ) order by Id1, Id2, M.Request;

USERNAME SID TY LMODE REQUEST ID1 ID2
---------------- ------- -- ------------- ------------- ---------- --------
ORAPLAYERS 10 TX Exclusive None 123456 200
ORAPLAYERS 100 TX None Exclusive 123456 200

Session 10 is blocking(LMODE=Exclusive)

Session 100 is waiting(REQUEST=Exclusive)

The meaning of ID1 and ID2 depends on the lock TYPE.

• We can see situations where a session is both a Blocker and a Waiter.

• If there are only two sessions and both are Blockers and Waiters then we got a deadlock situation (which Oracle will solve automatically).


To find waiters:
---------------
set pages 50000 lines 32767
col LOCK_TYPE for a10
col MODE_HELD for a10
col MODE_REQUESTED for a10

select * from dba_waiters;

WAITING_SESSION HOLDING_SESSION LOCK_TYPE MODE_HELD MODE_REQUESTED LOCK_ID1 LOCK_ID2
--------------- --------------- --------- --------- -------------- -------- --------
                           
Blocking details:
----------------
set pages 50000 lines 32767
select distinct s1.username || '@' || s1.machine || ' ( INST=' || s1.inst_id || ' SID=' || s1.sid || ' ) is blocking ' || s2.username || '@' || s2.machine || ' ( INST=' || s1.inst_id || ' SID=' || s2.sid || ' ) ' as blocking_status from gv$lock l1, gv$session s1, gv$lock l2, gv$session s2 where s1.sid=l1.sid and s2.sid=l2.sid and l1.BLOCK=1 and l2.request > 0 and l1.id1 = l2.id1 and l2.id2 = l2.id2 and l1.inst_id = s1.inst_id;

set pages 50000 lines 32767
col BLOCKER for a20
col BLOCKEE for a20
select (select username from v$session where sid = a.sid ) blocker,a.sid, 'is blocking ',(select username from v$session where sid =b.sid) blockee,b.sid from v$lock a, v$lock b where a.block =1 and b.request > 0 and a.id1 = b.id1 and a.id2 = b.id2;

BLOCKER SID       'ISBLOCKING' BLOCKEE SID
------- ---------- ----------  ------- --------


set pages 50000 lines 32767
select blocking_session, sid, serial#, wait_class,seconds_in_wait, username, osuser, program, logon_time from v$session where blocking_session is not NULL order by 1;

9. Check for alerts in OEM :-
============================
Login to Oracle Enterprise Manager with valid username and password
click on "Alerts" tab
then select the below tabs one by one to see the alerts generated
Targets Down/Critical/Warning/Errors/

How to check RMAN backup job status in Oracle using v$rman_backup_job_details


RMAN backup job details for 'n' number of days:-
=========================================
Monitoring RMAN backup status using v$rman_backup_job_details and v$rman_status.

Note : - Enter the number of days required for status report, for 1 day backup status report provide input as '1'.

RMAN backup status using v$rman_backup_job_details :-
set pages 9999 lines 500
col INSTANCE for a9
col ELAPSED for a30
SELECT (  SELECT   instance_name FROM v$instance)
              || ' '
              || (  SELECT   instance_number FROM v$instance)
                 instance,
            --  TO_CHAR (start_time, 'YYYY-MM-DD HH24:MI') start_time,
       to_date (start_time, 'DD-MM-YYYY HH24:MI:SS') start_time,
              TO_CHAR (output_bytes / 1048576, '999,999,999.9') output_mb,
              TO_CHAR (output_bytes_per_sec / 1048576, '999,999.9') output_mb_per_sec,
              time_taken_display elapsed,input_type,status
         FROM v$rman_backup_job_details
         where start_time >= sysdate - &NUMBER_OF_DAYS
         ORDER BY start_time
         /


RMAN backup status using v$rman_backup_job_details , v$rman_status:-
set pages 9999 lines 500
set numformat 99999.99
set trim on 
set trims on
alter session set nls_date_format = 'DD-MM-YYYY HH24:MI:SS';
col INSTANCE for a9
col status for a22
col COMMAND_ID for a20
col INPUT_TYPE for a10
col OUTPUT_DEVICE_TYPE for a10
col OUTPUT_BYTES_PER_SEC_DISPLAY for a9
col status heading "BACKUP|STATUS" 
col COMMAND_ID heading "BACKUP NAME" 
col STARTED_TIME heading "START TIME" 
COL END_TIME heading "END TIME" 
col ELAPSED_TIME heading "MINUTES | TAKEN" 
col INPUT_TYPE heading "INPUT|TYPE" 
col OUTPUT_DEVICE_TYPE heading "OUTPUT|DEVICES" 
col INPUT_SIZE heading  "INPUT SIZE|GB"
col OUTPUT_SIZE heading  "OUTPUT SIZE|GB" 
col OUTPUT_BYTES_PER_SEC_DISPLAY heading "OUTPUT | RATE|(PER SEC)"
SELECT (SELECT instance_name FROM v$instance) || ' ' || (SELECT instance_number FROM v$instance) instance,rs.sid,
rj.COMMAND_ID,
rj.STATUS,
max(rj.START_TIME) STARTED_TIME, 
rj.END_TIME,
rj.ELAPSED_SECONDS/60 ELAPSED_TIME,
rj.INPUT_TYPE,
rj.OUTPUT_DEVICE_TYPE,
rj.INPUT_BYTES/1024/1024/1024 INPUT_SIZE, 
rj.OUTPUT_BYTES/1024/1024/1024 OUTPUT_SIZE,
rj.OUTPUT_BYTES_PER_SEC_DISPLAY
from v$rman_backup_job_details rj, v$rman_status rs
where rj.COMMAND_ID=rs.COMMAND_ID
group by rs.sid,rj.COMMAND_ID,rj.STATUS,rj.START_TIME,rj.END_TIME,rj.ELAPSED_SECONDS,rj.INPUT_TYPE,rj.OUTPUT_DEVICE_TYPE,rj.INPUT_BYTES,rj.OUTPUT_BYTES,rj.OUTPUT_BYTES_PER_SEC_DISPLAY 
having max(rj.START_TIME) > sysdate-&NUMBER_OF_DAYS order by rj.START_TIME desc
/

                                  BACKUP                                                          MINUTES  INPUT      OUTPUT     INPUT SIZE OUTPUT SIZE OUTPUT RATE
INSTANCE  SID BACKUP NAME          STATUS                 START TIME          END TIME                TAKEN TYPE       DEVICES            GB          GB (PER SEC)
--------- --- -------------------- ---------------------- ------------------- ------------------- --------- ---------- ---------- ---------- ----------- ------------


To get the job details for a specific backup job,  use the following query:-

set lines 220
set pages 1000
col cf for 9,999
col df for 9,999
col elapsed_seconds heading "ELAPSED|SECONDS"
col i0 for 9,999
col i1 for 9,999
col l for 9,999
col output_mbytes for 9,999,999 heading "OUTPUT|MBYTES"
col session_recid for 999999 heading "SESSION|RECID"
col session_stamp for 99999999999 heading "SESSION|STAMP"
col status for a10 trunc
col time_taken_display for a10 heading "TIME|TAKEN"
col output_instance for 9999 heading "OUT|INST"
select
  j.session_recid, j.session_stamp,
  to_char(j.start_time, 'yyyy-mm-dd hh24:mi:ss') start_time,
  to_char(j.end_time, 'yyyy-mm-dd hh24:mi:ss') end_time,
  (j.output_bytes/1024/1024) output_mbytes, j.status, j.input_type,
  decode(to_char(j.start_time, 'd'), 1, 'Sunday', 2, 'Monday',
                                     3, 'Tuesday', 4, 'Wednesday',
                                     5, 'Thursday', 6, 'Friday',
                                     7, 'Saturday') dow,
  j.elapsed_seconds, j.time_taken_display,
  x.cf, x.df, x.i0, x.i1, x.l,
  ro.inst_id output_instance
from V$RMAN_BACKUP_JOB_DETAILS j
  left outer join (select
                     d.session_recid, d.session_stamp,
                     sum(case when d.controlfile_included = 'YES' then d.pieces else 0 end) CF,
                     sum(case when d.controlfile_included = 'NO'
                               and d.backup_type||d.incremental_level = 'D' then d.pieces else 0 end) DF,
                     sum(case when d.backup_type||d.incremental_level = 'D0' then d.pieces else 0 end) I0,
                     sum(case when d.backup_type||d.incremental_level = 'I1' then d.pieces else 0 end) I1,
                     sum(case when d.backup_type = 'L' then d.pieces else 0 end) L
                   from
                     V$BACKUP_SET_DETAILS d
                     join V$BACKUP_SET s on s.set_stamp = d.set_stamp and s.set_count = d.set_count
                   where s.input_file_scan_only = 'NO'
                   group by d.session_recid, d.session_stamp) x
    on x.session_recid = j.session_recid and x.session_stamp = j.session_stamp
  left outer join (select o.session_recid, o.session_stamp, min(inst_id) inst_id
                   from GV$RMAN_OUTPUT o
                   group by o.session_recid, o.session_stamp)
    ro on ro.session_recid = j.session_recid and ro.session_stamp = j.session_stamp
where j.start_time > trunc(sysdate)-&NUMBER_OF_DAYS
order by j.start_time;

Where,

CF: Number of controlfile backups included in the backup set

DF: Number of datafile full backups included in the backup set

I0: Number of datafile incremental level-0 backups included in the backup set

I1: Number of datafile incremental level-1 backups included in the backup set

 L: Number of archived log backups included in the backup set

Backup set details : -

To get the Backup set details for a specific backup job, identified by the (SESSION_RECID, SESSION_STAMP) pair, use the following query:
 
set lines 220
set pages 1000
col backup_type for a4 heading "TYPE"
col controlfile_included heading "CF?"
col incremental_level heading "INCR LVL"
col pieces for 999 heading "PCS"
col elapsed_seconds heading "ELAPSED|SECONDS"
col device_type for a10 trunc heading "DEVICE|TYPE"
col compressed for a4 heading "ZIP?"
col output_mbytes for 9,999,999 heading "OUTPUT|MBYTES"
col input_file_scan_only for a4 heading "SCAN|ONLY"
select
  d.bs_key, d.backup_type, d.controlfile_included, d.incremental_level, d.pieces,
  to_char(d.start_time, 'yyyy-mm-dd hh24:mi:ss') start_time,
  to_char(d.completion_time, 'yyyy-mm-dd hh24:mi:ss') completion_time,
  d.elapsed_seconds, d.device_type, d.compressed, (d.output_bytes/1024/1024) output_mbytes, s.input_file_scan_only
from V$BACKUP_SET_DETAILS d
  join V$BACKUP_SET s on s.set_stamp = d.set_stamp and s.set_count = d.set_count
where session_recid = &SESSION_RECID
  and session_stamp = &SESSION_STAMP
order by d.start_time;

Backup job output :-

To get the Backup job output for a specific backup job, identified by the (SESSION_RECID, SESSION_STAMP) pair, use the following query:
   
set lines 200
set pages 1000
select output
from GV$RMAN_OUTPUT
where session_recid = &SESSION_RECID
and session_stamp = &SESSION_STAMP
order by recid;

May 04, 2014

How to compress Listener log file in Linux

How to compress files in Linux

How to compress Listener log file in Linux

Step:-1
-------
cd /u01/app/oracle/10.2.0/db_1/network/admin --- listener log location
du -sh *|sort -n
du -sh listener.log

Step:-2
-------
vi filecompress.sh
cd /u01/app/oracle/10.2.0/db_1/network/admin --- listener log location
cp listener.log listener_currentdate.log
cat /dev/null > listener.log

-- press esc key
:wq

Run the filecompress.sh in nohup
---------------------------------
nohup sh -x filecompress.sh > filecompress.log 2>> filecompress.err &

Step:-3
-------
gzip -9 listener_currentdate.log
du -sh *.gz
--- OR ---
tar -zcvf listener_currentdate.tar.gz listener_currentdate.log
du -sh *.tar.gz

Note:-
====
Listener will be available in the above process and no data loss of listener log file.

For Example, 3 GB file will be compressed to 100M (approx).

February 22, 2014

Oracle DBA Performance Tuning Scripts

Performance Tuning Scripts

Listed below are some SQL queries which I find particularly useful for performance tuning. These are based on the Active Session History v$active_session_history
View to get a current perspective of performance and the DBA_HIST_* AWR history tables for obtaining performance data pertaining to a period of time in the past.

Top Recent Wait Events

set pages 50000 lines 32767
col EVENT format a60

select * from (
select active_session_history.event,
sum(active_session_history.wait_time +
active_session_history.time_waited) ttl_wait_time
from v$active_session_history active_session_history
where active_session_history.event is not null
group by active_session_history.event
order by 2 desc)
where rownum < 6
/

Top Wait Events Since Instance Startup

set pages 50000 lines 32767
col event format a60

select event, total_waits, time_waited
from v$system_event e, v$event_name n
where n.event_id = e.event_id
and n.wait_class !='Idle'
and n.wait_class = (select wait_class from v$session_wait_class
where wait_class !='Idle'
group by wait_class having
sum(time_waited) = (select max(sum(time_waited)) from v$session_wait_class
where wait_class !='Idle'
group by (wait_class)))
order by 3
/

List Of Users Currently Waiting
set pages 50000 lines 32767
col username format a12
col sid format 9999
col state format a15
col event format a50
col wait_time format 99999999
set pagesize 100
set linesize 120

select s.sid, s.username, se.event, se.state, se.wait_time
from v$session s, v$session_wait se
where s.sid=se.sid
and se.event not like 'SQL*Net%'
and se.event not like '%rdbms%'
and s.username is not null
order by se.wait_time
/

Find The Main Database Wait Events In A Particular Time Interval


First determine the snapshot id values for the period in question.

In this example we need to find the SNAP_ID for the period 10 PM to 11 PM on the 14th of November, 2013.

set pages 50000 lines 32767

select snap_id,begin_interval_time,end_interval_time
from dba_hist_snapshot
where to_char(begin_interval_time,'DD-MON-YYYY')='14-NOV-2013'
and EXTRACT(HOUR FROM begin_interval_time) between 22 and 23;
set verify off
select * from (
select active_session_history.event,
sum(active_session_history.wait_time +
active_session_history.time_waited) ttl_wait_time
from dba_hist_active_sess_history active_session_history
where event is not null
and SNAP_ID between &ssnapid and &esnapid
group by active_session_history.event
order by 2 desc)
where rownum
/

Top CPU Consuming SQL During A Certain Time Period


Note – in this case we are finding the Top 5 CPU intensive SQL statements executed between 9.00 AM and 11.00 AM

set pages 50000 lines 32767

select * from (
select
SQL_ID,
sum(CPU_TIME_DELTA),
sum(DISK_READS_DELTA),
count(*)
from
DBA_HIST_SQLSTAT a, dba_hist_snapshot s
where
s.snap_id = a.snap_id
and s.begin_interval_time > sysdate -1
and EXTRACT(HOUR FROM S.END_INTERVAL_TIME) between 9 and 11
group by
SQL_ID
order by
sum(CPU_TIME_DELTA) desc)
where rownum
/

Which Database Objects Experienced the Most Number of Waits in the Past One Hour

set pages 50000 lines 32767
col event format a40
col object_name format a40

select * from
(
select dba_objects.object_name,
dba_objects.object_type,
active_session_history.event,
sum(active_session_history.wait_time +
active_session_history.time_waited) ttl_wait_time
from v$active_session_history active_session_history,
dba_objects
where
active_session_history.sample_time between sysdate - 1/24 and sysdate
and active_session_history.current_obj# = dba_objects.object_id
group by dba_objects.object_name, dba_objects.object_type, active_session_history.event
order by 4 desc)
where rownum < 6
/

Top Segments ordered by Physical Reads

set pages 50000 lines 32767
col segment_name format a20
col owner format a10

select segment_name,object_type,total_physical_reads
from ( select owner||'.'||object_name as segment_name,object_type,
value as total_physical_reads
from v$segment_statistics
where statistic_name in ('physical reads')
order by total_physical_reads desc)
where rownum;

Top 5 SQL statements in the past one hour


set pages 50000 lines 32767

select * from (
select active_session_history.sql_id,
dba_users.username,
sqlarea.sql_text,
sum(active_session_history.wait_time +
active_session_history.time_waited) ttl_wait_time
from v$active_session_history active_session_history,
v$sqlarea sqlarea,
dba_users
where
active_session_history.sample_time between sysdate -  1/24  and sysdate
and active_session_history.sql_id = sqlarea.sql_id
and active_session_history.user_id = dba_users.user_id
group by active_session_history.sql_id,sqlarea.sql_text, dba_users.username
order by 4 desc )
where rownum
/

SQL with the highest I/O in the past one day


set pages 50000 lines 32767

select * from
(
SELECT /*+LEADING(x h) USE_NL(h)*/
h.sql_id,SUM(10) ash_secs
FROM   dba_hist_snapshot x,dba_hist_active_sess_history h
WHERE   x.begin_interval_time > sysdate -1
AND    h.SNAP_id = X.SNAP_id
AND    h.dbid = x.dbid
AND    h.instance_number = x.instance_number
AND    h.event in  ('db file sequential read','db file scattered read')
GROUP BY h.sql_id
ORDER BY ash_secs desc )
where rownum
/

Top CPU consuming queries since past one day

set pages 50000 lines 32767

select * from (
select SQL_ID, sum(CPU_TIME_DELTA),sum(DISK_READS_DELTA),count(*)
from DBA_HIST_SQLSTAT a, dba_hist_snapshot s
where
s.snap_id = a.snap_id
and s.begin_interval_time > sysdate -1
group by SQL_ID
order by sum(CPU_TIME_DELTA) desc)
where rownum
/

Find what the top SQL was at a particular reported time of day


First determine the snapshot id values for the period in question.

In thos example we need to find the SNAP_ID for the period 10 PM to 11 PM on the 14th of November, 2013.

set pages 50000 lines 32767

select snap_id,begin_interval_time,end_interval_time
from dba_hist_snapshot
where to_char(begin_interval_time,'DD-MON-YYYY')='14-NOV-2013'
and EXTRACT(HOUR FROM begin_interval_time) between 22 and 23;
select * from
(
select
sql.sql_id c1,
sql.buffer_gets_delta c2,
sql.disk_reads_delta c3,
sql.iowait_delta c4
from
dba_hist_sqlstat sql,dba_hist_snapshot s
where
s.snap_id = sql.snap_id
and
s.snap_id= &snapid
order by
c3 desc)
where rownum < 6
/

Analyse a particular SQL ID and see the trends for the past day


set pages 50000 lines 32767

select
s.snap_id,
to_char(s.begin_interval_time,'HH24:MI') c1,
sql.executions_delta c2,
sql.buffer_gets_delta c3,
sql.disk_reads_delta c4,
sql.iowait_delta c5,
sql.cpu_time_delta c6,
sql.elapsed_time_delta c7
from
dba_hist_sqlstat sql,
dba_hist_snapshot s
where
s.snap_id = sql.snap_id
and s.begin_interval_time > sysdate -1
and
sql.sql_id='&sqlid'
order by c7
/

Do we have multiple plan hash values for the same SQL ID – in that case may be changed plan is causing bad performance

set pages 50000 lines 32767

select
SQL_ID
, PLAN_HASH_VALUE
, sum(EXECUTIONS_DELTA) EXECUTIONS
, sum(ROWS_PROCESSED_DELTA) CROWS
, trunc(sum(CPU_TIME_DELTA)/1000000/60) CPU_MINS
, trunc(sum(ELAPSED_TIME_DELTA)/1000000/60)  ELA_MINS
from DBA_HIST_SQLSTAT
where SQL_ID in (
'&sqlid')
group by SQL_ID , PLAN_HASH_VALUE
order by SQL_ID, CPU_MINS
/

Top 5 Queries for past week based on ADDM recommendations


/*
Top 10 SQL_ID's for the last 7 days as identified by ADDM from DBA_ADVISOR_RECOMMENDATIONS and dba_advisor_log
*/

set pages 50000 lines 32767
col SQL_ID form a16
col Benefit form 9999999999999

select * from (
select b.ATTR1 as SQL_ID, max(a.BENEFIT) as "Benefit"
from DBA_ADVISOR_RECOMMENDATIONS a, DBA_ADVISOR_OBJECTS b
where a.REC_ID = b.OBJECT_ID
and a.TASK_ID = b.TASK_ID
and a.TASK_ID in (select distinct b.task_id
from dba_hist_snapshot a, dba_advisor_tasks b, dba_advisor_log l
where a.begin_interval_time > sysdate - 7
and  a.dbid = (select dbid from v$database)
and a.INSTANCE_NUMBER = (select INSTANCE_NUMBER from v$instance)
and to_char(a.begin_interval_time, 'yyyymmddHH24') = to_char(b.created, 'yyyymmddHH24')
and b.advisor_name = 'ADDM'
and b.task_id = l.task_id
and l.status = 'COMPLETED')
and length(b.ATTR4) > 1 group by b.ATTR1
order by max(a.BENEFIT) desc) where rownum < 6
/

Reference:-

http://gavinsoorma.com/2012/11/ash-and-awr-performance-tuning-scripts/

February 21, 2014

vi Editor Commands

vi Editor Commands

$ vi <filename>

Option ==> Action
vi     ==> Starts editing session in memory.
vi     ==> Starts session and opens the specified file.
vi *   ==> Opens first file that matches the wildcard pattern. Use :n to navigate to the next matched file.
view   ==> Opens file in read-only mode.
vi -R  ==> Opens file in read-only mode.
vi -r  ==> Recovers file and recent edits after abnormal abort from editing session (like a system crash).
vi +n  ==> Opens file at specified line number n.
vi +   ==> Opens file at the last line.
vi +/  ==> Opens file at first occurrence of specified string pattern.

Common Techniques to Enter vi Insert Mode:
Enter Insert Command ==> Action

i ==> Insert text in front of the cursor.
a ==> Insert text after the cursor.
I ==> Insert text at the beginning of the line.
A ==> Insert text at the end of the line.
o ==> Insert text below the current line.
O ==> Insert text above the current line.

Useful vi Exit Commands
Exit Command ==> Action

:wq ==> Save and exit.
ZZ  ==> Save and exit.
:x  ==> Save and exit.
:w  ==> Save the current edits without exiting.
:w! ==> Override file protections and save.
:q  ==> Exit the file.
:q! ==> Exit without saving.
:n  ==> Edit next file.
:e! ==> Return to previously saved version.

Common Navigation Commands
Command               ==> Action

j (or down arrow)     ==> Move down a line.
k (or up arrow)       ==> Move up a line.
h (or left arrow)     ==> Move one character left.
l (or right arrow)    ==> Move one character right.
Ctrl+f (or Page Down) ==> Scroll down one screen.
Ctrl+b (or Page Up)   ==> Scroll up one screen.
1G ==> Go to first line in file.
G  ==> Go to last line in file.
nG ==> Go to n line number.
H  ==> Go to top of screen.
L  ==> Go to bottom of screen.
w  ==> Move one word forward.
b  ==> Move one word backward.
0  ==> Go to start of line.
$  ==> Go to end of line.

Common Options for Copying, Deleting, and Pasting Text
Option ==> Action

yy  ==> Yank (copy) the current line.
nyy ==> Yank (copy) n number of lines.
p   ==> Put yanked line(s) below the cursor.
P   ==> Put yanked line(s) above the cursor.
x   ==> Delete the character that the cursor is on.
X   ==> Delete the character to the left of the cursor.
dw  ==> Delete the word the cursor is currently on.
dd  ==> Delete current line of text.
ndd ==> Delete n lines of text
D   ==> Delete to the end of the current line.

Common Options for Changing Text
Option ==> Action

r  ==> Replace the character that the curser is on with the next character you type.
~  ==> Change the case of a character.
cc ==> Delete the current line and insert text.
C  ==> Delete to the end of the line and insert text.
c$ ==> Delete to the end of the line and insert text.
cw ==> Delete to the end of the word and insert text.
R  ==> Type over the characters in the current line.
s  ==> Delete the current character and insert text.
S  ==> Delete the current line and insert text.

Common Options for Text Searching
Option ==> Action

/ ==> Search forward for a string.
? ==> Search backward for a string.
n ==> Repeat the search forward.
N ==> Repeat the search backward.
f ==> Search forward for a character in the current line.
F ==> Search backward for a character in the current line.

:set number ==> Displaying Line Numbers

u ==> Undoing a Command

February 20, 2014

Oracle DBA Interview Questions

Oracle DBA Interview Questions

What are the versions you are working on
Database
RAC database
Dataguard

What is the recent patch you applied?
What happens when you run Root.sh during installation

RAC Architechture?

What is Node Eviction? In what scenarios the node be evicted? Which background process is responsible for node eviction and fixing  evicted node  and bringing into cluster? How do you troubleshoot Node Eviction?

What is cache fusion? What is responsible for cache fusion?

How will you take VD backup in 11gR1 and 11gR2?

How to check VD backup location

How to check OCR backup location

Starup Restrict vs Startup Upgrade

Difference between 11g and 10g ?

Difference between sga_target and memory_target?

Difference between 11gR2,11gR1,10gR2 and 10gR1 RAC ?

Materialized views and its types

Database upgrade takes 1hr normally and client want to upgrade without down time.
How can you achieve that in a RAC and Standalone.How can we upgrade with only 5 min downtime instead of 1 hour, as per client requirement?

Can exp be faster than expdp? If yes? In which scenario it happens?

Exp vs Datapump

Datapump vs RMAN

If RMAN backs up only changed blocks, what happens if the database has some read only ts and I have taken level 0 backup. Will the readonly ts backs up or not as there are no changed blocks in them?

What is Dataguard?

Logical vs Physical Standby databases?

Protection modes in Dataguard? What Protection mode do you have in your project?

DB_LINK? Syntax?

DB_LINK VS NETWORK_LINK in Datapump

what happens internally when you export or import in Datapump

How to check whether DATAPUMP dump File is corrupted or not?

How to see the DDL contents of an export dump file in Data Pump import and Traditional import?

Datapump Import failed after running for long time and even resumable time also execeeded? What action will you take?

Datapump Import hanged after running for long time? What action will you take?

How will you stop and start an import in datapump.

From which view you will find out datapump jobs?

Tell me some issues you faced with Datapump and how did you fix them?

Tell me the toughest issue you faced with Dataguard and how did you fix it?

Tell me the toughest issue you faced with RAC and how did you fix it?

Tell me the toughest issue you faced in Performance Tuning and how did you fix it?

CPU VS PSU Patching? What patching you are implementing in your project?

What is the full form of Opatch

opatch apply vs napply

Pre requirement for upgrade to 11g from 10g.

Steps for database cloning using RMAN

Steps for DR rebuild


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

Temp ts is 100% full,adding space still filling up, we cant add more space to it, what fix will you apply?

How to make RMAN backups run  faster?

What is block change tracking? How does it work?

Apps team complained database is performing slow? How will you confirm the slowness being a DBA ? What actions will you perform?

Apps team complained database performence is low compared to last week? What actions will you take?

Which columns will you check in active_session_history

Write query for populating Active sessions excluding background processes?

Fast failover in DG? Is Fast Failover there  in your environment?

What is a Scan listener? How it works?