Tuesday, July 3, 2012

SHARED POOL QUERIES


TOTAL SIZE OF SGA 


select sum(value) SGA_SIZE_BYTES from V$SGA ;-- 8589934592;
select sum(value)/1024/1024/1024 SGA_SIZE_GB from V$SGA ;-- 8589934592;

SHARED POOL QUICK CHECK NOTES
select 'You may need to increase the SHARED_POOL_RESERVED_SIZE' Description,
       'Request Failures = '||REQUEST_FAILURES  Logic
from     v$shared_pool_reserved
where     REQUEST_FAILURES > 0
and     0 != (
    select     to_number(VALUE)
        from     v$parameter
        where     NAME = 'shared_pool_reserved_size')
union
select 'You may be able to decrease the SHARED_POOL_RESERVED_SIZE' Description,
       'Request Failures = '||REQUEST_FAILURES Logic
from     v$shared_pool_reserved
where     REQUEST_FAILURES < 5
and     0 != (
    select     to_number(VALUE)
    from     v$parameter
    where     NAME = 'shared_pool_reserved_size');

SHARED POOL MEMORY USAGE

select     OWNER,    NAME||' - '||TYPE object,    SHARABLE_MEM
from     v$db_object_cache
where     SHARABLE_MEM > 10000
and    type in ('PACKAGE','PACKAGE BODY','FUNCTION','PROCEDURE')
order     by SHARABLE_MEM desc;

LOADS INTO SHARED POOL NOTES

SELECT     OWNER,    NAME||' - '||TYPE OBJECT,    LOADS
FROM     V$DB_OBJECT_CACHE
WHERE     LOADS > 3
AND     TYPE IN ('PACKAGE','PACKAGE BODY','FUNCTION','PROCEDURE')
ORDER     BY LOADS DESC

SHARED POOL EXECUTION NOTES

select     OWNER,NAME||' - '||TYPE object,EXECUTIONS
from     v$db_object_cache
where     EXECUTIONS > 100
and     type in ('PACKAGE','PACKAGE BODY','FUNCTION','PROCEDURE')
order     by EXECUTIONS desc;

SHARED POOL DETAIL NOTES
select    OWNER,NAME,DB_LINK,NAMESPACE,TYPE,SHARABLE_MEM,LOADS,EXECUTIONS,LOCKS,PINS from v$db_object_cache order     by OWNER, NAME;

SHARED POOL V$LIBRARYCACHE STATISTIC NOTES
select     NAMESPACE,GETS,GETHITS,round(GETHITRATIO*100,2) gethit_ratio,PINS,PINHITS,round(PINHITRATIO*100,2) pinhit_ratio,RELOADS,INVALIDATIONS
from     v$librarycache;

SHARED POOL RESERVED SIZE NOTES
select     NAME, VALUE from     v$parameter where     NAME like '%reser%';

PINNED OBJECT NOTES
select     NAME,TYPE,KEPT from     v$db_object_cache where     KEPT = 'YES';

Shows chunks of memory in the shared pool 
CHUNK is the smallest unit of LOBSEGMENT allocation.It is a multiple of DB_BLOCK_SIZE
select /*+ RULE */
decode(sign(ksmchsiz-80),-1,0,trunc(1/log(greatest(ksmchsiz-15,2),2))-5) bucket_no,
decode(decode(sign(ksmchsiz-80),-1,0,trunc(1/log(greatest(ksmchsiz-15,2),2))-5),
  0,'up to 79 bytes',1,'80 to 143 bytes',2,'144 to 271 bytes',
  3,'272 to 527 bytes',4,'528 bytes to 1Kb',5,'1Kb',
  (to_char(power(2,max(trunc(1/log(greatest(ksmchsiz-15,2),2))-10))))||'Kb') chunk_size,
count(*) chunks,
sum(decode(ksmchcls,'freeabl',ksmchsiz,0))/1024 frbl_kb,sum(decode(ksmchcls,'free',ksmchsiz,0))/1024 free_kb,
sum(ksmchsiz/1024) avail_kb,min(ksmchsiz) sml_byte,max(ksmchsiz) lrg_byte
from SYS.X$KSMSP
where ksmchcls like 'free%'
group by decode(sign(ksmchsiz-80),-1,0,trunc(1/log(greatest(ksmchsiz-15,2),2))-5)
union
select
99 bucket_no,'reserved pool',count(*) chunks,
nvl(sum(decode(ksmchcls,'R-freeabl',ksmchsiz,0)),0)/1024 frbl_kb,
nvl(sum(decode(ksmchcls,'R-free',ksmchsiz,0)),0)/1024 free_kb,
nvl(sum(ksmchsiz/1024),0) avail_kb,
nvl(min(ksmchsiz),0) sml_byte,
nvl(max(ksmchsiz),0) lrg_byte
from SYS.X$KSMSP
where ksmchcls like 'R-free%'
order by 1;

TOP 10 COMPONENTS TO HAVE ALLOCATED MEMORY IN THE POOL
SELECT * FROM (SELECT NAME,BYTES/(1024*1024) BYTES_MB  FROM V$SGASTAT WHERE POOL='shared pool' order by bytes desc) where rownum<11;

select s.ksmchptr SP_CHUNK,s.ksmchsiz CH_SIZE,b.obj DATAOBJ#,b.ba BLOCKADDR,b.blsiz BLKSIZE,
       decode(b.class,1,'data block',2,'sort block',3,'save undo block',4,'segment header',5,'save undo header',6,'free list',7,'extent map',
                 8,'1st level bmb',9,'2nd level bmb',10,'3rd level bmb',11,'bitmap block',12,'bitmap index block',13,'file header block',14,'unused',
              15,'system undo header',16,'system undo block',17,'undo header',18,'undo block',class)  BLKTYPE,
      decode (b.state,0,'free',1,'xcur',2,'scur',3,'cr', 4,'read',5,'mrec',6,'irec',7,'write',8,'pi', 9,'memory',10,'mwrite',11,'donated',b.state) BLKSTATE
from x$bh b,x$ksmsp s
where ( b.ba >= s.ksmchptr and to_number(b.ba, 'XXXXXXXXXXXXXXXX') + b.blsiz < to_number(ksmchptr, 'XXXXXXXXXXXXXXXX') + ksmchsiz)
and s.ksmchcom = 'KGH: NO ACCESS'
order by s.ksmchptr, b.ba;


COLD BACKUP PROCESS MANUAL


BEFORE COLD BACKUP
select count(*) from v$controlfile;--    Present:3                     Previous: 3
select count(*)from v$logfile; --        Present:6                     Previous: 6
select count(*) from dba_temp_files;--    Present:4                    Previous: 3
select count(*) from v$datafile;--        Present:33                     Previous: 75
SELECT DBID FROM V$DATABASE;---- ----    Present: 468172852            Previous: 416759732
select INSTANCE_NAME,HOST_NAME,VERSION,STARTUP_TIME,STATUS,ARCHIVER,DATABASE_STATUS from v$INSTANCE;

SELECT to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time"
FROM   sys.v_$instance;   -----            Present:29-AUG-2010 13:41:44Previous: 27-JUN-2010 16:15:28

select sum(cnt) from (select count(*) cnt from v$controlfile
union
select count(*)from v$logfile
union
select count(*) from dba_temp_files
union
select count(*) from v$datafile
)
------TOTAL :46
AFTER COLD BACKUP 
select count(*) from v$controlfile;--    Present:3                     Previous: 3
select count(*)from v$logfile; --        Present:6                     Previous: 6
select count(*) from dba_temp_files;--    Present:4                    Previous: 3
select count(*) from v$datafile;--        Present:33                     Previous: 75
SELECT DBID FROM V$DATABASE;---- ----    Present: 468172852             Previous: 416759732
select INSTANCE_NAME,HOST_NAME,VERSION,STARTUP_TIME,STATUS,ARCHIVER,DATABASE_STATUS from v$INSTANCE;

SELECT to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time"
FROM   sys.v_$instance;   -----            Present:26-SEP-2010 15:16:41 Previous: 29-AUG-2010 13:23:59

select sum(cnt) from (select count(*) cnt from v$controlfile
union
select count(*)from v$logfile
union
select count(*) from dba_temp_files
union
select count(*) from v$datafile
)
------TOTAL :46

COLDBACKUP 
Step1. Preparation:
a)
File Checks
CONTROL FILES    V$CONTROLFILE  ((To check the controlfiles Information))
select name,status from v$controlfile;
b)
REDOLOGFILES    V$LOGFILE (To check the Redolog Files Information)
select group#,member from v$logfile order by group#;
c)
DATFILES        V$DATAFILE (To check the Data Files Information)
select name,bytes,creation_time from v$datafile;
d)
Tempfiles:( To check the tempfiles Information)
select * from dba_temp_files ;
select * from v$instance;
select INSTANCE_NAME,HOST_NAME,VERSION,STARTUP_TIME,STATUS,ARCHIVER,DATABASE_STATUS from v$INSTANCE;
--select * from v$database;

Step 2:
a)
Sql>
ALTER DATABASE BACKUP CONTROLFILE TO TRACE;
OR
b)
Sql>
ALTER DATABASE BACKUP CONTROLFILE TO TRACE AS ;

c)

Sql>
ALTER SYSTEM SWITCH LOGFILE;

d)

Sql>
SELECT DBID FROM V$DATABASE;---- ----416759732
 

Step 3: Shutdown the Database
a)

SQL>shutdown immediate
 

Step 4:
a)

Copy the C/R/D Files to Backup Destination
 

Step 5: Start the Database (UP the Database)
a)

SQL>startup
 

