How to enable archive log mode

In 10g Automatic archival is default.
But to set up the database is archival mode includes the following steps.

Shutdown the database

SQL > shutdown immediate;

Startup the database in mount mode

SQL > startup mount;

Change DB log mode

SQL > alter database archivelog;

Open the database

SQL > alter database open;

We can check the Db archivelog mode with the following query

SQL > select log_mode from v$database;
                       (or)
SQL > archive log list;

CPU Usage By Session
select nvl(ss.USERNAME,'ORACLE PROC') username,
se.SID,ss.status,
VALUE cpu_usage
from v$session ss,
v$sesstat se,
v$statname sn
where se.STATISTIC# = sn.STATISTIC#
and NAME like '%CPU used by this session%'
and se.SID = ss.SID and ss.username='%PROD%'
order by VALUE desc
/

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

Description

Script displays details so the session which have used the most CPU. Needs the Init.Ora parameter timed_statistics set to true to work.


col program form a30 heading "Program"
col CPUMins form 99990 heading "CPU Mins"
select rownum as rank, a.*
from (
    SELECT v.sid, program, v.value / (100 * 60) CPUMins
    FROM v$statname s , v$sesstat v, v$session sess
   WHERE s.name = 'CPU used by this session'
     and sess.sid = v.sid
     and v.statistic#=s.statistic#
     and v.value>0
   ORDER BY v.value DESC) a
where rownum < 11;

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


Resource Usage by a User:


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

select ses.SID,
nvl(ses.USERNAME,'ORACLE PROC') username,
sn.NAME statistic,
sest.VALUE
from v$session ses,
v$statname sn,
v$sesstat sest
where ses.SID = sest.SID
and sn.STATISTIC# = sest.STATISTIC#
and sest.VALUE is not null
and sest.VALUE != 0
order by ses.USERNAME, ses.SID, sn.NAME
/ 

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



AWR reports MANUAL SNAPSHOT 

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

SQL> exec dbms_workload_repository.create_snapshot;

PL/SQL procedure successfully completed.
------------------------------------------------------

As well we can change the retention period and the snapshot interval. In the example below we change the

retention period to 5 days ( 5 x 24 x 60 ) and the snapshot interval to 30 minutes.

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

SQL> exec dbms_workload_repository.modify_snapshot_settings (retention => 7200,interval => 30);

PL/SQL procedure successfully completed.


select * from dba_hist_wr_control;


exec DBMS_WORKLOAD_REPOSITORY.drop_snapshot_range (low_snap_id  => 3020,high_snap_id => 3040);

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


CREATE DATABASE LINK

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

create database link BHA_LINK.WORLD
connect to BHA_USER
identified by "BHARGAV"
using 'BHATNS';

GRANT CREATE DATABASE LINK TO BHA_USER;

Create synonym BHA_SYNM for BHATEST2.BHARGAV@BHA_LINK.WORLD;

--------------------------------------------
select host,username, db_link from dba_db_links order by host, username, db_link;

 set lines 200
 set pages 300
 col USERNAME for a25
 col PROFILE for a20
 col USERNAME for a20
 col HOST for a30


select OWNER,
        DB_LINK,
        USERNAME,
        HOST,
        to_char(CREATED,'MM/DD/YYYY HH24:MI:SS') created
from    dba_db_links
order   by OWNER,DB_LINK;

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


creation of Password file



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

$ORACLE_HOME/bin/orapwd file=$ORACLE_HOME/dbs/orapwBHATEST password=[REDACTED] entries=5

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

Sequences

To reset the value of a Sequence:

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

SQL> alter sequence x increment by -4;
Sequence altered.


SQL> SELECT X.NEXTVAL FROM DUAL;
1


SQL> alter sequence x increment by 1;
Sequence altered.

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

DEPENDENCIES OF A SEQUENCE:

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

 set lines 132

select distinct
   owner,
   name,
   referenced_name
from
   dba_dependencies
where
   type in ('PACKAGE BODY','PROCEDURE','TRIGGER')
and
   referenced_type = 'SEQUENCE';

select
   referenced_name,
   referenced_type
from
   dba_dependencies
where
   name='my_tablename';

----------------------------------------
 Synonyms


To Create Private Synonym:
-----------------------------------------------------------

create or replace synonym UDW1_DBA.DW_EV_BESHEB for DW1_DBA.DW_EV_BESHEB;


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

To create Public Synonym:
------------------------------------------------------------


create or replace public synonym DW_EV_BESHEB for DW1_DBA.DW_EV_BESHEB;