Step 6: Check C/R/D Files
----Check all C/R/D files whether offline or online.

SCRIPTS FOR ROLLBACK

SCRIPTS FOR ROLLBACK

Who is Using Which Rollback?
Description: Sometimes we need (or want) to know who is using rollback and how much they are using. This script will show you who is using which rbs, how much rollback they are using, their sid/serial, and, optionally, when their session began and when they were last active in the database.

SELECT r.name rbs,nvl(s.username, 'None')  oracle_user,s.osuser client_user,p.username unix_user,to_char(s.sid)||','||to_char(s.serial#) as sid_serial,
p.spid unix_pid,
--TO_CHAR(s.logon_time, 'mm/dd/yy hh24:mi:ss') as login_time,TO_CHAR(sysdate - (s.last_call_et) / 86400,'mm/dd/yy hh24:mi:ss') as last_txn,
t.used_ublk * TO_NUMBER(x.value)/1024  as undo_kb
FROM v$process     p,v$rollname    r,v$session     s,v$transaction t,v$parameter   x
WHERE s.taddr = t.addr AND s.paddr = p.addr(+) AND r.usn   = t.xidusn(+) AND x.name  = 'db_block_size'
ORDER BY r.name;

Tablespace Free Space Report
select total.tablespace_name sname,total.bytes/1048576 ssize,count(free.bytes) extents,max(free.bytes)/1048576 mbytes,
sum (free.bytes)/1048576 tbytes,(total.bytes - sum (free.bytes))/1048576 ubytes, round(sum(free.bytes)/total.bytes * 100) pct
from sys.tfview total,sys.dba_free_space free
where total.tablespace_name = free.tablespace_name
group by total.tablespace_name, total.bytes

Write a Message to the Alert Log
If you want to write a message to the alert log, you can use the undocumented KSDWRT procedure of the DBMS_SYSTEM package.
This procedure has two parameters, the first one must be "2" to write to the alert file, the second one is the message you want to write.

Here is an example:
execute sys.dbms_system.ksdwrt(2,to_char(sysdate)|| ' -- ');
Description: Finds the two highest salaries from table "emp".
Code:
select a.empno,a.sal from emp a  where 2>(select count(*) from emp where sal>a.sal);

Description: Finds the two lowest salaries from table "emp".
select a.empno,a.sal from emp a where 2>(select count(*) from emp where sa

MEMORY TUNING

Description: Computer TP rate to get a better idea on sizing memory objects
SELECT SUM(s.value/(86400*(SYSDATE - TO_DATE(i.VALUE,'J')))) "tps"
FROM V$SYSSTAT s, V$INSTANCE i
WHERE s.NAME in ('user commits','transaction rollbacks') AND i.KEY = 'STARTUP TIME - JULIAN';

Description: This script reports how many hours it has been since the rollback segments wrapped

select n.name,round(24*(sysdate-to_date(i1.value||' '||i2.value,'j SSSSS')) /(s.writes/s.rssize),1) "Hours"
from v$instance i1,v$instance i2,v$rollname n,v$rollstat s
where i1.key = 'STARTUP TIME - JULIAN' and i2.key = 'STARTUP TIME - SECONDS' and n.usn = s.usn and s.status = 'ONLINE'

Description: When you connect to sqlplus, you see the the following sql prompt

The following code works on Oracle 8i (8.1.5, 8.1.6, 8.1.7).You have to insert the following line of code in glogin.sql which is usually found in $ORACLE_HOME/sqlplus/admin

Select SYS_CONTEXT('USERENV','SESSION_USER' ) Usr From Dual;

The following does not work in 8.1.5 but works in 8.1.6 or above

Select SYS_CONTEXT('USERENV','DB_NAME') DBNAME From Dual;

If you are using 8.1.5, use this .

Select Global_Name DBNAME from Global_Name;

Please note that this method will work only when you make a new sql plus session because when you make a new sql plus session, then only glogin.sql is executed.
Description: This script will show you the user's OS name, Username in the database and the SQL Text they are running


SELECT osuser, username, sql_text from v$session a, v$sqltext b where a.sql_address =b.address order by address, piece

Description: In N tier structure it is really hard to track user session specially in a web enviroment,
All users connect to database using the same  application , so all requests are going to database on behalf of one oracle user. then how can you track actions of one ENDUSER (application user). In the v$session, there are serval columns you can use to distinguish ENDUSER such as Moule,Action and Client info. for example, you can use dbms_application_info.set_client_info('client info') to set client info accroding to user's ip or    loginname in your application, then it is easy to find out what sql statement was execute by this client use following script

    select s.sid, s.username, s.program, oc.sql_text
    from v$session s, v$open_cursor oc
    where s.saddr=oc.saddr and s.sid=oc.sid
    and s.client_info='client_info';

if you want to capture all sql in real time, then    there is a tool Oracle Session Manager in    http://www.wangz.net can help you do it.

Description: This script will display the estimated work and time remaining for long operations (i.e. over 10 minutes).
    select sid,    message || '(' || time_remaining || ')' "Long Ops"
    from v$session_longops
    where time_remaining > 600;

Description: The output of this script will display all sql statements in the shared pool that are doing full table scans.


    --run this as sys in SQL worksheet
    create table full_sql (sql_text varchar2(1000), executions number);
    create or replace procedure p_findfullsql as

    v_csr number;
    v_rc number;
    v_string varchar2(2000);

    v_count number;


    cursor c1 is select sql_text,executions from v$sqlarea where lower(sql_text) like '%select%';

    begin

    for x1 in c1 loop

    delete from plan_table ;
    Begin
    v_Csr := DBMS_SQL.OPEN_CURSOR;
    v_string := 'explain plan for ' ;
    v_string := v_string||x1.sql_text ;
    DBMS_SQL.PARSE(v_csr, v_string, DBMS_SQL.V7);
    v_rc := DBMS_SQL.EXECUTE(v_csr);
    DBMS_SQL.CLOSE_CURSOR(v_csr);
    Exception
    when others then
    null;
    End ;

    select count(*) into v_count from plan_table where options like '%FULL%' and operation like '%TABLE%' ;
    if v_count > 0 then
    insert into full_sql(sql_text,executions) values (x1.sql_text, x1.executions) ;
    end if;
    end loop ;
    commit;
    end ;
    /
    execute p_findfullsql ;
    select * from full_sql;
    drop table full_sql;





Description: An interesting script submitted by one of our readers to size the SGA

Code:

    set serverout on
    DECLARE
    l_uplift CONSTANT NUMBER := 0.3;
    /* i.e. 30% above calculated */
    l_numusers NUMBER DEFAULT 50;
    /* Change ths to a predicted number existing database */
    l_avg_uga NUMBER;
    l_max_uga NUMBER;
    l_sum_sql_shmem NUMBER;
    l_sum_obj_shmem NUMBER;
    l_total_avg NUMBER;
    l_total_max NUMBER;
    BEGIN
    dbms_output.enable(20000);

    IF ( l_numusers = 0) THEN
    SELECT sessions_highwater
    INTO l_numusers
    FROM v$license;
    dbms_output.put_line('Maximum concurrent users on this database = '||TO_CHAR(l_numusers));
    ELSE
    dbms_output.put_line('Calculating SGA for = '||TO_CHAR(l_numusers)||' concurrent users');
    END IF;
    dbms_output.new_line;

    SELECT
    avg(value)*l_numusers
    ,max(value)*l_numusers
    INTO l_avg_uga, l_max_uga
    FROM v$sesstat s, v$statname n
    WHERE s.statistic# = n.statistic#
    AND n.name = 'session uga memory max';

    SELECT sum(sharable_mem) INTO l_sum_sql_shmem FROM v$sqlarea;

    SELECT sum(sharable_mem) INTO l_sum_obj_shmem FROM v$db_object_cache;

    l_total_avg := l_avg_uga + l_sum_sql_shmem + l_sum_obj_shmem;
    l_total_max := l_max_uga + l_sum_sql_shmem + l_sum_obj_shmem;

    dbms_output.put_line('Recommended Shared_pool size between :' || TO_CHAR(ROUND(l_total_avg + (l_total_avg * l_uplift), 0) ) ||' and '
    || TO_CHAR(ROUND(l_total_max + (l_total_max * l_uplift), 0) ) ||' bytes');

    dbms_output.put_line('Recommended Shared_pool size between :' || TO_CHAR(ROUND((l_total_avg + (l_total_avg * l_uplift)) /(1024*1024), 0) )
    ||' and '|| TO_CHAR(ROUND((l_total_max + (l_total_max * l_uplift )) /1024*1024) ,0) ) ||' M bytes');

    end;
    /



Description: This script uses the new way of calculating DB_Block Buffer Efficiency. Logical Read: consistent gets + db block gets
Hit-Ratio: (logical reads - physical reads) / (logical reads)
Our Aim: OLTP >= 95%, DSS/Batch >= 85%
Solution: enlarge block buffers, tune SQL, check appropriateness of indexes

Code:

    select name, ((consistent_gets + db_block_gets) - physical_reads) /
    (consistent_gets + db_block_gets) * 100 "Hit Ratio%"
    from v$buffer_pool_statistics
    where physical_reads > 0;



Description: Haven't you ever thought there should be an easier way to do the EXPLAIN PLAN and TKPROF statistics than to edit your
queries to add the commands (like EXPLAIN PLAN SET...), or to have to find or write a script that automates this? It should
be an automatic part of SQL*Plus. Well, as of SQL*Plus 3.3 it is!! The command is called 'SET AUTOTRACE ON'!

Code:

    The SET AUTOTRACE Command

    In SQL*Plus 3.3 there is a little known command (at least I didn't know about it until recently) called SET AUTOTRACE. It is
    documented in the newest SQL*Plus document set, but who really reads the whole document set for changes? Well I did not. It
    is very simple to use. Just type the command:


    SET AUTOTRACE ON

    And then run your select statement. Example:


    SQL> SET AUTOTRACE ON
    SQL> SELECT d.deptno, d.dname, e.empno, e.ename
    2 FROM dept d, emp e
    3 WHERE d.deptno = e.deptno
    4 /

    DEPTNO DNAME EMPNO ENAME
    ---------- -------------- ---------- ----------
    10 ACCOUNTING 7839 KING
    .
    .
    30 SALES 7900 JAMES
    30 SALES 7521 WARD

    14 rows selected.

    Execution Plan
    ----------------------------------------------------------
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 MERGE JOIN
    2 1 SORT (JOIN)
    3 2 TABLE ACCESS (FULL) OF 'EMP'
    4 1 SORT (JOIN)
    5 4 TABLE ACCESS (FULL) OF 'DEPT'

    Statistics
    ----------------------------------------------------------
    0 recursive calls
    4 db block gets
    2 consistent gets
    0 physical reads
    0 redo size
    670 bytes sent via SQL*Net to client
    376 bytes received via SQL*Net from client
    3 SQL*Net roundtrips to/from client
    2 sorts (memory)
    0 sorts (disk)
    14 rows processed


    There are also some other options, for example there is a TRACEONLY option which supresses the SQL output. See the
    SQL*Plus 3.3 manual for a full description.

    Some setup issues:

    If you go off and try this on your instance, you may run into some problems. There are a few setup steps that need to be taken to
    make this work:

    1.Make sure you have access to PLAN_TABLE. If you don't, create it using utlxplan.sql (It should be in a directory like
    $ORACLE_HOME/rdbms73/admin/) and make sure you have access to it from the user you are using to tune the SQL.
    2.You also need to create the PLUSTRACE role, and grant it to the desired users. The script to create this role is in:

    $ORACLE_HOME/plus33/Plustrce.sql

    It has to be run from SYS in order to have the correct security access. Then grant the role to the desired users or ROLEs.

Description: Find the top 20 longest running processes in unix. Useful for high CPU bound systems with large number of users. Script also identifies processes without a oracle session.

Code:

    #!/bin/ksh
    #
    # Find Highest CPU used Oracle processes and get the Username
    # and SID from oracle
    # Only 3 character SIDNAME is displayed - Adjust the script according to your need.
    #
    date
    echo " Top 20 CPU Utilized Session from `hostname`"
    echo " ============================================"
    echo "O/S Oracle Session Session Serial UNIX Login Ora CPU Time"
    echo "ID User ID Status ID No ID MMDD:HHMISS SID Used"
    echo "-------- ----------- -------- ------- ------- ------- ----------- --- --------"
    ps -ef|grep LOCAL|cut -c1-15,42-79|sort -rn +2 | head -20 | while read LINE
    do
    SIDNAME=`echo $LINE | awk '{ print $4 }' | cut -c7-14`
    CPUTIME=`echo $LINE | awk '{ print $3 }'`
    UNIXPID=`echo $LINE | awk '{ print $2 }'`
    #echo $SIDNAME $CPUTIME $UNIXPID
    export ORACLE_SID=$SIDNAME
    SIDNAME=`echo $ORACLE_SID | cut -c4-6`
    export ORACLE_HOME=`/dba_script/bin/find_ohome.sh ${ORACLE_SID}`
    export SHLIB_PATH=$ORACLE_HOME/lib:/usr/lib
    export TMPDIR=/tmp
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib
    export SQLPLUS="$ORACLE_HOME/bin/sqlplus -s / "
    $SQLPLUS >> $wlogfile <    set pages 0 lines 80 trims on echo off verify off pau off
    column pu format a8 heading 'O/S|ID' justify left
    column su format a11 heading 'Oracle|User ID' justify left
    column stat format a8 heading 'Session|Status' justify left
    column ssid format 999999 heading 'Session|ID' justify right
    column sser format 999999 heading 'Serial|No' justify right
    column spid format 999999 heading 'UNIX|ID' justify right
    column ltime format a11 heading 'Login|Time' justify right
    select p.username pu,
    s.username su,
    s.status stat,
    s.sid ssid,
    s.serial# sser,
    lpad(p.spid,7) spid,
    to_char(s.logon_time, 'MMDD:HH24MISS') ltime,
    '$SIDNAME $CPUTIME'
    from v\$process p,
    v\$session s
    where p.addr=s.paddr
    and p.spid=$UNIXPID
    union all
    select a.username, 'Kill Me', 'NoOracle', a.pid, a.serial#,
    lpad(a.spid,7) spid, 'KILL UNIXID', '$SIDNAME $CPUTIME'
    from v\$process a
    where a.spid = $UNIXPID
    and not exists (select 1 from v\$session s
    where a.addr=s.paddr);
    EOF
    done
    echo "-------- ----------- -------- ------- ------- ------- ----------- --- --------"
    date
    #
    # End of Script



Description: Monitor and Verify DEAD Locks: Holding and Waiting Sessions

Code:

    Doc
    Verify DEAD LOCK situation

    Script: waiters.sql

    Date: 07/1999

    Revision:

    #

    set lines 80 echo on ver off timing on term on pages 60 feed on head on
    spool DEAD_LOCK_WAITERS.LST

    col " " for A25
    col "Holding Session Info" for A25
    col "Waiting Session Info" for A25

    select --+ ORDERED
    'Session ID' || CHR(10) ||
    'Mode Held' || CHR(10) ||
    'Lock Type' || CHR(10) ||
    'Mode Requested' || CHR(10) ||
    'Lock ID 1' || CHR(10) ||
    'Lock ID 2' " "
    -------------------------------- END of Header
    ,
    HH.session_id || CHR(10) ||
    HH.mode_held || CHR(10) ||
    HH.lock_type || CHR(10) ||
    HH.mode_requested || CHR(10) ||
    HH.lock_id1 || CHR(10) ||
    HH.lock_id2 "Holding Session Info"
    ------------------------------ END of Holding Session
    ,
    Ww.session_id || CHR(10) ||
    WW.mode_held || CHR(10) ||
    Ww.lock_type || CHR(10) ||
    Ww.mode_requested || CHR(10) ||
    Ww.lock_id1 || CHR(10) ||
    Ww.lock_id2 "Waiting Session Info"
    ------------------------------ END of Waiting Session
    from
    -----------------------------------------------------
    (
    select /*+ RULE */ *
    from SYS.dba_locks
    where blocking_others = 'Blocking' and
    mode_held != 'None' and
    mode_held != 'Null'
    ) HH,
    -----------------------------------------------------
    (
    select /*+ RULE */ *
    from SYS.dba_locks
    where mode_requested != 'None'
    ) WW
    -----------------------------------------------------
    where WW.lock_type = HH.lock_type and
    WW.lock_id1 = HH.lock_id1 and
    WW.lock_id2 = HH.lock_id2
    ;

    spool off



Description: This is possibly one of the most useful tuning scripts available. The V$SYSTEM_EVENT dynamic performance view is the highest-level view of the "Session Wait Interface". Information in this view is cumulative since the database instance was started, and one can get a very good idea of what types of contention a database instance is (or is not) experiencing by monitoring this view.

Code:

    /**********************************************************************
    * File: systemevent.sql
    * Type: SQL*Plus script
    * Description:
    * This is possibly one of the most useful tuning scripts
    * available.
    *
    * The V$SYSTEM_EVENT dynamic performance view is the highest-level
    * view of the "Session Wait Interface". Information in this view
    * is cumulative since the database instance was started, and one
    * can get a very good idea of what types of contention a database
    * instance is (or is not) experiencing by monitoring this view.
    *
    * NOTE: this script sorts output by the TIME_WAITED column in the
    * V$SYSTEM_EVENT view. If the Oracle initialization parameter
    * TIMED_STATISTICS is not set to TRUE, then the TIME_WAITED
    * column will not be populated.
    *
    * Please *disregard* the advice of people who insist that turning
    * off TIMED_STATISTICS is somehow a performance boost. Whatever
    * performance overhead that might be incurred is more than
    * compensated for by the incredible tuning information that
    * results...
    *
    *********************************************************************/
    set echo off feedback off timing off pause off verify off
    set pagesize 100 linesize 500 trimspool on trimout on
    col event format a26 truncate heading "Event Name"
    col total_waits format 999,990.00 heading "Total|Waits|(in 1000s)"
    col total_timeouts format 999,990.00 heading "Total|Timeouts|(in 1000s)"
    col time_waited format 999,990.00 heading "Time|Waited|(in Hours)"
    col pct_significant format 90.00 heading "% of|Concern"
    col average_wait format 990.00 heading "Avg|Wait|(Secs)"

    col instance new_value V_INSTANCE noprint
    select lower(replace(t.instance,chr(0),
    )) instance
    from sys.v_$thread t,
    sys.v_$parameter p
    where p.name = 'thread'
    and t.thread# = to_number(decode(p.value,'0','1',p.value));

    col total_time_waited new_value V_TOTAL_TIME_WAITED noprint
    select sum(time_waited) total_time_waited
    from sys.v_$system_event
    where event not in ('SQL*Net message from client',
    'rdbms ipc message',
    'slave wait',
    'pmon timer',
    'smon timer',
    'rdbms ipc reply',
    'SQL*Net message to client',
    'SQL*Net break/reset to client',
    'inactive session',
    'Null event')
    /

    select event,
    (total_waits / 1000) total_waits,
    (total_timeouts / 1000) total_timeouts,
    (time_waited / 360000) time_waited,
    decode(event,
    'SQL*Net message from client', 0,
    'rdbms ipc message', 0,
    'slave wait', 0,
    'pmon timer', 0,
    'smon timer', 0,
    'rdbms ipc reply', 0,
    'SQL*Net message to client', 0,
    'SQL*Net break/reset to client', 0,
    'inactive session', 0,
    'Null event', 0,
    (time_waited / &&V_TOTAL_TIME_WAITED)*100) pct_significant,
    (average_wait / 100) average_wait
    from sys.v_$system_event
    where (time_waited/360000) >= 0.01
    order by pct_significant desc, time_waited desc

    spool sysevent_&&V_INSTANCE
    /
    spool off

REPAIR DATAFILE WORKSAPCE JOBS

13) REPAIR DATAFILE WORKSAPCE JOBS

--select owner, segment_name, segment_type
--from dba_extents
--where file_id = 15 and
--66660 between block_id and block_id + blocks - 1;
-- MDSYS SYS_LOB0000046123C00006$$  LOBSEGMENT

--select *
--from dba_free_space
--where file_id = 15 and
--66660 between block_id and block_id + blocks - 1;
--select COUNT(*) from aud$
--  select uniqueness from dba_indexes where index_name = 'I_AUD1';
--select column_name from dba_indexes where index_name = 'PK_TIME_CARD'

--  select * from dba_indexes where index_name = 'I_AUD1' order by column_position;
--select * from dba_indexes where index_name = 'I_AUD1';
--DROP INDEX  I_AUD1
--alter table AUD$ drop INDEX  I_AUD1
--------------------------------------------------
--select * from v$session   where STATUS = 'ACTIVE'
--ALTER SYSTEM KILL SESSION '123,    16453'
alter system kill session '123,16453'
----------------------------------------------------------
select
b.username, a.sql_text
from
v$sqltext_with_newlines a, v$session b, v$process c
where
c.spid = to_number('300', 'xxx')
and
c.addr = b.paddr
and
b.sql_address = a.address;
--------------------------------------------------------------
SELECT table_name
FROM dba_tables d
WHERE d.owner='SYSTEM';
--------------------------------------------------------------
DECLARE num_corrupt INT;
CURSOR cur_table IS
SELECT table_name
FROM dba_tables d
WHERE d.owner='SYSTEM'
AND d.table_name NOT IN ('QUEST_TEMP_EXPLAIN')
;
BEGIN
FOR rec_table IN cur_Table
LOOP
num_corrupt := 0;
DBMS_REPAIR.CHECK_OBJECT (
SCHEMA_NAME => 'SYSTEM',
OBJECT_NAME => rec_Table.table_name,
REPAIR_TABLE_NAME => 'REPAIR_TABLE',
CORRUPT_COUNT => num_corrupt);
IF num_corrupt > 0 THEN
DBMS_OUTPUT.PUT_LINE('Table Name : '||rec_table.table_name||' number corrupt: ' || TO_CHAR (num_corrupt));
END IF;
END LOOP;