Data file queries
Adding Datafile to a Tablespace:
-----------------------------------------------------
Check whether mount point has sufficient space

        df -k mount_point

Check the available space in the existing tablespace

select sum(bytes)/1024/1024/1024 "GB_Allot",tablespace_name  from dba_data_files
where tablespace_name='PIAS_ACTIVITY_IS'
group by tablespace_name;

Adding datafile to the tablespace

alter tablespace PIAS_ACTIVITY_IS  add datafile
'/dev/oasvg_ops_40/rpoas_activity_is_20' size 1999M;

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

Manually Resizing a Datafile:
--------------------------------------------------------


ALTER DATABASE DATAFILE '/oracle/data/icmn/mna1/vol10/icmnmna1.tools.a001.dbf'
RESIZE 1000M;

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

How to Rename(change path) of a Non-System datafile:
--------------------------------------------------------

   1. Login to SQLPlus.

   2. Connect as SYS DBA with CONNECT / AS SYSDBA command.
                       "/ as sysdba"

   3. Make offline the affected tablespace with ALTER TABLESPACE  OFFLINE; command.
                       " ALTER TABLESPACE tablespace_name OFFLINE;"
       
   4. Rename or/and move the datafiles at operating system level.
                       " cp datafile_path/filename to datafile_path/filename"

   5. Modify the name or location of datafiles in Oracle data dictionary using following command syntax:
                        "ALTER DATABASE RENAME FILE ‘Old Path/filename’ TO ‘New Path/filename’;"

   6. Bring the tablespace online again with ALTER TABLESPACE alter tablespace  ONLINE; command.
                       " ALTER TABLESPACE tablespace_name ONLINE;"

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


How to Rename(change path) of a System or Tools datafile:
------------------------------------------------------



   1. Login to SQLPlus.

   2. Connect as SYS DBA with CONNECT / AS SYSDBA command.
                       "/ as sysdba"

   3. Shutdown the database instance with SHUTDOWN command.
                       " Shutdown immediate"
       
   4. Rename or/and move the datafiles at operating system level.
                       " cp datafile_path/filename to datafile_path/filename"

   5. Start Oracle database in mount state with STARTUP MOUNT command.
                       " Startup mount"

   6. Modify the name or location of datafiles in Oracle data dictionary using following command syntax:
                        "ALTER DATABASE RENAME FILE ‘Old Path/filename’ TO ‘New Path/filename’;"

   7. Open Oracle database instance completely with ALTER DATABASE OPEN command.
                       " Alter database open;"
----------------------------------------------------------

Free Space in Datafile:
----------------------------------------------------------

SET PAGES 2000
col rank form 99
col file_id form 9999 heading "F ID"
col tspace form a20 Heading "Tablespace"
col tot_ts_size form 99999999999999 Heading "Size (Mb)"
col free_ts_size form 99999999999999 Heading "Free (Mb)"
col used_ts_size form 99999999999999 Heading "Used (Mb)"
compute sum of tot_ts_size on report
compute sum of free_ts_size on report

select rownum as rank, a.*
from (
   select df.tablespace_name tspace,
       df.file_id,
       df.bytes/(1024*1024) tot_ts_size,
       sum(fs.bytes)/(1024*1024) free_ts_size,
       (df.bytes-sum(fs.bytes))/(1024*1024) used_ts_size
   from dba_free_space fs, (select tablespace_name,file_id, sum(bytes) bytes
                                 from dba_data_files
                                 group by tablespace_name,file_id ) df         
   where fs.tablespace_name = df.tablespace_name
   and fs.file_id = df.file_id
   and df.tablespace_name like UPPER('%&tablespace_name%')
   group by df.tablespace_name, df.file_id, df.bytes
   ORDER BY free_ts_size DESC) a
where rownum < 11
/

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

Shrink Datafile:
-----------------------------------------------------------

select file_name,
 ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
 ceil( blocks*&&blksize/1024/1024) currsize,
 ceil( blocks*&&blksize/1024/1024) -
 ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
 from dba_data_files a,
 ( select file_id, max(block_id+blocks-1) hwm
 from dba_extents
 group by file_id ) b
 where a.file_id = b.file_id(+)
 and a.tablespace_name ='&tabs';

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



Monitoring Temporary Space Usage

SELECT A.tablespace_name tablespace, D.mb_total,
SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_free
FROM v$sort_segment A,
(
SELECT B.name, C.block_size, SUM (C.bytes) / 1024 / 1024 mb_total
FROM v$tablespace B, v$tempfile C
WHERE B.ts#= C.ts#
GROUP BY B.name, C.block_size
) D
WHERE A.tablespace_name = D.name
GROUP by A.tablespace_name, D.mb_total;
--------------------------------------------

Sort Space Usage by Session
--------------------------------------------

SELECT S.sid || ',' || S.serial# sid_serial, S.username, S.osuser, P.spid, S.module,
S.program, SUM (T.blocks) * TBS.block_size / 1024 / 1024 mb_used, T.tablespace,
COUNT(*) sort_ops
FROM v$sort_usage T, v$session S, dba_tablespaces TBS, v$process P
WHERE T.session_addr = S.saddr
AND S.paddr = P.addr
AND T.tablespace = TBS.tablespace_name
GROUP BY S.sid, S.serial#, S.username, S.osuser, P.spid, S.module,
S.program, TBS.block_size, T.tablespace
ORDER BY sid_serial;
---------------------------------------

Sort Space Usage by Statement
---------------------------------------
SELECT S.sid || ',' || S.serial# sid_serial, S.username,
T.blocks * TBS.block_size / 1024 / 1024 mb_used, T.tablespace,
T.sqladdr address, Q.hash_value, Q.sql_text
FROM v$sort_usage T, v$session S, v$sqlarea Q, dba_tablespaces TBS
WHERE T.session_addr = S.saddr
AND T.sqladdr = Q.address (+)
AND T.tablespace = TBS.tablespace_name
ORDER BY S.sid;
------------------------------------

http://www.dbspecialists.com/presentations/temp_space.html

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

To know the sids which are using TEMP space:
-----------------------------------

set line 120
select rpad(sid,5,' ') sid,s.username,
rpad(program,15,' ') prgm,
rpad(blocks*16384/(1024*1024)||' MB ',10,' ') tempsize,
segtype from v$session s,v$sort_usage v
where s.saddr=v.session_addr
order by blocks ;

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

Users Accessing Temp Tablespace:
-----------------------------------


How can one see who is using a temporary segment?
For every user using temporary space, there is an entry in SYS.V$_LOCK with type 'TS'.
All temporary segments are named 'ffff.bbbb' where 'ffff' is the file it is in and 'bbbb' is first block of the segment.

If your temporary tablespace is set to TEMPORARY, all sorts are done in one large temporary segment. For usage stats, see SYS.V_$SORT_SEGMENT

From Oracle 8.0, one can just query SYS.v$sort_usage. Look at these examples:

        select s.username, u."USER", u.tablespace, u.contents, u.extents, u.blocks
        from   sys.v_$session s, sys.v_$sort_usage u
        where  s.saddr = u.session_addr
        /

        select s.osuser, s.process, s.username, s.serial#,
               sum(u.blocks)*vp.value/1024 sort_size
        from   sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter vp
        where  s.saddr = u.session_addr
          and  vp.name = 'db_block_size'
          and  s.osuser like '&1'
        group  by s.osuser, s.process, s.username, s.serial#, vp.value
        /

------------------------------------
DBMS_STATS


EXPORT STATS:
------------------------------------------------------

DBMS_STATS.EXPORT_TABLE_STATS (
   ownname  VARCHAR2,
   tabname  VARCHAR2,
   partname VARCHAR2 DEFAULT NULL,
   stattab  VARCHAR2,
   statid   VARCHAR2 DEFAULT NULL,
   cascade  BOOLEAN  DEFAULT TRUE,
   statown  VARCHAR2 DEFAULT NULL);

execute DBMS_STATS.export_table_stats('SYSTEM','MSWMART1.MTH_CUSTOMER_SELLOUT',NULL,'DBMS_STATS_TABLE',NULL,TRUE,NULL);

PL/SQL procedure successfully completed.

DBMS_STATS.EXPORT_SCHEMA_STATS (
   ownname VARCHAR2,
   stattab VARCHAR2,
   statid  VARCHAR2 DEFAULT NULL,
   statown VARCHAR2 DEFAULT NULL);

SQL> exec dbms_stats.export_schema_stats('MSWMART1','DBMS_STATS_TABLE','MSWMART1','SYSTEM');

PL/SQL procedure successfully completed.

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

TRANSFER STATS:
---------------------------------------------------------

1. Create the statistics table.
exec DBMS_STATS.CREATE_STAT_TABLE(ownname =>'SYSTEM' ,stat_tab => 'DBMS_STATS_TABLE' , tblspace => 'TOOLS');
Example:
exec DBMS_STATS.CREATE_STAT_TABLE(ownname =>'SYSTEM',stat_tab => 'DBMS_STATS_TABLE');