END;
--------------------------------------------------------------------
select owner, segment_name, segment_type from dba_extents where file_id = 15 and 66660 between block_id and block_id + blocks -1;
--------------------------------------------------------------------------
--select *
--from dba_free_space
--where file_id = 15 and
--66660 between block_id and block_id + blocks - 1;
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'AUD$'
----------------------------------------------------------
--BEGIN
--DBMS_REPAIR.ADMIN_TABLES (
--     TABLE_NAME => 'REPAIR_TABLE',
--     TABLE_TYPE => dbms_repair.repair_table,
--     ACTION     => dbms_repair.create_action,
--     TABLESPACE => 'USERS');
--END;
--/
--DESC  REPAIR_TABLE
SELECT * FROM  DBA_ORPHAN_KEY_TABLE WHERE ROWNUM < 6
----------------------------------------------------------------
BEGIN
DBMS_REPAIR.ADMIN_TABLES (
     TABLE_NAME => 'ORPHAN_KEY_TABLE',
     TABLE_TYPE => dbms_repair.orphan_table,
     ACTION     => dbms_repair.create_action,
     TABLESPACE => 'USERS');
END;
--------------------------------------------------------------------
DECLARE num_corrupt INT;
BEGIN
num_corrupt := 0;
DBMS_REPAIR.CHECK_OBJECT (
  SCHEMA_NAME => 'SYS',
     OBJECT_NAME => 'AUD$',
     REPAIR_TABLE_NAME => 'REPAIR_TABLE',
     CORRUPT_COUNT =>  num_corrupt);
DBMS_OUTPUT.PUT_LINE('number corrupt: ' || TO_CHAR (num_corrupt));
END;

--------------------------------------------------------------------
--SELECT OBJECT_NAME, BLOCK_ID, CORRUPT_TYPE, MARKED_CORRUPT,
--       CORRUPT_DESCRIPTION, REPAIR_DESCRIPTION
--     FROM REPAIR_TABLE;
--SELECT OWNER, TABLE_NAME, SKIP_CORRUPT FROM DBA_TABLES
--    WHERE OWNER = 'SYS';
SELECT OBJECT_NAME, BLOCK_ID, CORRUPT_TYPE, MARKED_CORRUPT,
       CORRUPT_DESCRIPTION, REPAIR_DESCRIPTION
     FROM REPAIR_TABLE;
------------------------------------------------------------------
DECLARE num_fix INT;
BEGIN
num_fix := 0;
DBMS_REPAIR.FIX_CORRUPT_BLOCKS (
     SCHEMA_NAME => 'SYS',
     OBJECT_NAME=> 'AUD$',
     OBJECT_TYPE => dbms_repair.table_object,
     REPAIR_TABLE_NAME => 'REPAIR_TABLE',
     FIX_COUNT=> num_fix);
DBMS_OUTPUT.PUT_LINE('num fix: ' || TO_CHAR(num_fix));
END;
--------------------------------------------------------------------
--SELECT OBJECT_NAME, BLOCK_ID, MARKED_CORRUPT
--     FROM REPAIR_TABLE;
--SELECT COUNT(*) FROM AUD$
--DECLARE num_orphans INT;
--BEGIN
--num_orphans := 0;
--DBMS_REPAIR.DUMP_ORPHAN_KEYS (
--     SCHEMA_NAME => 'SYS',
--     OBJECT_NAME => 'I_AUD1',
--     OBJECT_TYPE => dbms_repair.index_object,
--     REPAIR_TABLE_NAME => 'REPAIR_TABLE',
--     ORPHAN_TABLE_NAME=> 'ORPHAN_KEY_TABLE',
--     KEY_COUNT => num_orphans);
--DBMS_OUTPUT.PUT_LINE('orphan key count: ' || TO_CHAR(num_orphans));
--END;

--alter table time_cards drop primary key;
--ALTER SYSTEM SET audit_trail=false SCOPE=SPFILE;
--shutdown immediate
--drop user CONTRACTREPO cascade
----------------------------------------------------------------------------------
select * from v$parameter where NAME like '%audit%'
--------------------------------------------------------------------------------
--SELECT tablespace_name, largest_free_chunk
--     , nr_free_chunks, sum_alloc_blocks, sum_free_blocks
--     , to_char(100*sum_free_blocks/sum_alloc_blocks, '09.99') || '%'
--       AS pct_free
--FROM ( SELECT tablespace_name
--            , sum(blocks) AS sum_alloc_blocks
--       FROM dba_data_files
--       GROUP BY tablespace_name
--     )
--   , ( SELECT tablespace_name AS fs_ts_name
--            , max(blocks) AS largest_free_chunk
--            , count(blocks) AS nr_free_chunks
--            , sum(blocks) AS sum_free_blocks
--               FROM dba_free_space
--               GROUP BY tablespace_name )
--WHERE tablespace_name = fs_ts_name
--SELECT USERNAME,DEFAULT_TABLESPACE FROM DBA_USERS
--drop user GOLD_STAGING5 cascade ;

--drop user GOLD_STAGING5 cascade ;
--create user contractrepo identified by contractrepo default tablespace  cleanser32k temporary tablespace temp
--grant connect, resource to contractrepo
--grant dba to gold_staging
------------------------------------------------------------------------------------------------
--select * from v$session
--alter system kill session '126,    159'
------------------------------------------------------------------------------------------------

    

DBA CHECK LIST

12) DBA CHECK LIST

--------------------------- A.    Daily Procedures  -----------------------------
-------------------------   1.    Free.sql
--   To verify free space in tablespaces --   Minimum amount of free space --   document your thresholds: --   = m

SELECT  tablespace_name, sum ( blocks ) as free_blk , trunc ( sum ( bytes ) / (1024*1024) ) as free_m, max ( bytes ) / (1024) as big_chunk_k,
count (*) as num_chunks
FROM dba_free_space
GROUP BY tablespace_name ;

----------------------     2.    Space.sql
---- space.sql ---- To check free, pct_free, and allocated space within a tablespace ---- 11/24/98

SELECT tablespace_name, largest_free_chunk , nr_free_chunks, sum_alloc_blocks, sum_free_blocks,
to_char(100*sum_free_blocks/sum_alloc_blocks, '09.99') || '%'  AS pct_free
FROM ( SELECT tablespace_name  , sum(blocks) AS sum_alloc_blocks  FROM dba_data_files GROUP BY tablespace_name )
   , ( SELECT tablespace_name AS fs_ts_name, max(blocks) AS largest_free_chunk , count(blocks) AS nr_free_chunks , sum(blocks) AS sum_free_blocks
       FROM dba_free_space GROUP BY tablespace_name )
WHERE tablespace_name = fs_ts_name;

--SELECT A.TABLESPACE_NAME,A.BYTES TOTAL,B.BYTES USED,C.BYTES FREE,round((B.BYTES*100)/A.BYTES) "% USED",round((C.BYTES*100)/A.BYTES) "% FREE"
--FROM SYS.SM$TS_AVAIL A, SYS.SM$TS_USED B, SYS.SM$TS_FREE C
--WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME AND A.TABLESPACE_NAME=C.TABLESPACE_NAME;
--------------------------------------- 3.    analyze5pct.sql
---- analyze5pct.sql ---- To analyze tables and indexes quickly, using a 5% sample size -- (do not use this script if you are performing the overnight
-- collection of volumetric data) ---- 11/30/98

----BEGIN
----   dbms_utility.analyze_schema ( '&OWNER', 'ESTIMATE', NULL, 5 ) ;
----END ;
-------------------------------------   4.    nr_extents.sql
---- nr_extents.sql -- To find out any object reaching   -- extents, and manually upgrade it to allow unlimited
-- max_extents (thus only objects we *expect* to be big -- are allowed to become big) ---- 11/30/98

SELECT e.owner, e.segment_type , e.segment_name , count(*) as nr_extents , s.max_extents, to_char ( sum ( e.bytes ) / ( 1024 * 1024 ) , '999,999.90') as MB
FROM dba_extents e , dba_segments s
WHERE e.segment_name = s.segment_name
GROUP BY e.owner, e.segment_type , e.segment_name , s.max_extents ;
--HAVING count(*) > &THRESHOLD
--    OR ( ( s.max_extents - count(*) ) < &&THRESHOLD )
--ORDER BY count(*) desc

--------------------------------5.    spacebound.sql
---- spacebound.sql ---- To identify space-bound objects.  If all is well, no rows are returned.
-- If any space-bound objects are found, look at value of NEXT extent -- size to figure out what happened.
-- Then use coalesce (alter tablespace coalesce;).  -- Lastly, add another datafile to the tablespace if needed. ---- 11/30/98

SELECT a.table_name, a.next_extent, a.tablespace_name
FROM all_tables a,( SELECT tablespace_name, max(bytes) as big_chunk FROM dba_free_space GROUP BY tablespace_name ) f
WHERE f.tablespace_name = a.tablespace_name AND a.next_extent > f.big_chunk;

--------------------------------------B.    Nightly Procedures

--1.    mk_volfact.sql -- mk_volfact.sql (only run this once to set it up; do not run it nightly!) -- -- -- Table UTL_VOL_FACTS

CREATE TABLE utl_vol_facts
 (
  table_name                 VARCHAR2(30),
  num_rows                   NUMBER,
  meas_dt                    DATE
 )
TABLESPACE platab
 STORAGE   (
      INITIAL     128k
      NEXT        128k
      PCTINCREASE 0
      MINEXTENTS  1
      MAXEXTENTS  unlimited
   )
/

-- Public Synonym

CREATE PUBLIC SYNONYM utl_vol_facts FOR &OWNER..utl_vol_facts
/

-- Grants for UTL_VOL_FACTS

GRANT SELECT ON utl_vol_facts TO public
/

----------------------------------------  2.    analyze_comp.sql
-- -- analyze_comp.sql --
BEGIN
   sys.dbms_utility.analyze_schema ( '&OWNER','COMPUTE');
END ;
/
---------------------------------------- 3.    pop_vol.sql
-- -- pop_vol.sql--
--insert into utl_vol_facts
select table_name
     , NVL ( num_rows, 0) as num_rows
     , trunc ( last_analyzed ) as meas_dt
from all_tables           -- or just user_tables
where owner in ('&OWNER') -- or a comma-separated list of owners
/
commit
/

------------------------------ C.    Weekly Procedures
-- 1.nextext.sql
-- To find tables that don't match the tablespace default for NEXT extent.The implicit rule here is that every table in a given tablespace should
-- use the exact same value for NEXT, which should also be the tablespace's  default value for NEXT.
-- This tells us what the setting for NEXT is for these objects today. 11/30/98

SELECT segment_name, segment_type, ds.next_extent as Actual_Next, dt.tablespace_name,  dt.next_extent as Default_Next
FROM dba_tablespaces dt, dba_segments ds
WHERE dt.tablespace_name = ds.tablespace_name
  AND dt.next_extent !=ds.next_extent
AND ds.owner = UPPER ( '&OWNER' )
ORDER BY tablespace_name, segment_type, segment_name;

--------------------------------2.    existext.sql
---- existext.sql
-- To check existing extents
-- This tells us how many of each object's extents differ in size from the tablespace's default size. If this report shows a lot of different
-- sized extents, your free space is likely to become fragmented.  If so,this tablespace is a candidate for reorganizing. 12/15/98

SELECT segment_name, segment_type, count(*) as nr_exts, sum ( DECODE ( dx.bytes,dt.next_extent,0,1) ) as nr_illsized_exts
, dt.tablespace_name, dt.next_extent as dflt_ext_size
FROM dba_tablespaces dt, dba_extents dx
WHERE dt.tablespace_name = dx.tablespace_name
  AND dx.owner = '&OWNER'
GROUP BY segment_name, segment_type, dt.tablespace_name, dt.next_extent;

------------------------------3.    No_pk.sql
-- no_pk.sql
-- To find tables without PK constraint  11/2/98

SELECT table_name
FROM all_tables
WHERE owner = '&OWNER'
MINUS
SELECT table_name
FROM all_constraints
WHERE owner = '&&OWNER'
AND constraint_type = 'P' ;

--4.    disPK.sql -- disPK.sql -- To find out which primary keys are disabled -- 11/30/98

SELECT owner, constraint_name, table_name, status
FROM all_constraints
WHERE owner = '&OWNER' AND status = 'DISABLED' AND constraint_type = 'P';

--5.    nonuPK.sql --  nonuPK.sql -- To find tables with nonunique PK indexes.  Requires that PK names follow a naming convention.
----An alternative query follows that does not have this requirement, but runs more slowly.-- 11/2/98

SELECT index_name, table_name, uniqueness
FROM all_indexes
WHERE index_name like '&PKNAME%'
  AND owner = '&OWNER' AND uniqueness = 'NONUNIQUE'

SELECT c.constraint_name, i.tablespace_name, i.uniqueness
FROM all_constraints c , all_indexes i
WHERE c.owner = UPPER ( '&OWNER' ) AND i.uniqueness = 'NONUNIQUE'
AND c.constraint_type = 'P' AND i.index_name = c.constraint_name

--6.    mkrebuild_idx.sql -- Rebuild indexes to have correct storage parameters -- 11/2/98

SELECT 'alter index ' || index_name || ' rebuild '
     , 'tablespace INDEXES storage '
     || ' ( initial 256 K next 256 K pctincrease 0 ) ; '
FROM all_indexes
WHERE ( tablespace_name != 'INDEXES'
        OR next_extent != ( 256 * 1024 )
      )
  AND owner = '&OWNER'
/

--7.    datatype.sql ---- To check datatype consistency between two environments -- 11/30/98

SELECT table_name, column_name, data_type, data_length, data_precision, data_scale, nullable
FROM all_tab_columns -- first environment
WHERE owner = '&OWNER'
MINUS
SELECT table_name, column_name, data_type, data_length, data_precision, data_scale, nullable
FROM all_tab_columns@&my_db_link  -- second environment
WHERE owner = '&OWNER2'
order by table_name, column_name

--8.    obj_coord.sql -- To find out any difference in objects between two instances -- 12/08/98

SELECT object_name, object_type
FROM user_objects
MINUS
SELECT object_name, object_type
FROM user_objects@&my_db_link