2. Export statistics to statistics table
EXEC DBMS_STATS.EXPORT_SCHEMA_STATS('ORIGINAL_SCHEMA' ,'STATS_TABLE',NULL,'SYSTEM');

3. Import statistics into the data dictionary.
exec DBMS_STATS.IMPORT_SCHEMA_STATS('NEW_SCHEMA','STATS_TABLE',NULL,'SYSTEM');

4. Drop the statistics table.
exec DBMS_STATS.DROP_STAT_TABLE('SYSTEM','STATS_TABLE');

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

GATHER STATS:
---------------------------------------------------------

EXEC dbms_stats.gather_table_stats('MSWMART1','MTH_ST_INVOICE',estimate_percent => dbms_stats.auto_sample_size,degree => 8, cascade => true);

EXEC dbms_stats.gather_schema_stats('DW1_DBA', cascade=>TRUE);

EXEC DBMS_STATS.gather_index_stats('SCOTT', 'EMPLOYEES_PK');

exec DBMS_STATS.DELETE_SCHEMA_STATS('SCOTT');

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

To Delete Stats:
select 'exec dbms_stats.delete_schema_stats('''|| username || ''');' from dba_users where username not in ('SYS','SYSTEM');

To Export Stats:

select 'exec dbms_stats.export_schema_stats('''||username||''',''STATS_TABLE'','''||username||''',''SYSTEM'');' from dba_users where username != 'SYS' order by username

To Import Stats:

select distinct 'exec dbms_stats.import_schema_stats('''||statid||''',''STATS_TABLE'','''||statid||''',''SYSTEM'');' from system.stats_table;

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

Scheduling Stats:
---------------------------------------------------------
Scheduling the gathering of statistics using DBMS_Job is the easiest way to make sure they are always up to date:

SET SERVEROUTPUT ON
DECLARE
  l_job  NUMBER;
BEGIN

  DBMS_JOB.submit(l_job,
                  'BEGIN DBMS_STATS.gather_schema_stats(''SCOTT''); END;',
                  SYSDATE,
                  'SYSDATE + 1');
  COMMIT;
  DBMS_OUTPUT.put_line('Job: ' || l_job);
END;
/
The above code sets up a job to gather statistics for SCOTT for the current time every day. You can list the current jobs on the server using the DBS_JOBS and DBA_JOBS_RUNNING views.

Existing jobs can be removed using:

EXEC DBMS_JOB.remove(X);
COMMIT;

Where 'X' is the number of the job to be removed.

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

DELETE STATS:
--------------------------------------------------------

EXEC DBMS_STATS.delete_database_stats;
EXEC DBMS_STATS.delete_schema_stats('SCOTT');
EXEC DBMS_STATS.delete_table_stats('SCOTT', 'EMPLOYEES');
EXEC DBMS_STATS.delete_index_stats('SCOTT', 'EMPLOYEES_PK');

--------------------------------------------------------
GATHER STATS:
--------------------------------------------------------

EXEC DBMS_STATS.gather_database_stats;
EXEC DBMS_STATS.gather_database_stats(estimate_percent => 15);

EXEC DBMS_STATS.gather_schema_stats('SCOTT');
EXEC DBMS_STATS.gather_schema_stats('SCOTT', estimate_percent => 15);

EXEC DBMS_STATS.gather_table_stats('SCOTT', 'EMPLOYEES');
EXEC DBMS_STATS.gather_table_stats('SCOTT', 'EMPLOYEES', estimate_percent => 15);

EXEC DBMS_STATS.gather_index_stats('SCOTT', 'EMPLOYEES_PK');
EXEC DBMS_STATS.gather_index_stats('SCOTT', 'EMPLOYEES_PK', estimate_percent => 15);

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


SHARED POOL




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

col value format 999,999,999,999 heading "Shared Pool Size"
col bytes format 999,999,999,999 heading "Free Bytes"
SELECT to_number(v$parameter.value) value,
v$sgastat.bytes,
(v$sgastat.bytes/v$parameter.value)*100 "Percent Free"
FROM v$sgastat, v$parameter
WHERE v$sgastat.name = 'free memory' and
v$parameter.name = 'shared_pool_size' and
v$sgastat.pool='shared pool';

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

select sum(sharable_mem/1024/1024) from v$db_object_cache;

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

set lines 200
set pages 200
col OWNER for a30
col NAME for a30
col NAMESPACE for a30
col TYPE for a30
select OWNER, NAME, NAMESPACE, TYPE, SHARABLE_MEM, KEPT FROM V$DB_OBJECT_CACHE WHERE OWNER in ('LBUNAREP','LBUEUREP');

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

SELECT (1-(sum(getmisses)/sum(gets))) * 100 "Dict Cache Hit Ratio" FROM v$rowcache;

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

Alter system flush shared_pool;

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

alter system set shared_pool_size=210m;

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

Jobs
Jobs running in the database:
------------------------------------------------------------------------------

set linesize 250
col log_user for a10
col job for 9999999 head 'Job'
col broken for a1 head 'B'
col failures for 99 head "fail"
col last_date for a18 head 'Last|Date'
col this_date for a18 head 'This|Date'
col next_date for a18 head 'Next|Date'
col interval for 9999.000 head 'Run|Interval'
col what for a60

select j.log_user,
j.job,
j.broken,
j.failures,
j.last_date||':'||j.last_sec last_date,
j.this_date||':'||j.this_sec this_date,
j.next_date||':'||j.next_sec next_date,
j.next_date - j.last_date interval,
j.what
from (select dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
from dba_jobs dj) j;

scheduled_dbms_jobs.sql
------------------------------------------------------------------------------
set linesize 250
col log_user for a10
col job for 9999999 head 'Job'
col broken for a1 head 'B'
col failures for 99 head "fail"
col last_date for a18 head 'Last|Date'
col this_date for a18 head 'This|Date'
col next_date for a18 head 'Next|Date'
col interval for 9999.000 head 'Run|Interval'
col what for a60

select j.log_user,
j.job,
j.broken,
j.failures,
j.last_date||':'||j.last_sec last_date,
j.this_date||':'||j.this_sec this_date,
j.next_date||':'||j.next_sec next_date,
j.next_date - j.last_date interval,
j.what
from (select dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
from dba_jobs dj) j;


running_jobs.sql
----------------------------------------------------------------------------


set linesize 250
col sid for 9999 head 'Session|ID'
col log_user for a10
col job for 9999999 head 'Job'
col broken for a1 head 'B'
col failures for 99 head "fail"
col last_date for a18 head 'Last|Date'
col this_date for a18 head 'This|Date'
col next_date for a18 head 'Next|Date'
col interval for 9999.000 head 'Run|Interval'
col what for a60
select j.sid,
j.log_user,
j.job,
j.broken,
j.failures,
j.last_date||':'||j.last_sec last_date,
j.this_date||':'||j.this_sec this_date,
j.next_date||':'||j.next_sec next_date,
j.next_date - j.last_date interval,
j.what
from (select djr.SID,
dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
from dba_jobs dj, dba_jobs_running djr
where dj.job = djr.job ) j;


session_jobs.sql
---------------------------------------------------------------------------


set linesize 250
col sid for 9999 head 'Session|ID'
col spid head 'O/S|Process|ID'
col serial# for 9999999 head 'Session|Serial#'
col log_user for a10
col job for 9999999 head 'Job'
col broken for a1 head 'B'
col failures for 99 head "fail"
col last_date for a18 head 'Last|Date'
col this_date for a18 head 'This|Date'
col next_date for a18 head 'Next|Date'
col interval for 9999.000 head 'Run|Interval'
col what for a60
select j.sid,
s.spid,
s.serial#,
j.log_user,
j.job,
j.broken,
j.failures,
j.last_date||':'||j.last_sec last_date,
j.this_date||':'||j.this_sec this_date,
j.next_date||':'||j.next_sec next_date,
j.next_date - j.last_date interval,
j.what
from (select djr.SID,
dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
from dba_jobs dj, dba_jobs_running djr
where dj.job = djr.job ) j,
(select p.spid, s.sid, s.serial#
from v$process p, v$session s
where p.addr = s.paddr ) s
where j.sid = s.sid;

-------------------------------------------------------------------------------------
Jobs Running and Broken Jobs:
------------------------------------------------------------------------------------------

This script shows which jobs are currently executing, who owns them, and when they began:

/* Filename on companion disk: job2.sql */*
col job_definition format a30 word_wrap
col username format a15

ALTER SESSION SET NLS_DATE_FORMAT='YYYY:MM:DD:HH24:MI:SS';

SELECT  jr.job  job_id,username username ,jr.this_date start_date,what  job_definition
FROM dba_jobs_running  jr ,dba_jobs j,v$session s
WHERE  s.sid  = jr.sid
AND  jr.job = j.job   ORDER BY jr.this_date;

----------------------------------------------------------
BROKEN JOBS:

The following script shows failing or broken jobs (i.e., jobs that may need attention):

/* Filename on companion disk: job2.sql */*
col job_owner format a15
col job_definition format a30 word_wrap

SELECT  job         
       ,log_user     job_owner
       ,failures
       ,broken
       ,what         job_definition
  FROM
        dba_jobs
 WHERE
        broken = 'Y' OR NVL(failures,0) > 0 ;

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

---------------------------------------------------------------------------
-- Schedule the job using the DB Job System. This section can be removed if
-- the job is sceduled via an external scheduler.
---------------------------------------------------------------------------


declare
  v_job number;
begin
  select job into v_job from user_jobs where what like 'db_space_hist_proc%';
  dbms_job.remove(v_job);
  dbms_job.submit(v_job, 'db_space_hist_proc;', sysdate,
                        'sysdate+7');   -- Run every 7 days
  dbms_job.run(v_job);
  dbms_output.put_line('Job '||v_job||' re-submitted.');
exception
  when NO_DATA_FOUND then
       dbms_job.submit(v_job, 'db_space_hist_proc;', sysdate,
                      'sysdate+7');   -- Run every 7 days
       dbms_job.run(v_job);
       dbms_output.put_line('Job '||v_job||' submitted.');
end;
/
----------------------------------------------------------------------------

-- Schedule a snapshot to be run on this instance every hour

variable jobno number;
variable instno number;
begin

select instance_number into :instno from v$instance;
-- ------------------------------------------------------------
-- Submit job to begin at 0600 and run every hour
-- ------------------------------------------------------------
dbms_job.submit(
:jobno, 'statspack.snap;',
trunc(sysdate)+6/24,
'trunc(SYSDATE+1/24,''HH'')',
TRUE,
:instno);

-- ------------------------------------------------------------
-- Submit job to begin at 0900 and run 12 hours later
-- ------------------------------------------------------------
dbms_job.submit(
:jobno,
'statspack.snap;',
trunc(sysdate+1)+9/24,
'trunc(SYSDATE+12/24,''HH'')',
TRUE,
:instno);

-- ------------------------------------------------------------
-- Submit job to begin at 0600 and run every 10 minutes
-- ------------------------------------------------------------
dbms_job.submit(
:jobno,
'statspack.snap;',
trunc(sysdate+1/144,'MI'),
'trunc(sysdate+1/144,''MI'')',
TRUE,
:instno);

-- ----------------------------------------------------------------
-- Submit job to begin at 0600 and run every hour, Monday - Friday
-- ----------------------------------------------------------------
dbms_job.submit(
:jobno,
'statspack.snap;',
trunc(sysdate+1)+6/24,
'trunc(
least(
next_day(SYSDATE,''MONDAY''),
next_day(SYSDATE,''TUESDAY''),
next_day(SYSDATE,''WEDNESDAY''),
next_day(SYSDATE,''THURSDAY''),
next_day(SYSDATE,''FRIDAY'')
)
+1/24,''HH'')',
TRUE,
:instno);

commit;
end;
/

-------------------------------------------------------------------------
VARIABLE jobno number
 exec DBMS_JOB.SUBMIT(JOB=> :jobno,WHAT=> 'dbms_refresh.refresh(''"BPADB"."BPA_DAILY_DISPUTE_REPORT"'');',NEXT_DATE=>TO_DATE('2009-07-01:00:11:00','YYYY-MM-DD:HH24:MI:SS'),INTERVAL=> 'SYSDATE+1',NO_PARSE=> TRUE);

-------------------------------------------------------------------------------------
METADATA OF A JOB:
-------------------------------------------------------------------------------------

select dbms_metadata.get_ddl('JOB','BPADB') from dual;

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

DROP JOB:

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

exec dbms_job.remove(87);

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


LOCKS

Description

This script lists details of all current database locks on the system,

who is holding the lock, and the object name where the lock is held.


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

set pages 2000
col username form A10
col sid form 9990
col type form A4
col lmode form a10
col request form a20
col objname form A30 Heading "Object Name"
rem Display the object id's if the object_name is not unique
rem col id1 form 999999900  
rem col id2 form 999999900

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'
                 , lmode, 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'
                 , request, ltrim(to_char(request,'990'))) request,
         obj1.object_name objname, obj2.object_name objname
FROM v$session sn, V$lock m, dba_objects obj1, dba_objects obj2
WHERE sn.sid = m.sid
AND m.id1 = obj1.object_id (+)
AND m.id2 = obj2.object_id (+)
     AND lmode != 4
ORDER BY id1,id2, m.request
/

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

 COLUMN lock_id2 FORMAT A30

 select to_char(SESSION_ID,'999') sid ,
    substr(LOCK_TYPE,1,30) Type,
    substr(lock_id1,1,45) Object_Name,
    substr(mode_held,1,4) HELD,
    substr(mode_requested,1,4) REQ,
    lock_id2 lock_addr
 FROM dba_lock_internal
 WHERE
    mode_requested < 'None'
    and mode_requested < mode_held
 ;

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

ALL THE LOCKED OBJECTS , AND THE USER THAT IS USING IT:
------------------------------------------------------------------

COLUMN USER FORMAT A10;
COLUMN OBJETO FORMAT A10;
SELECT L.SID, S.USERNAME "USER", L.TYPE "TIPO", L.ID1, L.ID2, L.LMODE
"MODO", L.REQUEST "REQ", L.CTIME "TIEMPO", O.OBJECT_NAME "OBJETO"
FROM V$LOCK L, V$SESSION S, V$LOCKED_OBJECT B, OBJ O
WHERE L.SID = S.SID AND S.USERNAME <> 'OPS$PTRANS' AND L.SID = B.SESSION_ID AND
B.OBJECT_ID = O.OBJECT_ID
ORDER BY 1
/

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

rem -----------------------------------------------------------------------
rem Filename:   lock.sql
rem Purpose:    Display database locks and latches (with tables names, etc)
rem -----------------------------------------------------------------------

set pagesize 23
set pause on
set pause 'Hit any key...'

col sid format 999999
col serial# format 999999
col username format a12 trunc
col process format a8 trunc
col terminal format a12 trunc
col type format a12 trunc
col lmode format a4 trunc
col lrequest format a4 trunc
col object format a73 trunc

select s.sid, s.serial#,
       decode(s.process, null,
          decode(substr(p.username,1,1), '?',   upper(s.osuser), p.username),
          decode(       p.username, 'ORACUSR ', upper(s.osuser), s.process)
       ) process,
       nvl(s.username, 'SYS ('||substr(p.username,1,4)||')') username,
       decode(s.terminal, null, rtrim(p.terminal, chr(0)),
              upper(s.terminal)) terminal,
       decode(l.type,
          -- Long locks
                      'TM', 'DML/DATA ENQ',   'TX', 'TRANSAC ENQ',
                      'UL', 'PLS USR LOCK',
          -- Short locks
                      'BL', 'BUF HASH TBL',  'CF', 'CONTROL FILE',
                      'CI', 'CROSS INST F',  'DF', 'DATA FILE   ',
                      'CU', 'CURSOR BIND ',
                      'DL', 'DIRECT LOAD ',  'DM', 'MOUNT/STRTUP',
                      'DR', 'RECO LOCK   ',  'DX', 'DISTRIB TRAN',
                      'FS', 'FILE SET    ',  'IN', 'INSTANCE NUM',
                      'FI', 'SGA OPN FILE',
                      'IR', 'INSTCE RECVR',  'IS', 'GET STATE   ',
                      'IV', 'LIBCACHE INV',  'KK', 'LOG SW KICK ',
                      'LS', 'LOG SWITCH  ',
                      'MM', 'MOUNT DEF   ',  'MR', 'MEDIA RECVRY',
                      'PF', 'PWFILE ENQ  ',  'PR', 'PROCESS STRT',
                      'RT', 'REDO THREAD ',  'SC', 'SCN ENQ     ',
                      'RW', 'ROW WAIT    ',
                      'SM', 'SMON LOCK   ',  'SN', 'SEQNO INSTCE',
                      'SQ', 'SEQNO ENQ   ',  'ST', 'SPACE TRANSC',
                      'SV', 'SEQNO VALUE ',  'TA', 'GENERIC ENQ ',
                      'TD', 'DLL ENQ     ',  'TE', 'EXTEND SEG  ',
                      'TS', 'TEMP SEGMENT',  'TT', 'TEMP TABLE  ',
                      'UN', 'USER NAME   ',  'WL', 'WRITE REDO  ',
                      'TYPE='||l.type) type,
       decode(l.lmode, 0, 'NONE', 1, 'NULL', 2, 'RS', 3, 'RX',
                       4, 'S',    5, 'RSX',  6, 'X',
                       to_char(l.lmode) ) lmode,
       decode(l.request, 0, 'NONE', 1, 'NULL', 2, 'RS', 3, 'RX',
                         4, 'S', 5, 'RSX', 6, 'X',
                         to_char(l.request) ) lrequest,
       decode(l.type, 'MR', decode(u.name, null,
                            'DICTIONARY OBJECT', u.name||'.'||o.name),
                      'TD', u.name||'.'||o.name,
                      'TM', u.name||'.'||o.name,
                      'RW', 'FILE#='||substr(l.id1,1,3)||
                      ' BLOCK#='||substr(l.id1,4,5)||' ROW='||l.id2,
                      'TX', 'RS+SLOT#'||l.id1||' WRP#'||l.id2,
                      'WL', 'REDO LOG FILE#='||l.id1,
                      'RT', 'THREAD='||l.id1,
                      'TS', decode(l.id2, 0, 'ENQUEUE',
                                             'NEW BLOCK ALLOCATION'),
                      'ID1='||l.id1||' ID2='||l.id2) object
from   sys.v_$lock l, sys.v_$session s, sys.obj$ o, sys.user$ u,
       sys.v_$process p
where  s.paddr  = p.addr(+)
  and  l.sid    = s.sid
  and  l.id1    = o.obj#(+)
  and  o.owner# = u.user#(+)
  and  l.type   <> 'MR'
UNION ALL                          /*** LATCH HOLDERS ***/
select s.sid, s.serial#, s.process, s.username, s.terminal,
       'LATCH', 'X', 'NONE', h.name||' ADDR='||rawtohex(laddr)
from   sys.v_$process p, sys.v_$session s, sys.v_$latchholder h
where  h.pid  = p.pid
  and  p.addr = s.paddr
UNION ALL                         /*** LATCH WAITERS ***/
select s.sid, s.serial#, s.process, s.username, s.terminal,
       'LATCH', 'NONE', 'X', name||' LATCH='||p.latchwait
from   sys.v_$session s, sys.v_$process p, sys.v_$latch l
where  latchwait is not null
  and  p.addr      = s.paddr
  and  p.latchwait = l.addr
/
------------------------------------------------------

BLOCKS AND BLCOKER WHICH IS BLOCKING
--------------------------------------------------------
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;
--------------------------------------------------------

LOCKED OBJECTS USING BY THE USER
--------------------------------------------------------

set lin 120
col object_name for a30
select
  oracle_username
  os_user_name,
  locked_mode,
  object_name,
  object_type
from
  v$locked_object a,dba_objects b
where
  a.object_id = b.object_id;

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


 Restore a table from recycle bin




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

select object_name, original_name, type, droptime from recyclebin where original_name='';

flashback table table_name to before drop;

Changing NLS_CHARACTERSET for a Database

conn / as sysdba

SQL> shutdown immediate

SQL> startup mount

SQL> ALTER SYSTEM ENABLE RESTRICTED SESSION;

SQL> ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;

SQL> ALTER SYSTEM SET AQ_TM_PROCESSES=0;

SQL> ALTER DATABASE OPEN;

SQL> ALTER DATABASE CHARACTER SET WE8MSWIN1252;

SQL> SHUTDOWN IMMEDIATE

SQL> STARTUP


NOTE: It would be better to check the alert log for any ORA:00600 errors after we change the characterset.
If there is any problem, after we change the characterset there will be ORA:00600 errors.

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

select * from nls_database_parameters;




SQL Tuning Advisor




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

-- Tuning task created for specific a statement from the AWR.

DECLARE
  l_sql_tune_task_id  VARCHAR2(100);
BEGIN
  l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
                          begin_snap  => 3223,
                          end_snap    => 3230,
                          sql_id      => 'aak5zghvqpfva',
                          scope       => DBMS_SQLTUNE.scope_comprehensive,
                          time_limit  => 60,
                          task_name   => 'aak5zghvqpfva_AWR_tuning_task',
                          description => 'Tuning task for statement aak5zghvqpfva in AWR.');
  DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/

EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => 'aak5zghvqpfva_AWR_tuning_task');


SELECT DBMS_SQLTUNE.report_tuning_task('aak5zghvqpfva_AWR_tuning_task') AS recommendations FROM dual;

BEGIN
  DBMS_SQLTUNE.drop_tuning_task (task_name => '19v5guvsgcd1v_AWR_tuning_task');
  DBMS_SQLTUNE.drop_tuning_task (task_name => '19v5guvsgcd1v_tuning_task');
  DBMS_SQLTUNE.drop_tuning_task (task_name => 'sqlset_tuning_task');
  DBMS_SQLTUNE.drop_tuning_task (task_name => 'emp_dept_tuning_task');
END;
/


BEGIN
  DBMS_SQLTUNE.drop_tuning_task (task_name => '88td84pgvjh3m_AWR_tuning_task');
END;
/