----VI.    References
----
----1.    Loney, Kevin  Oracle8 DBA Handbook
----2.    Cook, David  Database Management from Crisis to Confidence
----[http://www.orapub.com/]
----3.    Cox, Thomas B.  The Database Administration Maturity Model

Cursors

CURSORS

------------------/* OPEN CURSOR (HIGHEST_OPEN_CUR) */--------------------------
select max(a.value) as highest_open_cur, p.value as max_open_cur
  from v$sesstat a, v$statname b, v$parameter p
  where a.statistic# = b.statistic#  and b.name = 'opened cursors current' and p.name= 'open_cursors'
 group by p.value;
--------------------------------------     open cursors with machine name
select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur,s.OSUSER,s.username,s.machine ,name
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid and b.name like '%opened cursors%'
group by s.username, s.machine,s.OSUSER,name
order by 1 desc;
------------------------------------------------------------------
--------------------------total cursors open, by session
select sum(value) from ( select a.value, s.username, s.sid, s.serial# from v$sesstat a, v$statname b, v$session s
                         where a.statistic# = b.statistic#  and s.sid=a.sid and b.name = 'opened cursors current' );

----------------------------------------------/* HIGHEST OPEN CURSORS */---------------------------
select max(a.value) as highest_open_cur, p.value as max_open_cur
from v$sesstat a, v$statname b, v$parameter p
where a.statistic# = b.statistic# and b.name = 'opened cursors current' and p.name= 'open_cursors'
group by p.value;
--SELECT * FROM V$DATAFILE WHERE NAME LIKE '%GOLD%'
--ALTER TABLESPACE GOLD32K ADD DATAFILE '/usr/oracle/oracle/product/10.2.0/db_1/oradata/proddb/GOLD32K37.dbf' SIZE 4096M
--------------------------------------/* OPEN CURSROS BY SESSION */------------------------------------
select a.value, s.username, s.sid, s.serial#
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic#  and s.sid=a.sid and b.name = 'session cursor cache count' ;
----------------------------------------/* OPEN CURSORS WITH SQL TEXT */---------------------
select c.user_name, c.sid, sql.sql_text
from v$open_cursor c, v$sql sql
where c.sql_id=sql.sql_id  -- for 9i and earlier use: c.address=sql.address
and c.sid=&sid;
------------------------------------------------/* SESSION CACHE CURSORS */----------------------
select cach.value cache_hits, prs.value all_parses, prs.value-cach.value sess_cur_cache_not_used
from v$sesstat cach, v$sesstat prs, v$statname nm1, v$statname nm2
where cach.statistic# = nm1.statistic# and nm1.name = 'session cursor cache hits' and prs.statistic#=nm2.statistic# and nm2.name= 'parse count (total)'
and cach.sid= &sid and prs.sid= cach.sid ;
----------------------------------------------/* COMPARE CACHE */---------------------------------
--session cached cursors, for a given SID, compared to max
select a.value curr_cached, p.value max_cached, s.username, s.sid, s.serial#
from v$sesstat a, v$statname b, v$session s, v$parameter2 p
where a.statistic# = b.statistic#  and s.sid=a.sid and a.sid=&sid and p.name='session_cached_cursors' and b.name = 'session cursor cache count';
--------------------------------/* LIST ALL OBJECTS CORRUPTED  */-----------------------
select a.FILE#,a.block#,segment_name,owner,tablespace_name
from V$DATABASE_BLOCK_CORRUPTION a, dba_extents b where a.file#=b.file_id and a.block#=b.block_id ;

----------------------------------------------------------------------------------------------------------------------
--1.------- TO FIND CURSORS
----select USERNAME,count(USERNAME) from v$session where osuser = 'root'  group by USERNAME
select distinct NAME from V$STATNAME where NAME like '%cursor%';

--------2.
select --sum(to_number(PROCESS))
distinct SID,USER#,USERNAME,OSUSER,PROCESS,program,module from v$session; ----v$sysstat;

--------3. select *from v$open_cursor
------------4. TO FIND CURSOR VALUE
--SELECT v$session.SID,USERNAME, VALUE FROM V$SESSTAT , V$STATNAME ,v$session
--WHERE V$SESSTAT.STATISTIC# = V$STATNAME.STATISTIC# and NAME LIKE 'opened cursors current'
--and V$SESSTAT.sid=v$session .sid

SELECT v$session.SID,USERNAME, VALUE,name FROM V$SESSTAT , V$STATNAME ,v$session
WHERE V$SESSTAT.STATISTIC# = V$STATNAME.STATISTIC# and NAME LIKE '%cursors%'and V$SESSTAT.sid=v$session .sid ;

----------5. MAIN QUERY FOR SUM OF OPENED CURSORS FOR EACH USER

SELECT distinct USERNAME, sum(VALUE),name FROM V$SESSTAT , V$STATNAME ,v$session
WHERE V$SESSTAT.STATISTIC# = V$STATNAME.STATISTIC# and NAME LIKE '%cursors%'
and V$SESSTAT.sid=v$session .sid and username is not null
group by USERNAME,name order by 1 ;

SELECT distinct USERNAME, sum(VALUE) FROM V$SESSTAT , V$STATNAME ,v$session
WHERE V$SESSTAT.STATISTIC# = V$STATNAME.STATISTIC# and NAME LIKE '%cursors%'
and V$SESSTAT.sid=v$session .sid and username is not null
group by USERNAME order by 1 ;

----------1.  SUM ALL OPENED CURSORS
select   user_process username,"Recursive Calls","Opened Cursors","Current Cursors"
from  (    select   nvl(ss.USERNAME,'ORACLE PROC')||'('||se.sid||') ' user_process,
                                    sum(decode(NAME,'recursive calls',value)) "Recursive Calls",
                                    sum(decode(NAME,'opened cursors cumulative',value)) "Opened Cursors",
                                    sum(decode(NAME,'opened cursors current',value)) "Current Cursors"
            from      v$session ss, v$sesstat se, v$statname sn
            where    se.STATISTIC# = sn.STATISTIC#
            and       (NAME  like '%opened cursors current%' or NAME  like '%recursive calls%' or NAME  like '%opened cursors cumulative%')
            and       se.SID = ss.SID
            and       ss.USERNAME is not null
            group    by nvl(ss.USERNAME,'ORACLE PROC')||'('||se.SID||') '
) orasnap_user_cursors
order     by USER_PROCESS,"Recursive Calls";
------------------------------------------------------/* SIZE OF SCHEMAS */---------------------------
----SELECT * FROM CL_CONTRACTS WHERE ROWNUM<10
--SELECT * FROM DBA_TABLESPACES

-----------------------------
--SELECT ---tablespace_name,
--Sum(bytes)/1024/1024 AS total_size_mb,Sum(bytes)/1024/1024/1024 AS total_size_gb
--FROM dba_segments;
--------------------------
----SELECT tablespace_name,
----Sum(bytes)/1024/1024 AS total_size_mb,Sum(bytes)/1024/1024/1024 AS total_size_gb
----FROM dba_segments
----group by tablespace_name
---------------------------- SIZE OF SCHEMAS
SELECT owner,Sum(bytes)/1024/1024 AS total_size_mb,Sum(bytes)/1024/1024/1024 AS total_size_gb
FROM dba_segments
group by owner order by 1 ;
----------------------------------------------------/* KILL THE SESSION */------------------
----select * from dual
--SELECT s.sid,       s.serial#,       s.osuser,       s.program FROM   v$session s;
select s.sid,s.serial#,s.program,sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur,s.OSUSER,s.username,s.machine ,name
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid
and b.name like '%opened cursors%' --and OSUSER like '%vkrishna%'
group by s.username, s.machine,s.OSUSER,name,s.sid,s.serial#,s.program
order by 4 desc;


select   b.username,   a.sql_text
from    v$sqltext_with_newlines a,   v$session b,   v$process c
where   c.spid = to_number('300', 'xxx') and    c.addr = b.paddr and   b.sql_address = a.address;

------------------/*   DISPLAYS ALL CONNECTED SESSIONS  */-------------

select rpad(c.name||':',11)||rpad(' current logons='|| (to_number(b.sessions_current)),20)||'cumulative logons='||
      rpad(substr(a.value,1,10),10)||'highwater mark='|| b.sessions_highwater Information
from   v$sysstat a,   v$license b,   v$database c
where a.name = 'logons cumulative';

--------------------------ttitle "dbname Database|UNIX/Oracle Sessions";
select 'Sessions on database '||substr(name,1,8) from v$database;
select substr(a.spid,1,9) pid,substr(b.sid,1,5) sid,substr(b.serial#,1,20) ser#,substr(b.machine,1,30) box,substr(b.username,1,10) username,-- b.server,
   substr(b.osuser,1,8) os_user,substr(b.program,1,30) program
from v$session b,v$process a
where b.paddr = a.addr and type='USER'
order by spid;
--------ttitle off;
----set heading off;
----select 'To kill, enter SQLPLUS> ALTER SYSTEM KILL SESSION',
----''''||'SID, SER#'||''''||';' from dual;

Select user,OSUSER,MACHINE,'alter system kill session '''||sid||','||serial#||''''
From v$session
Where --status = 'INACTIVE'
status = 'ACTIVE';
----And last_call_et > 7200;
alter system kill session '1857,44693'  IMMEDIATE;;
desc v$session;
--------------The SID and SERIAL# values of the relevant session can then be substituted into the following statement:

------ALTER SYSTEM KILL SESSION 'sid,serial#'
--alter system kill session '300,4035';

--In some situations the Oracle.exe is not able to kill the session immediately. In these cases the session will be "marked for kill".
--It will then be killed as soon as possible.Issuing the ALTER SYSTEM KILL SESSION command is the only safe way to kill an Oracle session.
--If the marked session persists for some time you may consider killing the process at the operating system level.
--However, this is not recommended as it is dangerous and can lead to instance failures.
--
--It is possible to force the kill by adding the IMMEDIATE keyword:

--ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE
--ALTER SYSTEM KILL SESSION '3267,1025' IMMEDIATE;

/* Kill Sessions Script */
--set serveroutput on
--BEGIN
--IF USER = 'SYS' THEN
--FOR i IN (SELECT sid ,s.serial# ,p.spid ,osuser ,status ,round((last_call_et / 60)) AS idle_time
--FROM v$session s ,v$process p WHERE p.addr = s.paddr AND status = 'INACTIVE' AND round((last_call_et / 60)) > 15
--ORDER BY osuser)
--LOOP dbms_output.put_line(rpad(i.osuser, 20, '.') || ' SPID ' || rpad(i.spid, 10, '.') || ' SID ' || rpad(i.sid, 10, '.') || ' SERIAL# ' || rpad(i.serial#, 10, '.'));
--EXECUTE IMMEDIATE 'Alter system kill session ' || '''' || i.sid || ',' || i.serial# || '''';
--END LOOP;
--END IF;
--END;
--/ exit; /* Batch file */ Save above script in file named killsession.sql. Save following string into file named killsession.bat
--and add .bet file into window scheduler. sqlplus sys/sgoracle@db15 as sysdba @killsession.sql
-----------------------------/* FIND THE LOCKED OBJECTS */---------------------

--------To avoid having to stare at the table and cross-compare ID1's and ID2's, put this in a query:
--select l1.sid, ' IS BLOCKING ', l2.sid
--from v$lock l1, v$lock l2 where l1.block =1 and l2.request > 0 and l1.id1=l2.id1 and l1.id2=l2.id2;
--
--
--select c.owner,c.object_name,c.object_type,b.sid,b.serial#,b.status,b.osuser,b.machine
--from v$locked_object a ,v$session b,dba_objects c
--where b.sid = a.session_id and a.object_id = c.object_id;
--
--alter system kill session '2141,211'  IMMEDIATE;;

----  SELECT *FROM V$SESSION WHERE STATUS='ACTIVE'
--SELECT * FROM V$SQLAREA WHERE SQL_ID='ggn0bnsv2849y'

Data Base Audit Queries

1)

SELECT 'SYSTEM AUDIT PERFOMED BY DB USER '||USER ||' AT ' || SYSTIMESTAMP AS "SYS AUDIT INFORMATION"
FROM dual

SELECT * FROM (
SELECT name,current_value,recommend_value
        FROM
            (SELECT name,value current_value,
                    (CASE/* General*/

                        WHEN LOWER(name) = 'open_cursors' AND TO_NUMBER(value) <> 512 THEN 'Recommended setting is 512'

                        WHEN LOWER(name) = 'cursor_sharing' AND LOWER(value) <> 'exact' THEN 'Not OK. Set the value to EXACT'

                        WHEN LOWER(name) = 'session_cached_cursors' AND TO_NUMBER(value) < 400 THEN 'Not OK. Set the parameter to 400'

                        WHEN LOWER(name) = 'db_block_checksum' AND LOWER(value) <> 'true' THEN 'Not OK. Set the parameter to TRUE'

                        WHEN LOWER(name) = 'db_files' AND TO_NUMBER(value) < 500 THEN 'Set the parameter to 500'

                        WHEN LOWER(name) = 'query_rewrite_enabled' AND LOWER(value) <> 'true' THEN 'Not OK. Set the parameter to TRUE'

                        WHEN LOWER(name) = 'query_rewrite_integrity' AND LOWER(value) <> 'trusted' THEN 'Not OK. Set the parameter to TRUSTED'

                        /*Optimizer*/

                        WHEN LOWER(name) = 'optimizer_mode' AND LOWER(value) <> 'first_rows' THEN 'Not OK. Set the parameter to FIRST_ROWS'

                        WHEN LOWER(name) = 'optimizer_index_caching' AND TO_NUMBER(value) <> 90 THEN 'Recommended setting is 90'

                        WHEN LOWER(name) = 'optimizer_index_cost_adj' AND TO_NUMBER(value) <> 25 THEN 'Recommended setting is 25'

                        WHEN LOWER(name) = '_sort_elimination_cost_ratio' AND TO_NUMBER(value) <> 4 THEN 'Recommended setting is 4'

                        WHEN LOWER(name) = '_b_tree_bitmap_plans' AND LOWER(value) <> 'false' THEN 'Not OK. Set the parameter to FALSE'

                        WHEN LOWER(name) = 'optimizer_dynamic_sampling' AND TO_NUMBER(VALUE) <= 1 THEN 'Set it to atleast 2. This will help in accessing data from global temporary tables as upto date statistics may not be available for temporary tables'

                        WHEN LOWER(name) = 'db_file_multiblock_read_count' AND TO_NUMBER(value) > 8 THEN 'Recommended setting is 8 for a OLTP system'

                        /*Auto Management*/

                        WHEN LOWER(name) = 'workarea_size_policy' AND LOWER(value) <> 'auto' THEN 'Not OK. Set the parameter to AUTO'

                        WHEN LOWER(name) = 'pga_aggregate_target' AND TO_NUMBER(value) < 1073741824 THEN 'Not OK. Recommended setting is 1073741824 (1g)'

                        WHEN LOWER(name) = 'sort_area_size' AND TO_NUMBER(value) < 1048576 THEN    'Increase to 1048576. (Ok, if pga_aggregate_target/work_area_policy are used)'

                        WHEN LOWER(name) = 'sort_area_retained_size' AND TO_NUMBER(value) < 16384 THEN'Increase to 16384. (Ok, if pga_aggregate_target/work_area_policy are used)'

                        /*Auto UNDO management*/

                        WHEN LOWER(name) = 'undo_management' AND LOWER(value) <> 'auto' THEN 'Not OK. Set the parameter to AUTO'

                        WHEN LOWER(name) = 'undo_retention' AND TO_NUMBER(value) <> 900 THEN 'Not OK. Recommended setting is 900'

                        /*Memory Management*/

                        WHEN LOWER(name) = 'db_cache_size' AND TO_NUMBER(value) < 1610612736 THEN 'Not OK. Increase to 1610612736 (1.5g) minimum. Recommended is 2147483648 (2g)'

                        WHEN LOWER(name) = 'db_cache_advice' AND LOWER(value) <> 'off' THEN 'Not OK. Set the parameter to OFF'

                        WHEN LOWER(name) = 'db_block_size' AND TO_NUMBER(value) <> 8192 THEN 'Not OK. Set the parameter to 8192 (8 kb)'

                        WHEN LOWER(name) = 'db_block_buffers' AND TO_NUMBER(value) <> 0 THEN 'Not OK. Set the parameter to 0 (zero)'

                        WHEN LOWER(name) = 'sga_max_size' AND TO_NUMBER(value) < 3221225472 THEN 'Not OK. Increase to 3221225472 (3g) (recommended)'

                        WHEN LOWER(name) = 'sga_target' AND TO_NUMBER(value) < 3221225472 THEN 'Not OK. Increase to 3221225472 (3g) (recommended)'

                        WHEN LOWER(name) = 'log_checkpoint_interval' AND TO_NUMBER(value) <> 0 THEN 'Not OK. Set the parameter to 0 (zero)'

                        WHEN LOWER(name) = 'shared_pool_size' AND TO_NUMBER(value) < 419430400 THEN 'Not OK. Increase to 419430400 (400m) minimum (recommended)'

                        WHEN LOWER(name) = 'shared_pool_reserved_size' AND TO_NUMBER(value) < 16777216 THEN 'Not OK. Increase to 16777216 (16m) mininum (recommended)'

                        WHEN LOWER(name) = 'log_buffer' AND TO_NUMBER(value) < 1048576 THEN 'Not OK. Increase to 1048576 (1m)'

                        WHEN LOWER(name) = 'processes' AND TO_NUMBER(value) <> 500 THEN 'Recommended setting is 500'

                        /*Recovery*/

                        WHEN LOWER(name) = 'fast_start_mttr_target' AND TO_NUMBER(value) <> 900 THEN 'Recommended setting is 900'

                        WHEN LOWER(name) = 'log_archive_start' AND LOWER(value) <> 'true' THEN 'Not Archiving?. Set the parameter to TRUE. Production databases should run under ARCHIVELOG mode'

                        /*Shared Server*/

                        WHEN LOWER(name) = 'shared_servers' AND TO_NUMBER(value) <> 0 THEN 'Not OK. Set the parameter to 0 (zero)'

                        WHEN LOWER(name) = 'dispatchers' AND UPPER(value) NOT LIKE '(PROTOCOL=TCP)%' THEN 'Not OK. Set the parameter to default'

                        /*Other*/

                        WHEN LOWER(name) = 'parallel_automatic_tuning' AND LOWER(value) <> 'false' THEN 'Not OK. Set the parameter to FALSE'

                        WHEN LOWER(name) = 'parallel_adaptive_multi_user' AND LOWER(value) <> 'false' THEN 'Not OK. Set the parameter to FALSE'

                        WHEN LOWER(name) = 'parallel_max_servers' AND TO_NUMBER(value) > 5 THEN 'Not OK. Set the parameter value to 5 (default)'

                        WHEN LOWER(name) = 'skip_unusable_indexes' AND LOWER(value) <> 'true' THEN 'Not OK. Set the parameter to TRUE'

                        WHEN LOWER(name) = 'plsql_optimize_level' AND TO_NUMBER(value) <> 1 THEN 'Not OK. Set the parameter value to 1'

                        WHEN LOWER(name) = 'audit_trail' AND (LOWER(value) not in ('none','false')) THEN 'Not OK. Audit is not recommended due to performance overhead'

                        /*Information*/

                        WHEN LOWER(name) = 'cluster_database' AND LOWER(value) = 'true' THEN 'OK. Database setup with RAC'

                            ELSE 'OK'

                                END) recommend_value

                                    FROM v$parameter
        UNION
            SELECT '_b_tree_bitmap_plans', 'Not Set', 'Add this parameter in your init.ora and set to FALSE'

                    FROM DUAL

                        WHERE NOT EXISTS

                            (SELECT 1

                                FROM v$parameter

                                  WHERE name = '_b_tree_bitmap_plans')
        UNION
            SELECT '_sort_elimination_cost_ratio', 'Not Set', 'Add this parameter in your init.ora and set it to 4'
                    FROM DUAL
                        WHERE NOT EXISTS
                             (SELECT 1
                            FROM v$parameter
                                WHERE name = '_sort_elimination_cost_ratio'))
                                ) a
                                 where RECOMMEND_VALUE <> 'OK'  ;

2) NLS PARAMETER SETTINGS

SELECT parameter,current_value,recommend_value FROM (SELECT parameter,value current_value,

(CASE WHEN LOWER(parameter) = 'nls_length_semantics' AND LOWER(value) <> 'char' THEN 'Change the semantics to CHAR'

      WHEN LOWER(parameter) = 'nls_characterset' AND LOWER(value) NOT IN ('utf8', 'al32utf8') THEN 'Database CharacterSet should be atleast UTF8 (Unicode)'

      ELSE  NULL END) recommend_value

FROM v$nls_parameters) ;

3) DB INFO

SELECT name,TO_CHAR(created, 'DD-MON-YYYY HH24:MI') AS created,TO_CHAR(resetlogs_time, 'DD-MON-YYYY HH24:MI') AS resetlogs_time,log_mode,open_mode,

database_role,protection_mode

FROM v$database ;

4) DB VERSION

SELECT * FROM v$version ;

5) USER AND TABLESPACE INFORMATION

SELECT username,default_tablespace,temporary_tablespace FROM dba_users
WHERE username ='CONTRACTREPO' ORDER BY username ;

6) SGA Size :

SHOW SGA

7) Database Archival:

ARCHIVE LOG LIST

8) Database Instance Information

SELECT instance_name,host_name,TO_CHAR(startup_time, 'DD-MON-YYYY HH24:MI') startup_time,version,status FROM v$instance;

9) Database Log Information

SELECT * FROM v$log;

10) Database Log Files Information

SELECT * FROM v$logfile ;

11) Database Control Files Information

SELECT status,name FROM v$controlfile;

12) HARED POOL USAGE IN MB

SELECT SUM(a.Bytes)/1048576 AS Shared_Pool_Used,MAX(b.Value)/1048576 AS Shared_Pool_Size,

(MAX(b.Value)/1048576)-(SUM(a.Bytes)/1048576) AS Shared_Pool_Avail,(SUM(a.Bytes)/MAX(b.Value))*100 AS Shared_Pool_Pct

FROM v$SgaStat a,v$Parameter b

WHERE a.Pool = 'shared pool' AND a.Name != 'free memory' AND b.Name = 'shared_pool_size'  ;

13) MEMORY ALLOCATION DATA

SELECT * FROM(SELECT NAME, BYTES/(1024*1024) MB FROM V$SGASTAT WHERE POOL = 'shared pool'ORDER BY BYTES DESC)WHERE ROWNUM <= 10;

14) Database Tablespace Information

SELECT tablespace_name,status,block_size,contents,extent_management,allocation_type,segment_space_management

FROM dba_tablespaces ;

15) Datafile Information

SELECT tablespace_name,file_name FROM dba_data_files UNION SELECT tablespace_name,file_name FROM dba_temp_files ORDER BY tablespace_name ;

16) OBJECTS THAT NEED TO PINNED IN SHARED POOL

SELECT owner||'.'||name as object_name,type as object_type,

'EXEC DBMS_SHARED_POOL.Keep('||chr(39)||OWNER||'.'||name||chr(39)||','||

chr(39)||decode(type,'PACKAGE','P','PROCEDURE','P','FUNCTION','P','SEQUENCE','Q','TRIGGER','R')||chr(39)||')' as pin_command

FROM v$db_object_cache

WHERE type NOT IN ('NOT LOADED','NON-EXISTENT','VIEW','TABLE','INVALID TYPE','CURSOR','PACKAGE BODY')

AND executions > loads AND executions > 1 AND kept='NO' AND OWNER <> 'SYS' ORDER BY owner, namespace, type, executions DESC ;

17) DBA Jobs Information

SELECT job,log_user,schema_user,TO_CHAR(last_date, 'DD-MON-YYYY HH24:MI') AS last_date,TO_CHAR(next_date, 'DD-MON-YYYY HH24:MI') AS next_date,

(total_time/60) AS total_time_min,failures

FROM dba_jobs ;

18) DBA Job Description

SELECT job,what FROM dba_jobs;

19) DBA SYS Privileges

SELECT grantee, privilege FROM dba_sys_privs WHERE grantee NOT IN (SELECT username FROM dba_users) ORDER by grantee;

20) DBA Roles

SELECT role FROM dba_roles ORDER BY role;

21) DBA Role Privileges

SELECT grantee, granted_role FROM dba_role_privs WHERE grantee NOT IN (SELECT username FROM dba_users) ORDER BY grantee ;

Machine Connections

1) MACHINE CONNECTIONS

SELECT USERNAME,COUNT(USERNAME)COUNT,SCHEMANAME,STATUS,OSUSER, MACHINE,PROGRAM ,to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS') TIME
------------------LOGON_TIME
FROM V$SESSION
WHERE MODULE = 'JDBC Thin Client' and osuser='root'
----AND SCHEMANAME='GOLD_STAGING'  osuser='root' AND TO_DATE(LOGON_TIME)=TO_DATE(SYSDATE)
GROUP BY USERNAME,STATUS,SCHEMANAME,OSUSER, MACHINE,PROGRAM order by 1;


select parsing_schema_name,user_io_wait_time,EXECUTIONS,first_load_time,last_load_time,module,sql_fulltext
from v$sql where  MODULE = 'JDBC Thin Client' --and USER_IO_WAIT_TIME > 100
and TO_DATE(SUBSTR(first_load_time,1,10),'YYYY-MM-DD') in ('08-04-2009')
----            BETWEEN '07-31-2009' AND to_date(sysdate,'mm-dd-yyyy')
where first_load_time like '2009-07-15%' and MODULE = 'JDBC Thin Client' and USER_IO_WAIT_TIME > 100
ORDER BY FIRST_LOAD_TIME

2) CURRENT RUNNIG QUERY

SELECT a.USERNAME, b.sql_text, a.STATUS FROM V$SESSION a INNER JOIN V$SQLAREA b ON a.SQL_ID = b.SQL_ID;

select SUBSTR(nvl(USERNAME,'ORACLE PROC')||'('||s.SID||')',1,12) username,SUBSTR(OSUSER,1,20) OSUSER,SUBSTR(MACHINE,1,20) MACHINE,MODULE,SQL_TEXT SQL_TEXT
from     v$open_cursor oc, v$session s
where     s.SQL_ADDRESS = oc.ADDRESS
and     s.SQL_HASH_VALUE = oc.HASH_VALUE AND MODULE = 'JDBC Thin Client'
order by SUBSTR(OSUSER,1,25);

SELECT USERNAME,COUNT(USERNAME)
FROM V$SESSION WHERE USERNAME IN ('GOLD_STAGING','CLEANSER','CONTRACTREPO')
GROUP BY USERNAME,SCHEMANAME

3) LIST ALL OBJECTS CORREPTED

select OWNER,SEGMENT_NAME,sum(BYTES)
from dba_segments group by OWNER,SEGMENT_NAME order by SEGMENT_NAME

select a.FILE#,a.block#,segment_name,owner,tablespace_name
from V$DATABASE_BLOCK_CORRUPTION a, dba_extents b where a.file#=b.file_id and a.block#=b.block_id;

SELECT SWITCHOVER_STATUS FROM V$DATABASE;

select * from dba_tables where table_name like '%AUD%'

TRUNCATE TABLE FGA_LOG$;

TRUNCATE TABLE AUD$;

4) Execute the following query to see if your database was started with a PFILE or SPFILE

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type"
FROM sys.v_$parameter WHERE name = 'spfile';

5) PARENT CHILD RELATION

SELECT PARENT.TABLE_NAME PARENT, CHILD.TABLE_NAME CHILD
FROM USER_CONSTRAINTS PARENT, USER_CONSTRAINTS CHILD
WHERE CHILD.CONSTRAINT_TYPE='R'
AND PARENT.CONSTRAINT_NAME=CHILD.R_CONSTRAINT_NAME
AND PARENT.OWNER = CHILD.OWNER
ORDER BY PARENT.TABLE_NAME, CHILD.TABLE_NAME;

6) PARENT CHILD RELATION FOR ALL SCHEMAS

SELECT DISTINCT P.CONSTRAINT_TYPE,P.CONSTRAINT_NAME PARENT_CONS,P.TABLE_NAME PARENT,C.CONSTRAINT_TYPE,C.CONSTRAINT_NAME CHILD_CONS,C.TABLE_NAME CHILD
FROM DBA_CONSTRAINTS P, DBA_CONSTRAINTS C
WHERE P.CONSTRAINT_NAME=C.R_CONSTRAINT_NAME AND C.CONSTRAINT_TYPE='R' AND C.TABLE_NAME ='OMS_CLIENTS'
ORDER BY 3

----select DEST_NAME,STATUS,DESTINATION from V$ARCHIVE_DEST;

7) OPENED CONNECTIONS IN ORACLE

select type,substr(a.spid,1,9) pid,substr(b.sid,1,5) sid,substr(b.serial#,1,5) ser#,substr(b.machine,1,50) box,substr(b.username,1,50) username,--b.server,
       substr(b.osuser,1,8) os_user,substr(b.program,1,30) program
from v$session b, v$process a
where b.paddr = a.addr and type='USER'
order by spid;

8) SHOW ORACLE PROCESS IN DETAIL

select     substr(s.username,1,18) username,s.OSUSER,substr(s.program,1,15) program,
        decode(s.command,0,'No Command',1,'Create Table',2,'Insert',3,'Select',6,'Update',7,'Delete',9,'Create Index',15,'Alter Table',21,'Create View',
        23,'Validate Index',35,'Alter Database',39,'Create Tablespace',41,'Drop Tablespace',40,'Alter Tablespace',53,'Drop User',62,'Analyze Table',
       63,'Analyze Index',s.command||': Other') command
from v$session     s,v$process     p,v$transaction t,v$rollstat    r,v$rollname    n
where s.paddr = p.addr and   s.taddr = t.addr (+) and   t.xidusn = r.usn (+) and   r.usn = n.usn (+)
order by 1;

9) DB STARTUP TIME

SELECT to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time"
FROM   sys.v_$instance;

SElect * from v$session where STATUS='ACTIVE'