Sei sulla pagina 1di 393

P.R.P.R.

Page 1

P.R.P.R.

Page 2

ORACLE 10g

DBA Demos

P.R.P.R.

Page 3

Contents
TABLESPACE MANAGEMENT .... 6 USER MANAGEMENT ....... 23 Creating and Maintaining a Password File ......... 33 ROLES .... 39 PROFILES .. 41 STORAGE PARAMETERS..... 44

ROLLBACK SEGMENTS . 53
UNDO MANAGEMENT ...55 DEFFERED ROLLBACK SEGMENT ..... 59 SNAP SHOT TOO OLD ERROR. (1555) .. 60 PENDING OFFLINE 62 FLASH BACK . 63
FLASHBACK TABLE ...... 63 FLASHBACK QUERY ...... 65 FLASHBACK VERSION QUERY 67

FLASH BACK TANSACTION .. 68 SP FILE ..... 69 ORACLE MANAGED FILES (OMF) 73 CONTROLFIILE MANAGEMENT .... 75 REDOLOGFILE MANAGEMENT .... 81 ARCHIVED REDO LOG FILES .. 86 NETWORKING .. 88 DATABASE LINKS 94 MATERIALIZED VIEWS .. 100 BACKUPS ... 109 LOGICAL BACKUPS ... 110 DATA PUMP .. 126
COLD BACLUPS
1) 2)

... 132

DATABASE CRASH . 134 LOSS OF CONTROLFILE ..... 138 3) LOSS OF SYSTEM DATAFILE . 141 4) LOSS OF NON SYSTEM DATAFILE ..... 143 5) LOSS OF REDOLOG FILES .... 146 6) LOSS OF NON SYSTEM DATAFILE WHICH IS NOT AVILABLE IN BACKUP SET ....... 149 7) LOSS OF SYSAUX 8) POINT - IN TIME RECOVERY .. 152 9) LOSS OF UNDO DATAFILE ........... 154 10) LOSS OF PARAMETER FILE ...... 155

11) LOSS OF TEMP 12) Same as SCENARIO No 6, but loss all C/R/D files HOT BACKUPS ... 156
DATABASE CRASH ... 157

RMAN .......... 160 Oracle 11g - RMAN Enhancments.. RMAN Cloning .. TRANSPORTABLE TABLESPACE .......... 190
TRANSPORTING THE TABLESPACE ACROSS PLOTFORMS .. 195

CLONING ...... 198 RESUMABLE TABLESPACE ................... 202 FLASHBACK DATABASE ..... 203 LOG MINER .... 209

P.R.P.R.

Page 4

SQL Loader ..... 268 Auditing 271 DBVERIFY 280 Performance Tuning 284 Database Buffer Cache 296 Multithread Server (MTS) 301 AWR 305 Oracle Enterprise Manager .... 309 Gather Schema Statistics 307 GENERAL NOTES ..... 212 SCRIPTS .. 270 Oracle useful Links . 307 Oracle 11g new features .. 317 TROUBLESHOOT 335

P.R.P.R.

Page 5

P.R.P.R.

Page 6

P.R.P.R.

Page 7

TABLESPACE MANAGEMENT

P.R.P.R.

Page 8

How to create Tablespace : Syntax: Create tablespace <tablespace Name> datafile <datafile Name> size <intezer>k/m/g;

SYS>> create tablespace t1 datafile /disk1/oradata/good/t1.dbf size 10m; To see the Tablespace information.. VIEW IS DBA_TABLESPACES >> Desc dba_tablespaces >> select tablespace_name, block_size, status, contents, logging, plugged_in from dba_tablespaces; >> save ts >> alter tablespace t1 offline; >> @ts (We cant select the data) >> alter tablespace t1 online; >>@ts >> alter tablespace t1 read only; >> @ts (We can select the data) >> alter tablespace t1 read write; >> @ts To see the information of Datafiles
P.R.P.R. Page 9

VIEW is DBA_DATA_FILES >> Desc dba_data_files >> select tablespace_name, file_name, file_id from dba_data_files; To see the size of a datafile in megabytes ( By default it shows in bytes) >> select tablespace_name, file_name, file_id, bytes from dba_data_files; (In bytes) >>select tablespace_name, file_name, file_id, bytes/ (1024*1024) from dba_data_files; (In megabytes) >> save DF How to add a datafile to existing tablespace >> alter tablespace t1 add datafile /disk1/oradata/good/ts.dbf size 10m; >> @DF How to Resize the Datafile >> alter database datafile <file_id> resize 20m;(Total Size is 20m) >> alter database datafile <file_name> resize 20m; To Auto extend a datafile >> alter database datafile < file_id> autoextend on; >> alter database datafile < file_id> autoextend off

P.R.P.R.

Page 10

Rename a Datafile 1. 2. 3. 4. MAKE TABLESPACE OFFLINE COPY (OR) RENAME AT OS LEVEL RENAME DATAFILE AT ORACLE LEVEL MAKE TABLESPACE ONLINE

>> 1 step u know >> 2 step u know >> alter tablespace <tablespacename> rename datafile < Old name/location> to < new name/location>; (OR) >>alter database rename file < Old filename> >> 4 step u know

to < new filename>;

Rename a Tablespace >> alter tablespace <old tablespace name> rename to < New name>; DROP A DATAFILE >> alter tablespace < tablespace name> drop datafile < filename>; DROP A TABLESPACE >> drop tablespace <tablespace name>; >> drop tablespace <tablespace name> including contents and datafiles;

P.R.P.R.

Page 11

REUSE A DATAFILE Tablespace name is Datafile name >> drop tablespace kk; >> Crerate tablespace km datafile /disk1/oradata/good/kk.dbf reuse; YOU CAN REUSE THIS DATAFILE FOR EXISTING TABLESPACE ALSO >> alter tablespace tt add datafile /disk1/oradata/good/kk.dbf reuse; KK /disk1/oradata/good/KK.dbf

CREATE A BIG FILE TABLESPACE >> Create bigfile tablespace < tablespace name> datafile < filename> size 10m; >> select tablespace_name, bigfile from dba_tablespaces;

RESIZE: >> alter database datafile < file_id> resize 20m; >> alter tablespace bigts resize 30m;

CREATE A TABLESPACE WITH DIFFERENT BLOCK SIZES..

1 OS BLOCK
P.R.P.R.

= 512 BYTES
Page 12

16 OS BLOCKS = 1 ORACLE BLOCK 16 * 512= 8142 8K IS DEFAULT BLOCK SIZE

IN 10g DEFAULT BLOCK SIZE IS 8K

U CAN CREATE WITH

2K, 4K, 8K, 16K, and 32K.

WITH 2K: IN PFILE MENTION 1 PARAMETER db_2k_cache_size=12m

>> Sho parameter db_2k_ >> create tablespace ts2k datafile /disk1/oradata/good/ts2k.dbf size 10m blocksize 2k;

{YOU CAN NOT MODIFY (ALTER) THE BLOCKSIZE}


LIKE ( 2K 4K)

CREATE UNDO TABLESPACE

>>create undo tablespace < tablespace name> datafile


P.R.P.R. Page 13

< File name> size 10m;

>> select tablespace_name from dba_tablespaces;

TEMPORARY TABLESPACE:

CREATE TEMPORARY TABLESPACE

>> create temporary tablespace < tablespace name> Tempfile <filename> size; >> create temporary tablespace temp1 Tempfile /disk1/oradata/good/temp1.tmp size 10m; ADD tempfile Alter tablespace <tablespace_name> add tempfile /location size 10m; RESIZE tempfile Alter database tempfile <filename> resize <mega_bytes_integer>M; DROP tempfile Alter database tempfile <filename> drop;
P.R.P.R. Page 14

Take Temporary Tablespace Off-line


ALTER DATABASE TEMPFILE '<path_and_file_name>' OFFLINE; ONLINE; REUSE Tempfile Alter tablespace <tablespacename> add tempfile location size m reuse;

CREATE TEMPOARY TABLESPACE GROUPS

>> Desc dba_tablespace_groups >>select * from dba_tablespace_groups; >> save TG >> create temporary tablespace tg tempfile location size 10m tablespace group g1; >> @tg

Group name is g1 Create 2 more temporary table spaces with name tg1 & tg2

NOW HOW TO ADD A TEMPOARY TABLESPACE TO A GROUP


P.R.P.R. Page 15

>> alter tablespace tg1 tablespace group g1 >> alter tablespace tg2 tablespace group g1 >> @tg REMOVE A TEMPORARY TS FROM GROUP >> alter tablespace tg2 tablespace group ; >> @tg
DROP A GROUP

TWO Ways 1. You can remove last temporary tablespace from that group 2. Drop that particular tablespace >> alter tablespace tg tablespace group ; (Automatically that group also removed) >> Drop tablespace tg including contents and datafiles;

@@@@@@@@@@@##################$$$$$$$$$$$$$$$$$$$

Desc Database_properties
>> select * from database_properties; Default permanent TS
P.R.P.R.

is

USERDATA
Page 16

I want to set default TS is T1 >> alter database default tablespace T1; >> select * from Database_properties; Default temporary TS is TEMP

NOW >> alter database default temporary tablespace TEMP1; >> select * from Database_properties;

Default tablespace type is SMALLFILE >> alter database set default bigfile tablespace; Smallfile

Display all datafiles, tempfiles and logfiles (and their sizes) set lines 100 pages 999 col name format a50 select name, bytes from (select name, bytes from v$datafile union all select name, bytes from v$tempfile union all select lf.member "name", l.bytes
P.R.P.R. Page 17

, /

from v$logfile lf , v$log l where lf.group# = l.group# union all select name, 0 from v$controlfile) used (select sum(bytes) as p from dba_free_space) free

Quick datafile health check You should only see online and system (maybe read-only too) select distinct status from v$datafile
/

List autoextensible datafiles select file_name from dba_data_files where autoextensible = 'YES' / Find duplicate filenames Searches for files with the same name in all directories select , from / count(substr(name, instr(name, '/', -1) + 1, 999)) "total" count(distinct substr(name, instr(name, '/', -1) + 1, 999)) "distinct" v$datafile

Show directories that contain datafiles select


P.R.P.R.

distinct substr(name, 1, instr(name, '/', -1)) DIR


Page 18

from v$datafile order by 1 /

List files that are in hot-backup mode set lines 100 pages 999 col name format a60 select df.name , b.status , to_char(time, 'hh24:mi:ss dd/mm/yyyy') time from v$datafile df , v$backup b where df.file# = b.file# and b.status = 'ACTIVE' order by b.file# /

List the contents of the temporary tablespace(s) set pages 999 lines 100 col username format a15 col mb format 999,999 select su.username , ses.sid , ses.serial# , su.tablespace , ceil((su.blocks * dt.block_size) / 1048576) MB from v$sort_usage su , dba_tablespaces dt , v$session ses where su.tablespace = dt.tablespace_name and su.session_addr = ses.saddr / Tablespace usage
P.R.P.R. Page 19

set pages 999 col tablespace_name format a40 col "size MB" format 999,999,999 col "free MB" format 99,999,999 col "% Used" format 999 select tsu.tablespace_name, ceil(tsu.used_mb) "size MB" , decode(ceil(tsf.free_mb), NULL,0,ceil(tsf.free_mb)) "free MB" , decode(100 - ceil(tsf.free_mb/tsu.used_mb*100), NULL, 100, 100 - ceil(tsf.free_mb/tsu.used_mb*100)) "% used" from (select tablespace_name, sum(bytes)/1024/1024 used_mb from dba_data_files group by tablespace_name union all select tablespace_name || ' **TEMP**' , sum(bytes)/1024/1024 used_mb from dba_temp_files group by tablespace_name) tsu , (select tablespace_name, sum(bytes)/1024/1024 free_mb from dba_free_space group by tablespace_name) tsf where tsu.tablespace_name = tsf.tablespace_name (+) order by 4 / Specific Tablespace Usage:
SELECT a.tablespace_name, ROUND (a.BYTES / 1024000) "Used (MB)", ROUND (b.BYTES / 1024000) "Free (MB)", ROUND (((a.BYTES - b.BYTES) / a.BYTES) * 100, 2) "% USED" (SELECT tablespace_name, SUM (BYTES) BYTES FROM dba_data_files GROUP BY tablespace_name) a, (SELECT tablespace_name, SUM (BYTES) BYTES, MAX (BYTES) largest FROM dba_free_space GROUP BY tablespace_name) b a.tablespace_name = b.tablespace_name a.tablespace_name LIKE '%' ((a.BYTES - b.BYTES) / a.BYTES) DESC

FROM

WHERE AND ORDER BY

If you want to list a particular table space replaces a.TABLESPACE_NAME like % with a.TABLESPACE_NAME like MY_TABLE_SPACE

Show the files that comprise a tablespace set lines 100 col file_name format a70
P.R.P.R. Page 20

select file_name , ceil(bytes / 1024 / 1024) "size MB" from dba_data_files where tablespace_name like '&TSNAME' / Tablespaces that are >=80% full, and how much to add to make them 80% again set pages 999 lines 100 col "Tablespace" for a50 col "Size MB" for 999999999 col "%Used" for 999 col "Add (80%)" for 999999 select tsu.tablespace_name "Tablespace" , ceil(tsu.used_mb) "Size MB" , 100 - floor(tsf.free_mb/tsu.used_mb*100) "%Used" , ceil((tsu.used_mb - tsf.free_mb) / .8) - tsu.used_mb "Add (80%)" from (select tablespace_name, sum(bytes)/1024/1024 used_mb from dba_data_files group by tablespace_name) tsu , (select ts.tablespace_name , nvl(sum(bytes)/1024/1024, 0) free_mb from dba_tablespaces ts, dba_free_space fs where ts.tablespace_name = fs.tablespace_name (+) group by ts.tablespace_name) tsf where tsu.tablespace_name = tsf.tablespace_name (+) and 100 - floor(tsf.free_mb/tsu.used_mb*100) >= 80 order by 3,4 /

1. To Find Tablespace TOTAL & USED & FREE Size :


select b.tablespace_name, tbs_size SizeMb, a.free_space FreeMb,tbs_size-a.free_space "USED" from (select tablespace_name, round(sum(bytes)/1024/1024 ,2) as free_space from dba_free_space group by tablespace_name) a,
P.R.P.R. Page 21

(select tablespace_name, sum(bytes)/1024/1024 as tbs_size from dba_data_files group by tablespace_name) b where a.tablespace_name(+)=b.tablespace_name /

2. Tablespace usage report along with allocated space: (Both r same)

set feedback off set verify off set echo off set pages 200 lines 200 select a.tablespace_name, a.bytes/1024/1024 MB_Allocated, (a.bytes - b.bytes)/1024/1024 MB_Used, b.bytes/1024/1024 MB_Free, round(((a.bytes - b.bytes)/a.bytes) * 100,2) percent_used from ( select tablespace_name, sum(bytes) BYTES from dba_data_files group by tablespace_name ) a, ( select tablespace_name, sum(bytes) BYTES from dba_free_space group by tablespace_name ) b where a.tablespace_name=b.tablespace_name order by ((a.bytes-b.bytes)/a.bytes) desc /

P.R.P.R.

Page 22

List all objects in a tablespace set pages 999 col owner format a15 col segment_name format a40 col segment_type format a20 select owner , segment_name , segment_type from dba_segments where lower(tablespace_name) like lower('%&tablespace%') order by owner, segment_name /

Show all tablespaces used by a user select tablespace_name , ceil(sum(bytes) / 1024 / 1024) "MB" from dba_extents where owner like '&user_id' group by tablespace_name order by tablespace_name /
Below query will tell you how much (upto what extend) you can resize your all datafile and how.

select 'TABLESPACE_NAME : ' || rpad(b.tablespace_name,30,' ') ||' -- ' || ' Alter database datafile ' || b.file_name || ' resize datafile ' || ceil( ( hwm)/1048576 ) || 'M;' from (select file_id, ( max(block_id+blocks-1) * 8192 ) hwm from dba_extents group by file_id ) a, (select file_id, tablespace_name, file_name, bytes tot from dba_data_files) b where a.file_id = b.file_id order by b.tablespace_name;

hiprpr@gmail.com

################## %%%%%%%%% &&&&&&&&& ************


P.R.P.R. Page 23

P.R.P.R.

Page 24

SMALL FILES GROW UPTO MAX 128GB ONLY.. BIG FILES GROW UPTO MAX 128TB ONLY.. IN 9i BLOCK SIZE IS

LINUX.. 2K WINDOWS .4K IN 10g BLOCKSIZE IS LINUX..8K WINDOWS..8K

NOTE:

1 ORACLE BLOCK = 2* OS BLOCK

BLOCKSIZE 2K 4K 8K
P.R.P.R.

SMALLFILE *4 8 GB 16 GB 32 GB

BIGFILE 8tb 16tb 32tb


Page 25

16K 32K

64 GB 128 GB

64tb 128tb

VIEWS: DBA_TABLESPACES DBA_DATA_FILES DBA_TEMP_FILES DBA_TABLESPACE_GROUPS DBA_FREE_SPACE V$TABLESPACE V$DATAFILE DBA_TS_QUOTAS USER_TS_QUOTAS..

P.R.P.R.

Page 26

P.R.P.R.

Page 27

USER MANAGEMENT

P.R.P.R.

Page 28

HOW TO CREATE A USER

>> Create user < username > identified by < password>;


P.R.P.R. Page 29

>> create user u1 identified by u1; >> dba_users >> select username from dba_users; Grant privileges to user >> Grant connect, resource to u1; (Or) At a time u can create and as well as grant the privs >> Grant connect, resource to uu identified by uu;

HOW TO ASSIGN A DEFAULT TABLESPACE TO THE USER

>> alter user < username> default tablespace < tablespace name>; >> alter user u1 default tablespace t1; (Or) >> create user u2 identified by u2 default tablespace t1; #########%%%%%%%%&&&&&&&&********* Sys>> create user u4 identified by u4 password expire; Sys>> Grant connect, resource to u4;

Sys>> connect u4/u4 Changing password for u4


P.R.P.R. Page 30

New password: xy U4>> connect / as sysdba

CHANGE THE PASSWORD Sys>> Alter user <username> identified by < new password>;

CHECK THE PRIVILAGES AT USER LEVEL

Sys>> grant connect,resource to user identified by user; Sys>> select * from session_privs;

Check the User Roles as a SYS

SQL> select * from dba_role_privs where grantee='USER';


GRANTEE GRANTED_ROLE ADM ------------------------------ ------------------------------ --USER CONNECT NO USER RESOURCE NO DEF --YES YES

To see PRIVILEGES of particular user as a SYS:

SQL> select * from DBA_SYS_PRIVS where GRANTEE='KK';

P.R.P.R.

Page 31

GRANTEE ------------------USER

PRIVILEGE --------------------------------UNLIMITED TABLESPACE

ADM --NO

Sys> grant create tablespace to KK; SQL> select * from dba_sys_privs where grantee='KK';
GRANTEE PRIVILEGE ------------------------------ ---------------------------------------USER CREATE TABLESPACE USER UNLIMITED TABLESPACE ADM --NO NO

MENTION QUOTAS.. >> create user u5 identified by u5 default tablespace tt quota 2m on tt1; >> alter user u5 quota 1m on tt3 Quota 2m on tt4; >> Desc dba_ts_quotas >>select tablespace_name, username, bytes/ (1024*1024) from dba_ts_quotas; >> select tablespace_name, username, max_bytes from dba_ts_quotas;

User quotas on all tablespaces col quota format a10 select username , tablespace_name , decode(max_bytes, -1, 'unlimited' , ceil(max_bytes / 1024 / 1024) || 'M' ) "QUOTA"
P.R.P.R. Page 32

from dba_ts_quotas where tablespace_name not in ('TEMP') /

@@@@@@@

>> alter user <username > account lock; >> alter user < username > account unlock;

To See the Timestamp of locked user: Select username,lock_date from dba_users where username=KK; Select username,account_status, to_char(lock_date,dd/mm/yyyy HH24:MI:SS) from dba_users where username =KK;

$$$$$$$$$$$$

With out DBA privilege is it possible to change the password for the user?
http://www.orafaq.com/forum/t/153942/0/ SQL> create or replace procedure change_password ( 2 p_username in varchar2, 3 p_password in varchar2 4 ) 5 is

P.R.P.R.

Page 33

6 begin 7 -- Check parameters 8 if p_username is null or p_password is null 9 or length(p_username) > 30 or length(p_password) < 8 -- minimum password length 10 or upper(p_username) in ('SYS','SYSTEM') -- and so on, or check if username is in a list 11 then 12 raise_application_error (-20000, 'Wrong parameter'); 13 end if; 14 execute immediate 15 'alter user '||dbms_assert.schema_name(p_username)|| 16 ' identified by "'||p_password||'"'; 17 end; 18 / Procedure created.

P.R.P.R.

Page 34

OS LEVEL AUTHENTICATION

IN PFILE MENTION 1 PARAMETER OS_AUTHENT_PREFIX= >>sho parameter os_authent_prefix >>create user <username/RAM> identified externally; >> Grant connect, resource to < username/RAM> >>connect / RAM>> Otherwise ~] $ sqlplus / RAM>> ORACLE USERS:
SYS

The SYS user owns all base tables and user-accessable view of the data dictionary (Oracle configuration information). No Oracle user should ever alter (update, delete, or insert) any rows or schema objects conatained in the SYS schema, because such activity can compromise data integrety. The security administrator must keep strict control of this central account. Changing the SYS user password: a) Login as Database Tier owner b) Login as a sysdba
P.R.P.R. Page 35

Syntax: Sys> alter user <username> identified by <password>; Egg: Sys> alter user sys identified by ram@admin;

SYSTEM

The SYSTEM user is used to create additional tables and views that display administrative information, and internal tables and views used by various Oracle options and tools.

Changing the SYSTEM user password: a) Login as Database Tier owner b) Connecting to Database as Sys Privileges Syntax: SYS> alter user <username > identified by <password>; Egg: SYS> alter user system identified by ram@123; c) Connect as a user and check it Sys> connect system/ram@123 System>

P.R.P.R.

Page 36

SYSMAN The SYSMAN user represents the Enterprise Manager super admin account. This EM admin can create and modify other EM admin accounts as well as admin the database instance itself.

How to change the password of the 10g database user sysman Doc ID: 259379.1

Changing the SYSMAN password: a) Login as Database Tier owner b) Stop the standalone dbconsole $ emctl stop dbconsole c) Check that the standalone dbconsole is stopped $ emctl status dbconsole d) Connect to the database as a user with DBA privilege with SQL*Plus and execute SQL> alter user sysman identified by <new_password>; e) Check the new password SQL> connect sysman/<new_password>[@database_alias]

f) Go to $ORACLE_HOME/host_sid/sysman/config Copy(Bkp) the file emoms.properties to emoms.properties.Bkp


P.R.P.R.

(BKP)
Page 37

Edit the file emoms.properties

Search for the line beginning with: oracle.sysman.eml.mntr.emdRepPwd= Replace the encrypted value by the new password value Search for the line: oracle.sysman.eml.mntr.emdRepPwdEncrypted=TRUE Replace TRUE by FALSE g) Restart the standalone dbconsole on Unix $ emctl start dbconsole h) Check that the password has been encrypted Open the file emoms.properties: Search for the line beginning with: oracle.sysman.eml.mntr.emdRepPwd= Check that the password is encrypted Search for the line beginning with: oracle.sysman.eml.mntr.emdRepPwdEncrypted= Check that the value is TRUE
This is for Reset & unlock SYSMAN account http://iadvise.blogspot.com/2008/02/sysman-account-is-locked.html

DBSNMP

The DBSNMP user is used by EM to monitor the database. EM uses this account to access performance stats about the database. The DBSNMP credentials sometimes referred to as the monitoring credentials.
P.R.P.R. Page 38

SYSDBA and SYSOPER Privileges:

In addition to these users, a user can connect with different levels of privileges, namely SYSDBA and SYSOPER. When you connect using "connect sys/passwd as sysdba" your connecting as the SYS user and requesting SYSDBA privs. Because the SYS user is the Oracle equivilent to the UNIX root user Oracle makes you specify the amount of control you have, which is why you'll get an error if you try to connect without specifying the privs: SQL> connect sys/passwd ERROR: ORA-28009: connection to sys should be as sysdba or sysoper SQL> connect sys/passwd as sysdba Connected. SQL> The big diffrence between SYSDBA and SYSOPER privs is that SYSDBA can do anything (just like root). The SYSOPER privs allow you just about the same amount of control but won't allow you to look at user data. Both privs allow you to ALTER DATABASE, CREATE SPFILE, STARTUP or SHUTDOWN, ALTER DATABASE ARCHIVELOG, and includes RESTRICTED SESSION privs. However, only SYSDBA can CREATE or DROP DATABASE and the ALTER DATABASE RECOVER options for SYSOPER are limited to complete recovery only.

P.R.P.R.

Page 39

o The following operations are authorized by the SYSDBA and SYSOPER system privileges:

SYSDBA
1) 2) 3) 4) 5) 6) 7) 8)

Perform STARTUP and SHUTDOWN operations ALTER DATABASE: open, mount, back up, or change character set CREATE DATABASE DROP DATABASE CREATE SPFILE ALTER DATABASE ARCHIVELOG ALTER DATABASE RECOVER Includes the RESTRICTED SESSION privilege

Effectively, this system privilege allows a user to connect as user SYS. SYSOPER
1) 2) 3) 4) 5)

6)

Perform STARTUP and SHUTDOWN operations CREATE SPFILE ALTER DATABASE OPEN/MOUNT/BACKUP ALTER DATABASE ARCHIVELOG ALTER DATABASE RECOVER (Complete recovery only. Any form of incomplete recovery, such as UNTIL TIME|CHANGE|CANCEL|CONTROLFILE requires connecting as SYSDBA.) Includes the RESTRICTED SESSION privilege

To see which user having sysdba & sysoper privs:

>>SELECT * FROM V$PWFILE_USERS The manner in which you are authorized to use these privileges depends upon the method of authentication that you use.

P.R.P.R.

Page 40

When you connect with SYSDBA or SYSOPER privileges, you connect with a default schema, not with the schema that is generally associated with your username. For SYSDBA this schema is SYS; for SYSOPER the schema is PUBLIC.

Connecting with Administrative Privileges:

Example: This example illustrates that a user is assigned another schema (SYS) when connecting with the SYSDBA system privilege. Assume that the sample user oe has been granted the SYSDBA system privilege and has issued the following statements: CONNECT oe/oe CREATE TABLE admin_test(name VARCHAR2(20));

Later, user oe issues these statements: CONNECT oe/oe AS SYSDBA SELECT * FROM admin_test;

User oe now receives the following error: ORA-00942: table or view does not exist

Having connected as SYSDBA, user oe now references the SYS schema, but the table was created in the oe schema. SYS Password:
>> Alter user sys identified by syspw; SQL> conn system/manager Connected. SQL> conn sys as sysdba P.R.P.R. Page 41

Enter password: syspw Connected. SQL> sho user USER is "SYS"

??? ( its accepting anything)

SQL> select count(*) from session_privs; COUNT(*) ---------166

If u connect sys as sysoper then the default user is PUBLIC

SQL> conn system/manager Connected. SQL> sho user USER is "SYSTEM" SQL> conn sys as sysoper Enter password: syspw (should be SYS Password) Connected. SQL> sho user USER is "PUBLIC" SQL> select count(*) from session_privs; COUNT(*) ---------3 SQL> select * from session_privs; PRIVILEGE ---------------------------------------CREATE SESSION RESTRICTED SESSION SYSOPER

P.R.P.R.

Page 42

Oracle User Account Details


Default Users
Username Default Password Account Description All of the base tables and views for the database's data dictionary are stored in the schema SYS. These base tables and views are critical for the operation of Oracle. To maintain the integrity of the data dictionary, tables in the SYS schema are manipulated only by Oracle; they should change_on_install never be modified by any user or database administrator, and no one should create any tables in the schema of the user SYS. The DBA should change the password for SYS immediately after database creation!!! The SYSTEM username creates additional tables and views that display administrative information, and internal tables and views used by Oracle tools. Never create in the SYSTEM schema tables of interest to individual users. SYSTEM is a little bit "weaker" user than SYS, for example, it has no access to so called X$ tables (the very internal structure tables of Oracle). SYSTEM manager Although in real life you may be in a situation when some product or whatever you want to create objects in above mentioned user's schemas. Be flexible, don't sacriface a product only because it will create some objects in SYS or SYSTEM schema The DBA should change the password for SYSTEM immediately after database creation!!! Supports Oracle SNMP (Simple Network Management Protocol). The Oracle Intelligent Agent requires a database logon for each SID that it manages. By default this account is called "DBSNMP" and the password is "DBSNMP". The account name and/or password SHOULD be changed from the default but you will need to make a few additional modifications. In the examples below, you will need to replace any information with brackets < > with the information from your system. 1. 2. Remove all Jobs and Events currently registered against this database. Stop the Intelligent Agent Oracle7 - Oracle8i

SYS

DBSNMP

dbsnmp

P.R.P.R.

Page 43

% lsnrctl dbsnmp_stop Oracle9i % agentctl stop 3. Edit the $ORACLE_HOME/network/admin/snmp_rw.ora file. Add the following parameter: SNMP.CONNECT.<connect_string>.NAME=<username> SNMP.CONNECT.<connect_string>.PASSWORD=<password> The variable <connect_string> is the exact listing of the database name as it appears in the snmp_ro.ora file. If <username> is the default (DBSNMP), there is no need to specify the user here. Only the password is required. On UNIX, set the following permission on the "SNMP_RW.ORA" file: % chmod 600 snmp_rw.ora 4. Change the DBSNMP password on the database. You can use either Security Manager, Sqlplus, or Server Manager. If you use SQLPlus or Server Manager, you can issue the following command: SQL> alter user "dbsnmp" identified by "<newpassword>"; 5. Stop and restart the Intelligent Agent.

Oracle8i adds the OUTLN user schema to support Plan Stability. The OUTLN user acts as a place to centrally manage metadata associated with stored outlines. This user has DBA role. It is used for plan stability ie. to keep the same execution plans for the same queries even if your system configuration or statistics changes. Execution plans will be the same in different Oracle releases with different optimizers. The DBA should either lock the user account or change the password for the OUTLN user immediately after database creation!!! Supports Oracle Spatial. Oracle Spatial is an integrated set of functions and procedures that enables spatial data to be stored, accessed, and analyzed quickly and efficiently in an Oracle8i database. MDSYS mdsys [..] The spatial attribute of a spatial feature is the geometric representation of its shape in some coordinate space. This is referred to as its geometry. The DBA should either lock the user account or change the password for the MDSYS user immediately after database creation!!!

OUTLN

outln

P.R.P.R.

Page 44

ORDSYS

ordsys

Supports Oracle8i Time Series. Oracle8i Time Series (in previous releases called the Oracle8 Time Series Cartridge) is an extension to Oracle8i that provides storage and retrieval of timestamped data through object types. Oracle8i Time Series is a building block for applications rather than being an end-user application in itself. It consists of data types along with related functions for managing and processing time series data. The DBA should either lock the user account or change the password for the ORDSYS user immediately after database creation!!! Supports Oracle interMedia. Oracle interMedia is a single product that enables Oracle8i to store, manage, and retrieve text, documents, geographic location information, images, audio, and video in an integrated fashion with other enterprise information. Oracle interMedia extends Oracle8i reliability, availability, and data management to text and multimedia content in Internet, electronic commerce, and media-rich applications as well as online Internet-based geocoding services for locator applications. The DBA should either lock the user account or change the password for the ORDPLUGINS user immediately after database creation!!! Supports Oracle ConText Cartridge. Oracle8 ConText Cartridge provides powerful search, retrieval, and viewing capabilities for text stored in an Oracle8 database. In addition, ConText provides advanced linguistic processing of English-language text. The DBA should either lock the user account or change the password for the CTXSYS user immediately after database creation!!! Dynamic Services Secured Web Service. Dynamic Services Engine (DS Engine) allows creation, aggregation and deployment of services from a variety of content sources. At the moment, Dynamic Services supports content access from databases (SQL/PLSQL) as well as Internet applications (HTTP/HTTPS). DS Engine can interpret XML and HTML content along with the result sets returned from database access. DS Engine is integrated with Oracle Portal via a Web Provider mechanism. This integration allows all the services registered with DS Engine to be accessible as portlets. The DBA should either lock the user account or change the password for the DSSYS user immediately after database creation!!! Oracle Statistics Package (STATSPACK) user that supersedes UTLBSTAT/UTLESTAT. The PERFSTAT user will hold all of the tables and packages for the performance diagnostic tool STATSPACK. Created By: $ORACLE_HOME/rdbms/admin/spcusr.sql

ORDPLUGINS ordplugins

CTXSYS

ctxsys

DSSYS

dssys

PERFSTAT

perfstat

WKPROXY

Used to support Oracle's Ultrasearch option. This feature (and user) was introduced in Oracle9i. The user account IS NOT locked by default is change_on_install only assigned the "CREATE SESSION" privilege. None the less, this account is not locked by default and Oracle highly recommends that this default password be changed.

P.R.P.R.

Page 45

Created By: $ORACLE_HOME/ultrasearch/admin/wk0csys.sql Used to support Oracle's Ultrasearch option. This feature (and user) was introduced in Oracle9i. The user account IS NOT locked by default and as you can see below, is granted the highly privileged role of DBA. Given that this user is granted the DBA role and is not locked by default, Oracle highly recommends that this default password be changed. This support account is assigned the following privileges in Oracle9i: CONNECT RESOURCE DBA ALL PRIVILEGES CTXAPP CREATE PUBLIC SYNONYM DROP PUBLIC SYNONYM CREATE ANY VIEW DROP ANY VIEW CREATE ANY TABLE DROP ANY TABLE CREATE ANY INDEX DROP ANY INDEX CREATE ANY SEQUENCE DROP ANY SEQUENCE CREATE ANY TRIGGER DROP ANY TRIGGER JAVAUSERPRIV JAVASYSPRIV SELECT ON SYS.USER$ SELECT ON SYS.V_$PARAMETER SELECT ON SYS.GV_$INSTANCE SELECT ON SYS.V_$DATABASE SELECT ON SYS.DBA_CONSTRAINTS SELECT ON SYS.DBA_JOBS SELECT ON SYS.DBA_DB_LINKS SELECT ON SYS.DBA_ROLE_PRIVS SELECT ON SYS.DBA_LOCK SELECT ON SYS.DBMS_LOCK_ALLOCATED SELECT ON SYS.PROCEDURE$ SELECT ON SYS.DBA_TABLES SELECT ON SYS.DBA_VIEWS SELECT ON SYS.DBA_TAB_COLUMNS EXECUTE ON SYS.DBMS_LOCK EXECUTE ON SYS.DBMS_PIPE EXECUTE ON SYS.DBMS_REGISTRY

WKSYS

change_on_install

The default tablespace for this user will be "DRSYS" while its temporary tablespace will be "TEMP". Created By: $ORACLE_HOME/ultrasearch/admin/wk0install.sql

P.R.P.R.

Page 46

WMSYS

wmsys

Used to store all the metadata information for Oracle Workspace Manager. This user was introduced in Oracle9i and (like most Oracle9i supporting accounts) is locked by default. The user account is locked because we want the password to be public but restrict access to the account to the SYS schema. So, to unlock the account, DBA privileges are required. Created By: $ORACLE_HOME/rdbms/admin/owmctab.plb

XDB

Used to support SQL XML management: XML DB. This user is granted two roles: "RESOURCE" and "JAVAUSERPRIV". Oracle recommends changing the password for this user after creation. This user is configured change_on_install with a default tablespace of "XDB" and a temporary tablespace of "TEMP". Created By: $ORACLE_HOME/rdbms/admin/catqm.sql

...IDENTIFIED ANONYMOUS BY VALUES 'anonymous'

Used to support SQL XML management: XML DB. Allows HTTP access to Oracle XML DB. This user should only be used for HTTP logins. The account is locked near the end of the catqm.sql script. Created By: $ORACLE_HOME/rdbms/admin/catqm.sql Used to support Oracle Data Mining. In Oracle9i, this user is granted the roles: "SELECT_CATALOG_ROLE", "HS_ADMIN_ROLE", "AQ_USER_ROLE". Oracle recommends changing the default password as the account IS NOT locked after creation. The default tablespace for this user is "ODM" with temporary tablespace "TEMP". The "ODM" tablespace is populated with segments from users ODM and ODM_MTR. Created By: $ORACLE_HOME/dm/admin/dmcrt.sql Used to support Oracle Data Mining. In Oracle9i, this user is granted "SELECT_CATALOG_ROLE" and "HS_ADMIN_ROLE". Oracle recommends changing the default password as the account IS NOT locked after creation. The default tablespace for this user is "ODM" with temporary tablespace "TEMP". The "ODM" tablespace is populated with segments from users ODM and ODM_MTR. Created By: $ORACLE_HOME/dm/admin/dmcrt.sql This user is create if OLAP option is installed and is used to create OLAP metadata structures. In Oracle9i, this user is granted "SELECT_CATALOG_ROLE" and "HS_ADMIN_ROLE". Oracle recommends changing the default password. The default tablespace for this user is "ODM" with temporary tablespace "TEMP". The "ODM" tablespace is populated with segments from users ODM and ODM_MTR. Created By: $ORACLE_HOME/dm/admin/dmcrt.sql Oracle Trace server. Supports Oracle Trace for OEM in Oracle7. Oracle Trace is used to collect a wide variety of data, such as performance statistics, diagnostic data, system resource usage, and business transaction details. This user was last used in Oracle7 and can be dropped from databases

ODM

odm

ODM_MTR

mtrpw

OLAPSYS

mtrpw

TRACESVR

trace

P.R.P.R.

Page 47

using Oracle8 and higher. Replication user. This user is manually created by the DBA using Managed by DBA CREATE USER... This user is also created in the scripts: when user is $ORACLE_HOME/ldap/admin/oidrsrms.sql and created. $ORACLE_HOME/ldap/admin/oidrsms.sql. Oracle recommends changing the default password if automatically created.

REPADMIN

P.R.P.R.

Page 48

P.R.P.R.

Page 49

Creating and Maintaining a Password File:


You can create a password file using the password file creation utility, ORAPWD. For some operating systems, you can create this file as part of your standard installation.

Using ORAPWD When you invoke this password file creation utility without supplying any parameters, you receive a message indicating the proper use of the command as shown in the following sample output: > orapwd Usage: orapwd file=<fname> password=<password> entries=<users> force=<y/n>

{$orapwd file=orapw$ORACLE_SID password=www force=y}


Where File Password Entries Force - name of password file (mand), - password for SYS (mand), - maximum number of distinct DBAs and OPERs (opt), - whether to overwrite existing file (opt) There are no spaces around the equal-to (=) character.

The following command creates a password file named www that allows up to 30 privileged users with different passwords. In this example, the file is initially created with the password secret for users connecting as SYS. orapwd FILE=www PASSWORD=secret ENTRIES=30
P.R.P.R. Page 50

The parameters in the ORAPWD utility are described in the sections that follow.

FILE This parameter sets the name of the password file being created. You must specify the full path name for the file. The contents of this file are encrypted, and the file cannot be read directly. This parameter is mandatory. The types of filenames allowed for the password file are operating system specific. Some operating systems require the password file to adhere to a specific format and be located in a specific directory. Other operating systems allow the use of environment variables to specify the name and location of the password file. For name and location information for the Unix and Linux operating systems, see Administrator's Reference for UNIX-Based Operating Systems. For Windows, see Platform Guide for Microsoft Windows. For other operating systems, see your operating system documentation. If you are running multiple instances of Oracle Database using Oracle Real Application Clusters, the environment variable for each instance should point to the same password file. Caution: It is critically important to the security of your system that you protect your password file and the environment variables that identify the location of the password file. Any user with access to these could potentially compromise the security of the connection. PASSWORD This parameter sets the password for user SYS. If you issue the ALTER USER statement to change the password for SYS after connecting to the database, both the password stored in the data dictionary and the password stored in the password file are updated. This parameter is mandatory. Note: You cannot change the password for SYS if REMOTE_LOGIN_PASSWORDFILE is set to SHARED. An error message is issued if you attempt to do so.
P.R.P.R. Page 51

ENTRIES This parameter specifies the number of entries that you require the password file to accept. This number corresponds to the number of distinct users allowed to connect to the database as SYSDBA or SYSOPER. The actual number of allowable entries can be higher than the number of users, because the ORAPWD utility continues to assign password entries until an operating system block is filled. For example, if your operating system block size is 512 bytes, it holds four password entries. The number of password entries allocated is always a multiple of four. Entries can be reused as users are added to and removed from the password file. If you intend to specify REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE, and to allow the granting of SYSDBA and SYSOPER privileges to users, this parameter is required. Caution: When you exceed the allocated number of password entries, you must create a new password file. To avoid this necessity, allocate a number of entries that is larger than you think you will ever need. FORCE This parameter, if set to Y, enables you to overwrite an existing password file. An error is returned if a password file of the same name already exists and this parameter is omitted or set to N.

Setting REMOTE_LOGIN_ PASSWORDFILE In addition to creating the password file, you must also set the initialization parameter REMOTE_LOGIN_PASSWORDFILE to the appropriate value. The values recognized are:

NONE: Setting this parameter to NONE causes Oracle Database to behave as if the password file does not exist. That is, no privileged connections are allowed over nonsecure connections. EXCLUSIVE: (The default) An EXCLUSIVE password file can be used with only one instance of one database. Only an EXCLUSIVE file can be modified. Using an

P.R.P.R.

Page 52

EXCLUSIVE password file enables you to add, modify, and delete users. It also enables you to change the SYS password with the ALTER USER command. SHARED: A SHARED password file can be used by multiple databases running on the same server, or multiple instances of a Real Application Clusters (RAC) database. A SHARED password file cannot be modified. This means that you cannot add users to a SHARED password file. Any attempt to do so or to change the password of SYS or other users with the SYSDBA or SYSOPER privileges generates an error. All users needing SYSDBA or SYSOPER system privileges must be added to the password file when REMOTE_LOGIN_PASSWORDFILE is set to EXCLUSIVE. After all users are added, you can change REMOTE_LOGIN_PASSWORDFILE to SHARED, and then share the file. This option is useful if you are administering multiple databases or a RAC database.

If REMOTE_LOGIN_PASSWORDFILE is set to EXCLUSIVE or SHARED and the password file is missing, this is equivalent to setting REMOTE_LOGIN_PASSWORDFILE to NONE.

Adding Users to a Password File When you grant SYSDBA or SYSOPER privileges to a user, that user's name and privilege information are added to the password file. If the server does not have an EXCLUSIVE password file (that is, if the initialization parameter REMOTE_LOGIN_PASSWORDFILE is NONE or SHARED, or the password file is missing), Oracle Database issues an error if you attempt to grant these privileges. A user's name remains in the password file only as long as that user has at least one of these two privileges. If you revoke both of these privileges, Oracle Database removes the user from the password file. Creating a Password File and Adding New Users to It Use the following procedure to create a password and add new users to it: 1. Follow the instructions for creating a password file 2. Set the REMOTE_LOGIN_PASSWORDFILE initialization parameter to EXCLUSIVE. (This is the default.)

P.R.P.R.

Page 53

Note: REMOTE_LOGIN_PASSWORDFILE is a static initialization parameter and therefore cannot be changed without restarting the database. 3. Connect with SYSDBA privileges as shown in the following example: 4. CONNECT SYS/password AS SYSDBA 5. 6. Start up the instance and create the database if necessary, or mount and open an existing database. 7. Create users as necessary. Grant SYSDBA or SYSOPER privileges to yourself and other users as appropriate. >> sho parameter password NAME TYPE VALUE ------------------------------------ ---------------------------------------remote_login_passwordfile string EXCLUSIVE Viewing Password File Members Use the V$PWFILE_USERS view to see the users who have been granted SYSDBA or SYSOPER system privileges for a database. The columns displayed by this view are as follows: Column Description

USERNAME This column contains the name of the user that is recognized by the password file. SYSDBA SYSOPER If the value of this column is TRUE, then the user can log on with SYSDBA system privileges. If the value of this column is TRUE, then the user can log on with SYSOPER system privileges.

Maintaining a Password File This section describes how to:

P.R.P.R.

Page 54

Expand the number of password file users if the password file becomes full Remove the password file

Expanding the Number of Password File Users If you receive the file full error (ORA-1996) when you try to grant SYSDBA or SYSOPER system privileges to a user, you must create a larger password file and regrant the privileges to the users. Replacing a Password File Use the following procedure to replace a password file: 1. Identify the users who have SYSDBA or SYSOPER privileges by querying the V$PWFILE_USERS view. 2. Delete the existing password file. 3. Follow the instructions for creating a new password file using the ORAPWD utility. Ensure that the ENTRIES parameter is set to a number larger than you think you will ever need. 4. Follow the instructions in Adding Users to a Password File Removing a Password File If you determine that you no longer require a password file to authenticate users, you can delete the password file and then optionally reset the REMOTE_LOGIN_PASSWORDFILE initialization parameter to NONE. After you remove this file, only those users who can be authenticated by the operating system can perform SYSDBA or SYSOPER database administration operations.

hiprpr@gmail.com

@@@@@@@@@@@@$$$$$$$$$$$$$$$$$$$$$$$$&&&&&&&&&&&&&&

P.R.P.R.

Page 55

ROLES

A Role is created as a container for group of privileges You may also grant a role to user and another role The role must be unique A user can have n no. of roles

CREATE A ROLE >> create role <role name>; >> create role r1; >> Desc dba_roles;

ASSIGN PRIVILEGES TO A ROLE >>Grant create user, create tablespace to r1;

ASSIGN ROLE TO A USER >> grant r1 to u1;

P.R.P.R.

Page 56

How to see Assigned roles for a User: select * from dba_role_privs where grantee='U1' DBA_ROLE_PRIVS

HOW TO SEE THE PRIVILEGES IN A ROLE

>>Desc role_sys_privs >> select * from role_sys_privs where role=R1; >> select * from role_sys_privs where role=CONNECT; >> select * from role_sys_privs where role=RESOURCE;
Show what roles are granted to a user select grantee, granted_role, admin_option from dba_role_privs where grantee like upper('&username') / Show what table privileges are granted to a role select / owner || '.' || table name "TABLE", column_name, privilege, grantable from role_tab_privs where role like '&role'

P.R.P.R.

Page 57

Grant select on all tables owned by specific user: This is for exsisting tables only,If u cr8 new table u wont select that table.
Select 'GRANT SELECT ON OwningUser.'||Table_Name||' TO ReceivingUser ; ' From All_Tables Where Owner='OWNINGUSER' ;

This is for all tables exsisting & new tables also Syntax: Grant select any table to username; Eg: Grant select any table to bb; User bb can select any table of any user. Demo: Sys> grant connect,resource to uu identified by uu; Sys> grant connect,resource to pp identified by pp; Sys> grant connect,resource to kk identified by kk; uu> create table uu(no number); insert some records.. pp> create table pp(no number); Insert some records Sys> grant select any table to kk; kk> select * from uu.uu;
P.R.P.R. Page 58

rows selected kk> select * from pp.pp; rows selected..

SQL> revoke select any table from kk; Revoke succeeded. Creating synonyms for all tables in a user. I granted SELECT Privs for a user,But that user accesing like. Username.<tablename> In stead of this I am going to cr8 synonyms for all objects in the second user. SYN: >> select 'create synonym ' || table_name || ' for ap.' || table_name || ';' from all_tables where owner='AP' AP is username

P.R.P.R.

Page 59

PRIVILEGES
System privileges Object privileges

Grant the privileges with admin option With grant option

With admin option: Scenario: 1. The DBA grants the CREATE TABLE system privilege to User1 with the ADMIN OPTION. 2. User1 creates a table. 3. User1 grants the CREATE TABLE system privilege to User2. 4. User2 creates a table. 5.The DBA revokes the CREATE TABLE system privilege from User1. The result: User1 table still exists, but no new tables can be created. User2 table still exists and she still has the CREATE TABLE system privilege With Grant Option: Scenario User1 is granted the SELECT object privilege on EMPLOYEES with the GRANT OPTION. User1 grants the SELECT privilege on EMPLOYEES to User2. Later, the SELECT privilege is revoked from User1. This revoke is cascaded to User2 as well.

P.R.P.R.

Page 60

PROFILES
SET OF RESOURCES A USER CAN HAVE ONLY ONE PROFILE AT A TIME. MENTION 1 PARAMETER IN PFILE RESOURCE_LIMIT=TRUE >> Create profile p1 Limit failed_login_attempts 3 idle_time 20 Password_lock_time 1/24 sessions_per_user 2; >> alter user u1 profile p1; >> Desc dba_profiles >> Select username, profile from dba_users; ALTER a Profile: SQL> alter profile p1 limit failed_login_attempts 5; Profile altered. Sql> alter profile p1 Limit Failed_login_attempts unlimited;
P.R.P.R. Page 61

Profile altered. VIEWS:


USER: DBA_USERS USER_USERS ALL_USERS DBA_TS_QUOTAS USER_TS_QUOTAS

# DBA_SUBSRIPTIONS # DBA_CONNECT_ROLE_GRANTEES # DBA_APPLICATION_ROLES

ROLES: DBA_ROLES DBA_ROLE_PRIVS ROLE_SYS_PRIVS SESSION_ROLES ROLE_ROLE_PRIVS

USER_ROLE_PRIVS USER_SYS_PRIVS

PROFILES: DBA_PROFILES USER_PASSWORD_LIMITS USER_RESOURCE_LIMITS PRIVILEGES: DBA_TAB_PRIVS DBA_SYS_PRIVS@ DBA_COL_PRIVS ALL_TAB_PRIVS ALL_TAB_PRIVS_MADE ALL_TAB_PRIVS_RECD COLUMN_PRIVILEGES SYSTEM_PRIVILEGE_MAP SESSION_PRIVS USER_TAB_PRIVS USER_COL_PRIVS ALL_COL_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD

P.R.P.R.

Page 62

Profiles in ORACLE:
Profiles are a means to limit resources a user can use. Before profiles can be assigned, they must be created with create profile. Then, they can be assigned to users with alter user ... profile. Limitable resources The following limits can be specified: Kernel limits Maximum concurrent sessions for a user (sessions_per_user) CPU time limit per session (cpu_per_session) CPU time limit per call (cpu_per_call) Call being parse, execute and fetch Maximum connect time (connect_time) The session will be dropped by oracle after specified time. Maximum idle time (idle_time) The session will be dropped by oracle after specified time of doing nothing. Long running processes are not idle! Maximum blocks read per session (logical_reads_per_session) Maximum blocks read per call (logical_reads_per_call) Maximum amount of SGA (private_sga) .... (composite_limit) In order to enforce kernel limits, resource_limit must be set to true. Password limits Maximum failed login attempts (failed_login_attempts) Maximum time a password is valid (password_life_time) Minimum of different passwords before password can be reused (password_reuse_max) Minimum of days before a password can be reused (password_reuse_time) Number of days an account is locked after failing to login (password_lock_time) P.R.P.R. Page 63

??? (password_grace_time) Verify function for passwords (password_verify_function) If a session exceeds one of these limits, Oracle will terminate the session. If there is a logoff trigger, it won't be executed. History of passwords In order to track password related profile limits, Oracle stores the history of passwords for a user in user_history$. Quering created profiles Profiles already created and their settings can be queried through dba_profiles

P.R.P.R.

Page 64

P.R.P.R.

Page 65

STORAGE PARAMETERS

LMTS

DMTS

UNIFORM

INITIAL NEXT MIN MAX PCT

64k __ 1 2147483645 __

40k 40K 1 505 50%

1m __ 1 2147483645 0%

>> Desc dba_tablespaces

>> select tablespace_name, extent_management, segment_space_management From dba_tablespaces;

>> save sp >> create tablespace lmts datafile location size 10m; >> @sp
P.R.P.R. Page 66

>> Select tablespace_name, initial_extent, next_extent, min_extents, max_extents, Pct_increase From dba_tablespaces where tablespace_name=LMTS; O/p Tsname Lmts initial 65536 next min 1 max 2147483645 pct

>> Create tablespace lmts1 datafile location size 10m Default storage(initial 20k next 3 minextents 4 maxextents 23); Tablespace created. >>Select tablespace_name, initial_extent, next_extent, min_extents, max_extents, Pct_increase From dba_tablespaces where tablespace_name=LMTS1

O/p Tsname Lmts1 initial 65536 next min 1 max 2147483645 pct

Creating a tablespace with extent management Dictionary: Condition: The System tablespace extent management should be DICTIONARY, Then only we can create >> create tablespace dmts datafile location size 10m Extent management dictionary;
P.R.P.R. Page 67

>> select tablespace_name, initial_extent, next_extent, min_extents, max_extents, Pct_increase From dba_tablespaces where tablespace_name=DMTS; O/p Tsname DMTS Initial 40 next 40 min 1 max 505 pct 50

Create a tablespace with extent management dictionary and mention storage parameters.

>> create tablespace dmts1 datafile location size 10m Extent management dictionary Default storage (initial 20k next 20k minextents 2 maxextents 100 Pctincrease 30); >> select tablespace_name, initial_extent, next_extent, min_extents, max_extents, Pct_increase From dba_tablespaces where tablespace_name=DMTS1;

YOU CAN ALTER >> alter tablespace dmts1 default storage (maxextents 120 pct increase 50)

P.R.P.R.

Page 68

UNIFORM SIZE :

>> create tablespace xy datafile location size 10m uniform size 1m; >> select tablespace_name, extent_management, Segment_space_management from dba_tablespaces; O/p Xy local auto

>> select initial_extent, next, min_extent, max_extent, pct_increase from dba_tablespaces where tablespace_name =XY; O/p Initial 1048576 next 1048576 min 1 max 2147483645 pct 0

****** YOU CANT MENTION UNIFORM SIZE FOR DICTIONARY MANAGED TABLESPACE &&&&&&&&&&

P.R.P.R.

Page 69

E.g.: >> create tablespace ABC datafile location size 10m Extent management dictionary uniform size 1m; ORA-25140

MIGRATE

LMTS TO DMTS

CONDITION: 1. THE TABLESPACE SEGMENT SPACE MANAGEMENT SHOULD BE MANUAL

LMTS DMTS
Create TT tablespace with LMTS MANUAL

>> Exec dbms_space_admin.tablespace_migrate_from_local (TT); >> Desc dba_tablespaces Check it TT DMTS MANUAL

P.R.P.R.

Page 70

DMTS

LMTS

>Exec dbms_space_admin.tablespace_migrate_to_local (TABLESPACENAME);

MENTIONING STORAGE PARAMETERS AT SEGMENT LEVEL.


1. Create tablespace with LMTS AUTO 2. Create a user 3. assign that tablespace as a default for that user

User>> create table t (no number); User>> desc user_tables User>> select initaial_extent, next_extent, min_extents, max_extents, Pct_increase From user_tables; O/p Initial 65536 next min 1 max 2147483645 pct

P.R.P.R.

Page 71

User>> create table Prasad (no number) Storage (initial 20k Next 2 Minextents 2 Maxextents 10 Pctincrease 40); User>> select initaial_extent, next_extent, min_extents, max_extents, Pct_increase From user_tables where table_name=PRASAD;

Initial 35184

next

min 1

max 2147.

pct

Show segments that are approaching max_extents col segment_name format a40 select owner , segment_type , segment_name , max_extents - extents as "spare" , max_extents from dba_segments where owner not in ('SYS','SYSTEM') and (max_extents - extents) < 10 order by 4 / To change maxextents alter <segment_type> <segment_name> storage(maxextents 150);

P.R.P.R.

Page 72

VIEWS: DBA_SEGMENTS DBA_EXTENTS DBA_TABLES DBA_INDEXES

@@@@@@@@@@@@###########################$$$$$$$$$$$$$$$$$$$$$

P.R.P.R.

Page 73

Where as in LMTS
64k (If data reaches) 8m {Each Next extent size 1m.} (If data reaches) 64m {Each Next extent size 8m.} (If data reaches) 1 GB.. {Each Next extent size 64m.} Initially extent size

..8m. 64m.................. 1 GB.. 64k { 1m } { 8m } { 64m

P.R.P.R.

Page 74

P.R.P.R.

Page 75

ROLLBACK SEGMENTS.

We can create rollback segments in DMTS U can cr8 in LMTS also but segment space management should be MANUAL In Pfile undo_management =MANUAL >> Cr8 ts roll location size 10m Extent management dictionary; TO CREATE A ROLLBACK SEGMENT >> create rollback segment rbs tablespace roll; >> Desc dba_rollback_segs >> select segment_name, tablespace_name, status from dba_rollback_segs; >> save roll >> alter rollback segment rbs online; >> @roll TO DROP A ROLLBACK SEGMENT >> alter rollback segment rbs offline; >> drop rollback segment rbs; @@@@
P.R.P.R. Page 76

>> create rollback segment rbs2 tablespace roll storage (optimal 150k); @@@@ >> create rollback segment rbs3 tablespace roll Storage (initial 20k optimal 100k);

FOR AUTOMATIC ONLINE RBS In PFILE Rollback segment=rbs, rbs1, rbs2.

@@@@ >> set transaction use rollback segment rbs3; @@@@ >> alter rollback segment rbs3 shrink to 100k;
hiprpr@gmail.com

@@@@@@@@@@@&&&&&&&&&&&&&&%%%%%%%%%%%

P.R.P.R.

Page 77

UNDO MANAGEMENT

P.R.P.R.

Page 78

IN PFILE Undo_management= AUTO >> Sho parameter undo_ undo_management = AUTO undo_tablespace = UNDOTBS undo_retention = 900

>> create undo tablespace undo1 location size 10m;

NOTE: 1) 2) By default ORACLE will create 10 rollback segments for 1 UNDO Tablespace. By default RETENTION is NOGUARANTEE

>> select segment_name, tablespace_name, status from dba_rollback_segs; >> select tablespace_name, retention from dba_tablespaces; >> alter tablespace undo1 retention guarantee; Noguarantee; SET RETENTION PERIOD >> Alter system set undo_retention =1500; >> Sho parameter undo_
P.R.P.R. Page 79

(You can mention in PFILE also.)

SET AS DEFAULT UNDO TABLESPACE FOR DATABASE >> Sho parameter undo_ Undo_tablespace UNDOTBS

>> alter system set undo_tablespace=UNDO1; >> Sho parameter undo_ undo_tablespace UNDO1

What's in undo
select , , from group , / tablespace_name status count(*) as HOW_MANY dba_undo_extents by tablespace_name status

P.R.P.R.

Page 80

Is anything rolling back at the moment?


Look for the used_ublk value decreasing. If it is, the session connected with it is rolling back. When it reaches zero, rollback is complete. set lines 100 pages 999 col username format a15 col command format a20 select ses.username , substr(ses.program, 1, 19) command , tra.used_ublk from v$session ses , v$transaction tra where ses.saddr = tra.ses_addr / !!!!!!
SQL> select status, count (*) from dba_undo_extents Where tablespace_name like 'UNDOTBS' group by status; STATUS COUNT (*) --------- ---------UNEXPIRED 130 EXPIRED 73

P.R.P.R.

Page 81

DEFFERED ROLLBACK SEGMENT.


Create a tablespace ts1 Create a user ts1 Assign ts1 --------------ts1 Ts1> create a table Do some TXs.. / / / FROM 2ND SESSION Sys> alter tablespace ts1 offline; Sys> select segment_type, segment_name, Tablespace_name from dba_segments Where segment_type like %DEF%; O/p SYSTEM ts will take care of the data SYS> save def SYS> alter tablespace ts1 online; SYS> @def No rows

###########@@@@@@%%%%&&&&&&&&&&&&&

P.R.P.R.

Page 82

SNAP SHOT TOO OLD ERROR. (1555)

>> Sho parameter undo_ O/p Undotablespace Undotbs

>> create undo ts undo1 location size 4m; >> alter system set undo_tablespace=UNDO1; >> Sho parameter undo_ O/p Undo tablespace >> Cr8 a tablespace >> Cr8 a user Assign Snp> cr8 a table Do some TX. / / / Up to ts filled up / Commit SNP SNP SNP SNP Undo1

P.R.P.R.

Page 83

OPEN ONE MORE SESSION 2S Sys> Ed snp 1. begin 2. loop 3. update emp set Sal=3000 where empno=7902; 4. commit; 5. end loop; 6. end; 7. /

Sys> Snp> @snp FROM 1ST SESSION SNP> select * from EMP; ---ORA- 1555 too small SOL: 1. RESIZE THE DATAFILE SIZE 2. ADD ONE MORE DATAFILE TO THE UNDO TS 3. SET UNDO RETENTION ZERO
############

P.R.P.R.

Page 84

PENDING OFFLINE.
>> Sho parameter undo_ O/p Undo tablespace >> cr8 1 undo ts u1> Do some TX.. / / / / FROM 2ND SESSION Sys>> alter system set undo_tablespace=UNDO1; >> Desc V$ROLLSTAT; >> Select USN, status from v$rollstat; undo1; undotbs

{Sys>> Select a.usn, b.name, a.xacts, a.statys


From v$rollstat a, v$rollname b Where a.usn=b.usn and a. status like %PENDING %;}

hiprpr@gmail.com

=====####=====#####=====######

P.R.P.R.

Page 85

...

FLASH BACK

1. 2. 3. 4.

FLASHBACK TABLE (10g) FLASHBACK QUERY (9i) FLASHBACK VERSION QUERY (10g) FLASHBACK TRANSACTION QUERY (10g)

FLASHBACK TABLE: >> Cr8 a tablespace >> Cr8 a user FLB FLB

(Dont use UNDO)

FLB> Demobld (Default location : $ORACLE_HOME/rdbms/admin/utlsampl.sql) > Sho recyclebin >select * from tab; > Drop table EMP; > select * from tab; $BIN. > Sho recyclebin $BIN EMP table time

> Flashback table EMP to before drop; > select * from tab; > Sho recyclebin

P.R.P.R.

Page 86

DROP TABLE PERMINENTLY. Drop table emp PURGE; We cant flashback.

REMOVE TABLES FROM RECYCLEBIN purge recyclebin Recyclebin Views: DBA_RECYCLEBIN USER_RECYCLEBIN RECYCLEBIN

@@@@@#######$$$$$$$$

RENAMING A TABLE WHILE FLASHBACK TIME..

FLB> select * from tab; > select count (*) from EMP; 14 >drop table EMP; > select * from tab; $BIN.. EMP
P.R.P.R.

table
Page 87

> Demobld > select * from tab; EMP table exist > do some TXs in EMP table.. > select count (*) from EMP; 100 >drop table EMP; > Sho recyclebin $BIN. $BIN.

EMP EMP

table table

timestamp timestamp

> Flashback table EMP to before drop; >select * from tab; >select count (*) from EMP 14 > Sho recyclebin $BIN. EMP > Flashback table EMP to before drop; ORA- 38312

table

timestamp

(Bcoz already with the same name 1 table is exist.)

> Flashback table EMP to before drop rename to emp1;

########################

P.R.P.R.

Page 88

FLASHBACK QUERY:

(USE UNDO)

Note: 1) For Flashback Query that undo tablespace retention should be Guarantee 2) By default Retention is NOGUARANTEE SYS>> create undo tablespace undo1 location size 10m Retention guarantee; >> select tablespace_name, retention from dba_tablespaces; >> alter system set undo_tablespace=UNDO1; User> delete from EMP; User> commit; User> select * from EMP as of timestamp sysdate -2/1440; User> create table EMP as of select * from EMP as of timestamp sysdate 2/1440;

###############

P.R.P.R.

Page 89

FLASHBACK VERSION QUERY :

(USE UNDO)

For each commit point ORACLE will gives one XID (transaction id)

User> create table stud (sname varchar2 (12), sno number); User> insert into stud values (ram, 1); User> commit; User> insert into stud values (Prasad, 2); User> commit; User> update stud set sno=10 where sname = ram; User> commit; User> update stud set sno=20 where sname = Prasad; User> commit; User> select * from stud; O/p Sname Ram Prasad sno 10 20

User>Ed versions Select versions_starttime, versions_endtime, versions_xid, versions_operation, Sname from stud Versions between timestamp minvalue and maxvalue Order by versions_starttime;

P.R.P.R.

Page 90

FLASH BACK TANSACTION

(USE UNDO)

Sys>> Desc flashback_transaction_query >> select undo_sql from flashback_transaction_query Where xid=060005005G000000; O/p Update USER.STUD set SNO =1 Where ROWID=

{Execute this statement as a user level or SYS level} 1 row updated..

P.R.P.R.

Page 91

P.R.P.R.

Page 92

P.R.P.R.

Page 93

SP FILE (Server parameter file)

PFILE 1. ASCII Format 1. 2nd preference 2. Dynamic -- 20% Static -- 80%

SPFILE 1. Semi Binary Format 2. 1st preference 3. Dynamic -- 80% Static -- 20%

P.R.P.R.

Page 94

We can create SPFILE at any stage.

ADVANTAGES: 1. We can change the parameters dynamically 2. No need to shut down the database 3. spfile contains 3 options : scope = memory (Default) scope = spfile scope = both MEMORY : It will going to effect current Instance SPFILE : It will going to effect to the upcoming (next) instance. BOTH : It will going to effect to the current Instance as well as upcoming Instance

If i create Pfile from Spfile It takes only ACTIVE PARAMETERS * (STAR) for ACTIVE PARAMETERS (DOT) for INACTIVE PARAMETERS

DIS ADVANTAGES: We cant trace the control file We cant recreate the control file We cant rename the database

HOW TO SEE WHICH PARAMETER IS DYNOMIC.. & WHICH PARAMETER IS STATIC.....???


P.R.P.R. Page 95

>> DESC V$PARAMETER >> Select issys_modifiable from v$parameter; In ISSYS_MODIFIABLE column we have 3 options. If
IMMEDIATE DEFFERED FLASE (DYNOMIC) (SEMI DYNOMICSESSION DEPENDENT) (STATIC)

HOW TO SEE CURRENT DB RUNNING WITH PFILE OR SPFILE? >> Sho parameter pfile/spfile; O/p In VALUE column If NULL value is there then the DB running with PFILE If DB running with SPFILE then in VALUE column it Gives the total Location of SPFILE CREATE A SPFILE: >> Sho parameter pfile; PFILE >> create spfile from pfile; >> Sho parameter pfile; PFILE
P.R.P.R. Page 96

>> Startup force; / (Restart the Instance manually) >> Sho parameter pfile SPFILE >> Sho parameter resource_limit TRUE >> alter system set resource_limit = flase scope= MEMORY; >> Sho parameter resource_limit; FLASE >> Startup force >> Sho parameter resource_limit; TRUE >> alter system set resource_limit= flase scope=SPFILE; >> Sho parameter resource_limit; TRUE >> Startup force >> Sho parameter resource_limit; FLASE >> alter system set resource_limit =true scope=BOTH; >> Sho parameter resource_limit; TRUE >> Startup force >> Sho parameter resource_limit; TRUE CREATE A PFILE USING SPFILE: >>create pfile from spfile;

P.R.P.R.

Page 97

OMF
(ORACLE MANAGED FILES)

P.R.P.R.

Page 98

In Pfile mention 2 parameters... db_create_file_dest=location db_create_online_log_dest_1=location #control_files #undo_tablespace Create required directory structure Startup nomount Create database; (for data files) (for ctrl & log files)

Default tablespace size is 100mb

P.R.P.R.

Page 99

CONTROLFIILE MANAGEMENT

P.R.P.R.

Page 100

V$CONTROLFIILE V$CONTROLFILE_RECORD_SECTION MIN MAX 1 8

MULTIPLEXING THE CONTRILFILES.. SYS>> sho parameter control_files SYS>> shut immediate ] $ go to cont. file location ] $ copy the control files to new locations
] $ open parameter file. ] $ mention the new location in Control_files= ( , )

RECREATING THE CONTROLFILE


>>startup >> alter database backup conttrolfile to trace; Or >> alter database backup controlfile to trace as '/disk1/cont.trc'; >> Exit ] $ go to UDUMP location Udump] $ ls -lrt ] $ cp _..._.trc ~/cont.trc

P.R.P.R.

Page 101

~] $ vi cont.trc ] $ edit that trace file

dgg removing
Up to beginning of the Page Startup nomount

Character set US7ASCII ;

dG

removing up to end of the page

P.R.P.R.

Page 102

TRACE FILE ..
STARTUP NOMOUNT CREATE CONTROLFILE REUSE DATABASE "TEST" RESETLOGS ARCHIVELOG MAXLOGFILES 16 MAXLOGMEMBERS 2 MAXDATAFILES 30 MAXINSTANCES 1 MAXLOGHISTORY 292 LOGFILE GROUP 1 '/disk1/oradata/pavan/redolog1a.log SIZE 4M, GROUP 2 '/disk1/oradata/pavan/redolog2a.log SIZE 4M -- STANDBY LOGFILE DATAFILE '/disk1/oradata/pavan/system.dbf', '/disk1/oradata/pavan/kk.dbf', '/disk1/oradata/pavan/sysaux1.dbf', '/disk1/oradata/pavan/ts2.dbf', '/disk1/oradata/pavan/undo1.dbf', CHARACTER SET US7ASCII ;

>> Startup Error: identifying control file.

>> @cont.trc Control file created .. Open >> Sho parameter cont_
P.R.P.R. Page 103

RENAME A DATABASE

SAME AS RECREATING CONTROLFILE .EVERYTHING IS SAME

BUT in trace file u have to remove old db name and mention new db name Startup nomount CREATE CONTROLFILE REUSE DATABASE RAM RESETLOGS NOARCHIVELOGS

1. IN THE PLACE OF REUSE JUST MENTION SET 2. HERE ram is old name REMOVE THIS and u put ur new name. 3. Same way mentions in parameter file also Startup nomount CREATE CONTROLFILE SET DATABASE PRASAD RESETLOGS NOARCHIVELOGS .EVERYTHING IS SAME

hiprpr@gmail.com

P.R.P.R.

Page 104

P.R.P.R.

Page 105

REDOLOGFILE MANAGEMENT

P.R.P.R.

Page 106

MIN

MAX

GROUPS MEMBERS

2 1

ABOVE 4000 5

VIEWS: V$LOG V$LOGFILE V$LOG_HISTORY V$LOGHIST V$RECOVERY_LOG V$ARCHIVED_LOG MINIMUM REDOLOG FILE SIZE IS 4M.

P.R.P.R.

Page 107

REDOLOGS STATUS 1. CURRENT

I.UNUSED

2. ACTIVE

3. INACTIVE

4 OPTIONS. UNUSED CURRENT ACTIVE INACTIVE

>> select members, group#, status from v$log; ADD A GROUP >> alter database add logfile group 3 /disk1/oradata/good/redo3.log size 5m;

P.R.P.R.

Page 108

ADD A NEW MEMBER TO EXSITING GROUP

>> Alter database add logfile member /disk1/oradata/good/redo4.log to group 3;

TO RENAME A LOGFILE 1. 2. 3. 4. DB in mount stage At OS level copy/rename the old logfiles At ORACLE level RENAME logfile using ALTER command open

~]$ good]$ mv redo4.log redo4a.log SYS>> Alter database rename file /disk1/oradata/good/redo4.log to /disk1/oradata/good/redo4a.log; >> open

TO CLEAR ONLINE REDOLOG FILES.

>>Alter database clear unachieved logfile group 3; Note: If redolog files are lost, the above command will recreate those logfiles

P.R.P.R.

Page 109

DROP A GROUP To drop the redolog file, its status should be INACTIVE

>> Alter database drop logfile group 3;

DROP A MEMBER >> Alter database drop logfile member /disk1/oradata/good/redo4.log; MANUAL LOG SWITCH. >> Alter system switch logfile;
List members and sizes col member format a60 col "Size MB" format 9,999,999 select lf.member , ceil(lg.bytes / 1024 / 1024) "Size MB" from v$logfile lf , v$log lg where lg.group# = lf.group# order by 1 /

P.R.P.R.

Page 110

ARCHIVED REDO LOG FILES


ARCH: ARCH (Archiver) is the Optional background process Max: 10 Views: 1. V$ARCHIVED_LOG 2. V$ARCHIVE_DEST 3. V$ARCHIVE_PROCESSES

TO CONVERT THE DB ARCH MODE We have to one parameter in parameter file dbs] $ vi init$ORACLE_SID.ora log_archive_dest=location create required directory structure >> startup mount >> alter database archivelog; >> alter database open; >> archive log list TO DISEBLE THE ARCH MODE IN MOUNT STAGE >> alter database noarchivelog; >> Archive log list;

P.R.P.R.

Page 111

To check archive log status enabled/disabled


>> select * from V$ARCHIVE_DEST

In Schedule column, if it is ACTIVE then db is in Arch log Mode. In Schedule column,if it is INACTIVE then db is in No Arch Mode.

P.R.P.R.

Page 112

NETWORKING

SERVER SIDE LISTENER.ORA 1. 2. 3. 4. Listener name Protocol Port number SID names

CLIENT SIDE TNSNAMES.ORA 1.Alias name 2.Protocal 3.Port number (Same as server Port) 4. SID names (Same as server SID)

In .bash_profile

TNS_ADMIN=$HOME DEFAULT LOCATION

LISTENER.ORA & TNSNAMES.ORA IS. $ORACLE_HOME/network/admin Port range 1024 to 65536 (Default port number is 1521)
P.R.P.R.

Page 113

LISTENER.ORA LISTENER {Original listener File} (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCAL = IPC) (KEY = ORCL)) (ADDRESS = (PROTOCAL = TCP) (HOST =) (PORT = 1521)) ) ) ) SID_LIST_LISTENER = (SID_LIST = (SID_DESC = (SID_NAME = ORCL) (ORACLE_HOME = /oraeng/app/oracle/product/10.2.0) ) ) @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ RED (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCAL = IPC) (KEY = ORCL)) (ADDRESS = (PROTOCAL = TCP/IP) (HOST = 10.0.0.5) (PORT = 6666)) ) ) )

{After Modification}

SID_LIST_RED = (SID_LIST = (SID_DESC = (SID_NAME = RAM) (ORACLE_HOME = /oraeng/app/oracle/product/10.2.0) ) ) : wq


P.R.P.R. Page 114

Save the file and start the LISTENER .. $ lsnrctl start <listener name> E.g.: $ lsnrctl start RED
@@@ ### &&&&&&&&&&&&&&&&& &&&&& &&&&&& &&&&&&& TNSNAMES.ORA

ALIAS = (DESCRIPTION = {Original Tns File} (ADDRESS_LIST = (ADDRESS = (PROTOCAL = TCP) (HOST = ) (PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = ORCL) ) ) @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GREEN = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCAL = TCP/IP) (HOST = 10.0.0.5) (PORT = 6666)) ) (CONNECT_DATA = (SERVICE_NAME = RAM) ) ) :wq
P.R.P.R.

{After Modification}

Page 115

Ping the tnsnames.ora file $ tnsping <Alias name> E.g.: $ tnsping GREEN

Then u can connect to server .. $ sqlplus username/password@aliasname Username: server side username Password: that user password Alias name: tns name. (GREEN)

SERVER SIDE; My Listener name is SID: ram Port: 6666 Protocol: TCP/IP CLIENT SIDE: My Tnsname (alias name) is GREEN RED

{here database name is PRASAD}

SID: ram (Same as server side) Port: 6666 (Same as server side) Protocol: TCP/IP (Same as server side)

{Here database name is REDDY}

P.R.P.R.

Page 116

$ lsnrctl start RED $ tnsping GREEN $ sqlplus kk/kk@GREEN KK> select * from tab; KK> {KK is server side user}

Like this we can connect to only USER (KK) But if u want connect to SYS (server side) then u should know the PASSWORD FILE of server

CREATE A PASSWORD FILE

In pfile Remote_login_passwordfile=exclusive

dbs] $ orapwd file=orapw$ORACLE_SID password=www force=y SYS> startup force SYS> select * from v$pwfile_users;

$ sqlplus sys/www@GREEN as sysdba SYS> select name from v$instance; o/p ram (This is server side instance name)

P.R.P.R.

Page 117

SYS> select name from v$database; o/p PRASAD (this is server side DB NAME)

Sys>> select * from all_users; Sys>> drop user bb cascade; Sys>> grant connect, resource to bb identified by bb;
hiprpr@gmail.com

P.R.P.R.

Page 118

DATABASE LINKS

P.R.P.R.

Page 119

SERVER SIDE; My Listener name is SID: ram Port: 6666 Protocol: TCP/IP CLIENT SIDE: My Tnsname (alias name) is SID: ram Port: 6666 Protocol: TCP/IP GREEN RED

{Here database name is PRASAD}

(Same as server side) (Same as server side) (Same as server side)

{Here database name is REDDY}

$ lsnrctl start RED $ tnsping GREEN PRIVATE DATABASE LINKS

Sys> select username from dba_users; o/p kk pr Sys>

P.R.P.R.

Page 120

Sys> select username from dba_users; o/p U1 U2 U3 U4 Sys> grant create database link to u1; Sys> Sho parameter global_names TRUE (default) Make it FALSE .. in parameter file. (CLIENT SIDE)

global_names=FALSE

If TRUE: The database link name should be PRASAD (this is db name of server side) U can create with different name also but U cant access the data of server (Prasad) If FALSE: You can create with any name . & you can access the data also.. U1> create database link lnk1 connect to kk identified by kk using GREEN; U1> Desc USER_DB_LINKS; U1> select db_link,username,password from user_db_links; kk> select * from tab; o/p emp dept kk>select count (*) from emp; 14 rowss selected
P.R.P.R. Page 121

U1> select * from tab@lnk1; o/p emp dept U1> select count (*) from emp@lnk1; 14 rows selected U2> select * from tab@lnk1; ERROR U2 cant access the data (Its private DB link)

U1> Insert into emp@lnk1 select * from emp@lnk1; Commit; U1> select count (*) from emp@lnk1; 28 rows selected KK> select count (*) from emp; 28 rows selected

PUBLIC DATABASE LINKS

Sys> grant create public database link to U2; Sys> U2> create public database link lnk2 connect to pr identified by pr Using GREEN; U2> Desc USER_DB_LINKS; U2> select db_link,username,password from user_db_links; View : DBA_DB_LINKS ALL_DB_LINKS
P.R.P.R. Page 122

Sys> Pr> select * from tab; o/p abc xyz Pr>select count(*) from abc; 100 rows selected U2> select * from tab@lnk2; o/p abc xyz U2> select count(*) from abc@lnk2; 100 rows selected From client side using lnk2 (public database link) any user can access Coz lnk2 is public database link

U3> select count(*) from abc@lnk2; 100 rows selected U4> select count(*) from abc@lnk2; 100 rows selected

P.R.P.R.

Page 123

To drop a Public Database link: > drop public database link <link name>;

hiprpr@gmail.com

P.R.P.R.

Page 124

MATERIALIZED VIEWS

P.R.P.R.

Page 125

1. Configure Network links 2. Configure database links

$ lsnrctl start RED $ tnsping GREEN SYS> kk> select count (*) from emp; 14 rows selected SYS> U1> create db link lnk1.. U1> select * from emp@lnk1; 14 rows selected
@@@ Materialized Views can we create in 3 ways. REFRESH REFRESH REFRESH Complete Fast Force

COMPLETE: Entire data is Regenerated every time the MATERIALIZED VIEW Refreshed. FAST: Only the rows that are modified are generated every time the MATERIALIZED VIEW is Refreshed using the MATERIALIZED VIEW log. Changed information is stored in the MATERIALIZED VIEW log. MATERIALIZED VIEW log is a table in the master database that is associated With the master table. Oracle uses a MATERIALIZED VIEW log to track the rows that have been updated on the master table

P.R.P.R.

Page 126

FORCE: Complete + Fast

Sys>grant create materialized view to U1; Sys> U1> select * from tab; Emp Dept

COMPLETE: U1>create materialized view mvn refresh complete with rowid Start with sysdate next sysdate +1/ (24*60*60) As select * from emp@lnk1; {For every second} Check in the client side User(u1) tables, { One more object(mvn) will create) This mvn is the READ ONLY TABLE (ROT), we can select only. U1> select * from tab; Emp Dept Mvn U1> select * from mvn; 14 rows selected KK> insert into emp select * from emp; KK> commit; KK> select count (*) from emp; 28 rows selected

P.R.P.R.

Page 127

U1> select count (*) from mvn; 28 rows selected

REFRESH FAST: KK> select * from tab; Emp Dept KK> select count (*) from dept; 4 rows selected KK> alter table dept add primary key (deptno); KK> create materialized view log on dept;

KK> select * from tab; Emp Dept mlog$_dept

In Parameter file mention (CJQ Background process) From 10g (COORDINATOR JOB QUEUE PROCESS) Max processes: 1000 Job_queue_processes=5 U1> create materialized view mvf refresh fast with primary key start with sysdate Next sysdate +1/ (24*60*60) As select * from dept@lnk1;
P.R.P.R. Page 128

U1> select * from tab; U1 > select count (*) from mvf; 4 rows selected

KK> select count (*) from dept; 4 rows selected KK> insert into dept values (66,DBA,HYD); 1 row created (Not committed) KK>select * from tab;

KK>select * from mlog$_dept; o/p KK> commit; KK> select * from mlog$_dept; o/p KK> / (Some times then observe)

(Observe the Outputs)

U1> select count (*) from mvf; 5 rows selected

P.R.P.R.

Page 129

NOTE:

The MATERIALIZED VIEWS can be manually refreshed using DBMS package

Syntax: >> EXECUTE DBMS_MVIEW.RFRESH (materialized viewname,refresh_option) U1> Exec dbms_mview.refresh (MVN,COMPLETE);

(M.view name) (Option)

DROP Materialized View:


DROP MATERIALIZED VIEW < MV name>;

DROP Materialized View Log:


DROP MATERIALIZED VIEW LOG ON customers;

VIEWS: DBA_MVIEWS DBA_MVIEW_COMMENTS DBA_MVIEW_DETAILS_RELATIONS DBA_MVIEW_LOGS DBA_MVIEW_REFRESH_TIMES DBA_MVIEW_LOG_FILTER_COLS

P.R.P.R.

Page 130

List all materialized view logs


select , from / log_owner log_table dba_mview_logs

Show all materialized and resfresh times


set lines 100 pages 999 col last_refresh format a20 select owner , mview_name , to_char(last_refresh_date, 'dd/mm/yy hh24:mi') last_refresh from dba_mviews order by owner, last_refresh /

Show materialized view tables and masters


set lines 100 col mview format a40 col master format a40 select owner || '.' || name mview , master_owner || '.' || master master from dba_mview_refresh_times /

P.R.P.R.

Page 131

Show refresh jobs in dba_jobs


This is useful for spotting failures
set lines 100 col job format 9999 col log_user format a15 col last format a15 col next format a15 col fail format 9999 col what format a20 select job , log_user , to_char(last_date, 'dd/mm/yy hh24:mi') last , to_char(next_date, 'dd/mm/yy hh24:mi') next , failures fail , replace(what, '"') what from dba_jobs where what like '%dbms_refresh.refresh%' /

o Fast = update changes only o Complete = wipe and repopulate the mview o Force = fast if possible, complete if not.

P.R.P.R.

Page 132

P.R.P.R.

Page 133

BACKUPS

LOGICAL BACKUPS PHYSICAL BACKUPS RMAN

LOGICAL BACLUPS 1. EXPORT / IMPORT 2. DATAPUMP (10g) (Expdp/Impdp)

PHYSICAL BACKUPS 1. COLD BACKUP 2. HOT BACKUP

P.R.P.R.

Page 134

LOGICAL BACKUPS: Default Buffer size 256kb Default Path Conventional Path.

P.R.P.R.

Page 135

] $ exp help=y USERID must be the first parameter on the command line. Keyword Description (Default) Keyword Description (Default) -------------------------------------------------------------------------USERID username/password FULL entire file (N) BUFFER size of data buffer OWNER list of owner usernames FILE output files TABLES list of table names (EXPDAT.DMP) COMPRESS import into one extent (Y) RECORDLENGTH length of IO record GRANTS export grants (Y) INCTYPE incremental export type INDEXES export indexes (Y) RECORD track incr. export (Y) DIRECT direct path (N) TRIGGERS export triggers (Y) LOG log file of screen output STATISTICS analyze objects (ESTIMATE) ROWS export data rows (Y) PARFILE parameter filename CONSISTENT cross-table consistency (N) CONSTRAINTS export constraints (Y)

OBJECT_CONSISTENT transaction set to read only during object export (N) FEEDBACK display progress every x rows (0) FILESIZE maximum size of each dump file FLASHBACK_SCN SCN used to set session snapshot back to FLASHBACK_TIME time used to get the SCN closest to the specified time QUERY select clause used to export a subset of a table RESUMABLE suspend when a space related error is encountered (N) RESUMABLE_NAME text string used to identify resumable statement RESUMABLE_TIMEOUT wait time for RESUMABLE TTS_FULL_CHECK perform full or partial dependency check for TTS VOLSIZE number of bytes to write to each tape volume TABLESPACES list of tablespaces to export TRANSPORT_TABLESPACE export transportable tablespace metadata (N) TEMPLATE template name which invokes iAS mode export

P.R.P.R.

Page 136

] $ imp help=y

Keyword Description (Default) Keyword Description (Default) -------------------------------------------------------------------------USERID username/password FULL import entire file (N) BUFFER size of data buffer FROMUSER list of owner usernames FILE input files (EXPDAT.DMP TOUSER list of usernames SHOW just list file contents (N) TABLES list of table names IGNORE ignore create errors (N) RECORDLENGTH length of IO record GRANTS import grants (Y) INCTYPE incremental import type INDEXES import indexes (Y) COMMIT commit array insert (N) ROWS import data rows (Y) PARFILE parameter filename LOG log file of screen output CONSTRAINTS import constraints (Y) DESTROY overwrite tablespace data file (N) INDEXFILE write table/index info to specified file SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N) FEEDBACK display progress every x rows (0) TOID_NOVALIDATE skip validation of specified type ids FILESIZE maximum size of each dump file STATISTICS import precomputed statistics (always) RESUMABLE suspend when a space related error is encountered (N) RESUMABLE_NAME text string used to identify resumable statement RESUMABLE_TIMEOUT wait time for RESUMABLE COMPILE compile procedures, packages, and functions (Y) STREAMS_CONFIGURATION import streams general metadata (Y) STREAMS_INSTANTIATION import streams instantiation metadata (N) VOLSIZE number of bytes in file on each volume of a file on tape

P.R.P.R.

Page 137

] $ exp full=y {Oracle will take the default file name expdat.dmp}

FULL DATABASE EXPORT Sys>> select * from all_users; kk pr rp Sys>> select username, default_tablespace from dba_users; Kk pr rp Sys>> KK>> select * from tab; KK>> select count (*) from emp; 14 rows selected Sys>> pr>> select * from tab; pr> select count (*) from dept; 4 rows selected ] $ exp file=full.dmp log=full.log full=y Username: / as sysdba (Or) $ exp file=full.dmp log=full.log full=y Username: system/manager kk pr rp

P.R.P.R.

Page 138

Sys>> Drop tablespace pr including contents and datafiles; Sys>> Drop user kk cascade; Sys>> exit ] $ imp file=full.dmp log=full.log full=y ignore=y Sys>> select * from all_users; Sys>> select tablespace_name from dba_tablespaces; Pr exists KK>> select count (*) from emp; 14 rows selected PR>> select count (*) from dept; 4 rows selected

@@@ Sys>> select username, default_tablespace from dba_users; ts ts

Sys>> TS>> select * from tab; emp dept ...... TS>> select count (*) from emp; 14.......... exit ] $ exp file=ts.dmp full=y / as sysdba
P.R.P.R. Page 139

Sys>> Sys>> drop tablespace ts including contents and datafiles; exit ] $ imp file=ts.dmp full=y ignore=y Sys>> Sys>> select tablespace_name from dba_tablespaces; ts ........ Sys>> TS>> select count (*) from emp; 14 row's............

@@@ Sys>> cr8 a tablespace tt Sys>> cr8 a user tt (no data in TT user) Sys>> alter user tt default tablespace tt; Sys>> select username, default_tablespace from dba_users; exit ] $ exp file=tt.dmp tt.log full=y Sys>> drop tablespace tt; ] $ imp file=tt.dmp tt.log full=y ignore=y Sys>> select tablespace_name from dba_tablespaces; o/p There is no tt tablespace.

P.R.P.R.

Page 140

REASON: Here TT user doesnt have any data... (Of course if data is there we cant drop tablespace like this (everyone knows)). But here we r dropping TT Tablespace at only ORACLE level In OS level (tt.dbf) will be exist So we cant import at this time... It will import but the ERROR like in the BLOW { .Importing SYSTEM'S objects into SYSTEM IMP-00017: following statement failed with ORACLE error 1119: "CREATE TABLESPACE "TT" BLOCKSIZE 8192 DATAFILE /disk1/oradata/pavan/tt.dbf' SIZE 4194304 EXTENT MANAGEMENT LOCAL AUTOALLOCATE ONLINE PERMANENT SEGMENT SPACE MANAGEMENT AUTO" IMP-00003: ORACLE error 1119 encountered ORA-01119: error in creating database file '/disk1/oradata/pavan/dd.dbf' ORA-27038: created file already exists }

NOTE: In the same scenario if you drop TT tablespace with INCLUDING OPTION (there is no data in TT user) by importing in the same way you can get back the TT tablespace

P.R.P.R.

Page 141

Tablespace Level:
>> create tablespace kk >> create a user kk >> create a user pp >> Assign KK & PP user default tablespace as KK tablepace >> conn kk/kk kk> Demobld kk> kk> select * from tab; TNAME TABTYPE CLUSTERID ------------------------------ ---------------BONUS TABLE DEPT TABLE EMP TABLE SALGRADE TABLE

>> conn pp/pp pp> create table ppt(no number,name varchar2(12)); pp> insert into ppt pp>select count(*) from ppt; 10 rows

Exporting tablespace D:\app\oracle\product\11.1.0>exp file=kk.dmp log=kk.log tablespaces=kk Export: Release 11.1.0.6.0 - Production on Wed Apr 28 16:33:27 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. Username: / as sysdba Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Productio With the Partitioning, OLAP, Data Mining and Real Application Testing options Export done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set server uses AL32UTF8 character set (possible charset conversion) P.R.P.R. Page 142

About to export selected tablespaces ... For tablespace KK ... . exporting cluster definitions . exporting table definitions . . exporting table BONUS 0 rows exported . . exporting table DEPT 4 rows exported . . exporting table EMP 14 rows exported . . exporting table SALGRADE 5 rows exported . . exporting table PPT 6 rows exported . exporting referential integrity constraints . exporting triggers Export terminated successfully without warnings.

>> conn kk/kk kk>> drop table salgrade purge; >> conn pp/pp pp>> drop table ppt purge;

D:\app\oracle\product\11.1.0>imp file=kk.dmp log=kk.log tablespaces=kk Import: Release 11.1.0.6.0 - Production on Wed Apr 28 16:35:51 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. Username: / as sysdba Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options Export file created by EXPORT:V11.01.00 via conventional path import done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set import server uses AL32UTF8 character set (possible charset conversion) IMP-00031: Must specify FULL=Y or provide FROMUSER/TOUSER or TABLES arguments IMP-00000: Import terminated unsuccessfully

P.R.P.R.

Page 143

Here we need to Use FROMUSER & TOUSER Options..@ Importing..


D:\app\oracle\product\11.1.0>imp file=kk.dmp log=kk.log tablespaces=kk fromuser=kk touser=kk ignore=y Import: Release 11.1.0.6.0 - Production on Wed Apr 28 17:20:59 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. Username: / as sysdba Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options Export file created by EXPORT:V11.01.00 via conventional path import done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set import server uses AL32UTF8 character set (possible charset conversion) . importing KK's objects into KK . . importing table "BONUS" 0 rows imported . . importing table "DEPT" 4 rows imported . . importing table "EMP" 14 rows imported . . importing table "SALGRADE" 5 rows imported Import terminated successfully without warnings.

But we didnt get PPT table of PP user. Again.@


D:\app\oracle\product\11.1.0>imp file=kk.dmp log=kk.log tablespaces=kk fromuser=pp touser=pp ignore=y Import: Release 11.1.0.6.0 - Production on Wed Apr 28 17:25:41 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. Username: / as sysdba Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options

P.R.P.R.

Page 144

Export file created by EXPORT:V11.01.00 via conventional path import done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set import server uses AL32UTF8 character set (possible charset conversion) . importing PP's objects into PP . . importing table "PPT" 6 rows imported Import terminated successfully without warnings.

NOTE: If u want to import at a time both users tables then use FULL=Y option

Here we will get all tables from kk & pp user.

D:\app\oracle\product\11.1.0>imp file=kk.dmp log=kk.log tablespaces=kk full=y ignore=y Import: Release 11.1.0.6.0 - Production on Wed Apr 28 17:29:31 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved. Username: / as sysdba Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options Export file created by EXPORT:V11.01.00 via conventional path import done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set import server uses AL32UTF8 character set (possible charset conversion) . importing SYS's objects into SYS . importing KK's objects into KK . . importing table "BONUS" 0 rows imported . . importing table "DEPT" 4 rows imported . . importing table "EMP" 14 rows imported . . importing table "SALGRADE" 5 rows imported . importing PP's objects into PP . . importing table "PPT" 6 rows imported Import terminated successfully without warnings.

Noe u can got all tables from both the users..@

P.R.P.R.

Page 145

SCHEMA LEVEL:

Sys>> select * from all_users; kk pp pr Sys>> KK>> Demobld exit ] $ exp file=kk.dmp log=kk.log username: kk/kk Sys>> KK>> select drop table ' || tname || ' purge; ' from tab; KK>> spool on KK>> / KK>> spool off KK>>ed on.lst KK>> @on.lst ] $ imp file=kk.dmp log=kk.log ignore=y KK>> select * from tab; all tables are exist @@@ ] $ exp file= kkk.dmp log=kkk.log owner= kk, pp, pr / as sysdba Sys>>
P.R.P.R. Page 146

KK>> select drop table ' || tname || ' purge; ' from tab; KK>> spool on KK>> / KK>> spool off KK>>ed on.lst KK>> @on.lst ] $ imp file=kkk.dmp log=kkk.log fromuser=kk

KK>> select * from tab; all tables are exist

@@@ >> select * from all_users; kk pr rp KK>> select count (*) from emp; 100 rows ] $ exp file=kk.dmp log=kk.log owner=kk / as sysdba ] $ imp file=kk.dmp log=kk.log fromuser=kk touser=ram / as sysdba IMP-00003: ORACLE error 1435 encountered ORA-01435: user does not exist Sys>> grant connect, resource to ram identified by ram;
P.R.P.R. Page 147

] $ imp file=kk.dmp log=kk.log fromuser=kk touser=ram Sys>> RAM>> select count (*) from emp; 100 rows selected

TABLE (OBJECT) LEVEL....

PP>> select * from tab; emp having dept having ] $ exp file=pp.dmp tables=emp, dept username: pp/pp PP>> drop table emp purge; ] $ imp file=pp.dmp tables=emp username: pp/pp

14 rows 4 rows

PP>> select count (*) from EMP; 14 row's.................. @@@


P.R.P.R. Page 148

Moving the object from one user to other user ] $ exp file=ff.dmp log=ff.log owner=kk Sys>> If the same tables are exist then u cant import gives the errorlike
IMP-00015: following statement failed because the object already exists: "CREATE TABLE "EMP" ("EMPNO" NUMBER(4, 0), "ENAME" VARCHAR2(10), "JOB" VARCH" "AR2(9), "MGR" NUMBER(4, 0), "HIREDATE" DATE, "SAL" NUMBER(7, 2), "COMM" NUM" "BER(7, 2), "DEPTNO" NUMBER(2, 0)) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRAN" "S 255 STORAGE(INITIAL 65536 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAU" "LT) LOGGING NOCOMPRESS"

Pr>> drop table EMP purge; Pr>> drop table dept purge; Now it will import Pr>> select count (*) from salgrade;

] $ imp file=ff.dmp log=ff.log fromuser=kk touser=pr ignore=y Pr>> select count (*) from salgrade; Pr>> select * from tab;

P.R.P.R.

Page 149

REORGANIZATION AT TABLESPACES LEVEL Sys>> create a tablespace REG with DMTS >> Grant connect, resource to reg identified by reg; >> Reg default TS REG.

Sys>> Reg>> Demobld Reg>> insert into EMP select * from EMP; / / / Reg>> commit; Sys>>select segment_name, extent_id, file_id, block_id, blocks, bytes from dba_extents Where tablespace_name = REG order by extent_id, block_id; Observe the no. of extents Sys>> save reg ] $ exp file=reg.dmp log=reg.log tables=EMP Username: Reg/reg Reg>> drop table EMP purge; ] $ imp file=reg.dmp log=reg.log tables=EMP Sys>>@reg Observe the no. of extents.
P.R.P.R. Page 150

Senario (1):
Exporting from 9i importing into 11g Export multiple tables from a user (apps) Tables owner is apps Exporting as system/manager

$ exp system/manager file=xyka_tab.dmp log=xyka_tab.log tables=apps.XYKA_CTRL_TOT_BONUS,apps.XYKA_SAL_TOT_BONUS,apps.xyka_nbb_trns_bonus Export: Release 9.2.0.5.0 - Production on Tue Sep 14 12:32:38 2010 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.

Connected to: Oracle9i Enterprise Edition Release 9.2.0.5.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.5.0 - Production Export done in UTF8 character set and AL16UTF16 NCHAR character set About to export specified tables via Conventional Path ... Current user changed to APPS . . exporting table XYKA_CTRL_TOT_BONUS 1 rows exported . . exporting table XYKA_SAL_TOT_BONUS 1 rows exported . . exporting table XYKA_NBB_TRNS_BONUS 95 rows exported Export terminated successfully without warnings.

Import in different server


[oravis@erpdb xyka]$ imp system/manager file=xyka_tab.dmp log=xyka_tab.log fromuser=apps touser=apps Import: Release 11.1.0.7.0 - Production on Tue Sep 14 15:08:57 2010 Copyright (c) 1982, 2007, Oracle. All rights reserved.

Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options Export file created by EXPORT:V09.02.00 via conventional path import done in AL32UTF8 character set and UTF8 NCHAR character set export client uses UTF8 character set (possible charset conversion) export server uses AL16UTF16 NCHAR character set (possible ncharset conversion) . importing APPS's objects into APPS . . importing table "XYKA_CTRL_TOT_BONUS" 1 rows imported . . importing table "XYKA_SAL_TOT_BONUS" 1 rows imported . . importing table "XYKA_NBB_TRNS_BONUS" 95 rows imported Import terminated successfully without warnings.

P.R.P.R.

Page 151

Senario (2): Rename a USER Export all objects from a user Import same dump in to another user.
We need to rename a the User is KK Exporting total schema of kk user
[oracle@rac1 ~]$ exp system/manager file=kk9.dmp log=kk9.log owner=kk
. . . . . . . about to export KK's tables via Conventional Path ... . exporting table BONUS 0 rows exported . exporting table DEPT 1024 rows exported . exporting table EMP 14336 rows exported . exporting table SALGRADE 5 rows exported . exporting table T 0 rows exported exporting synonyms

Create a user and import same dump in to that user

Here I created a user called PR


[oracle@rac1 ~]$ imp system/manager file=kk9.dmp log=kk9.log fromuser=kk touser=pr . importing KK's objects into PR IMP-00017: following statement failed with ORACLE error 1658: "CREATE TABLE "BONUS" ("ENAME" VARCHAR2(10), "JOB" VARCHAR2(9), "SAL" NUMBER" ", "COMM" NUMBER) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 STORAGE(INI" "TIAL 65536 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "K" "K" LOGGING NOCOMPRESS" IMP-00003: ORACLE error 1658 encountered ORA-01658: unable to create INITIAL extent for segment in tablespace KK

When I am trying to import from the dump file it is giving above error. But, the kk user default tablespace is kk PR user default tablespace is PR As per above error, I understood I need to increase the size of KK tablespace. I increased the size and againg imported.. this time
P.R.P.R. Page 152

[oracle@rac1 ~]$ imp system/manager file=kk9.dmp log=kk9.log fromuser=kk touser=pr . importing KK's objects into PR . . importing table "BONUS" . . importing table "DEPT" . . importing table "EMP" . . importing table "SALGRADE" . . importing table "T" Import terminated successfully without warnings.

0 1024 14336 5 0

rows rows rows rows rows

imported imported imported imported imported

Successfully imported.. I tested the default tablespace for the user PR is PR tablespace only. For checking purpose, I made offline the KK tablespace and connected to PR user and selected the tables Alter tablespace kk offline; Conn pr/pr
SQL> select count(*) from emp; select count(*) from emp * ERROR at line 1: ORA-00376: file 5 cannot be read at this time ORA-01110: data file 5: '/oradata/prod/data/kk.dbf'

It is imported in to PR user but not in PR default tablespace (PR) ??????

P.R.P.R.

Page 153

DATABASE REORG.
STEPS: Take a cold backup ( safety purpose) Export the Full backup Drop the database Create brand new database Import the full database

P.R.P.R.

Page 154

P.R.P.R.

Page 155

INCREMENTAL & CUMULATIVE & COMPLETE

COMPLETE BACKUP:

$ exp file=com.dmp log=com.log inctype=complete Username: / as sysdba Sys>> Desc dba_exp_files Sys>> select * from dba_exp_files; Sys>> select * from dba_exp_objects; Sys>> select * from dba_exp_versions; Pr>>

Sys>> pp>> Demobld EMP ----- 14 Dept ------ 4 $ exp file=com.dmp inctype=complete username: / as sysdba sys>> pp>> insert into emp values (ename, empno, sal) values ('geetha', 99, 9999); pp>> insert into emp values (ename, empno, sal) values ('seetha', 23, 3245); pp>> insert into emp values (ename, empno, sal) values ('neetha', 54, 4352); commit;
P.R.P.R. Page 156

pp>> select count (*) from emp; 17 $ exp file=inc.dmp inctype=incremental / as sysdba pp>> delete from emp where sal=9999; 1 row's pp>> select count (*) from emp; 16 $ imp file=inc.dmp ignore=y / as sysdba IMP-00031: Must specify FULL=Y or provide FROMUSER/TOUSER or TABLES arguments IMP-00000: Import terminated unsuccessfully $ imp file=inc.dmp fromuser=pp touser=pp ignore=y / as sysdba . importing PP's objects into PP . . importing table sys>> pp>> select count (*) from emp; 17 rows....
@@@@@@@@@

"EMP"

17 rows imported

Pr>> Demobld Pr>> select count (*) from tab;


P.R.P.R. Page 157

$ exp file=c1.dmp inctype=complete / as sysdba Sys>> select * from dba_exp_files; Pr>> insert into emp select * from emp; Pr>> commit; $ exp file=i1.dmp inctype=incremental / as sysdba Sys>> select * from dba_exp_files; Sys>> select * from dba_exp_versions; Sys>> select * from dba_exp_objects where owner =PR; Pr>> insert into salgrade select * from salgrade; Pr>> commit; $ exp file=i2.dmp inctype=incremental / as sysdba Sys>> select * from dba_exp_files; Sys>> select * from dba_exp_objects where owner =PR; Pr>> drop table salgrade purge; Pr>> insert into dept select * from dept; Pr>> commit; $ exp file=cu1.dmp inctype=cumulative / as sysdba Sys>> select * from dba_exp_files; Sys>> select * from dba_exp_objects where owner =PR; $ imp file=cu1.dmp inctype=restore ignore=y / as sysdba
P.R.P.R. Page 158

Pr>> select * from salgrade;

P.R.P.R.

Page 159

DATA PUMP

P.R.P.R.

Page 160

expdp help=y
Keyword Description (Default) -----------------------------------------------------------------------------ATTACH Attach to existing job, e.g. ATTACH [=job name]. COMPRESSION Reduce size of dumpfile contents where valid keyword values are: (METADATA_ONLY) and NONE. CONTENT Specifies data to unload where the valid keywords are: (ALL), DATA_ONLY, and METADATA_ONLY. DIRECTORY Directory object to be used for dumpfiles and logfiles. DUMPFILE List of destination dump files (expdat.dmp), e.g. DUMPFILE=scott1.dmp, scott2.dmp, dmpdir: scott3.dmp. ENCRYPTION_PASSWORD Password key for creating encrypted column data. ESTIMATE Calculate job estimates where the valid keywords are: (BLOCKS) and STATISTICS. ESTIMATE_ONLY Calculate job estimates without performing the export. EXCLUDE Exclude specific object types, e.g. EXCLUDE=TABLE : EMP. FILESIZE Specify the size of each dumpfile in units of bytes. FLASHBACK_SCN SCN used to set session snapshot back to. FLASHBACK_TIME Time used to get the SCN closest to the specified time. FULL Export entire database (N). HELP Display Help messages (N). INCLUDE Include specific object types, e.g. INCLUDE=TABLE_DATA. JOB_NAME Name of export job to create. LOGFILE Log file name (export. log). NETWORK_LINK Name of remote database link to the source system. NOLOGFILE Do not write logfile (N). PARALLEL Change the number of active workers for current job. PARFILE Specify parameter file. QUERY Predicate clause used to export a subset of a table. SAMPLE Percentage of data to be exported; SCHEMAS List of schemas to export (login schema). STATUS Frequency (secs) job status is to be monitored where the default (0) will show new status when available. TABLES Identifies a list of tables to export - one schema only. TABLESPACES Identifies a list of tablespaces to export. TRANSPORT_FULL_CHECK Verify storage segments of all tables (N). TRANSPORT_TABLESPACES List of tablespaces from which metadata will be unloaded. VERSION Version of objects to export where valid keywords are:
P.R.P.R. Page 161

(COMPATIBLE), LATEST, or any valid database version. The following commands are valid while in interactive mode. Note: abbreviations are allowed Command Description -----------------------------------------------------------------------------ADD_FILE Add dumpfile to dumpfile set. CONTINUE_CLIENT Return to logging mode. Job will be re-started if idle. EXIT_CLIENT Quit client session and leave job running. FILESIZE Default filesize (bytes) for subsequent ADD_FILE commands. HELP Summarize interactive commands. KILL_JOB Detach and delete job. PARALLEL Change the number of active workers for current job. PARALLEL=<number of workers>. START_JOB Start/resume current job. STATUS Frequency (secs) job status is to be monitored where the default (0) will show new status when available. STATUS [=interval] STOP_JOB Orderly shutdown of job execution and exits the client. STOP_JOB=IMMEDIATE performs an immediate shutdown of the Data Pump job.

hiprpr@gmail.com

P.R.P.R.

Page 162

Impdp help=y

Keyword Description (Default) -----------------------------------------------------------------------------ATTACH Attach to existing job, e.g. ATTACH [=job name]. CONTENT Specifies data to load where the valid keywords are: (ALL), DATA_ONLY, and METADATA_ONLY. DIRECTORY Directory object to be used for dump, log, and sql files. DUMPFILE List of dumpfiles to import from (expdat.dmp), e.g. DUMPFILE=scott1.dmp, scott2.dmp, dmpdir: scott3.dmp. ENCRYPTION_PASSWORD Password key for accessing encrypted column data. This parameter is not valid for network import jobs. ESTIMATE Calculate job estimates where the valid keywords are: (BLOCKS) and STATISTICS. EXCLUDE Exclude specific object types, e.g. EXCLUDE=TABLE: EMP. FLASHBACK_SCN SCN used to set session snapshot back to. FLASHBACK_TIME Time used to get the SCN closest to the specified time. FULL Import everything from source (Y). HELP Display help messages (N). INCLUDE Include specific object types, e.g. INCLUDE=TABLE_DATA. JOB_NAME Name of import job to create. LOGFILE Log file name (import. log). NETWORK_LINK Name of remote database link to the source system. NOLOGFILE Do not write logfile. PARALLEL Change the number of active workers for current job. PARFILE Specify parameter file. QUERY Predicate clause used to import a subset of a table. REMAP_DATAFILE Redefine datafile references in all DDL statements. REMAP_SCHEMA Objects from one schema are loaded into another schema. REMAP_TABLESPACE Tablespace object are remapped to another tablespace. REUSE_DATAFILES Tablespace will be initialized if it already exists (N). SCHEMAS List of schemas to import. SKIP_UNUSABLE_INDEXES Skip indexes that were set to the Index Unusable state. SQLFILE Write all the SQL DDL to a specified file. STATUS Frequency (secs) job status is to be monitored where the default (0) will show new status when available. STREAMS_CONFIGURATION Enable the loading of Streams metadata
P.R.P.R. Page 163

TABLE_EXISTS_ACTION Action to take if imported object already exists. Valid keywords: (SKIP), APPEND, REPLACE and TRUNCATE. TABLES Identifies a list of tables to import. TABLESPACES Identifies a list of tablespaces to import. TRANSFORM Metadata transform to apply to applicable objects. Valid transform keywords: SEGMENT_ATTRIBUTES, STORAGE OID and PCTSPACE. TRANSPORT_DATAFILES List of datafiles to be imported by transportable mode. TRANSPORT_FULL_CHECK Verify storage segments of all tables (N). TRANSPORT_TABLESPACES List of tablespaces from which metadata will be loaded. Only valid in NETWORK_LINK mode import operations. VERSION Version of objects to export where valid keywords are: (COMPATIBLE), LATEST, or any valid database version. Only valid for NETWORK_LINK and SQLFILE.

The following commands are valid while in interactive mode. Note: abbreviations are allowed Command Description (Default) -----------------------------------------------------------------------------CONTINUE_CLIENT Return to logging mode. Job will be re-started if idle. EXIT_CLIENT Quit client session and leave job running. HELP Summarize interactive commands. KILL_JOB Detach and delete job. PARALLEL Change the number of active workers for current job. PARALLEL=<number of workers>. START_JOB Start/resume current job. START_JOB=SKIP_CURRENT will start the job after skipping any action which was in progress when job was stopped. STATUS Frequency (secs) job status is to be monitored where The default (0) will show new status when available. STATUS [=interval] STOP_JOB Orderly shutdown of job execution and exits the client. STOP_JOB=IMMEDIATE performs an immediate shutdown of the Data Pump job.
P.R.P.R. Page 164

SQL> sho parameter stream NAME TYPE VALUE ------------------------------------ ----------- -----------------------------streams_pool_size big integer 200M SQL> SQL> desc dba_directories Name Null? Type ----------------------------------------- -------- ---------------------------OWNER NOT NULL VARCHAR2(30) DIRECTORY_NAME NOT NULL VARCHAR2(30) DIRECTORY_PATH VARCHAR2(4000) SQL> SQL> SQL> create directory dpump as '/oradata/prod/dpump'; Directory created.

Full database Backup:


SQL> conn kk/kk Connected. SQL> SQL> select count(*) from emp; COUNT(*) ---------14 [oracle@rac1 ~]$ [oracle@rac1 ~]$ expdp directory=dpump dumpfile=full.dmp logfile=full.log full=y Export: Release 10.2.0.3.0 - Production on Tuesday, 10 August, 2010 1:47:24 Copyright (c) 2003, 2005, Oracle. Username: / as sysdba Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Production With the Partitioning, OLAP and Data Mining options Starting "SYS"."SYS_EXPORT_FULL_01": /******** AS SYSDBA directory=dpump dumpfile=full.dmp logfile=full.log full=y Estimate in progress using BLOCKS method... Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE_DATA All rights reserved.

After that I drop the user KK SQL> drop user kk cascade; User dropped.

P.R.P.R.

Page 165

[oracle@rac1 ~]$ impdp directory=dpump dumpfile=full.dmp logfile=full.log ignore=y LRM-00101: unknown parameter name 'ignore' [oracle@rac1 ~]$ impdp directory=dpump dumpfile=full.dmp logfile=full.log Import: Release 10.2.0.3.0 - Production on Tuesday, 10 August, 2010 1:51:02 Copyright (c) 2003, 2005, Oracle. Username: / as sysdba All rights reserved.

SQL> conn kk/kk Connected. SQL> SQL> select count(*) from emp; COUNT(*) ---------14

REMAP_SCHEMA

[oracle@rac1 ~]$ expdp directory=dpump dumpfile=full1.dmp logfile=full1.log full=y job_name=full1 Drop kk user Then import in to kk1 (New)user. [oracle@rac1 ~]$ impdp directory=dpump dumpfile=full1.dmp logfile=full1.log full=y remap_schema=kk:kk1 Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE_DATA . . imported "KK1"."DEPT" 5.648 . . imported "KK1"."EMP" 7.812 . . imported "KK1"."SALGRADE" 5.578 . . imported "KK1"."BONUS" 0

KB KB KB KB

4 14 5 0

rows rows rows rows

SQL> select * from all_users; USERNAME USER_ID CREATED ------------------------------ ---------- --------KK1 31 10-AUG-10

Oracle will create kk1 user and import total schema of kk. SQL> alter user kk1 identified by kk1; User altered. SQL> conn kk1/kk1 Connected.

P.R.P.R.

Page 166

SQL> select * from tab; TNAME TABTYPE CLUSTERID ------------------------------ ------- ---------DEPT TABLE EMP TABLE BONUS TABLE SALGRADE TABLE SQL> SQL> select count(*) from emp; COUNT(*) ---------14

But above 2 senarios are importing specific user (KK) and remap to kk1 user, meanwhile it is importing the full database also. But we need import only specific user. Using schemas option we can import only a perticuler schema (2) Deleted(DML) some records from a table and trying to import from full export using option schemas=kk (username) In this case it will gives the error
ORA-39151: Table "KK"."DEPT" exists. All dependent metadata and data will be skipped due to table_exists_action of skip ORA-39151: Table "KK"."EMP" exists. All dependent metadata and data will be skipped due to table_exists_action of skip ORA-39151: Table "KK"."BONUS" exists. All dependent metadata and data will be skipped due to table_exists_action of skip ORA-39151: Table "KK"."SALGRADE" exists. All dependent metadata and data will be skipped due to table_exists_action of skip

Already table is exsisting, so we cant import But, If u loss a table (DROP) then it will import the table perfectly using schemas=username (3) Using table_exists_action parameter we can import a specific user Even u perform DML operations on a table also,you can import original table from full export.
P.R.P.R. Page 167

[oracle@rac1 ~]$ impdp directory=dpump dumpfile=full.dmp logfile=full.log schemas=kk table_exists_action=append Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE_DATA . . imported "KK"."DEPT" 5.648 KB 4 . . imported "KK"."EMP" 16.32 KB 224 . . imported "KK"."SALGRADE" 5.578 KB 5 . . imported "KK"."BONUS" 0 KB 0 Job "SYS"."SYS_IMPORT_SCHEMA_02" completed with 5 error(s) at 20:04:42

rows rows rows rows

Stop and Start the Jobs:


[oracle@rac1 ~]$ expdp directory=dpump dumpfile=full.dmp logfile=full.log full=y job_name=fulljob Export: Release 10.2.0.3.0 - Production on Sunday, 15 August, 2010 20:56:55 Copyright (c) 2003, 2005, Oracle. Username: / as sysdba All rights reserved.

To Stop the JOB Press CTRL+C Then u will get Export> To stop the job write stop_job=immediate

Export> stop_job=immediate Are you sure you wish to stop this job ([yes]/no): y

Check in the Base tables Sys> select count(*) from tab; Sys> Select * from tab where tname like FULLJOB;

To restart the job


[oracle@rac1 ~]$ expdp attach=fulljob (Job Name)

Export: Release 10.2.0.3.0 - Production on Sunday, 15 August, 2010 21:11:07 Copyright (c) 2003, 2005, Oracle. Username: / as sysdba All rights reserved.

P.R.P.R.

Page 168

Export> continue_client Job FULLJOB has been reopened at Sunday, 15 August, 2010 21:11 Restarting "SYS"."FULLJOB": /******** AS SYSDBA directory=dpump dumpfile=full.dmp logfile=full.log full=y job_name=fulljob Master table "SYS"."FULLJOB" successfully loaded/unloaded ******************************************************************************

To stop & start the jobs while importing time alsoSamething. To check the status of Datapump Job
>> Select job_name, operation, job_mode, state from user_datapump_jobs

Mechanics of the DataPump: To perform complete datapump job it uses several processes which are new background process to our database 10g, Master process,worker process,shadow processes. Master Process:(MCP) That is Master control process recognized at DMnn. from the backend <instance>_DMnn_<pid>. MCP 1) creates jobs and controls them 2)creates and manages the worker processes 3)Monitor the jobs and log the progress 4) Maintain the job state and restart information in the Master table 5)manages the necessary files, including dump file set. What is master table?? MCP uses a special table called Master table(MT) to log the location of the various database objects in the export dump file. MCP maintain the information like job state and restart information in the master table Where this Master table resides?? Oracle creates the master table in the schema of the user who is running the Datapump job at the begining of every export job. so Master table will have info like what all parameters of the export job, status of all worker process, location of the objects which are inside the dumpfile set.

P.R.P.R.

Page 169

P.R.P.R.

Page 170

P.R.P.R.

Page 171

COLD BACLUPS

SYNTAX FOR MEDIA RECOVERY: >> RECOVER [AUTOMATIC] [FROM LOCATION] [DATABASE] | UNTIL TIME/DATE | UNTIL CANCEL | UNTIL CHANGE USING BACKUP CONTROLFILE; RECOVER Command for INCOMPLETE Recovery:

P.R.P.R.

Page 172

UNTIL CANCEL: Recover database until cancel UNTIL TIME: Recover database Until time 2009-04-15:12:15:36 Recover using backup controlfile: Recover database Until time 2009-04-15:12:15:36 Using backup controlfile AUTOMATIC Automatically applies archived and redo log files OPTION: Until Time YYYY-MM-DD:HH:MI:SS; Until cancel; Until scn < integer>; Using backup controlfile; The ALTER DATABASE RECOVER syntax can be used instead. HOW TO PERFORM COLD BACKUP 1. Shutdown the DB with gracefully 2. Create a directory (To store the C/R/D files) 3. Copy all files in to that directory

P.R.P.R.

Page 173

SCENARIO. 1 DATABASE CRASH (Or) LOSS OF C/R/D FILES.. Sys>> startup Sys>>Archive log list Archivelog mode enabled Sys>> create tablespace kk datafile /disk1/oradata/good/kk.dbf size 10m; Sys>> grant connect, resource to kk identified by kk; Sys>> alter user kk default tablespace kk; Sys>> Kk>> Demobld Kk>> Sys>> shutdown immediate Sys>> exit ~] $ cd /disk1/oradata/good/ Good] $ ls All file are available. Good] $ mkdir cold Good] $ cp * cold/ Good] $ cd cold Cold] $ ls All files are in backup
P.R.P.R. Page 174

(For backup) (Take a backup)

cold] $ cd ~] $ sqlplus /as sysdba Sys>> startup Sys>> kk>> select count (*) from emp; 14 rows Kk>> insert into EMP select * from EMP; / / / / / Kk>> commit; Kk>> same like Do some Transactions in DEPT also.. Kk>> select count (*) from EMP; 1024 rows Kk>> select count (*) from dept; 100 rows Kk>> Sys>> archive log list Sys>> alter system switch logfile; (Manual log switch) / / / Sys>> archive log list Sys>> exit ~] $ ~] $ cd /disk1/oradata/good Good] $ rm * (Remove all files) (You loss all files) Good] $ !sq Sys>> Desc dba_users
P.R.P.R. Page 175

Error Kk>> insert into emp select * from emp; Error Kk>> Sys>> shut immediate Error Sys>> shutdown abort Sys>> exit ~] $ cd /disk1/oradata/good good] $ ls good] $ cd cold/ cold] $ cp * .. (Simple Restore) cold] $ cd .. good] $ ls all files exist good] $ cd ~] $ sqlplus /as sysdba Sys>> startup mount Sys>> Alter database recover automatic using backup controlfile until cancel; Errors Sys>> Recover cancel; Sys>> Alter database open resetlogs; Sys>> Kk>> select count (*) from emp; 1024 rows Kk>. Select count (*) from dept; 100 rows selected Sys>> archive log list; Sys>> select status, resetlog_id from v$database_incarnation;
P.R.P.R. Page 176

SCENARIO.2

LOSS OF CONTROLFILE: Sys>> Kk>> select count (*) from emp; 14 rows Kk>> select count (*) from dept; 4 rows

TAKE A COLD BACKUP 1. SHUT DB 2. COPY ALL FILES AT OS LEVEL 3. STARTUP

Sys>> Kk>> select count (*) from emp; 14 rows Kk>> insert into emp select * from emp; / / / Kk>> commit; Kk>> select count (*) from EMP; 1024 rows Kk>> same like in DEPT also Kk>> select count (*) from dept; 100 rows
P.R.P.R. Page 177

Kk>> Sys>> Alter system switch logfile; / / Sys>> Sys>> exit ~] $ cd /disk1/oradata/good Good] $ rm *.ctl ~] $ Sys>> Desc dba_users Error Sys>> Sys>> shut abort Sys>> exit ~] $ cd /disk1/oradata/good Good] $ cd cold Cold] $ cp *.ctl .. (Simple Restore) Cold] $ cd .. Good] $ ls Ctrl files exist Good] $ cd ~] $ sqlplus /as sysdba Sys>> Sys>> startup mount Sys>> Alter database recover automatic using backup controlfile until cancel; Error: Sys>> Recover cancel;

P.R.P.R.

Page 178

[SOME TIMES WE HAVE APPLY REDOLOG FILES MANULLY] THEN: Sys>> select member from v$logfile; o/p /disk1/oradata/good/redo1.log /disk1/oradata/good/redo2.log

Sys>> Recover automatic using backup controlfile; Specify log : {RET = suggested | filename | AUTO | CANCEL } /disk1/oradata/good/redo1.log

Sys>> Recover automatic using backup controlfile; Specify log : {RET = suggested | filename | AUTO | CANCEL } /disk1/oradata/good/redo2.log Log applied Sys>> alter database open resetlogs; Sys>> Kk>> select count (*) from emp; 1024 kk>> select count (*) from dept; 100

P.R.P.R.

Page 179

SCENARIO.3

LOSS OF SYSTEM DATAFILE

Sys>> Kk>> select count (*) from emp; 14 rows Kk>> select count (*) from dept; 4 rows

TAKE A COLD BACKUP 4. SHUT DB 5. COPY ALL FILES AT OS LEVEL 6. STARTUP

Sys>> Kk>> select count (*) from emp; 14 rows Kk>> insert into emp select * from emp; / / / Kk>> commit; Kk>> select count (*) from emp; 1024 rows

P.R.P.R.

Page 180

Sys>> alter system switch logfile; / / Sys>> exit ~] $ cd /disk1/oradata/good good] $ rm system.dbf Sys>> Desc dba_tablespaces; Sys>> shut abort Sys>> exit ~] $ cd /disk1/oradata/good good] $ cd cold cold] $ cp system.dbf .. cold] $ cd .. good] $ ls good] $ cd ~] $ Sys>> startup mount Sys>> Recover database; [Some it asks..] (Mention here auto/ path)

Specify log : {RET = suggested | filename | AUTO | CANCEL } auto Media recovery complete Sys>> alter database open; Sys>> Kk>> select count (*) from emp; 1024
P.R.P.R. Page 181

SCENARIO.4 LOSS OF NON SYSTEM DATAFILE

Sys>> create tablespace pr datafile /disk1/oradata/good/pr.dbf size 10m; Sys>> grant connect, resource to pr identified by pr; Sys>> alter user pr default tablespace pr; Sys>> Pr>> Demobld Pr>> Sys>> Sys>> shut immediate TAKE Sys>> exit A ~] $ cd /disk1/oradata/good good] $ cp * cold COLD good] $ cd ~] $ BACLUP Sys>> Sys>> startup Sys>> Pr>> select count (*) from emp; 14 Pr>> insert into emp select * from emp; / / / (Do more Transactions. Up to TS filled up .) Pr>> commit; Pr>> select count (*) from emp; 114688 rows selected
P.R.P.R. Page 182

Sys>> alter system switch logfile; / / / Sys>> exit

~] $ cd /disk1/oradata/good good] $ rm pr.dbf good] $ Sys>> Pr>> select * from salgrade; Error datafile 6

pr.dbf.

Pr>> Sys>> Alter database datafile 6 offline; Sys>> ! ~] $ cd /disk1/oradata/good Good] $ cd cold Cold] $ cp pr.dbf .. Cold] $ cd ~] $ exit Sys>>Recover datafile 6; Specify log : {RET = suggested | filename | AUTO | CANCEL } auto Log applied Sys>> alter database datafile 6 online; pr>> select * from salgrade; 5 rows pr>> select count (*) from emp; 114688 ..
P.R.P.R. Page 183

RECOVER STEPS:
OFFLINE THE DATAFILE USING FILEID/FILENAME RESTORE DATAFILE FROM LAST BACKUP RECOVER DATAFILE USING FILE ID/FILENAME ONLINE THE DATAFILE USING FILE ID

Loss of SYSAUX: (Online Recovery) Even if u loss SYSAUX Datafile,to recover same as above scenario...

hiprpr@gmail.com

P.R.P.R.

Page 184

SCENARIO.5

LOSS OF ONLINE REDOLOG FILES.

Sys>> kk tablespace Sys>> kk user Sys>> kk kk (as a default) kk>> Demobld

TAKE A COLD BACKUP

Sys>> startup kk>> insert into emp select * from emp; / / / kk>> commit; kk>> select count (*) from emp; 14336 rows selected kk>> Sys>> alter system switch logfile; / / Sys>>! ~] $ Good] $ rm *.log
P.R.P.R. Page 185

Good] $ exit Sys>>

Kk>> insert into EMP select * from EMP; / / (Most of the times itll hang ..) Otherwise

{Some times it allows you to insert the Records


Means you can insert the records and u can give commit also . But the new data (even committed (new) data) it wont recover (Coz already u loss Redo files) }

At that time open 1 more session and. Sys>> shut abort >> Exit ~] $ cd /disk1/oradata/good Good] $ cd cold Cold] $ cp *.dbf *.ctl .. (Restore the datafiles and control files) Sys>> startup mount Sys>> alter database recover automatic using backup controlfile until cancel; Sys>> recover cancel; (Check at OS level Redo logfiles are not exist)

P.R.P.R.

Page 186

Sys>> alter database open resetlogs; (Check now Redo logfiles are exist) Sys>> Kk>> select count (*) from EMP; 14336 NOTE: If u loss online redo logs just restore all datafiles (no need to restore ctrl file also) and recover It will work. But if u restore only control file it will not work. Restore Ctrl + *.dbf Restore only Ctrl file Restore only *.dbf = YES (we can recover) = NO (we cant recover) = YES (we can recover)

Loss of INACTIVE Redo log file:


If all the members of a redo log group goes missing before the ARC process could archive it. Oracle complains with error ORA-00313,ORA-00312,ORA-27037 once all members of the log file group goes missing. The database halts unable to switch the log file.
SQL> select members, status, group# from v$log; MEMBERS ---------1 1 1 STATUS GROUP# ---------------- ---------INACTIVE 1 INACTIVE 3 CURRENT 2

SQL> select member, status, group# from v$logfile MEMBER STATUS GROUP#

P.R.P.R.

Page 187

-------------------------------- ------- ---------D:\APP\ORACLE\ORADATA\REDO03.LOG 3 D:\APP\ORACLE\ORADATA\REDO02.LOG 2 D:\APP\ORACLE\ORADATA\REDO01.LOG 1

>> Drop INACTIVE Redolog file (REDO03.log) at OS level

SQL> startup ORACLE instance started. Total System Global Area 535662592 bytes Fixed Size 1334380 bytes Variable Size 314573716 bytes Database Buffers 213909504 bytes Redo Buffers 5844992 bytes Database mounted. ORA-00313: open failed for members of log group 3 of thread 1 ORA-00312: online log 3 thread 1: 'D:\APP\ORACLE\ORADATA\REDO03.LOG'

>> In mount stage


SQL> select members,status,group# from v$log; MEMBERS ---------1 1 1 STATUS GROUP# ---------------- ---------INACTIVE 1 INACTIVE 3 CURRENT 2

SQL> alter database clear unarchived logfile group 3; Database altered. SQL> recover database until cancel; Media recovery complete. SQL> SQL> alter database open resetlogs; Database altered. SQL> archive log list Database log mode Automatic archival Archive destination Oldest online log sequence Next log sequence to archive

Archive Mode Enabled USE_DB_RECOVERY_FILE_DES 1 1

P.R.P.R.

Page 188

Current log sequence 1 SQL> SQL> SQL> select members,status,group# from v$log; MEMBERS ---------1 1 1 STATUS GROUP# ---------------- ---------CURRENT 1 UNUSED 2 UNUSED 3

>> http://www.lazydba.com/oracle/0__66824.html @@@

P.R.P.R.

Page 189

SCENARIO.6

LOSS OF NON SYSTEM DATAFILE WHICH IS NOT AVILABLE IN OUR BACKUP SET
Sys>> create tablespace pr datafile /disk1/oradata/good/pr.dbf size 10m; Sys>> create a user pr Sys>> alter user pr default tablespace pr; Pr>> Demobld
TAKE A COLD BACKUP

Pr>> insert into emp select * from emp; / / / ERROR at LINE : 1 ORA-01653: unable to extend table PR.EMP by 128 in tablespace PR Pr>> insert into dept select * from dept; / / / ERROR at LINE : 1 ORA-01653: unable to extend table PR.DEPT by 128 in tablespace PR Pr>> insert into salgrade select * from salgrade; / / ERROR at LINE : 1
P.R.P.R. Page 190

ORA-01653: unable to extend table PR.SALGRADE by 128 in tablespace PR Pr>> commit; Pr>> select count (*) from salgrade; 500 rows Sys>> alter tablespace pr add datafile /disk1/oradata/good/pr1.dbf size 10m; Again do some Transactions in salgrade.. Pr>> insert into salgrade select * from salgrade; Pr>>Commit; Pr>>Select count (*) from salgrade; 1000 rows Sys>> alter system switch logfile; / / / Sys>> exit ~] $ good] $ rm pr1.dbf Sys>> Pr>> select count (*) from salgrade;
ORA-01116: error in opening database file 9 ORA-01110: data file 9: /disk1/oradata/good/pr1.dbf ORA-27041: unable to open file Linux Error : 2: No such file or directory Sys>> ALTER DATABASE DATAFILE 9 OFFLINE DROP; Sys>> ALTER DATABASE CREATE DATAFILE 9; Sys>> RECOVER DATAFILE 9; Specify log : {RET = suggested | filename | AUTO | CANCEL } auto Log applied

P.R.P.R.

Page 191

Sys>> ALTER DATABASE DATAFILE 9 ONLINE;

Pr>> select count (*) from salgrade;


1000 rows

In the same scenario, creating datafile in different location: Sys>> ALTER DATABASE DATAFILE 9 OFFLINE DROP; Sys>> ALTER DATABASE CREATE DATAFILE /disk1/oradata/good/pr1.dbf as /disk2/oradata2/good2/pr2.dbf; Sys>> RECOVER DATAFILE 9; Sys>> ALTER DATABASE DATAFILE 9 ONLINE;

P.R.P.R.

Page 192

SCENARIO.7

POINT - IN TIME RECOVERY

CREATE A TABLESPACE PTR CRERATE A USER PTR ASSIGN PTR PTR SYS>> PTR>> SET TIME ON PTR>> DEMOBLD TAKE A COLD BACKUP (DIR NAME IS COLD)

PTR>>

EMP ------- 14 ROWS DEPT -------- 4 ROWS

PTR>> DO SOME TRANSACTIONS IN EMP TABLE 12:00:22:PTR>> SELECT COUNT(*) FROM EMP; 500 ROWS {A}

PTR>>COMMIT; SYS>> MANUAL LOG SWITCH 12:01:44:PTR>>DROP TABLE EMP PURGE; DO SOME TRANSACTIONS IN DEPT ALSO SELECT COUNT(*) FROM DEPT; 250 ROWS {B}

13:15:45:PTR>>SELECT * FROM EMP; ORA : 00942 TABLE OR VIEW DOES NOT EXIST SYS>> SHUT IMMEDIATE AT OS LEVEL TAKE ONE MORE BKP
P.R.P.R. Page 193

(THE DIR NAME IS NEW) THEN RESTORE FROM COLD BKP STARTUP MOUNT RECOVER UPTO 12:00

SYS>> ALTER DATABASE RECOVER AUTOMATIC USING BACKUP CONTROLFILE UNTIL TIME 2009:08:04:12:00:22; DATABASE ALTERED PTR>> SELECT COUNT(*) FROM EMP; 500 ROWS {A}

PTR>> SELECT COUNT(*) FROM DEPT; 4 ROWS EXPORT TABLE EMP

SYS>> SHUT IMMEDIATE RESTORE FROM NEW BKP STS>> STARTUP (NO NEED TO RECOVER) PTR>> SELECT COUNT(*) FROM DEPT; 250 ROWS {B}

PTR>> SELECT COUNT(*) FROM EMP; ORA 00942 TABLE OR VIEW DOES NOT EXIST

IMPORT THE EMP TABLE SELECT COUNT(*) FROM EMP; 500 ROWS {A}

P.R.P.R.

Page 194

SCENARIO.8

LOSS OF UNDO DATAFILE


(Off line Recovery) RECOVERY SYEPS: FIRST RESTORE UNDO DATAFILE cold] $ cp undotbs.dbf .. RECOVER IN MOUNT STAGE <FILE ID>

SYS>> RECOVER DATAFILE

Specify log : {RET = suggested | filename | AUTO | CANCEL } auto Log applied Media Recovery complete SYS>>ALTER DATABASE OPEN;

Notes: If u loss Undo datafile, U cant create another undo tablespace but u can create normal tablespaces. This is Offline Recovery.

hiprpr@gmail.com

P.R.P.R.

Page 195

SCENARIO.9

LOSS OF PARAMETER FILE


OPEN THE ALERLOG FILE THEN COPY RESENT PFILE LIKE

Create new file between these two line numbers

:20,40 W /oraeng/app/oracle/product/10.2.0/dbs/initram.ora
Append the file 20 & 40 line numbers ( Means B/W 20 to 40 )

:20,40 w >> /oraeng/app/oracle/product/10.2.0.dbs/initram.ora Overwrite the file :20,40 w! //oraeng/app/oracle/product/10.2.0.dbs/initram.ora

Loss Of Temp file:

Offline tempfile
>> alter database tempfile <file_id> offline; Create temporary tablespace <New Name> tempfile <New Temp File>;

Assign as default
>> alter database default temporary tablespace NAME; @@@

P.R.P.R.

Page 196

SCENARIO.10 Take a cold backup (Apr 1st 2010) Next day added 2 datafiles (Apr 2nd 2010) Database crashed (loss of C/R/D files old & New ) (Apr 3rd 2010) How to recover?? Same as SCENARIO No 6, but loss all C/R/D files.

Steps:
Sys> shutdown immediate $cd /oradata/prod/data $cp * /backup/cold_bkp Sys>> startup (Apr 2nd 2010)
SQL> create tablespace tt datafile '/oradata/prod/data/tt.dbf' size 10m; SQL> create tablespace yy datafile '/oradata/prod/data/yy.dbf' size 10m; SQL> grant connect, resource to tt identified by tt; Grant succeeded. SQL> grant connect, resource to yy identified by yy; Grant succeeded. SQL> alter user tt default tablespace tt; User altered. SQL> alter user yy default tablespace yy; User altered. SQL> conn tt/tt Connected. SQL> @demobld

(Apr 1st 2010)

P.R.P.R.

Page 197

SQL> insert into emp select * from emp; SQL> select count(*) from emp; COUNT(*) ---------7168 SQL> conn yy/yy Connected. SQL> @demobld SQL> insert into salgrade select * from salgrade; SQL> select count(*) from salgrade; COUNT (*) ---------10240 SQL> conn / as sysdba Connected. SQL> alter system switch logfile; [oracle@linux ~]$ cd /oradata/prod/data [oracle@linux data]$ rm -rf * SQL> desc dba_users ERROR: ORA-00604: error occurred at recursive SQL level 1 ORA-01116: error in opening database file 1 ORA-01110: data file 1: '/oradata/prod/data/system.dbf' ORA-27041: unable to open file Linux Error: 2: No such file or directory Additional information: 3 SQL> shut abort ORACLE instance shut down.

Restore last backup (Apr 1st 2010)


[oracle@linux data]$ cd /backup/prod_bkp/ [oracle@linux prod_bkp]$ cp * /oradata/prod/data/ SQL> startup mount ORACLE instance started. Total System Global Area 146472960 bytes Fixed Size 1335080 bytes Variable Size 92274904 bytes Database Buffers 50331648 bytes Redo Buffers 2531328 bytes Database mounted. SQL>

P.R.P.R.

Page 198

Recover the database


SQL> alter database recover automatic using backup controlfile until cancel; alter database recover automatic using backup controlfile until cancel * ERROR at line 1: ORA-00283: recovery session canceled due to errors ORA-01244: unnamed datafile(s) added to control file by media recovery ORA-01110: data file 6: '/oradata/prod/data/tt.dbf' ### Alert log file Content

alter database recover automatic using backup controlfile until cancel Media Recovery Start Serial Media Recovery started Media Recovery Log /oraeng/prod/arch/1_5_732321543.dbf File #6 added to control file as 'UNNAMED00006'. Originally created as: '/oradata/prod/data/tt.dbf' Recovery interrupted!
###

SQL> alter database create datafile 6; alter database create datafile 6 * ERROR at line 1: ORA-01111: name for data file /oraeng/oracle/product/11.1.0/dbs/UNNAMED00006 is unknown - rename to correct file

SQL> alter database rename file '/oraeng/oracle/product/11.1.0/dbs/UNNAMED00006' to '/oradata/prod/data/tt.dbf'; alter database rename file '/oraeng/oracle/product/11.1.0/dbs/UNNAMED00006' to '/oradata/prod/data/tt.dbf' * ERROR at line 1: ORA-01511: error in renaming log/data files ORA-01141: error renaming data file 6 - new file '/oradata/prod/data/tt.dbf' not found ORA-01111: name for data file 6 is unknown - rename to correct file ORA-01110: data file 6: '/oraeng/oracle/product/11.1.0/dbs/UNNAMED00006' ORA-27037: unable to obtain file status Linux Error: 2: No such file or directory Additional information: 3

SQL> alter database create datafile '/oraeng/oracle/product/11.1.0/dbs/UNNAMED00006' as '/oradata/prod/data/tt.dbf'; Database altered.

P.R.P.R.

Page 199

SQL> alter database recover automatic using backup controlfile until cancel; alter database recover automatic using backup controlfile until cancel * ERROR at line 1: ORA-00283: recovery session canceled due to errors ORA-01244: unnamed datafile(s) added to control file by media recovery ORA-01110: data file 7: '/oradata/prod/data/yy.dbf' ### Alert log file Content

alter database recover automatic using backup controlfile until cancel Media Recovery Start Serial Media Recovery started Media Recovery Log /oraeng/prod/arch/1_5_732321543.dbf File #7 added to control file as 'UNNAMED00007'. Originally created as: '/oradata/prod/data/yy.dbf' Recovery interrupted! ###
SQL> alter database create datafile 7; alter database create datafile 7 * ERROR at line 1: ORA-01111: name for data file /oraeng/oracle/product/11.1.0/dbs/UNNAMED00007 is unknown - rename to correct file

SQL> alter database create datafile '/oraeng/oracle/product/11.1.0/dbs/UNNAMED00007' as '/oradata/prod/data/yy.dbf'; Database altered. SQL> alter database recover automatic using backup controlfile until cancel; alter database recover automatic using backup controlfile until cancel * ERROR at line 1: ORA-00279: change 253981 generated at 10/13/2010 22:52:29 needed for thread 1 ORA-00289: suggestion : /oraeng/prod/arch/1_11_732321543.dbf ORA-00280: change 253981 for thread 1 is in sequence #11 ORA-00278: log file '/oraeng/prod/arch/1_11_732321543.dbf' no longer needed for this recovery ORA-00308: cannot open archived log '/oraeng/prod/arch/1_11_732321543.dbf' ORA-27037: unable to obtain file status Linux Error: 2: No such file or directory Additional information: 3 #### Alert log file Content

alter database recover automatic using backup controlfile until cancel Media Recovery Start Serial Media Recovery started Media Recovery Log /oraeng/prod/arch/1_5_732321543.dbf Media Recovery Log /oraeng/prod/arch/1_6_732321543.dbf

P.R.P.R.

Page 200

Media Recovery Log /oraeng/prod/arch/1_7_732321543.dbf Media Recovery Log /oraeng/prod/arch/1_8_732321543.dbf Media Recovery Log /oraeng/prod/arch/1_9_732321543.dbf Media Recovery Log /oraeng/prod/arch/1_10_732321543.dbf Media Recovery Log /oraeng/prod/arch/1_11_732321543.dbf Errors with log /oraeng/prod/arch/1_11_732321543.dbf ORA-279 signalled during: alter database recover automatic using backup controlfile until cancel...
####

SQL> recover cancel; Media recovery complete.

SQL> alter database open resetlogs; alter database open resetlogs * ERROR at line 1: ORA-01153: an incompatible media recovery is active

SQL> select file#,name,status from v$datafile; FILE# NAME STATUS ---------- --------------------------------------------- ------1 /oradata/prod/data/system.dbf SYSTEM 2 /oradata/prod/data/sysaux.dbf ONLINE 3 /oradata/prod/data/undotbs.dbf ONLINE 4 /oradata/prod/data/userdata.dbf ONLINE 5 /oradata/prod/data/kk.dbf ONLINE 6 /oradata/prod/data/tt.dbf RECOVER 7 /oradata/prod/data/yy.dbf RECOVER SQL> recover datafile 6; ORA-00283: recovery session canceled due to errors ORA-01610: recovery using the BACKUP CONTROLFILE option must be done

SQL> recover datafile 6 using backup controlfile; ORA-00274: illegal recovery option USING

SQL> alter database datafle 6 recover until cancel; alter database datafle 6 recover until cancel * ERROR at line 1: ORA-02231: missing or invalid option to ALTER DATABASE

Unable to recover those 2 datafiles. Then


SQL> shut immediate ORA-01109: database not open Database dismounted.

P.R.P.R.

Page 201

ORACLE instance shut down.

Recreate a controlfile. Add those 2 datafiles in the controlfile creation script


[oracle@linux ~]$ cat cont.trc STARTUP NOMOUNT CREATE CONTROLFILE REUSE DATABASE "PROD" RESETLOGS ARCHIVELOG MAXLOGFILES 16 MAXLOGMEMBERS 2 MAXDATAFILES 30 MAXINSTANCES 1 MAXLOGHISTORY 292 LOGFILE GROUP 1 '/oradata/prod/data/redo1.log' SIZE 4M BLOCKSIZE 512, GROUP 2 '/oradata/prod/data/redo2.log' SIZE 4M BLOCKSIZE 512 -- STANDBY LOGFILE DATAFILE '/oradata/prod/data/system.dbf', '/oradata/prod/data/sysaux.dbf', '/oradata/prod/data/undotbs.dbf', '/oradata/prod/data/userdata.dbf', '/oradata/prod/data/kk.dbf', '/oradata/prod/data/tt.dbf', '/oradata/prod/data/yy.dbf' CHARACTER SET US7ASCII ; SQL> startup nomount ORACLE instance started. Total System Global Area 146472960 bytes Fixed Size 1335080 bytes Variable Size 92274904 bytes Database Buffers 50331648 bytes Redo Buffers 2531328 bytes SQL> @cont.trc Control file created. SQL> select status from v$instance; STATUS -----------MOUNTED SQL> select file#,name,status from v$datafile; FILE# NAME STATUS ---------- -------------------------------------------- ------1 /oradata/prod/data/system.dbf SYSTEM 2 /oradata/prod/data/sysaux.dbf RECOVER 3 /oradata/prod/data/undotbs.dbf RECOVER 4 /oradata/prod/data/userdata.dbf RECOVER

P.R.P.R.

Page 202

5 /oradata/prod/data/kk.dbf 6 /oradata/prod/data/tt.dbf 7 /oradata/prod/data/yy.dbf

RECOVER RECOVER RECOVER

SQL> alter database recover automatic using backup controlfile until cancel; alter database recover automatic using backup controlfile until cancel * ERROR at line 1: ORA-00279: change 253981 generated at 10/13/2010 22:52:29 needed for thread 1 ORA-00289: suggestion : /oraeng/prod/arch/1_11_732321543.dbf ORA-00280: change 253981 for thread 1 is in sequence #11 ORA-00278: log file '/oraeng/prod/arch/1_11_732321543.dbf' no longer needed for this recovery ORA-00308: cannot open archived log '/oraeng/prod/arch/1_11_732321543.dbf' ORA-27037: unable to obtain file status Linux Error: 2: No such file or directory Additional information: 3 ###

Alert Logfile Content alter database recover automatic using backup controlfile until cancel Media Recovery Start Serial Media Recovery started Media Recovery Log /oraeng/prod/arch/1_11_732321543.dbf Errors with log /oraeng/prod/arch/1_11_732321543.dbf ORA-279 signalled during: alter database recover automatic using backup controlfile until cancel...
###

SQL> recover cancel; Media recovery complete. SQL> select file#,status,name from v$datafile; FILE# STATUS NAME ---------- ------- -------------------------------------------1 SYSTEM /oradata/prod/data/system.dbf 2 RECOVER /oradata/prod/data/sysaux.dbf 3 RECOVER /oradata/prod/data/undotbs.dbf 4 RECOVER /oradata/prod/data/userdata.dbf 5 RECOVER /oradata/prod/data/kk.dbf 6 RECOVER /oradata/prod/data/tt.dbf 7 RECOVER /oradata/prod/data/yy.dbf 7 rows selected. SQL> alter database open resetlogs; Database altered. SQL> select file_name,status from dba_data_files; FILE_NAME STATUS -------------------------------------------- --------/oradata/prod/data/system.dbf AVAILABLE /oradata/prod/data/yy.dbf AVAILABLE

P.R.P.R.

Page 203

/oradata/prod/data/tt.dbf /oradata/prod/data/kk.dbf /oradata/prod/data/userdata.dbf /oradata/prod/data/undotbs.dbf /oradata/prod/data/sysaux.dbf SQL> conn tt/tt Connected. SQL> select count(*) from emp; COUNT(*) ---------7168 SQL> conn yy/yy Connected. SQL> select count(*) from salgrade; COUNT(*) ---------10240

AVAILABLE AVAILABLE AVAILABLE AVAILABLE AVAILABLE

@@@@

P.R.P.R.

Page 204

P.R.P.R.

Page 205

P.R.P.R.

Page 206

HOT BACKUPS

1. Controlfile backup By using SQL stat 2. Redo we cant take 3. Datafiles at OS level

P.R.P.R.

Page 207

HOW TO TAKE HOT BACKUP:

1. KEEP THE DATABASE IN BEGIN BACKUP MODE SYS>> ALTER DATABASE BEGIN BACKUP; 2. CREATE ONE DIRECTORY AT OS LEVEL TO STORE THE DATAFILE & CONTROLFILES 3. COPY ONLY DATAFILES TO THAT DIRECTORY 4. COME OUT FROM BEGIN BACKUP MODE SYS>> ALTER DATABASE END BACKUP; 5. AT ORACLE LEVEL TAKE THE BACKUP OF CONTROLFILES 6. MANUAL LOG SWITCH

A SINGLE TABLESPACE ALSO WE CAN KEEP IN BEGIN BACKUP MODE SYS>> ALTER TABLESPACE < TS NAME> BEGIN BACKUP;

SCENARIO.1
DATABASE CRASH (LOSS OF C/R/D/ FILES) :

Sys>> create tablespace hot Sys>> create user hot Sys>> assign hot hot Hot>> Demobld Hot>> Sys>> Alter database begin backup; Sys>>> ! ~] $ cd /disk1/oradata/good
P.R.P.R. Page 208

good] $ mkdir hot good] $ cp *.dbf hot/ good] $ cd ~] $ exit Sys>> Alter database end backup; Sys>> Alter database backup controlfile to /disk1/oradata/good/hot/cont.ctl; Sys>> Alter system switch logfile; Hot>> Hot>> select count (*) from emp; 14 rows Hot>> insert into emp select * from emp; / / / Hot>> commit; Hot>> same like Do some Transactions in DEPT also.. Hot>> select count (*) from emp; 1024 rows Hot>> select count (*) from dept; 100 rows Sys>> archive log list Sys>> alter system switch logfile; (Manual log switch) / / / Sys>> archive log list Sys>> exit ~] $ ~] $ cd /disk1/oradata/good good] $ rm * (Remove all files) (You loss all files) good] $!sq

P.R.P.R.

Page 209

Sys>> Desc dba_users Error Hot>> insert into emp select * from emp; Error Hot>> Sys>> shut immediate Error Sys>> shutdown abort Sys>> exit ~] $ cd /disk1/oradata/good good] $ ls good] $ cd hot/ hot] $ cp * .. (Simple Restore) hot] $ cd .. good] $ ls all files exist good] $ cd ~] $ sqlplus /as sysdba Sys>> startup mount Sys>> Alter database recover automatic using backup controlfile until cancel; Errors Sys>> Recover cancel; Sys>> Alter database open resetlogs; Sys>> Hot>> select count (*) from emp; 1024 rows Hot>> Select count (*) from dept; 100 rows selected

P.R.P.R.

Page 210

RMAN
{RECOVERY MANAGER}

SERVER SIDE 1. Configure N/W Listener.ora 2. Create a directory 3. Create password file ( to store the backup pieces)

CLIENT SIDE 1. Configure N/W Tnsnames.ora 2. Create a tablespace(min 30m) 3. Grant privilege to a user (Racovery_catalog_owner) 4. Create a catalog

P.R.P.R.

Page 211

SERVER SIDE; My Listener name is RED SID: ram Port: 6666 Protocol: TCP/IP Location: /disk1/oradata/good CLIENT SIDE: My Tnsname (alias name) is GREEN

(Here database name is PRASAD)

SID: ram (Same as server side) Port: 6666 (Same as server side) Protocol: TCP/IP (Same as server side) Location: /disk2/oradata/bad

(Here database name is REDDY)

] $ lsnrctl start RED ] $ tnsping GREEN

~] $ mkdir p /disk1/oradata/good/rman ~] $ cd $ORACLE_HOME/dbs dbs] $ orapwd file=orapw$ORACLE_SID password=www force=y ~] $ sqlplus /as sysdba Sys>> startup Sys>> archive log list;
P.R.P.R. Page 212

Must be enabled Sys>> startup Sys>> create tablespace rmn datafile /disk2/oradata/bad/rmn.dbf size 30m; Sys>> create user rmn default tablespace rmn; Sys>> grant connect, resource, Racovery_catalog_owner to rmn; Sys>> exit (Username) ~] $ rman catalog rmn/rmn (Password) RMAN>> create catalog; | Recovery catalog created | | | In 2nd session(client side) | Sys>> | Rmn>> select * from tab; | o/p | 90 views ..(In 11g 142) | V RMAN>> exit Recovery manager completed ] $ rman catalog rmn/rmn target sys/www@GREEN RMAN>> register database;

RMAN>> show all;


RMAN configuration parameters are: CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default CONFIGURE BACKUP OPTIMIZATION OFF; # default CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default P.R.P.R. Page 213

CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default CONFIGURE MAXSETSIZE TO UNLIMITED; # default CONFIGURE ENCRYPTION FOR DATABASE OFF; # default CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/oraeng/app/oracle/product/10.2.0/dbs/snapcf_ram.f'; # default

RMAN> SPOOL LOG TO 'show.log' RMAN> show all; RMAN> spool log off;
CONFIGURE RETENTION POLICY TO REDUNDANCY 3; # default CONFIGURE BACKUP OPTIMIZATION ON; # default CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default CONFIGURE CONTROLFILE AUTOBACKUP ON; # default CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/disk1/oradata/good/rman/%F'; # default CONFIGURE DEVICE TYPE DISK PARALLELISM 2 BACKUP TYPE TO BACKUPSET; # default CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT /disk1/oradata/good/rman/%U.bkp; CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT /disk1/oradata/good/rman/%U.bkp; CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default CONFIGURE MAXSETSIZE TO UNLIMITED; # default CONFIGURE ENCRYPTION FOR DATABASE OFF; # default CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default CONFIGURE SNAPSHOT CONTROLFILE NAME TO /disk1/oradata/good/rman/snapcf_ram.f'; # default

P.R.P.R.

Page 214

: wq ~] $ rman catalog rmn/rmn target sys/www@GREEN cmdfile=show. log


RMAN>> report need backup; RMAN>> list backup summary RMAN>> list archive log all;

RMAN>>Backup database;

rman] $ ls
RMAN>> report need backup; RMAN>> backup database plus archivelog; RMAN>> report need backup; RMAN>> list backup;

Complete info about channels


RMAN>> list backup summary; RMAN>> backup tablespace kk; RMAN>> backup database tag =ram; RMAN>> backup datafile 1; RMAN>> backup datafile 2;

If you want to skip offline TSs


RMAN>> backup database skip offline; Read only; RMAN>> backup database skip offline skip read only; RMAN>> backup database force;

Itll take backup of all .. Offlineread only..


P.R.P.R. Page 215

RMAN>> backup database; (New datafiles)


RMAN>> backup database not backed up; RMAN>> backup database not backed up since time=sysdate-2;

RMAN>> backup archivelog all; RMAN>> backup database plus archivelog all; RMAN>> backup archivelog from time sysdate -1; RMAN>> backup tablespace kk plus archivelog all; RMAN>> backup current controlfile plus archivelog all; RMAN>> backup archivelog from sequence 150; (150 sequence no)

To see the backup:


RMAN>> list backup; RMAN>> list backup summery; RMAN>> list backup by file RMAN>> list backup of controlfile; RMAN>> list backup of spfile; RMAN>> list backup of datafile 1;

RMAN>> report obsolete;

Delete all backups, copies and archived redo log files based on the configured Retention policy:
RMAN>>delete obsolete;

You can also specify the REDUNDANCY and RECOVERY WINDOW options on the DELETE command as in the following e.g.
RMAN>> Delete obsolete recovery window of 7 days;
P.R.P.R. Page 216

To deletion of expired backup:


RMAN>> crosscheck backup; RMAN>>crosscheck backupset;

O/p Youll get two status


RMAN>> delete expired backup; RMAN>> list backup;

Available & Expired

To clear the screen:


Rman> host clear

Example:
RMAN> crosscheck backup;
using channel ORA_DISK_1 using channel ORA_DISK_2 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oradata/app/oracle/oracle/product/10.2.0/db_1/dbs/02kugndh_1_1 stamp=703094193 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oldproddb/CRMSYSR1_flash_recovery_area/0bkvq8kb_1_1.bkp stamp=704455307 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oldproddb/CRMSYSR1_flash_recovery_area/0akvq8kb_1_1.bkp stamp=704455307 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oldproddb/CRMSYSR1_flash_recovery_area/c-3800788184-20091201-00 stamp=704455958 Crosschecked 4 objects

recid=2

recid=6

recid=7

recid=8

P.R.P.R.

Page 217

crosschecked backup piece: found to be 'EXPIRED' backup piece handle=/oldproddb/CRMSYSR1_flsh_recovery_area/03kujfb1_1_1.bkp stamp=703184225 crosschecked backup piece: found to be 'EXPIRED' backup piece handle=/oldproddb/CRMSYSR1_flsh_recovery_area/06kujfl0_1_1.bkp stamp=703184545 crosschecked backup piece: found to be 'EXPIRED' backup piece handle=/oldproddb/CRMSYSR1_flsh_recovery_area/05kujfl0_1_1.bkp stamp=703184545 Crosschecked 3 objects

recid=3

recid=4

recid=5

RMAN> delete expired backup;


using channel ORA_DISK_1 using channel ORA_DISK_2 List of BP Key ------3 4 5 Backup Pieces BS Key Pc# Cp# Status Device Type Piece Name ------- --- --- ----------- ----------- ---------3 1 1 EXPIRED DISK /oldproddb/CRMSYSR1_flsh_recovery_area/03kujfb1_1_1.bkp 4 1 1 EXPIRED DISK /oldproddb/CRMSYSR1_flsh_recovery_area/06kujfl0_1_1.bkp 5 1 1 EXPIRED DISK /oldproddb/CRMSYSR1_flsh_recovery_area/05kujfl0_1_1.bkp

Do you really want to delete the above objects (enter YES or NO)? y
deleted backup piece backup piece handle=/oldproddb/CRMSYSR1_flsh_recovery_area/03kujfb1_1_1.bkp stamp=703184225 deleted backup piece backup piece handle=/oldproddb/CRMSYSR1_flsh_recovery_area/06kujfl0_1_1.bkp stamp=703184545 deleted backup piece backup piece handle=/oldproddb/CRMSYSR1_flsh_recovery_area/05kujfl0_1_1.bkp stamp=703184545 Deleted 3 EXPIRED objects recid=3

recid=4

recid=5

RMAN> crosscheck backup;


using channel ORA_DISK_1 using channel ORA_DISK_2 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oradata/app/oracle/oracle/product/10.2.0/db_1/dbs/02kugndh_1_1 stamp=703094193 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oldproddb/CRMSYSR1_flash_recovery_area/0bkvq8kb_1_1.bkp stamp=704455307 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oldproddb/CRMSYSR1_flash_recovery_area/0akvq8kb_1_1.bkp stamp=704455307 crosschecked backup piece: found to be 'AVAILABLE' backup piece handle=/oldproddb/CRMSYSR1_flash_recovery_area/c-3800788184-20091201-00 stamp=704455958 Crosschecked 4 objects

recid=2

recid=6

recid=7

recid=8

P.R.P.R.

Page 218

RMAN>

>> list backup; RMAN> list backup;


List of Backup Sets =================== BS Key Type LV Size Device Type Elapsed Time Completion Time ------- ---- -- ---------- ----------- ------------ --------------2 Full 152.00K DISK 00:00:00 16-NOV-09 BP Key: 2 Status: AVAILABLE Compressed: NO Tag: TAG20091116T155633 Piece Name: /oradata/app/oracle/oracle/product/10.2.0/db_1/dbs/02kugndh_1_1 List of Datafiles in backup set 2 File LV Type Ckp SCN Ckp Time Name ---- -- ---- ---------- --------- ---16 Full 347120274 16-NOV-09 /nonproddb/oradata/dbfiles/CRMSYSR1/tt.dbf BS Key Type LV Size Device Type Elapsed Time Completion Time ------- ---- -- ---------- ----------- ------------ --------------6 Full 7.18G DISK 00:09:49 01-DEC-09 BP Key: 6 Status: AVAILABLE Compressed: NO Tag: TAG20091201T100147 Piece Name: /oldproddb/CRMSYSR1_flash_recovery_area/0bkvq8kb_1_1.bkp List of Datafiles in backup set 6 File LV Type Ckp SCN Ckp Time Name ---- -- ---- ---------- --------- ---1 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/system01.dbf 4 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/users01.dbf 5 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs01.dbf 7 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs02.dbf 8 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs03.dbf 9 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs04.dbf 12 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_index_tbs03.dbf 14 Full 349306218 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/sysaux02.dbf BS Key Type LV Size Device Type Elapsed Time Completion Time ------- ---- -- ---------- ----------- ------------ --------------7 Full 11.32G DISK 00:10:45 01-DEC-09 BP Key: 7 Status: AVAILABLE Compressed: NO Tag: TAG20091201T100147 Piece Name: /oldproddb/CRMSYSR1_flash_recovery_area/0akvq8kb_1_1.bkp List of Datafiles in backup set 7 File LV Type Ckp SCN Ckp Time Name ---- -- ---- ---------- --------- ---2 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/undotbs01.dbf 3 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/sysaux01.dbf 6 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_index_tbs01.dbf 10 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs05.dbf 11 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_index_tbs02.dbf 13 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/system02.dbf 15 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/rman_tbs01.dbf 16 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/tt.dbf 17 Full 349306217 01-DEC-09 /nonproddb/oradata/dbfiles/CRMSYSR1/rman.dbf BS Key Type LV Size Device Type Elapsed Time Completion Time ------- ---- -- ---------- ----------- ------------ --------------8 Full 18.48M DISK 00:00:01 01-DEC-09

P.R.P.R.

Page 219

BP Key: 8 Status: AVAILABLE Compressed: NO Tag: TAG20091201T101238 Piece Name: /oldproddb/CRMSYSR1_flash_recovery_area/c-3800788184-20091201-00 Control File Included: Ckp SCN: 349306637 Ckp time: 01-DEC-09 RMAN>

Delete an expired backup without the confirmation:


>>Delete noprompt expired backup of tablespace kk;

RMAN>>delete backupset; Delete a specific Backupset


RMAN>> delete backupset 120;

Changing the Availability Status:


You can use CHANGEUNAVAILABLE command when a backup or copy cant be found or is unavailable Bcoz of hardware maintenance. If a file marked UNAVAILABALE, RMAN will not use the file when a RESTORE or RECOVER command is issued. When the file is found or the maintenance is completed, you can mark it available again by issuing the CHANGE.AVAILABLE command.

CHANGE BACKUPSET 120 UNAVAILABLE; Change the status of a specific datafile:


CHANGE DATAFILECOPY .../../userdata.dbf UNAVAILABLE

Change the status of a controlfile backup;


P.R.P.R. Page 220

CHANGE BACKUP OF CONTROLFILE UNAVAILABLE; Change the status of archived redo log files: CHANGE BACKUP OF ARCHIVELOG SEQUENCE BETWEEN 222 AND 252 UNAVAILABLE; Compressed backups: (10g)
RMAN>> backup as compressed backupset database; RMAN>> backup as compressed backupset database plus archivelog; RMAN>> backup as compressed backupset tablespace <Tablespacename>; RMAN>> backup as compressed backupset datafile 1, 4, 5;

Configuring Compressed Backups as Default for Tape or Disk:


RMAN>>CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COMPRESSED BACKUPSET; RMAN>> CONFIGURE DEVICE TYPE SBT BACKUP TYPE TO COMPRESSED BACKUPSET;

Image copies:
Using BACKUP AS COPY command to make an image copy of both system, sysaux RMAN>> backup as copy database; RMAN>> Backup as copy tablespace system, sysaux; (When we r going for cloning)

P.R.P.R.

Page 221

Drop Database in RMAN:


Restrictions:
Execute this command only in RMAN prompt You must be connected to the target database, which must either mounted exclusive and not open.

RMAN>> DROP DATABASE INCLUDING BACKUPS; SHOW


To display the current CONFIGURE command settings. The output of SHOW consists of the CONFIGURE commands used to set the configuration. RMAN default configurations are suffixed with #default.

E.g.:
SHOW CHANNEL; SHOW DEVICE TYPE; SHOW DEFAULT DEVICEC TYPE; SHOW MAXSETSIZE SHOW ALL;

RMAN> show channel;


RMAN configuration parameters are: CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT '/oldproddb/CRMSYSR1_flash_recovery_area/%U.bkp'; CONFIGURE CHANNEL 2 DEVICE TYPE DISK FORMAT '/oldproddb/CRMSYSR1_flash_recovery_area/%U.bkp'; RMAN>

RMAN> show device type;


RMAN configuration parameters are: CONFIGURE DEVICE TYPE DISK PARALLELISM 2 BACKUP TYPE TO BACKUPSET;

P.R.P.R.

Page 222

RMAN>

RMAN> show default device type;


RMAN configuration parameters are: CONFIGURE DEFAULT DEVICE TYPE TO DISK; RMAN>

RMAN> show maxsetsize;


RMAN configuration parameters are: CONFIGURE MAXSETSIZE TO UNLIMITED; RMAN> RMAN> show all; RMAN configuration parameters are: CONFIGURE RETENTION POLICY TO REDUNDANCY 2; CONFIGURE BACKUP OPTIMIZATION ON; CONFIGURE DEFAULT DEVICE TYPE TO DISK; CONFIGURE CONTROLFILE AUTOBACKUP ON; CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/oldproddb/CRMSYSR1_flash_recovery_area/%F'; CONFIGURE DEVICE TYPE DISK PARALLELISM 2 BACKUP TYPE TO BACKUPSET; CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT '/oldproddb/CRMSYSR1_flash_recovery_area/%U.bkp'; CONFIGURE CHANNEL 2 DEVICE TYPE DISK FORMAT '/oldproddb/CRMSYSR1_flash_recovery_area/%U.bkp'; CONFIGURE MAXSETSIZE TO UNLIMITED; CONFIGURE ENCRYPTION FOR DATABASE OFF; CONFIGURE ENCRYPTION ALGORITHM 'AES128'; CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/oldproddb/CRMSYSR1_flash_recovery_area/snapcf_CRMSYSR1.f'; RMAN>

Level 0 for complete backup Level 1 for cumulative backup Level 2 for incremental backup
RMAN>> backup incremental level 0 database; RMAN>> backup incremental level 1 database; RMAN>> backup incremental level 2 database;
P.R.P.R.

(complete) (cumulative) (incremental)


Page 223

ENABLING & DISABLING BLOCK CHANGE TRACKING:


Sys>> Alter database enable block change tracking Using file /disk1/oradata.good/rman/change.log; This command creates a binary file called rman/change. log For tracking purpose

Sys>> select filename, status from v$block_change_tracking; DISABLE: Sys>> Alter database disable block change tracking;

Block Media Recovery with RMAN:


Block Media Recovery recovers as individual corrupt datablock or set of datablocks with in a datafile

Restrictions for block media recovery: You can only perform block media recovery with Recovery Manager. No SQL * Plus recovery interface is available You can only perform complete recovery of individual blocks. In other words, you cant stop recovery before all redo has been applied to the block. You can only recover blocks marked media corrupt. The V$DATABASE_BLOCK_CORRUPTION view indicates which Blocks in a file were marked corrupt since the most recent BACKUP, BACKUP.VALIDATE or COPY command was run against the file. You must have a full RMAN backup. Incremental backups are not Allowed

P.R.P.R.

Page 224

Blocks that are marked media corrupt are not accessible to users until recovery is complete. Any attempt to use a block undergoing media recovery results in an error message indicating that the block is media corrupt. You may discover the following messages in a user trace file: ORA-01578 : ORACLE data block corrupted (file # 6, block # 3) ORA-01110 : data file 6 : /oracle/oradata/trgt/tool01.dbf ORA-01578 : ORACLE data block corrupted (file # 7, block # 4) ORA-01110 : data file 7 : /oracle/oradata/trgt/tool02.dbf You can specify the corrupt blocks in the BLOCKRECOVER command as follows RMAN>> BLOCKRECOVER DATAFILE 6 BLOCK 3 DATAFILE 7 BLOCK 4; RMAN>> blockrecover datafile 5 block 150; RMAN>> blockrecover datafile 5 block 160,161; ###

# restore from backupset RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 15 FROM BACKUPSET; # restore from datafile image copy RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 15 FROM DATAFILECOPY; # restore from backup set with tag "Sunday" RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 15 FROM TAG = Sunday; # restore using backups created before log sequence 100 RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 15 RESTORE UNTIL SEQUENCE 100; # restore using one week ago backups RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 15 RESTORE UNTIL 'SYSDATE-7'; # restore using backups until SCN 100 RMAN> BLOCKRECOVER DATAFILE 5 BLOCK 15 RESTORE UNTIL SCN 100; 3 . Recovering blocks listed in V$DATABASE_BLOCK_CORRUPTION view Run the below command to recover all blocks marked corrupt in V$DATABASE_BLOCK_CORRUPTIONRMAN RMAN> BLOCKRECOVER CORRUPTION LIST;

P.R.P.R.

Page 225

Restores blocks from backup sets created more than 7 days ago RMAN> BLOCKRECOVER CORRUPTION LIST FROM BACKUPSET RESTORE UNTIL TIME 'SYSDATE7';

@@@

You can use the VALIDATE command to confirm that all database files exist, are in their correct location, and are free of physical corruption. The CHECK LOGICAL option also checks for logical block corruption. To validate database files: 1. Start RMAN and connect to a target database. 2. Run the VALIDATE command for the desired files. For example, enter the following commands to validate all database files and archived redo log files for physical and Logical corruption: BACKUP VALIDATE CHECK LOGICAL DATABASE ARCHIVELOG ALL; You can also use the VALIDATE command to individual data blocks, as shown in the following example: VALIDATE DATAFILE 4 BLOCK 10 TO 13; You can also validate backup sets, as shown in the following example: VALIDATE BACKUPSET 3; You specify backup sets by primary key, which is shown in the output of the LIST BACKUP command.

### The following example appends the output from an RMAN session to a text file.
% rman TARGET / LOG /tmp/msglog.log APPEND
Ex: $ rman target / LOG /backup/rman.log append RMAN> RMAN> report need backup; P.R.P.R. Page 226

RMAN> list backup summary; The output u get in /backup/rman.log Cd /backup $tail f rman.log RMAN> using target database control file instead of recovery catalog RMAN retention policy will be applied to the command RMAN retention policy is set to redundancy 1 Report of files with less than 1 redundant backups File #bkps Name ---- ----- ----------------------------------------------------1 0 /nonproddb/oradata/dbfiles/CRMSYSR1/system01.dbf 2 0 /nonproddb/oradata/dbfiles/CRMSYSR1/undotbs01.dbf 3 0 /nonproddb/oradata/dbfiles/CRMSYSR1/sysaux01.dbf 4 0 /nonproddb/oradata/dbfiles/CRMSYSR1/users01.dbf 5 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs01.dbf 6 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_index_tbs01.dbf 7 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs02.dbf 8 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs03.dbf 9 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs04.dbf 10 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_data_tbs05.dbf 11 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_index_tbs02.dbf 12 0 /nonproddb/oradata/dbfiles/CRMSYSR1/siebel_index_tbs03.dbf 13 0 /nonproddb/oradata/dbfiles/CRMSYSR1/system02.dbf 14 0 /nonproddb/oradata/dbfiles/CRMSYSR1/sysaux02.dbf 15 0 /nonproddb/oradata/dbfiles/CRMSYSR1/rman_tbs01.dbf RMAN> List of Backups =============== Key TY LV S Device Type Completion Time #Pieces #Copies Compressed Tag ------- -- -- - ----------- --------------- ------- ------- -----------2 B F A DISK 16-NOV-09 1 1 NO TAG20091116T155633

P.R.P.R.

Page 227

Related Views:
RC_BACKUP_SET RC_BACKUP_SPFILE RC_BACKUP_FILES RC_BACKUP_PIECE Datafiles: RC_TABLESPACE RC_DATAFILE RC_BACKUP_DATAFILE RC_DATAFILE_COPY RC_PROXY_DATAFILE Control Files: RC_BACKUP_CONTROLFILE RC_PROXY_CONTROLFILE RC_CONTROLFILE_COPY hiprpr@gmail.com V$BACKUP_DATAFILE Control files in backup sets V$PROXY_DATAFILE Control file backups created by proxy copy V$DATAFILE_COPY Control file copies on disk V$TABLESPACE All tablespaces registered in the recovery catalog. V$DATAFILE All datafiles registered in the recovery catalog V$BACKUP_DATAFILE Datafiles in backup sets V$DATAFILE_COPY Datafile image copies V$PROXY_DATAFILE Datafile backups created by proxy copy V$BACKUP_SET Backup sets V$BACKUP_SPFILE Server parameter files in backup sets V$BACKUP_FILES RMAN backups and copies in the repository. V$BACKUP_PIECE Backup pieces

P.R.P.R.

Page 228

Typical Backup Options The BACKUP command includes a host of options, parameters, and clauses that control backup output. The following table lists some typical backup options.

P.R.P.R.

Page 229

RMAN EXAMPLES:
Examples Allocating a Single Channel for a Backup: Example This command allocates a tape channel for a whole database and archived redo log backup: RUN { ALLOCATE CHANNEL c1 DEVICE TYPE sbt; BACKUP DATABASE PLUS ARCHIVELOG; } Spreading a Backup Across Multiple Disks: Example When backing up to disk, you can spread the backup across several disk drives. Allocate one DEVICE TYPE DISK channel for each disk drive and specify the format string so that the filenames are on different disks: RUN { ALLOCATE CHANNEL disk1 DEVICE TYPE DISK FORMAT '/disk1/backups/%U'; ALLOCATE CHANNEL disk2 DEVICE TYPE DISK FORMAT '/disk2/backups/%U'; BACKUP DATABASE PLUS ARCHIVELOG; # AS COPY is default when backing up to disk } Creating Multiple Copies of a Backup: Example When creating multiple copies of a backup, you can specify the SET BACKUP COPIES command. The following example generates a single backup of the database to disk, and then creates two identical backups of datafile 1 to two different file systems: RUN { ALLOCATE CHANNEL c1 DEVICE TYPE DISK MAXPIECESIZE 5M; BACKUP DATABASE PLUS ARCHIVELOG; # AS COPY is the default, so RMAN creates image copies SET BACKUP COPIES = 2; BACKUP DATAFILE 1 FORMAT '/disk1/backups/%U', '/disk2/backups/%U'; } Allocating an Auxiliary Channel for Database Duplication: Example When creating a duplicate database, allocate a channel by using the AUXILIARY option: RUN { ALLOCATE AUXILIARY CHANNEL c1 DEVICE TYPE sbt; ALLOCATE AUXILIARY CHANNEL c2 DEVICE TYPE sbt; P.R.P.R. Page 230

DUPLICATE TARGET DATABASE TO ndbnewh LOGFILE '?/oradata/aux1/redo01.log' SIZE 200K, '?/oradata/aux1/redo02.log' SIZE 200K '?/oradata/aux1/redo03.log' SIZE 200K SKIP READONLY NOFILENAMECHECK; }

Deleting a Backup Set: Example This example deletes backup sets from tape created more than a week ago: ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE sbt; DELETE NOPROMPT BACKUP OF DATABASE COMPLETED BEFORE 'SYSDATE-7'; Crosschecking Archived Logs: Example This example crosschecks all archived logs on disk and tape. For disk, the preconfigured disk channel is used; for tape, an SBT channel is allocated manually. If the logs are not found, then RMAN marks them as EXPIRED in the repository: ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE sbt; CROSSCHECK ARCHIVELOG ALL; Crosschecking on Multiple Nodes of an Oracle Real Application Clusters Configuration: Example In this example, you perform a crosscheck of backups on two nodes of an Oracle Real Application Clusters configuration, where each node has access to a subset of backups. It is assumed here that all backups are accessible by at least one of the two nodes used in the crosscheck. Any backups not accessible from at least one of the nodes are marked EXPIRED after the crosscheck. ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE DISK CONNECT 'SYS/change_on_install@inst1'; ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE DISK CONNECT 'SYS/change_on_install@inst2'; CROSSCHECK BACKUP;

Deleting on Disk and sbt Channels with One Command: Example In this example, you delete a backup from both disk and tape: # back up datafile to disk and tape BACKUP DEVICE TYPE DISK DATAFILE 1 TAG "weekly_bkup"; BACKUP DEVICE TYPE sbt DATAFILE 1 TAG "weekly_bkup";
P.R.P.R. Page 231

# manually allocate gsbt channel and disk channel ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE DISK; ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE sbt; DELETE BACKUPSET TAG "weekly_bkup";

Configuring an Automatic Channel: Example This example configures a persistent disk channel: CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT = '?/oradata/bkup_%U'; Configuring a Channel for a Backup: Example This example manually allocates an sbt channel and then runs a whole database backup: RUN { ALLOCATE CHANNEL c1 DEVICE TYPE sbt MAXPIECESIZE 800M; BACKUP DATABASE; } Allocating a Channel for a Backup: Example This example configures a default media management library, then makes a database backup by using this library. Then, the example backs up the database again using a different library, then finally makes a third backup using the default library: CONFIGURE DEFAULT DEVICE TYPE TO sbt; CONFIGURE CHANNEL DEVICE TYPE sbt PARMS="SBT_LIBRARY=/mediavendor/lib/mm_lib1.so"; BACKUP DATABASE; RUN { ALLOCATE CHANNEL c1 DEVICE TYPE sbt PARMS="SBT_LIBRARY=/mediavendor/lib/mm_lib2.so"; BACKUP DATABASE; } BACKUP ARCHIVELOG ALL;

Opening the Database After a Backup: Example This example mounts the database, takes a whole database backup, then opens the database. At the RMAN prompt enter: STARTUP MOUNT; P.R.P.R. Page 232

BACKUP DATABASE; # now that the backup is complete, open the database. ALTER DATABASE OPEN; Mounting the Database After Restoring the Control File: Example To restore the control file to its default location when connected to a recovery catalog, enter the following:

STARTUP NOMOUNT; RESTORE CONTROLFILE; ALTER DATABASE MOUNT; # you must run the RECOVER command after restoring a control file even if no datafiles # require recovery RECOVER DATABASE; ALTER DATABASE OPEN RESETLOGS; Performing RESETLOGS After Incomplete Recovery: Example This example uses a manually allocated channel to perform incomplete recovery and then resets the online redo logs: RUN { ALLOCATE CHANNEL ch1 DEVICE TYPE sbt; SET UNTIL SCN 1024; RESTORE DATABASE; RECOVER DATABASE; ALTER DATABASE OPEN RESETLOGS; }

Specifying Records by Completion Time: Example This example deletes all archived redo logs that were created more than two weeks ago: DELETE ARCHIVELOG ALL COMPLETED BEFORE 'SYSDATE-14'; Specifying Records by Recovery Point-in-Time : Example This example backs up all logs that could be used to recover to a point one week ago: BACKUP ARCHIVELOG UNTIL TIME 'SYSDATE-7'; Specifying Records by SCN: Example This example restores backup archived redo log files from tape that fall within a range of SCNs: RESTORE ARCHIVELOG SCN BETWEEN 94097 AND 106245;

P.R.P.R.

Page 233

Specifying a Single Log Sequence Number: Example This example backs up only archived log 30 of thread 1 and then deletes it. BACKUP ARCHIVELOG SEQUENCE 30 DELETE INPUT; Specifying a Range of Records by Log Sequence Number: Example This example backs up all archived logs from sequence 431 to sequence 440 on thread 1 and deletes the archived logs after the backup is complete. If the backup fails, the logs are not deleted. RUN { ALLOCATE CHANNEL dev1 DEVICE TYPE sbt; BACKUP ARCHIVELOG SEQUENCE BETWEEN 31 AND 40 THREAD 1 # delete original archived redo logs after backup completes DELETE INPUT; } Specifying All Log Sequence Numbers in a Thread This example crosschecks all archived redo logs in thread 1: CROSSCHECK ARCHIVELOG FROM SEQUENCE 0 THREAD 1;

P.R.P.R.

Page 234

Oracle 11g - RMAN Enhancments:


(1) Proactive Health Check:

RMAN> list backup summary;

RMAN> list archivelog all; specification does not match any archived log in the recovery catalog RMAN> list failure; no failures found that match specification RMAN> validate database; Starting validate at 28-APR-10 allocated channel: ORA_DISK_1 channel ORA_DISK_1: SID=134 device type=DISK allocated channel: ORA_DISK_2 channel ORA_DISK_2: SID=131 device type=DISK channel ORA_DISK_1: starting validation of datafile channel ORA_DISK_1: specifying datafile(s) for validation input datafile file number=00006 name=D:\APP\ORACLE\ORADATA\SIEBEL_TBS02.DBF input datafile file number=00003 name=D:\APP\ORACLE\ORADATA\UNDOTBS01.DBF input datafile file number=00008 name=C:\APP\ORACLE\ORADATA\SYSAUX02.DBF input datafile file number=00009 name=D:\APP\ORACLE\ORADATA\KK.DBF input datafile file number=00004 name=D:\APP\ORACLE\ORADATA\USERS01.DBF channel ORA_DISK_2: starting validation of datafile channel ORA_DISK_2: specifying datafile(s) for validation input datafile file number=00005 name=D:\APP\ORACLE\ORADATA\SIEBEL_TBS01.DBF input datafile file number=00007 name=C:\APP\ORACLE\ORADATA\SYSTEM02.DBF input datafile file number=00002 name=D:\APP\ORACLE\ORADATA\SYSAUX01.DBF input datafile file number=00001 name=C:\APP\ORACLE\ORADATA\SYSTEM01.DBF channel ORA_DISK_1: validation complete, elapsed time: 00:27:29

P.R.P.R.

Page 235

List of Datafiles ================= File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------3 OK 0 48 198400 5562469 File Name: D:\APP\ORACLE\ORADATA\UNDOTBS01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 0 Index 0 0 Other 0 198352 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------4 OK 0 659 1408 5562230 File Name: D:\APP\ORACLE\ORADATA\USERS01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 154 Index 0 120 Other 0 475 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------6 OK 0 542534 640000 5168010 File Name: D:\APP\ORACLE\ORADATA\SIEBEL_TBS02.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 57531 Index 0 37599 Other 0 2336 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------8 OK 0 124772 128000 5561783 File Name: C:\APP\ORACLE\ORADATA\SYSAUX02.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 1194 Index 0 1743 Other 0 291 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------9 OK 0 2490 2560 5530132 File Name: D:\APP\ORACLE\ORADATA\KK.DBF P.R.P.R. Page 236

Block Type ---------Data Index Other

Blocks Failing -------------0 0 0

Blocks Processed ---------------35 0 35

channel ORA_DISK_1: starting validation of datafile channel ORA_DISK_1: specifying datafile(s) for validation channel ORA_DISK_2: validation complete, elapsed time: 00:13:04 List of Datafiles ================= File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------1 OK 0 9597 88320 5563124 File Name: C:\APP\ORACLE\ORADATA\SYSTEM01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 64005 Index 0 12102 Other 0 2616 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------2 OK 0 26841 99056 5563122 File Name: D:\APP\ORACLE\ORADATA\SYSAUX01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 20789 Index 0 22118 Other 0 29308 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------5 OK 0 432788 640000 5434168 File Name: D:\APP\ORACLE\ORADATA\SIEBEL_TBS01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 60409 Index 0 62883 Other 0 83920 File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------7 OK 0 245073 256000 5562689 File Name: C:\APP\ORACLE\ORADATA\SYSTEM02.DBF Block Type Blocks Failing Blocks Processed P.R.P.R. Page 237

---------Data Index Other

-------------0 0 0

---------------5838 5081 8

including current control file for validation channel ORA_DISK_1: validation complete, elapsed time: 00:00:01

List of Control File and SPFILE =============================== File Type Status Blocks Failing Blocks Examined ------------ ------ -------------- --------------Control File OK 0 614 Finished validate at 28-APR-10 RMAN> validate tablespace kk; Starting validate at 28-APR-10 using channel ORA_DISK_1 using channel ORA_DISK_2 channel ORA_DISK_1: starting validation of datafile channel ORA_DISK_1: specifying datafile(s) for validation input datafile file number=00009 name=D:\APP\ORACLE\ORADATA\KK.DBF channel ORA_DISK_1: validation complete, elapsed time: 00:00:04 List of Datafiles ================= File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------9 OK 0 2490 2560 5530132 File Name: D:\APP\ORACLE\ORADATA\KK.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 35 Index 0 0 Other 0 35 Finished validate at 28-APR-10 RMAN> validate tablespace users; Starting validate at 28-APR-10 using channel ORA_DISK_1 using channel ORA_DISK_2 channel ORA_DISK_1: starting validation of datafile P.R.P.R. Page 238

channel ORA_DISK_1: specifying datafile(s) for validation input datafile file number=00004 name=D:\APP\ORACLE\ORADATA\USERS01.DBF channel ORA_DISK_1: validation complete, elapsed time: 00:00:01 List of Datafiles ================= File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------4 OK 0 659 1408 5562230 File Name: D:\APP\ORACLE\ORADATA\USERS01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 154 Index 0 120 Other 0 475 Finished validate at 28-APR-10 RMAN> validate tablespace system; Starting validate at 28-APR-10 using channel ORA_DISK_1 using channel ORA_DISK_2 channel ORA_DISK_1: starting validation of datafile channel ORA_DISK_1: specifying datafile(s) for validation input datafile file number=00001 name=C:\APP\ORACLE\ORADATA\SYSTEM01.DBF channel ORA_DISK_2: starting validation of datafile channel ORA_DISK_2: specifying datafile(s) for validation input datafile file number=00007 name=C:\APP\ORACLE\ORADATA\SYSTEM02.DBF channel ORA_DISK_1: validation complete, elapsed time: 00:01:20 List of Datafiles ================= File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------1 OK 0 9597 88320 5565051 File Name: C:\APP\ORACLE\ORADATA\SYSTEM01.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 64005 Index 0 12102 Other 0 2616 channel ORA_DISK_1: starting validation of datafile channel ORA_DISK_1: specifying datafile(s) for validation channel ORA_DISK_2: validation complete, elapsed time: 00:03:47 P.R.P.R. Page 239

List of Datafiles ================= File Status Marked Corrupt Empty Blocks Blocks Examined High SCN ---- ------ -------------- ------------ --------------- ---------7 OK 0 245073 256000 5564684 File Name: C:\APP\ORACLE\ORADATA\SYSTEM02.DBF Block Type Blocks Failing Blocks Processed ---------- -------------- ---------------Data 0 5838 Index 0 5081 Other 0 8 including current control file for validation channel ORA_DISK_1: validation complete, elapsed time: 00:00:02 List of Control File and SPFILE =============================== File Type Status Blocks Failing Blocks Examined ------------ ------ -------------- --------------Control File OK 0 614 Finished validate at 28-APR-10 RMAN>

P.R.P.R.

Page 240

P.R.P.R.

Page 241

RMAN Scenarios:

SCENARIO. 1

LOSS of C/R/D files:


After loss of C/R/D files:
RMAN> shutdown abort; RMAN> startup nomount; RMAN> restore controlfile; RMAN> mount database; RMAN> restore database; RMAN> recover database; RMAN> alter database open resetlogs; RMAN> backup database;

SCENARIO. 2

Loss of SYSTEM datafile:


RMAN> shutdown abort; RMAN> startup mount; RMAN> restore datafile 1; RMAN> recover database; RMAN> alter database open;

SCENARIO. 3

Loss os NON System datafile:


RMAN> shutdown abort; RMAN> startup mount; RMAN> sql alter database datafile 4 offline; RMAN> restore datafile 4; RMAN> recover datafile 4; P.R.P.R. Page 242

RMAN> sql alter database datafile 4 online; RMAN> alter database open;

SCENARIO. 4

Loss of Controlfile:
RMAN> shutdown abort RMAN> startup nomount; RMAN> restore controlfile; RMAN> mount database; RMAN> recover database; RMAN> alter database open resetlogs; RMAN> backup database;

U can restore a specific controlfile. Rman> restore controlfile from '/oracle/app/oracle/product/10.2.0/dbs/02lkfom9_1_1';


Restoring a Control File Autobackup to a Nondefault Location The control file autobackup is located on disk in a nondefault location. RMAN starts searching for backups with a sequence number of 20, and searches backward for 5 months:
CONNECT TARGET / STARTUP FORCE NOMOUNT SET DBID 36508508; # required when restoring control file in NOCATALOG mode RUN { SET CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/disk1/prod_cf_auto_%F'; RESTORE CONTROLFILE TO '/tmp/cf_auto.dbf' FROM AUTOBACKUP MAXSEQ 20 MAXDAYS 150; ALTER DATABASE MOUNT; RESTORE DATABASE; RECOVER DATABASE; } ALTER DATABASE OPEN RESETLOGS;

SCENARIO. 5

Loss of Redologs:
RMAN> shutdown abort RMAN> startup nomount RMAN> restore controlfile P.R.P.R. Page 243

RMAN> mount database; RMAN> restore database; RMAN> recover database; (Some times u may get errors {Media recovery}) RMAN> alter database open resetlogs;

Incremental

Rman> backup incremental level 0 database; Rman> Report obsolete; Rman> Delete noprompt obsolete; $] du f Rman> Backup incremental level 1 database; Rman> Backup incremental level 2 database; Rman> List backup summery; Rman> Report need backup; Rman> Crosscheck backup; Rman> Report obsolete; Rman> Delete obsolete; Rman> Delete noprompt obsolete Rman> Select * from rc_database; Rman> Select * from rc_tablespace; Rman> Select * from rc_backup_set (To see the how many backup setswe have) Rman> Select * from rc_backup_piece; Rman> select * from bkp; Rman> host clear; Rman> Crosscheck backup; Rman> Delete expired backup; hiprpr@gmail.com

P.R.P.R.

Page 244

RMAN INFO.@ RMAN LINKS: http://tahiti.oracle.com/


http://download.oracle.com/docs/cd/B19306_01/backup.102/b14194/toc.htm http://download.oracle.com/docs/cd/B19306_01/backup.102/b14192/toc.htm http://download.oracle.com/docs/cd/B19306_01/backup.102/b14193/toc.htm http://download.oracle.com/docs/cd/B19306_01/backup.102/b14194/toc.htm

http://www.morganslibrary.com/reference/rman_demos.html

RMAN: Restoring an RMAN Backup to Another Node Doc ID: 73974.1 RMAN: Creating a Duplicate Database

Doc ID: 73912.1


What is a Flash Recovery Area and how to configure it ? Doc ID: 305648.1
Setting Up a Flash Recovery Area for RMAN

http://download.oracle.com/docs/cd/B19306_01/backup.102/b14192/setup00 5.htm
How To Restore Rman Backups On A Different Node When The Directory Structures Are Different [ID 419137.1]

P.R.P.R.

Page 245

Backup - RMAN
Create a catalog
create a tablespace create a user grant connect, resource, recovery_catalog_owner to user rman catalog user/pass@db create catalog tablespace "<tablespace_name>";

Note. <tablespace_name> is case sensitive (i.e. it must be uppercase) Note. If you get the error 'rman: can't open catalog', make sure that oracle's rman is being run (which rman). X11 also has a command called rman. Rename it if necessary.

Register a database Note. ensure the target db has a password file


rman catalog user/pass@rmandb target user/pass@db register database;

Un-register a database
sqlplus user/pass@rmandb select * from rc_database; select db_key, db_id from db; execute dbms_rcvcat.unregisterdatabase(<db_key>, <db_id>);

Reset the catalog after a restlogs on the target


reset database;

Resync the catalog with the target controlfile


resync catalog;

P.R.P.R.

Page 246

Delete a backup
allocate channel... delete backuppiece <number>; release channel;

Backup a database
backup database plus archivelog format '/u01/ora_backup/rman/%d_%u_%s'; run { allocate channel t1 type disk; backup current controlfile format '/u01/ora_backup/rman/%d_%u_%s'; backup database format '/u01/ora_backup/rman/%d_%u_%s'; backup archivelog all delete input format '/u01/ora_backup/rman/arch_%d_%u_%s'; release channel t1; } run { allocate channel t1 type disk; backup archivelog all delete input format '/u01/ora_backup/rman/arch_%d_%u_%s'; release channel t1; }

Cold backup (archivelog or noarchivelog mode)


run { allocate channel t1 type disk; shutdown immediate; startup mount; backup database include current controlfile format '/u01/ora_backup/rman/%d_%u_%s'; alter database open; }

run { allocate channel t1 type disk; backup archivelog all delete input; }

P.R.P.R.

Page 247

Restore/recover a database Full restore and recovery


startup nomount; run { allocate channel t1 type disk; allocate channel t2 type disk; allocate channel t3 type disk; allocate channel t4 type disk; restore controlfile; restore archivelog all; alter database mount; restore database; recover database; } sql 'alter database open resetlogs';

Restore and roll forward to a point in time


startup nomount; run { set until time ="to_date('30/08/2006 12:00','dd/mm/yyyy hh24:mi')"; allocate channel t1 type disk; allocate channel t2 type disk; allocate channel t3 type disk; allocate channel t4 type disk; restore controlfile; restore archivelog all; alter database mount; restore database; recover database; } sql 'alter database open resetlogs'; If the archive logs are already in place: startup mount; run { set until time ="to_date('08/02/2007 14:00','dd/mm/yyyy hh24:mi')"; allocate channel t1 type disk; allocate channel t2 type disk; allocate channel t3 type disk; allocate channel t4 type disk; restore database; recover database; } sql 'alter database open resetlogs'; startup mount; run { allocate channel t1 type disk; recover database; }

P.R.P.R.

Page 248

Show the controlfile backup record


set pages 999 lines 100 col name format a60 break on set_stamp skip 1 select set_stamp , to_char(ba.completion_time, 'HH24:MI DD/MM/YY') finish_time , df.name from v$datafile df , v$backup_datafile ba where df.file# = ba.file# and ba.file# != 0 order by set_stamp, ba.file# /

Misc commands
list backupset; list backup of database; list backup of archivelog all; report obsolete; report obsolete redundancy = 2; delete obsolete; - remove unneeded backups restore database validate; - check the backup report unrecoverable; report schema; - show current db files crosscheck backup; - make sure the backups in the catalog still physically exist delete expired backup; - delete epired backups found by crosscheck rman target sys/*****@scr10 catalog rman/rman@dbarep LIST BACKUPSET OF DATABASE; ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE DISK; DELETE OBSOLETE REDUNDANCY = 4 device type disk; delete obsolete REDUNDANCY = 2 device type disk;

Delete archive log older than...


DELETE NOPROMPT ARCHIVELOG UNTIL TIME "SYSDATE-5"

Crosscheck the available archivelogs (fixes RMAN-06059)


change archivelog all crosscheck;

P.R.P.R.

Page 249

RMAN CLONING
Source Side: Database name: PROD C/R/D files location: /oradata/prod/data RMAN Backup location: /oracle/app/oracle/product/10.2.0/dbs / (1) Move the RMAN fresh backup and parameter file to target side. (2) If datafiles locations are same in source and target side then skip below step (3), If not the follow... (3) Prepare the script to rename the datafiles at target side. Sql>Spool rename.lst
Sql>select 'set newname for datafile '||FILE_ID||' to '||''''||file_name||''''||';' from dba_data_files;

Sql> spool off Sql> exit Move this rename.lst file to target. Target Side: (1) Copy the parameter file to ORACLE_HOME/dbs location (2) Edit the file parameter > Control file location > Archive location > Cdump & bdump & udump locations (3) Create required directory structure. (4) Move the c/r/d file to specific location from backup. Here I am planning to kept c/r/d files in /software/dev/data/ location. (5) Export ORACLE_SID (6) Startup the database in Nomount stage. (7) Connect to the rman

P.R.P.R.

Page 250

$rman target / nocatalog Rman> Rman> run 2> { 3> set controlfile autobackup format for device type disk to '/software/dev/data/cont1.ctl/%F'; 4> allocate channel disk1 device type disk format '/software/dev/data/%U'; 5> allocate channel disk2 device type disk format '/software/dev/data/%U'; 6> restore controlfile from /oracle/app/oracle/product/10.2.0/dbs/02lkfom9_1_1'; 7> sql "alter database mount"; 8> } executing command: SET CONTROLFILE AUTOBACKUP FORMAT allocated channel: disk1 channel disk1: sid=47 devtype=DISK allocated channel: disk2 channel disk2: sid=46 devtype=DISK Starting restore at 05-AUG-10 channel disk2: skipped, autobackup already found channel disk1: restoring control file channel disk1: restore complete, elapsed time: 00:00:09 output filename=/software/dev/data/cont1.ctl Finished restore at 05-AUG-10 sql statement: alter database mount released channel: disk1 released channel: disk2 RMAN> run 2> { 3> set newname for datafile 1 to '/software/dev/data/system.dbf'; 4> set newname for datafile 2 to '/software/dev/data/undotbs.dbf'; 5> set newname for datafile 3 to '/software/dev/data/sysaux.dbf'; 6> set newname for datafile 4 to '/software/dev/data/userdata.dbf'; 7> set newname for datafile 5 to '/software/dev/data/kk.dbf'; 8> set newname for datafile 6 to '/software/dev/data/yy.dbf'; 9> restore database; 10> switch datafile all; 11> recover database; 12> release channel disk1; 13> release channel disk2; 14> } P.R.P.R. Page 251

executing command: SET NEWNAME executing command: SET NEWNAME executing command: SET NEWNAME executing command: SET NEWNAME executing command: SET NEWNAME executing command: SET NEWNAME Starting restore at 05-AUG-10 allocated channel: ORA_DISK_1 channel ORA_DISK_1: sid=47 devtype=DISK channel ORA_DISK_1: starting datafile backupset restore channel ORA_DISK_1: specifying datafile(s) to restore from backup set restoring datafile 00001 to /software/dev/data/system.dbf restoring datafile 00002 to /software/dev/data/undotbs.dbf restoring datafile 00003 to /software/dev/data/sysaux.dbf restoring datafile 00004 to /software/dev/data/userdata.dbf restoring datafile 00005 to /software/dev/data/kk.dbf restoring datafile 00006 to /software/dev/data/yy.dbf channel ORA_DISK_1: reading from backup piece /oracle/app/oracle/product/10.2.0/dbs/01lkfolp_1_1 channel ORA_DISK_1: restored backup piece 1 piece handle=/oracle/app/oracle/product/10.2.0/dbs/01lkfolp_1_1 tag=TAG20100804T070945 channel ORA_DISK_1: restore complete, elapsed time: 00:00:25 Finished restore at 05-AUG-10 datafile 1 switched to datafile copy input datafile copy recid=12 stamp=726209374 filename=/software/dev/data/system.dbf datafile 2 switched to datafile copy input datafile copy recid=13 stamp=726209374 filename=/software/dev/data/undotbs.dbf datafile 3 switched to datafile copy input datafile copy recid=14 stamp=726209374 filename=/software/dev/data/sysaux.dbf datafile 4 switched to datafile copy input datafile copy recid=15 stamp=726209374 filename=/software/dev/data/userdata.dbf datafile 5 switched to datafile copy input datafile copy recid=16 stamp=726209374 filename=/software/dev/data/kk.dbf datafile 6 switched to datafile copy input datafile copy recid=17 stamp=726209374 filename=/software/dev/data/yy.dbf Starting recover at 05-AUG-10 using channel ORA_DISK_1

P.R.P.R.

Page 252

starting media recovery archive log thread 1 sequence 349 is already on disk as file /oradata/prod/data/redo1.log archive log thread 1 sequence 350 is already on disk as file /oradata/prod/data/redo2.log archive log filename=/oracle/prod/arch/1_347_724346062.dbf thread=1 sequence=347 archive log filename=/oracle/prod/arch/1_348_724346062.dbf thread=1 sequence=348 archive log filename=/oradata/prod/data/redo1.log thread=1 sequence=349 archive log filename=/oradata/prod/data/redo2.log thread=1 sequence=350 media recovery complete, elapsed time: 00:00:07 Finished recover at 05-AUG-10

SQL> select instance_name,status from v$instance; INSTANCE_NAME STATUS --------------------------PROD MOUNTED SQL> recover database using backup controlfile until cancel; ORA-00279: change 568446 generated at 08/05/2010 04:46:18 needed for thread 1 ORA-00289: suggestion : /oracle/prod/arch/1_350_724346062.dbf ORA-00280: change 568446 for thread 1 is in sequence #350

Specify log: {<RET>=suggested | filename | AUTO | CANCEL} cancel Media recovery cancelled.

SQL> select member from v$logfile; MEMBER -------------------------------------------------------------------------------/oradata/prod/data/redo1.log /oradata/prod/data/redo2.log SQL> alter database rename file '/oradata/prod/data/redo1.log' to '/software/dev/data/redo1.log'; Database altered. SQL> alter database rename file '/oradata/prod/data/redo2.log' to '/software/dev/data/redo2.log'; Database altered. SQL> select name from v$tempfile; NAME P.R.P.R. Page 253

-------------------------------------------------------------------------------/oradata/prod/data/temp.tmp /oradata/prod/data/temp1.tmp SQL> alter database rename file '/oradata/prod/data/temp.tmp' to '/software/dev/data/temp.tmp'; Database altered. SQL> alter database rename file '/oradata/prod/data/temp1.tmp' to '/software/dev/data/temp1.tmp'; Database altered. SQL> alter database open resetlogs; Database altered. SQL> sho parameter db_name NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_name string PROD SQL> SQL> sho parameter instance_name NAME TYPE VALUE ------------------------------------ ----------- -----------------------------instance_name string PROD

http://download.oracle.com/docs/cd/B28359_01/backup.111/b28273/rcmsynta037.htm

P.R.P.R.

Page 254

P.R.P.R.

Page 255

TRANSPORTABLE TABLESPACE

P.R.P.R.

Page 256

TRANSPORTING TABLESPACE USING EXPORT & IMPORT (SAME PLATFORM)

>> Cr8 a tablespace TTS >> Cr8 a user TTS >> Assign TTS TTS Sys>> TTS>> Demobld >> select * from tab; >> create table t (no number, name varchar2 (12)); >> insert into t values&no,&name); / / TTS>> select * from t;

TTS>> Sys>> alter tablespace TTS read only;

Sys>> (Tablespacename) Sys>> exec dbms_tts.transport_set_check (TTS);


Sys>> select * from transport_set_violations; Sys>> exit dba11@ram ~] $ exp file=tts.dmp log=tts.log transport_tablespace=y tablespaces=tts Username: / as sysdba dba11@ram ~] $ cp /disk1/oradata/good/tts.dbf ~

P.R.P.R.

Page 257

dba11@ram ~] $ ls tts.dmp tts.dbf (Hostname or IP address) dba11@ram ~] $ ftp i dba15 Name: Prasad Ftp> mput tts.dmp tts.dbf Ftp> bye (Username)

dba15@prasad ~] $ ls tts.dbf tts.dmp ~] $ sqlplus / as sysdba Sys>> startup Sys>> create user tts Sys>> exit

(Same user)

~] $ cp tts.dbf /disk2/oradata/bad /disk2/oradata/bad this is the location of C/R/D files in the dba15 server Database.

dba15~] $ imp file=tts.dmp transport_tablespace=y datafiles=/disk2/oradata/bad/tts.dbf Username: / as sysdba ~] $


P.R.P.R. Page 258

Sys>> Tts>> select * from tab; T Tts>> select * from t;

hiprpr@gmail.com

P.R.P.R.

Page 259

TRANSPORTING THE TABLESPACE ACROSS PLOTFORMS: [LINUX WINDOWS] Using Datapump

Sys>> create a tablespace TTS Sys>> create user TTS Sys>> Assign TTS TTS Sys>> Tts>> Demobld Sys>> Exec dbms_tts.transport_set_check (TTS); Sys>> select * from transport_set_violations; O/p No rows selected Sys>> select * from dba_directories; Sys>> create directory dp as /disk1/oradata/good/dp; Sys>> Alter tablespace read only; Sys>> ~] $ mkdir p /disk1/oradata/good/dp ~] $ expdp directory=dp dumpfile=tts.dmp transport_tablespaces=tts Username: / as sysdba ~] $ cd /disk1/oradata/good good] $ cp tts.dbf dp good] $ cd dp dp] $ ls tts.dbf tts.dmp

P.R.P.R.

Page 260

WINDOWS

C :\> sqlplus /as sysdba SQL> select status from v$instance; SQL>grant connect, resource to tts identified by tts; SQL>create directory d1 as c:\d1; SQL> exit C :\> mkdir d1 C :\> cd d1 C:\d1> ftp i 192.168.0.11 Ftp> pwd /disk1/oradata/good/dp Ftp> mget * Ftp> bye C:\d1> dir Observe Tts.dbf Tts.dmp C:\d1>impdp directory=d1 dumpfile=tts.dmp transport_datafiles=c:\d1\tts.dbf Username: / as sysdba C:\d1> conn tts/tts Tts>> select * from tab; Tts>> conn / as sysdba SQL>> select tablespace_name, status, plugged_in from dba_tablespaces; SQL>> Alter tablespace tts read write;
P.R.P.R. Page 261

P.R.P.R.

Page 262

CLONING

dba11 Source SID: Ram DBNAME: Ram LOCATION: /disk1/oradata/good

dba15 Target SID: Prasad DBNAME: Prasad LOCATION: /disk2/oradata/bad

Sys>> shut immediate dba11 ~] $ ] ls ] $ cd /disk1/oradata/good good] $ mkdir clone ] $ cd dba11 ~] $ sqlplus / as sysdba Sys>> startup Sys>> startup mount Sys>> alter database backup controlfile to /disk1/oradata/good/clone/clone.ctl; Sys>> shut Sys>> exit dba11 ~] $ cd /disk1/oradata/good good] $ cp *.dbf *.log clone/ good] $ cd clone clone] $ ls clone.ctl *.dbf *.log

clone] $ cd $ORACLE_HOME/dbs dbs] $ cp init$ORACLE_SID.ora /disk1/oradata/good/clone/ dbs] $ cd /disk1/oradata/good/clone


P.R.P.R. Page 263

clone] $ ls clone.ctl *.dbf *.log initram.ora

@@@ dba15 ~] $ dba15 ~] $ ls dba15 ~] $ mkdir clone dba15 ~] $ cd clone clone] $ @@ dba11 ~] $ cd /disk1/oradata/good/clone clone] $ ftp i dba15 Username: Prasad Ftp> pwd /user/Prasad/clone Ftp>!pwd /disk1/oradata/good/clone Ftp> mput * Ftp> bye dba15 ~] $ echo $ORACLE_SID Prasad dba15 ~] $ export ORACLE_SID=ram dba15 ~] $ echo $ORACLE_SID ram dba15 ~] $ cd clone

P.R.P.R.

Page 264

clone] $ ls clone.ctl *.dbf *.log initram.ora clone] $ cp initram.ora $ORACLE_HOME/dbs clone] $ cd $ORACLE_HOME/dbs dbs] $ vi initram.ora control_files= /disk2/oradata/good2/clone.ctl background_dump_dest = core_dump_dest = user_dump_dest = db_file_name_convert = /disk1/oradata/good/ /disk2/oradata/good2 log_file_name_convert = /disk1/oradata/good/ /disk2/oradata/good2 : wq dbs] $ cd dba15 ~] $ mkdir p /disk2/oradata/good2/{bdump,cdump,udump} dba15 ~] $ cd /disk2/oradata/good2/ good2] $ ls bdump cdump udump good2] $ cd dba15 ~] $ cd clone clone] $ cp *.dbf *.log *.ctl /disk2/oradata/good2/ clone] $ cd /disk2/oradata/good2/ good2] $ ls bdump cdump udump *.dbf *.log dba15 ~] $ sqlplus / as sysdba Sys>> startup nomount
P.R.P.R. Page 265

clone.ctl

Sys>> alter database mount clone database; Sys>> select file#, name, status from v$datafile; MAKE ALL DATAFILES ONLINE Sys>> alter database datafile &n online; Sys>> alter database open resetlogs; Sys>> select open_mode, controlfile_type from v$database;

{ One More way to CLONE


1. 2. 3. 4. 5. Restore the lastnight Backup Check the owner ship of the files.. Recreate the controlfile Check the ARCH mode Log switch alter ayatem switch logfile (check in alert logfile ull get some error abt TEMP Tablespace) 6. In Os level u have temp file, so add that temp file to TEMP tablespace Alter tablespace temp add tempfile /location size 0m reuse; Check tempfile size in OS level and give the same thing. 7. Reset the system user password Just check it out if any scripts u need to run after the clone (depends on DB/Server/Setup) OR any tables/user account locking/unlocing/DB Links.. Like this check it out.

}
hiprpr@gmail.com

P.R.P.R.

Page 266

RESUMABLE TABLESPACE
Sys>> create tablespace RTS Sys>> create user RTS Sys>> Assign RTS RTS Sys>> grant resumable to RTS; Sys>> Alter session enable resumable; Sys>> Rts>> alter session enable resumable timeout = 1800;

{You can
Sys>> Alter session enable resumable name Wake up DBA ;} Rts>> Demobld Rts>> insert into emp select * from emp; / / ORA- 01653 unable to extend table.. In 2nd session open Alert log file for checking purpose Rts>> insert into emp select * from emp; Session will hang. Sys>> select file_id, tablespace_name from dba_data_files; Sys>> alter database datafile <file_id> resize 20m; If I press enter automatically records will insert in 1st session.

P.R.P.R.

Page 267

FLASHBACK DATABASE
Flashback Database using: Conditions: 1. DB should be in ARCH mode 2. Mention the parameters db_recovery_file_dest db_recovery_file_dest_size db_flashback_retention_target = 1440 By default flashback is OFF TIME SCN

Flashback DB with SCN: Sys>> shut immediate Sys>> Exit ~] $ vi $ORACLE_HOME/dbs/init$ORACLE_SID.ora db_recovery_file_dest = /disk1/oradata/good/flash db_recovery_file_dest_size = 300m : wq ~] $ mkdir p /disk1/oradata/good/flash Sys>> Sys>> startup mount Sys>> Sho parameter flashback; Sys>> Alter database flashback on; Sys>> Alter database open; Sys>> Desc v$database;
P.R.P.R. Page 268

Sys>> select current_scn from v$database; 336699 Sys>> create user ii identified by ii Sts>> create a tablespace tt Sys>> drop user ii cascade; Sys>> drop tablespace tt; Sys>> shut immediate Sys>> startup mount Sys>> Flashback database to scn 336699; Sys>> alter database open resetlogs; Sys>> select * from all_users; ii doesnt exist Sys>> select tablespace_name from dba_tablespaces; tt doesnt exist

WITH TIME: Sys>> Pr>> set time on 12:30:15 pr>>select * from emp; 12:30:16 pr>>select * from dept; 12:30:17 pr>> drop table emp purge; 12:30:18 pr>> drop table dept purge; Sys>> shut immediate Sys>> startup mount Sys>> Flashback database to timestamp to_timestamp (2008/15/04:12:30:16,yyyy/dd/mm:hh24:mi:ss); Sys>> Alter database open resetlogs;

P.R.P.R.

Page 269

Pr>> select * from tab; Emp & Dept tables exist @@@@@ Sys>> grant connect, resource to kk identified by kk; Sys>> kk>> Demobld kk>> Sys>> create restore point p1; Sys>> drop user kk cascade; Sys>> shut immediate Sys>> startup mount Sys>> Flashback database to restore point p1; Sys>> alter database read only; Sys>> select * from all_users; Kk user will exist

P.R.P.R.

Page 270

How to get back dropped Tablespace using Flashback Database.


It needs to remember that if you drop your tablespace with including datafiles option then it is not possible to get your tablespace back with flashback database. While dropping if you use DROP TABLESPACE INCLUDING CONTENTS option then it is possible to get back tablespace. Procedures with and Example: --------------------------------1)Create a Tablespace and Table inside it. SQL> create tablespace test_restore datafile '/oradata2/test_restore01.dbf' size 5m; Tablespace created. SQL> create table test tablespace test_restore as select level a1 from dual connect by level <99; Table created. 2)Note the SCN and Drop the Tablespace with including contents option. --------------------------------------------------------------------------SQL> select current_scn from v$database; CURRENT_SCN ----------938686 SQL> drop tablespace test_restore including contents; Tablespace dropped. 3)Mount the database. SQL> shutdown immediate Database closed. Database dismounted. ORACLE instance shut down. SQL> startup mount ORACLE instance started. Total System Global Area 167772160 bytes Fixed Size 2019288 bytes Variable Size 104857640 bytes Database Buffers 54525952 bytes Redo Buffers 6369280 bytes Database mounted. 4)Perform FlashBack. SQL> flashback database to scn 938686; flashback database to scn 938686 * ERROR at line 1: ORA-38795: warning: FLASHBACK succeeded but OPEN RESETLOGS would get error below

P.R.P.R.

Page 271

ORA-01245: offline file 5 will be lost if RESETLOGS is done ORA-01111: name for data file 5 is unknown - rename to correct file ORA-01110: data file 5: '/oracle/app/oracle/product/10.2.0/db_1/dbs/UNNAMED00005' 5)The datafile Become Unnamed. So rename it with original data file location. SQL> alter database rename file '/oracle/app/oracle/product/10.2.0/db_1/dbs/UNNAMED00005' to 2 '/oradata2/test_restore01.dbf'; Database altered. 6)Now perforem Flashback and Open the database with read only mode. SQL> flashback database to scn 938686; Flashback complete. SQL> alter database open read only; Database altered. SQL> select count(*) from test; COUNT(*) ---------98

http://arjudba.blogspot.com/2008/04/how-to-get-back-dropped-tablespace.html

P.R.P.R.

Page 272

Backup Flashback:

To put the session back in time Note. undo management must be auto Note. Take a look at undo_retention to get an idea of how far back you might be able to go. Note. This can't be run as sys - system works though
exec dbms_flashback.enable_at_time(to_date('2006-AUG-24 12:00:00', 'YYYY-MON-DD HH24:MI:SS'));

To disable flashback run...


exec dbms_flashback.disable;

Copy old data into a new table First, create an empty copy of the source table...
create table old_test_table tablespace andy as select * from test_table where rownum < 1 /

Now, insert the old data into it...


insert /*+ APPEND */ old_test_table (select * from test_table as of timestamp to_timestamp('24-AUG-06 12:00:00','DD-MON-YY HH24:MI:SS')) /

Export a database from a point in time


exp / file=full_scr9.dmp log=full_scr9.log flashback_time=TO_TIMESTAMP('10-09-2006 09:00:00', 'DD-MM-YYYY HH24:MI:SS') exp / parfile=full_scr9.par

P.R.P.R.

Page 273

parfile...
userid=system/****** file=full_scr9.dmp log=full_scr9.log flashback_time='2006-09-13 12:00:00'

Find the current SCN number


select dbms_flashback.get_system_change_number from dual /

Set the database recovery directory and size These settings are dynamic
alter system set db_recovery_file_dest='<path>' scope=both / alter system set db_recovery_file_dest_size=<size> scope=both /

Set the flashback database retention target


alter system set db_flashback_retention_target=<minutes> scope=both /

Turn on flashback database


shutdown immediate startup mount alter database flashback on; alter database open;

What is the earliest time the database can be flashed back to?
select oldest_flashback_scn scn , to_char(oldest_flashback_time, 'hh24:mi:ss dd/mm/yyyy') oldest_time from v$flashback_database_log /

P.R.P.R.

Page 274

Get a list of times and scn numbers


set pages 999 select scn , to_char(time_dp, 'hh24:mi:ss dd/mm/yyyy') time from smon_scn_time order by scn /

Flash the database back


shutdown immediate startup mount exclusive

flashback database to scn <scn>;

or...
flashback database to timestamp to_timestamp('22/04/2007 19:30:00','dd/mm/yyyy hh24:mi:ss');

alter database open resetlogs;

P.R.P.R.

Page 275

LOG MINER

>> Archive log list >> shut In Pfile utl_file_dir=/disk1/oradata/good/utl Create required directory structure $ mkdir p /disk1/oradata/good/utl SYS>> Startup >> Archive log list >> U1> delete from I; (E.g. 3 rows deleted) > commit; SYS>> alter system switch logfile; SYS>> Exec dbms_logmnr_d.build (orcl,//disk1/oradata/good/utl); Orcl = file name (any name u can give)

2S

OPEN 1 MORE SESSION & TAKE THE ARCHIVE LOG FILE Arch] $ ls lrt

P.R.P.R.

Page 276

1S >> Exec dbms_logmnr.add_logfile (/disk1/oradata/good/arch/ archive file);

>>Exec dbms_logmnr.start_logmnr (dictfile name => /disk1/oradata/good/utl/orcl); >> select sql_undo from v$logmnr_contents where seg_owner = U1 and seg_name=I;

>> spool on >> / >> spool off >> Ed on.lst

SYS>> @on.lst

1 row created 1 row created 1 row created

U1> select * from I;

3 rows selected.

P.R.P.R.

Page 277

SQL LOADER

SQL Loader (sqlldr): It is a tool which is used to load the data from flatfile to Database.

P.R.P.R.

Page 278

Types of Files: 2) Controlfile: Crucial info about all files, control file contains information that describes how the data will be loaded. It contains the table name, column datatypes, field delimiters, etc. It simply provides the guts for all SQL*Loader processing. 3) Datafile: It contains the Data. 4) Logfile: Ascii Format 5) Discard Files: User rejected records 6) Bad Files: System rejected records.(Invalid Datatypes)

Options to Load the Data: 1) 2) 3) 4) INSERT: When the table is Empty. APPEND : If already data Exists TRUNCATE: Truncate the data. REPLACE: It overwrites the data.

Note: Every record using Sqlloder is commit by default,It will allow 50 error. Deafult path is conventional Path. Direct: Skip the Buffers. Conventional: It will touch the SQL layers.

P.R.P.R.

Page 279

$vi New.ctl Load data Infile * Insert Into table DEPT Fields terminated by , (deptno,dname,loc) Begindata 10,ACCOUNTS,HYD 20,FINANCE,SEC :wq $sqlldr control=New.ctl log=New.log Username: - u1/u1

P.R.P.R.

Page 280

AUDITING

Auditing: Database AUDITING is the monitoring and recording of activities Occuring within a database.

P.R.P.R.

Page 281

SCOPE OF AUDITING The AUDIT facility allows you to specify the scope of AUDIT action As follows:

BY USER - Allows you to specify a specific user to audit. (Default ALL USERS) WHENEVER SUCCESSFUL / WHENEVER NOT SUCCESSFUL - Allows you to specify whether you wand AUDITING to occur at all Times, or only whenever the specific action was successful or Unsuccessful. (Default BOTH) BY SESSION / BY ACCESS - Allows you to specify how often AUDIT records are to be generated.

LIMITATIONS OF AUDITING

Oracle's AUDITING facility only works at the statement level. It is able to capture that a particular user executed a SELECT statement against a specific table, but it is not able to tell you which rows were retrieved.

IMPLEMENTING AUDITING

AUDITING can be activated by following these steps: 1. Enable AUDITING at the database level with the INIT.ORA parameter audit_trail 2. Enable the level of AUDITING through the AUDIT SQL statement The audit_trail parameter must be enabled for auditing to work. The valid values for this parameter are DB, NONE and OS. DB : Enables auditing to the internal data dictionary P.R.P.R. Page 282

OS : Enables auditing to the operating system audit trail. When set to OS, another parameter audit_file_dest has to be set in the INIT.ORA, for dumping audit_trail files in the OS. NONE : Disables all auditing

Types: 2) Object level 3) Privilege level 4) Statement level

1) Object level: Object level auditing can perform a normal user also not only SYS. Session 1 login as kk user Session 2 login as tt user By Scope (Default)

kk> grant select on emp to tt; kk> audit select on emp; kk> select username,obj_name,action,owner from user_audit_trail;
No rows

kk> save aud tt> select * from kk.emp; kk> @aud USER OBJ_NAME ---- ---TT EMP
P.R.P.R.

ACTION ---------103

OWNER ----KK
Page 283

tt> select count(*) from kk.emp;

kk> @aud USER OBJ_NAME ---- ---TT EMP ACTION ---------103 OWNER ----KK

You can check as SYS user also


Sys> select owner, object_name, object_type, sel, upd, del from dba_obj_audit_opts where owner='KK;

Sys> select os_username, username, owner, action_name, obj_name, to_char(timestamp,'dd/mm/yyyy:hh24:mi:ss') Time-Stamp from dba_audit_trail;

Scope = Session Once u login to tt user and selecting the records of kk.emp multiple times also audit will generate one time only for a session Because by default scope is by session But reconnect again.. Like tt> conn / as sysdba Sys> conn tt/tt

tt> select count(*) from kk.emp;

P.R.P.R.

Page 284

kk>@aud USERN OBJ_NAME -----------TT EMP TT EMP ACTION OWNER -------------103 KK 103 KK

By Access kk> grant select on dept to tt; kk> audit select on dept by access; tt> select count(*) from kk.dept;

kk> @aud USERN ----TT TT TT TT TT OBJ_NAME -------EMP EMP EMP EMP DEPT ACTION ---------103 103 103 103 3 OWNER ----KK KK KK KK KK

tt> select count(*) from kk.dept; kk> @aud USERN ----TT TT TT TT TT TT


P.R.P.R.

OBJ_NAME -------EMP EMP EMP EMP DEPT DEPT

ACTION ---------103 103 103 103 3 3

OWNER ----KK KK KK KK KK KK
Page 285

For Every select statement on kk.dept it will generate a audit.

2) PRIVILEGE LEVEL: Only SYSDBA can do. All System privileges. By default all Users Sys> audit create session Sys> select username,os_username,to_char(timestamp,'dd-mon-yy:hh24:mi:ss') Login, to_char(logoff_time,'dd-mon-yy:hh24:mi:ss') logoff, decode (returncode,1017,'fail','SUCCESS') "fail/success" from dba_audit_trail Sys> save privs_audit From another session SQL> conn tt/good {Wrong password} ERROR: ORA-01017: invalid username/password; logon denied

From 1st Session Sys> @privs_audit


USERNAME OS_USERNAM LOGIN LOGOFF fail/success -------- ---------- ------------------ ------------------ ------PUBLIC oracle 25-jul-10:07:53:28 SUCCESS PUBLIC oracle 25-jul-10:07:54:28 SUCCESS PUBLIC oracle 25-jul-10:07:55:28 SUCCESS TT oracle 25-jul-10:07:56:26 fail

2nd session
P.R.P.R. Page 286

Sys> Conn tt/tt

1st session Sys> @privs_audit


USERNAME OS_USERNAM LOGIN LOGOFF fail/success -------- ---------- ------------------ ------------------ ------PUBLIC oracle 25-jul-10:07:53:28 SUCCESS PUBLIC oracle 25-jul-10:07:54:28 SUCCESS PUBLIC oracle 25-jul-10:07:55:28 SUCCESS TT oracle 25-jul-10:07:56:26 fail TT oracle 25-jul-10:07:56:46 SUCCESS

2nd Seesion
SQL> sho user USER is "TT" SQL> SQL> conn / as sysdba Connected. SQL> SQL> sho user USER is "SYS" SQL>

1st Session Sys> @privs_audit


USERNAME OS_USERNAM LOGIN LOGOFF fail/success -------- ---------- ------------------ ------------------ ------PUBLIC oracle 25-jul-10:07:53:28 SUCCESS PUBLIC oracle 25-jul-10:07:54:28 SUCCESS PUBLIC oracle 25-jul-10:07:55:28 SUCCESS TT oracle 25-jul-10:07:56:26 fail TT oracle 25-jul-10:07:56:46 SUCCESS TT oracle 25-jul-10:07:56:26 fail

P.R.P.R.

Page 287

TT TT

oracle oracle

25-jul-10:07:56:46 SUCCESS 25-jul-10:08:04:14 25-jul-10:08:04:21 SUCCESS

Privilege level auditing for a specific User:


Here dd is a user: Sys> audit create session by dd; Sys> audit create session whenever successful; Not successful;

3) Statement Level:
If you audit on a SQL Preserved keywords is nothing but statement level auditing. Sys> audit a table Sys> select username,action,action_name,obj_name,obj_privilege from dba_audit_trail; Sys> save stat_audit ii> create table t(no number); Sys>@stat_audit

P.R.P.R.

Page 288

DISABLING AUDITING:
Using this command. Sys> select user_name, audit_option, success, failure from dba_stmt_audit_opts; USER_NAME ------------------II AUDIT_OPTION ------------------------CREATE TABLESPACE CREATE SESSION TABLE SUCCESS ---------BY ACCESS BY ACCESS BY ACCESS FAILURE ---------BY ACCESS BY ACCESS BY ACCESS

Commands Sys> noaudit table by <username>; Sys> noaudit CREATE SESSION; Sys> noaudit CREATE VIEW by <username>;

You can disable AUDITING for individual each STATEMENT or COMPLETELY. If you want to DISABLE AUDITING completely just (comment/remove) the PARAMETER in (init<sid>.ora) file. parameter : # audit_trail = true

AUDIT TRAIL VIEWS - DBA_AUDIT_OBJECT - DBA_AUDIT_SESSION - DBA_AUDIT_STATEMENT - DBA_AUDIT_TRAIL - DBA_OBJ_AUDIT_OPTS - DBA_PRIV_AUDIT_OPTS - DBA_STMT_AUDIT_OPTS - DBA_AUDIT_EXISTS - AUDIT_ACTIONS

P.R.P.R.

Page 289

P.R.P.R.

Page 290

Utilities: Database Verification Utility (DBVERIFY)


DBVERIFY is an external command-line utility that performs a physical data structure integrity check. DBVERIFY can be used on offline or online databases, as well on backup files. You use DBVERIFY primarily when you need to ensure that a backup database (or data file) is valid before it is restored, or as a diagnostic aid when you have encountered data corruption problems. Because DBVERIFY can be run against an offline database, integrity checks are significantly faster. DBVERIFY checks are limited to cache-managed blocks (that is, data blocks). Because DBVERIFY is only for use with data files; it does not work against control files or redo logs. There are two command-line interfaces to DBVERIFY. With the first interface, you specify disk blocks of a single data file for checking. With the second interface, you specify a segment for checking. Both interfaces are started with the dbv command.

1) Using DBVERIFY to Validate Disk Blocks of a Single Data File 2) Using DBVERIFY to Validate a Segment

1) Using DBVERIFY to Validate Disk Blocks of a Single Data File: In this mode, DBVERIFY scans one or more disk blocks of a single data file and performs page checks. Example: To see the options of DBVERIFY
[oracle@rac1 data]$ dbv DBVERIFY: Release 10.2.0.3.0 - Production on Mon Sep 20 00:07:24 2010 Copyright (c) 1982, 2005, Oracle. All rights reserved.

P.R.P.R.

Page 291

Keyword Description (Default) ---------------------------------------------------FILE File to Verify (NONE) START Start Block (First Block of File) END End Block (Last Block of File) BLOCKSIZE Logical Block Size (8192) LOGFILE Output Log (NONE) FEEDBACK Display Progress (0) PARFILE Parameter File (NONE) USERID Username/Password (NONE) SEGMENT_ID Segment ID (tsn.relfile.block) (NONE) HIGH_SCN Highest Block SCN to Verify (NONE) (Scn_wrap.scn_base OR scn)

I am going to verify the kk.dbf file (db is running).


[oracle@rac1 data]$ dbv file=kk.dbf feedback=100 DBVERIFY: Release 10.2.0.3.0 - Production on Sun Sep 19 21:14:38 2010 Copyright (c) 1982, 2005, Oracle. All rights reserved.

... [oracle@rac1 data]$ dbv file=kk.dbf feedback=100 DBVERIFY: Release 10.2.0.3.0 - Production on Sun Sep 19 21:14:46 2010 Copyright (c) 1982, 2005, Oracle. All rights reserved.

DBVERIFY - Verification starting: FILE = kk.dbf ... DBVERIFY - Verification complete Total Pages Examined Total Pages Processed (Data) Total Pages Failing (Data) Total Pages Processed (Index) Total Pages Failing (Index) Total Pages Processed (Other) Total Pages Processed (Seg) Total Pages Failing (Seg) Total Pages Empty Total Pages Marked Corrupt Total Pages Influx Highest block SCN [oracle@rac1 data]$ : : : : : : : : : : : : 256 133 0 0 0 30 0 0 93 0 0 849517 (0.849517)

P.R.P.R.

Page 292

Notes:
Pages = Blocks Total Pages Examined = number of blocks in the file Total Pages Processed = number of blocks that were verified (formatted blocks) Total Pages Failing (Data) = number of blocks that failed the data block checking routine Total Pages Failing (Index) = number of blocks that failed the index block checking routine Total Pages Marked Corrupt = number of blocks for which the cache header is invalid, thereby making it impossible for DBVERIFY to identify the block type Total Pages Influx = number of blocks that are being read and written to at the same time. If the database is open when DBVERIFY is run, then DBVERIFY reads blocks multiple times to get a consistent image. But because the database is open, there may be blocks that are being read and written to at the same time (INFLUX).

DBVERIFY cannot get a consistent image of pages that are in flux

2) Using DBVERIFY to Validate a Segment In this mode, DBVERIFY enables you to specify a table segment or index segment for verification. It checks to ensure that a row chain pointer is within the segment being verified. This mode requires that you specify a segment (data or index) to be validated. It also requires that you log on to the database with SYSDBA privileges, because information about the segment must be retrieved from the database. During this mode, the segment is locked. If the specified segment is an index, then the parent table is locked. Note that some indexes, such as IOTs, do not have parent tables.

Example: I have table (emp having records 14336) and the owner is kk,I am going to verify this segment
SQL> select t.ts#, s.header_file, s.header_block from v$tablespace t, dba_segments s Where s.segment_name='EMP' And t.name = s.tablespace_name and s.owner='KK'

P.R.P.R.

Page 293

SQL> / TS# HEADER_FILE HEADER_BLOCK ----- ----------- -----------5 5 19

[oracle@rac1 ~]$ dbv userid=system/manager segment_id=5.5.19 DBVERIFY: Release 10.2.0.3.0 - Production on Sun Sep 19 20:48:50 2010 Copyright (c) 1982, 2005, Oracle. All rights reserved.

DBVERIFY - Verification starting: SEGMENT_ID = 5.5.19

DBVERIFY - Verification complete Total Pages Examined Total Pages Processed (Data) Total Pages Failing (Data) Total Pages Processed (Index) Total Pages Failing (Index) Total Pages Processed (Other) Total Pages Processed (Seg) Total Pages Failing (Seg) Total Pages Empty Total Pages Marked Corrupt Total Pages Influx Highest block SCN : : : : : : : : : : : : 128 118 0 0 0 9 1 0 0 0 0 849517 (0.849517)

P.R.P.R.

Page 294

Performance Tuning

P.R.P.R.

Page 295

Demo on Table Cache:


It locks the table in DBC.It will not allow to remove from the cache (DBC).

SQL> conn kk/kk Connected. SQL> SQL> sho user USER is "KK" SQL> select * from tab; TNAME TABTYPE CLUSTERID ------------------------------ ------- --------DEPT TABLE EMP TABLE BONUS TABLE SALGRADE TABLE SQL> SQL> select count (*) from EMP; COUNT (*) -------14 SQL> SQL> SQL> select table_name, cache from user_tables; TABLE_NAME CACHE ------------------------------ ----DEPT N EMP N BONUS N SALGRADE N SQL> SQL> SQL> alter table EMP cache; Table altered. SQL> SQL> select table_name, cache from user_tables; TABLE_NAME CACHE ------------------------------ ----DEPT N EMP Y BONUS N SALGRADE N SQL>

P.R.P.R.

Page 296

SQL> alter table EMP nocache; Table altered. SQL> SQL> select table_name, cache from user_tables; TABLE_NAME CACHE ------------------------------ ----DEPT N EMP N BONUS N SALGRADE N SQL>

Multiple DBwriters:
SQL> sho parameter db_writer NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_writer_processes integer 1 SQL> SQL> !ps -x Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.3/FAQ PID TTY STAT TIME COMMAND 6312 ? S 0:00 sshd: oracle@pts/1 6313 pts/1 Ss 0:00 -bash 6346 pts/1 S+ 0:00 sqlplus 6361 ? Ss 0:00 ora_pmon_PROD 6363 ? Ss 0:00 ora_psp0_PROD 6364 ? S 0:00 sshd: oracle@pts/2 6365 pts/2 Ss+ 0:00 -bash 6370 ? Ss 0:00 ora_mman_PROD 6372 ? Ss 0:00 ora_dbw0_PROD 6374 ? Ss 0:00 ora_lgwr_PROD 6378 ? Ss 0:01 ora_ckpt_PROD 6380 ? Ss 0:01 ora_smon_PROD 6382 ? Ss 0:00 ora_reco_PROD 6384 ? Ss 0:01 ora_mmon_PROD 6386 ? Ss 0:00 ora_mmnl_PROD 6411 ? Ss 0:00 ora_arc0_PROD 6413 ? Ss 0:00 ora_arc1_PROD 6778 ? Ss 0:00 oraclePROD (DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq))) 6781 pts/1 R+ 0:00 ps -x SQL> SQL> shut immediate

P.R.P.R.

Page 297

Edit the parameter file

Db_writer_processes=3

SQL> startup SQL> SQL> sho parameter db_writer NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_writer_processes integer 3 SQL> SQL> !ps -x Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.3/FAQ PID TTY STAT TIME COMMAND 6312 ? S 0:01 sshd: oracle@pts/1 6313 pts/1 Ss 0:00 -bash 6364 ? S 0:00 sshd: oracle@pts/2 6365 pts/2 Ss+ 0:00 -bash 6793 pts/1 S+ 0:00 sqlplus 6798 ? Ss 0:00 ora_pmon_PROD 6800 ? Ss 0:00 ora_psp0_PROD 6802 ? Ss 0:00 ora_mman_PROD 6804 ? Ss 0:00 ora_dbw0_PROD 6806 ? Ss 0:00 ora_dbw1_PROD 6808 ? Ss 0:00 ora_dbw2_PROD 6810 ? Ss 0:00 ora_lgwr_PROD 6812 ? Ss 0:00 ora_ckpt_PROD 6814 ? Ss 0:00 ora_smon_PROD 6816 ? Ss 0:00 ora_reco_PROD 6818 ? Ss 0:00 ora_mmon_PROD 6820 ? Ss 0:00 ora_mmnl_PROD 6822 ? Ss 0:01 oraclePROD (DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq))) 6824 ? Ss 0:00 ora_arc0_PROD 6826 ? Ss 0:00 ora_arc1_PROD 6831 pts/1 R+ 0:00 ps -x SQL>

P.R.P.R.

Page 298

Software striping:
SQL> create tablespace str datafile '/oradata/prod/data/str1.dbf' size 2m, '/oradata/prod/data/str2.dbf' size 2m extent management dictionary; Tablespace created. SQL> grant connect, resource to STR identified by STR; Grant succeeded. SQL> alter user STR default tablespace STR; User altered. SQL> conn str/str Connected. 1st Session SQL> select count (*) from EMP; COUNT (*) ---------14 2nd Session SQL> select file_name, tablespace_name, file_id from dba_data_files where tablespace_name like 'STR' FILE_NAME TABLESPA FILE_ID ---------------------------------------- -------- ---------/oradata/prod/data/str1.dbf STR 7 /oradata/prod/data/str2.dbf STR 8

SQL> select owner, segment_name, tablespace_name, extent_id, file_id from dba_extents where owner='STR' OWNER ----STR STR STR STR SEGMENT_NA TABLESPA EXTENT_ID FILE_ID ---------- -------- ---------- ---------SALGRADE STR 0 7 BONUS STR 0 7 EMP STR 0 7 DEPT STR 0 7

1st SQL> insert into EMP select * from EMP;

P.R.P.R.

Page 299

2nd SQL> select owner, segment_name, tablespace_name, extent_id, file_id from dba_extents where owner='STR' OWNER ----STR STR STR STR 1st SQL> insert into emp select * from emp; 28 rows created. SQL> / 56 rows created. 2nd SQL> select owner, segment_name, tablespace_name, extent_id, file_id from dba_extents where owner='STR' OWNER ----STR STR STR STR STR SEGMENT_NA TABLESPA EXTENT_ID FILE_ID ---------- -------- ---------- ---------SALGRADE STR 0 7 BONUS STR 0 7 EMP STR 0 7 DEPT STR 0 7 EMP STR 1 8 SEGMENT_NA TABLESPA EXTENT_ID FILE_ID ---------- -------- ---------- ---------SALGRADE STR 0 7 BONUS STR 0 7 EMP STR 0 7 DEPT STR 0 7

1st SQL> / 112 rows created. SQL> / 224 rows created 2nd

P.R.P.R.

Page 300

SQL> select owner, segment_name, tablespace_name, extent_id, file_id from dba_extents where owner='STR'

OWNER ----STR STR STR STR STR STR STR

SEGMENT_NA TABLESPA EXTENT_ID FILE_ID ---------- -------- ---------- ---------SALGRADE STR 0 7 BONUS STR 0 7 EMP STR 2 7 EMP STR 0 7 DEPT STR 0 7 EMP STR 3 8 EMP STR 1 8

1st SQL> / 448 rows created SQL> / 896 rows created. SQL> / 1792 rows created. SQL> / 3584 rows created. SQL> commit; Commit complete. 2nd SQL> select owner, segment_name, tablespace_name, extent_id, file_id from dba_extents where owner='STR' OWNER ----STR STR STR STR STR STR STR STR SEGMENT_NA TABLESPA EXTENT_ID FILE_ID ---------- -------- ---------- ---------SALGRADE STR 0 7 BONUS STR 0 7 EMP STR 4 7 EMP STR 2 7 EMP STR 0 7 DEPT STR 0 7 EMP STR 3 8 EMP STR 1 8

P.R.P.R.

Page 301

Parralel Query Option:


SQL> sho parameter parallel_max NAME TYPE VALUE ------------------------------------ ----------- -----------------------------parallel_max_servers integer 5 SQL> SQL>Shut immediate Edit Parameter file Parallel_max_servers=3 SQL> startup SQL> sho parameter parallel_max NAME TYPE VALUE ------------------------------------ ----------- -----------------------------parallel_max_servers integer 3 SQL> SQL> conn str/str Connected. SQL> SQL> select table_name,degree from user_tables; TABLE_NAME DEGREE ------------------------------ ---------DEPT 1 EMP 1 BONUS 1 SALGRADE 1 SQL> SQL> alter table emp parallel 3; Table altered. SQL> SQL> select table_name,degree from user_tables; TABLE_NAME DEGREE ------------------------------ ---------DEPT 1 EMP 3 BONUS 1 SALGRADE 1

P.R.P.R.

Page 302

SQL> alter table emp parallel 1; Table altered. SQL> select table_name,degree from user_tables; TABLE_NAME DEGREE ------------------------------ ---------DEPT 1 EMP 1 BONUS 1 SALGRADE 1 SQL> SQL> alter table emp noparallel; Table altered. SQL> select table_name,degree from user_tables; TABLE_NAME DEGREE ------------------------------ ---------DEPT 1 EMP 1 BONUS 1 SALGRADE 1 SQL> alter table emp parallel; Table altered. SQL>

P.R.P.R.

Page 303

Application Tunning (1) Tkprof (Trace Kernel profile) (2) Explain Plan (3) SQL trace

(1) Demo on TKPROF:


SQL> sho parameter sql_trace NAME TYPE VALUE ------------------------------------ ----------- -----------------------------sql_trace boolean FALSE

>> Shut immediate Edit the parameter file Sql_trace=TRUE >> startup

SQL> conn pr/pr Connected. SQL> select * from emp where empno=7566; SQL> exit $cd /oracle/prod/udump $ls lrt $ tkprof prod_ora_32118.trc output=~/show.out sys=no $cd

P.R.P.R.

Page 304

$vi show.out

******************************************************************************** select * from emp where empno=7566

call count ------- -----Parse 2 Execute 2 Fetch 4 ------- -----total 8

cpu elapsed disk query current -------- ---------- ---------- ---------- ---------0.00 0.00 0 1 0 0.00 0.00 0 0 0 0.00 0.00 0 8 0 -------- ---------- ---------- ---------- ---------0.00 0.00 0 9 0

rows ---------0 0 2 ---------2

Misses in library cache during parse: 1 Optimizer mode: ALL_ROWS Parsing user id: 33 Rows ------1 Row Source Operation --------------------------------------------------TABLE ACCESS FULL EMP (cr=4 pr=0 pw=0 time=74 us)

********************************************************************************

$sqlplus pr/pr SQL> alter table emp add primary key(empno); SQL> select * from emp where empno=7566; SQL> exit $cd /oracle/prod/udump $ls lrt $ tkprof prod_ora_32153.trc output=~/show1.out sys=no $cd

P.R.P.R.

Page 305

$vi show1.out ******************************************************************************** select * from emp where empno=7566

call count ------- -----Parse 1 Execute 1 Fetch 2 ------- -----total 4

cpu elapsed disk query current -------- ---------- ---------- ---------- ---------0.00 0.00 0 1 0 0.00 0.00 0 0 0 0.00 0.00 0 2 0 -------- ---------- ---------- ---------- ---------0.00 0.00 0 3 0

rows ---------0 0 1 ---------1

Misses in library cache during parse: 1 Optimizer mode: ALL_ROWS Parsing user id: 33 Rows ------1 1 Row Source Operation --------------------------------------------------TABLE ACCESS BY INDEX ROWID EMP (cr=2 pr=0 pw=0 time=92 us) INDEX UNIQUE SCAN SYS_C003059 (cr=1 pr=0 pw=0 time=33 us)(object id 10840)

********************************************************************************

(2) Demo On Explain Plan

$cd $ORACLE-HOME/rdbms/admin $sqlplus /as sysdba SQL> conn kk/kk SQL>!ls utlxplan.sql utlxplan.sql SQL> select * from tab; TNAME TABTYPE CLUSTERID ------------------------------ ------- ---------DEPT TABLE EMP TABLE BONUS TABLE SALGRADE TABLE

P.R.P.R.

Page 306

SQL> SQL> @utlxplan.sql Table created. SQL> select * from tab; TNAME TABTYPE CLUSTERID ------------------------------ ------- ---------DEPT TABLE EMP TABLE BONUS TABLE SALGRADE TABLE PLAN_TABLE TABLE SQL> explain plan set statement_id='stmt1' for select * from emp where empno=7788; Explained. SQL> select operation,options,optimizer from plan_table where statement_id='stmt1'; OPERATION OPTIONS OPTIMIZER ------------------ ---------- ---------SELECT STATEMENT ALL_ROWS TABLE ACCESS FULL SQL> save stmt Created file stmt.sql SQL> desc emp Name Null? Type ----------------------------------------- -------- ---------------------------EMPNO NUMBER(4) ENAME VARCHAR2(10) JOB VARCHAR2(9) MGR NUMBER(4) HIREDATE DATE SAL NUMBER(7,2) COMM NUMBER(7,2) DEPTNO NUMBER(2) SQL> alter table EMP add primary key (empno); Table altered. SQL> explain plan set statement_id='stmt2' for select * from emp where empno=7788; Explained.

P.R.P.R.

Page 307

SQL> select operation,options,optimizer from plan_table where statement_id='stmt2' OPERATION OPTIONS OPTIMIZER ------------------ --------------- ---------SELECT STATEMENT ALL_ROWS TABLE ACCESS BY INDEX ROWID INDEX UNIQUE SCAN ANALYZED

(3) Demo on Sqltrace:

Autotrace Generates a report on the execution path used by the SQL optimizer and the statement execution statistics. The report is useful to monitor and tune the performance of DML statements.

SET AUTOT[RACE] {ON | OFF | TRACE[ONLY]} [EXP[LAIN]] [STAT[ISTICS]]


SQL> @ORACLE_HOME/sqlplus/admin/plustrace.sql >grant plustrace to pr; PR> set autotrace on; PR> select * from emp where empno=7900;

P.R.P.R.

Page 308

Memory Tunning:
Keep pool This pool is intended for blocks that were accessed frequently, but which aged out of the default pool because of lack of space. The goal of the keep buffer pool is to retain objects in memory, thus avoiding I/O operations. Recycle pool This pool is intended for blocks that are used infrequently. A recycle pool prevents objects from consuming unnecessary space in the cache.
SQL> SQL> sho parameter db_keep NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_keep_cache_size big integer 0 SQL> SQL> sho parameter db_recycle NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_recycle_cache_size big integer 0 SQL> SQL> Shut immediate Edit Parameter file SQL> startup SQL> sho parameter db_keep

Keep pool & Recycle pool

NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_keep_cache_size big integer 12M SQL> SQL> sho parameter db_recycle NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_recycle_cache_size big integer 12M SQL> SQL> SQL> conn kk/kk

P.R.P.R.

Page 309

KK> select * from tab; TNAME TABTYPE CLUSTERID ------------------------------ ------- ---------DEPT TABLE EMP TABLE BONUS TABLE SALGRADE TABLE SQL>

KK> select table_name,buffer_pool from user_tables; TABLE_NAME BUFFER_ ------------------------------ ------DEPT DEFAULT EMP DEFAULT BONUS DEFAULT SALGRADE DEFAULT KK> alter table emp storage(buffer_pool recycle); Table altered. KK> alter table dept storage(buffer_pool keep); Table altered. KK> select table_name,buffer_pool from user_tables; TABLE_NAME BUFFER_ ------------------------------ ------DEPT KEEP EMP RECYCLE BONUS DEFAULT SALGRADE DEFAULT KK> alter table emp storage(buffer_pool default); Table altered. KK> select table_name,buffer_pool from user_tables; TABLE_NAME BUFFER_ ------------------------------ ------DEPT KEEP EMP DEFAULT BONUS DEFAULT SALGRADE DEFAULT

P.R.P.R.

Page 310

Database Buffer Cache

Organization of the Database Buffer Cache: The buffers in the cache are organized in two lists: the write list and the least recently used (LRU) list. The write list holds dirty buffers, which contain data that has been modified but has not yet been written to disk. The LRU list holds free buffers, pinned buffers, and dirty buffers that have not yet been moved to the write list. Free buffers do not contain any useful data and are available for use. Pinned buffers are currently being accessed. When an Oracle process accesses a buffer, the process moves the buffer to the most recently used (MRU) end of the LRU list. As more buffers are continually moved to the MRU end of the LRU list, dirty buffers age toward the LRU end of the LRU list. P.R.P.R. Page 311

SQL>select name,sum(physical_reads),sum(db_block_gets),sum(consistent_gets), 1-(sum(physical_reads)/(sum(db_block_gets)*sum(consistent_gets))) "HIT RATIO" from v$buffer_pool_statistics group by name SQL>

SQL> sho parameter db_cache_size NAME TYPE VALUE ------------------------------------ ----------- -----------------------------db_cache_size big integer 48M

Library Cache:
SQL> select sum(pinhits)/sum(pins) "LC Hit Ratio" from v$librarycache; LC Hit Ratio -----------.767868371 SQL>

Data dictionary Cache:

SQL> select (sum(gets-getmisses-fixed)/sum(gets)) "DBC HIT Ratio" from v$rowcache

DBC HIT Ratio ------------.731173488 SQL>

Redolog Buffer Cache:

SQL> select name,value from v$sysstat where name like '%redo%';

NAME VALUE ---------------------------------------------------------------- ---------redo synch writes 48

P.R.P.R.

Page 312

redo redo redo redo redo redo redo redo redo redo

synch time blocks read for recovery entries size buffer allocation retries wastage writer latching time writes blocks written write time

11 0 2243 835676 0 21404 1 83 1730 121

NAME VALUE ---------------------------------------------------------------- ---------redo log space requests 0 redo log space wait time 0 redo log switch interrupts 0 redo ordering marks 0 redo subscn max counts 0 16 rows selected. SQL> Open 1 more session do some Transaction in PR User SQL> conn pr/pr Connected. SQL> cl scr SQL> SQL> SQL> select count(*) from emp; COUNT(*) ---------14 SQL> insert into emp select * from emp; 14 rows created. SQL> / 28 rows created. At the same time check SQL> / NAME VALUE ---------------------------------------------------------------- ---------redo synch writes 56 redo synch time 11 redo blocks read for recovery 0 redo entries 2720 redo size 1198176 redo buffer allocation retries 0 redo wastage 25172

P.R.P.R.

Page 313

redo redo redo redo

writer latching time writes blocks written write time

1 96 2469 127

NAME VALUE ---------------------------------------------------------------- ---------redo log space requests 0 redo log space wait time 0 redo log switch interrupts 0 redo ordering marks 0 redo subscn max counts 0 16 rows selected.

SQL> / NAME VALUE ---------------------------------------------------------------- ---------redo synch writes 57 redo synch time 11 redo blocks read for recovery 0 redo entries 2748 redo size 1233252 redo buffer allocation retries 0 redo wastage 25776 redo writer latching time 1 redo writes 98 redo blocks written 2541 redo write time 128 NAME VALUE ---------------------------------------------------------------- ---------redo log space requests 0 redo log space wait time 0 redo log switch interrupts 0 redo ordering marks 0 redo subscn max counts 0 16 rows selected.

P.R.P.R.

Page 314

Program Global Area(PGA)


A program global area (PGA) is a memory region that contains data and control information for a server process. It is a nonshared memory created by Oracle when a server process is started. Access to it is exclusive to that server process and is read and written only by Oracle code acting on behalf of it. The total PGA memory allocated by each server process attached to an Oracle instance is also referred to as the aggregated PGA memory allocated by the instance.

SQL> sho parameter pga NAME TYPE VALUE ------------------------------------ ----------- -----------------------------pga_aggregate_target big integer 60M SQL> SQL>select count(*) from v$sort_usage; 2nd session login as a user SQL> select empno,deptno from emp order by empno; From 1st session SQL> select count(*) from v$sort_usage;

P.R.P.R.

Page 315

Multithread Server (MTS)

Server Side: 1) Configure and start the Listener at server side 2) Edit the parameter file like below

Parameters are: Local_listener=(address=(PROTOCOL=TCP)(HOST=Serverhost)(PORT=1521)) Max_dispatchers=3 Shared_servers=5

P.R.P.R.

Page 316

Client Side: 1) Tnsping 2) Connect to one of the user in server $sqlplus user1/user1@client From server side SQL> select distinct username, server, machine from v$session; It will show for SERVER column User1 none

(none means Shared server process) Again client side configure one more tnasname.ora
CLIENT1 = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCAL = TCP) (HOST = ) (CONNECT_DATA = (SERVER = dedicated (SERVICE_NAME = ORCL) ) )

) (PORT = 1521))

(Add this line in tnsnames.ora file)

Tnsping client1 Connect to the server $sqlplus user2/user2@client1 Same query SQL> select distinct username, server, machine from v$session; Now it will show for SERVER column User1 none User2 dedicated

P.R.P.R.

Page 317

Row Chaining and Migrating


Row Chaining In two circumstances, the data for a row in a table may be too large to fit into a single data block. In the first case, the row is too large to fit into one data block when it is first inserted. In this case, Oracle stores the data for the row in a chain of data blocks (one or more) reserved for that segment. Row chaining most often occurs with large rows, such as rows that contain a column of datatype LONG or LONG RAW. Row chaining in these cases is unavoidable. Row Migrating A row that originally fit into one data block is updated so that the overall row length increases, and the block's free space is already completely filled. In this case, Oracle migrates the data for the entire row to a new data block, assuming the entire row can fit in a new block. Oracle preserves the original row piece of a migrated row to point to the new block containing the migrated row. The rowid of a migrated row does not change. When a row is chained or migrated, I/O performance associated with this row decreases because Oracle must scan more than one data block to retrieve the information for the row. The PCTFREE Parameter The PCTFREE parameter sets the minimum percentage of a data block to be reserved as free space for possible updates to rows that already exist in that block. For example, assume that you specify the following parameter within a CREATE TABLE statement:
PCTFREE 20

This states that 20% of each data block in this table's data segment be kept free and available for possible updates to the existing rows already within each block. New rows can be added to the row data area, and corresponding information can be added to the variable portions of the overhead area, until the row data and overhead total 80% of the total block size.

The PCTUSED Parameter The PCTUSED parameter sets the minimum percentage of a block that can be used for row data plus overhead before new rows are added to the block. After a data block is filled to the limit determined by PCTFREE, Oracle considers the block unavailable for the insertion of new rows until the percentage of that block falls beneath the parameter PCTUSED. Until this value is achieved, Oracle uses the free space of the data block only for updates to rows already contained in the data block. For example, assume that you specify the following parameter in a CREATE TABLE statement: P.R.P.R. Page 318

PCTUSED 40

In this case, a data block used for this table's data segment is considered unavailable for the insertion of any new rows until the amount of used space in the block falls to 39% or less (assuming that the block's used space has previously reached PCTFREE).

P.R.P.R.

Page 319

AWR Automatic Workload Repository

AWR: A built-in repository in every Oracle Database. At regular intervals, the Oracle Database makes a snapshot of all its vital statistics and workload information and stores them here Script name & Location : Awrrpt.sql (ORACLE_HOME/rdbms/admin)

SQL> @awrrpt.sql Current Instance ~~~~~~~~~~~~~~~~ DB Id DB Name Inst Num Instance ----------- ------------ -------- -----------136184398 PROD1 1 PROD

Specify the Report Type ~~~~~~~~~~~~~~~~~~~~~~~ Would you like an HTML report, or a plain text report? Enter 'html' for an HTML report, or 'text' for plain text Defaults to 'html' Enter value for report_type: text Type Specified: text

Instances in this Workload Repository schema ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DB Id Inst Num DB Name Instance Host ------------ -------- ------------ ------------ -----------136184398 1 PROD PROD rac1.nalsoft .net * 136184398 1 PROD1 PROD rac1.nalsoft .net Using Using 136184398 for database Id 1 for instance number

P.R.P.R.

Page 320

Specify the number of days of snapshots to choose from ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Entering the number of days (n) will result in the most recent (n) days of snapshots being listed. Pressing <return> without specifying a number lists all completed snapshots. Enter value for num_days: 5 Listing the last 5 days of Completed Snapshots Snap Instance DB Name Snap Id Snap Started Level ------------ ------------ --------- ------------------ ----PROD PROD1 44 10 Aug 2010 01:38 1 45 10 Aug 2010 02:30 46 10 Aug 2010 18:12 47 10 Aug 2010 19:30 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 10 10 10 10 11 11 11 11 11 11 11 11 11 12 12 12 12 12 12 12 Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug Aug 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 20:30 21:30 22:30 23:30 00:30 01:30 02:30 18:01 19:30 20:30 21:30 22:30 23:30 00:30 01:30 02:30 20:53 21:31 22:30 23:30 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

68 13 Aug 2010 00:30 69 13 Aug 2010 01:30 70 13 Aug 2010 02:30

Specify the Begin and End Snapshot Ids ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Enter value for begin_snap: 68 Begin Snapshot Id specified: 68 Enter value for end_snap: 69

P.R.P.R.

Page 321

End

Snapshot Id specified: 69

Specify the Report Name ~~~~~~~~~~~~~~~~~~~~~~~ The default report file name is awrrpt_1_68_69.txt. To use this name, press <return> to continue, otherwise enter an alternative. Enter value for report_name: awr_prpr Using the report name awr_prpr WORKLOAD REPOSITORY report for DB Name DB Id Instance Inst Num Release RAC Host ------------ ----------- ------------ -------- ----------- --- -----------PROD1 136184398 PROD 1 10.2.0.3.0 NO rac1.nalsoft Snap Id Snap Time Sessions Curs/Sess --------- ------------------- -------- --------Begin Snap: 68 13-Aug-10 00:30:50 17 1.5 End Snap: 69 13-Aug-10 01:30:55 18 1.4 Elapsed: 60.08 (mins) DB Time: 0.01 (mins) Cache Sizes ~~~~~~~~~~~

Begin End ---------- ---------Buffer Cache: 48M 48M Shared Pool Size: 160M 160M

Std Block Size: 8K Log Buffer: 6,956K

. . This will prepare a report with the name awr_prpr.lst in the os level(current location)

P.R.P.R.

Page 322

P.R.P.R.

Page 323

OEM Oracle Enterprise Manager

Overview When you choose to create a preconfigured database during the Oracle 10g installation, you can select the Oracle Enterprise Manager (OEM) interface that you want to use to manage the database. The following options are available:

Database Grid Control

This option is available only if an Oracle Management Agent is installed on the system. When the Installer detects an Oracle Management Agent on the system, it allows you to choose this option and specify the Oracle Management Service that you want to use to manage the database. If an Oracle Management Agent is not installed, you must choose to use Database Control to manage the database. However, if you install Oracle Management Agent after you install Oracle Database, you can then use Grid Control to manage this database.

Database Control

This option is selected by default if an Oracle Management Agent is not installed on the system. However, even if a Management Agent is installed, you can still choose to configure Database Control to manage the database.

For connection from OEM as a user, create a user and grant Create Session & Select any dictionary Privs to the user

P.R.P.R.

Page 324

Gather Schema Statistics


Gathering statistics an individual table
exec dbms_stats.gather_table_stats( ownname => ' Schema_name ', tabname => ' Table_name ', estimate_percent => 100, cascade => TRUE, method_opt => 'FOR ALL COLUMNS SIZE 1' );

Eg:
exec dbms_stats.gather_table_stats(ownname => 'KK',tabname => 'DEPT',cascade=> TRUE);

Gathering statistics for all objects in a schema


exec dbms_stats.gather_schema_stats( ownname => ' Schema_name ', cascade => TRUE, method_opt => 'FOR ALL COLUMNS SIZE 1' );

Eg:
exec dbms_stats.gather_schema_stats (ownname => 'KK',cascade => TRUE,method_opt => 'FOR ALL COLUMNS SIZE 1');

Gathering statistics for all objects in the database:


exec dbms_stats.gather_database_stats( cascade => TRUE, method_opt => 'FOR ALL COLUMNS SIZE 1' );

Master Note: Recommendations for Gathering Optimizer Statistics on 10g [ID 605439.1]

P.R.P.R.

Page 325

GENERAL NOTES :

To Kill the Session; Select sid,serial#,program,osuser from v$session; Alter system kill session sid,serial#;
It is possible to force the kill by adding the IMMEDIATE keyword:

Alter system kill session sid,serial immediate;

The NT Approach
To kill the session via the NT operating system, first identify the session as follows: Select s.sid,p.sid,s.osuser,s.program from v$session s,v$process p Where p.addr=s.paddr;

In Windows: C:> orakill ORACLE_SID spid In Unix; $ kill spid If after a few minutes the process hasn't stopped, terminate the session using:

$ kill -9 spid If in doubt check that the SPID matches the UNIX PROCESSID shown using: $ ps -ef | grep ora

P.R.P.R.

Page 326

Checking Your Current Release Number

To identify the release of Oracle Database that is currently installed and to see the release levels of other database components you are using, query the data dictionary view PRODUCT_COMPONENT_VERSION. A sample query follows. (You can also query the V$VERSION view to see component-level information.) Other product release levels may increment independent of the database server.
SQL> COL PRODUCT FORMAT A35 COL VERSION FORMAT A15 COL STATUS FORMAT A15 SELECT * FROM PRODUCT_COMPONENT_VERSION; PRODUCT ----------------------------------NLSRTL Oracle Database 10g Enterprise Edition PL/SQL TNS for HPUX: VERSION --------------10.2.0.1.0 10.2.0.1.0 10.2.0.1.0 10.2.0.1.0 STATUS --------------Production 64bi Production Production

It is important to convey to Oracle the results of this query when you report problems with the software.
SQL> select * from v$version; BANNER ---------------------------------------------------------------Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi PL/SQL Release 10.2.0.1.0 - Production CORE 10.2.0.1.0 Production TNS for HPUX: Version 10.2.0.1.0 - Production NLSRTL Version 10.2.0.1.0 Production

P.R.P.R.

Page 327

SCRIPTS:

1) Startup time
select to_char(startup_time, 'HH24:MI DD-MON-YY') "Startup time" from v$instance /

2) How large is the database (Database Size)


col "Database Size" format a20 col "Free space" format a20 col "Used space" format a20 select round(sum(used.bytes) / 1024 , round(sum(used.bytes) / 1024 round(free.p / 1024 / 1024 / , round(free.p / 1024 / 1024 / from (select bytes from v$datafile union all select bytes from v$tempfile union all select bytes from v$log) used , (select sum(bytes) as p from dba_free_space) free group by free.p /

/ 1024 / / 1024 / 1024) || 1024) ||

1024 ) || ' GB' "Database Size" 1024 ) ' GB' "Used space" ' GB' "Free space"

DB size in KB
col "Database Size" format a20 col "Free space" format a20 col "Used space" format a20

select round(sum(used.bytes) / 1024 ) || ' KB' "Database Size" , round(sum(used.bytes) / 1024 ) round(free.p / 1024 ) || ' KB' "Used space" , round(free.p / 1024 ) || ' KB' "Free space" from (select bytes from v$datafile union all select bytes from v$tempfile union all select bytes from v$log) used

P.R.P.R.

Page 328

(select sum(bytes) as p from dba_free_space) free group by free.p /

DB size in Bytes
col "Database Size" format a20 col "Free space" format a20 col "Used space" format a20

select round(sum(used.bytes)) || 'B' "Database Size" , round(sum(used.bytes)) round(free.p) || 'B' "Used space" , round(free.p) || 'B' "Free space" from (select bytes from v$datafile union all select bytes from v$tempfile union all select bytes from v$log) used , (select sum(bytes) as p from dba_free_space) free group by free.p / DB size in GB
col "Database Size" format a20 col "Free space" format a20 col "Used space" format a20

select round(sum(used.bytes) / 1024 / 1024 / 1024 ) || ' GB' "Database Size" , round(sum(used.bytes) / 1024 / 1024 / 1024 ) round(free.p / 1024 / 1024 / 1024) || ' GB' "Used space" , round(free.p / 1024 / 1024 / 1024) || ' GB' "Free space" from (select bytes from v$datafile union all select bytes from v$tempfile union all select bytes from v$log) used , (select sum(bytes) as p from dba_free_space) free group by free.p

P.R.P.R.

Page 329

hiprpr@gmail.com

DBGROWTH in MB: select name,sum(a.dbsz)/1024/1024 "Physical siZe MB",b.actsz/1024/1024 "Actual Size in Mb" from (select sum(bytes) dbsz from dba_data_files union all select sum(bytes) dbsz from dba_temp_files union all select sum(bytes) dbsz from v$log) a , (select sum(bytes) actsz from dba_extents) b ,v$database group by name,b.actsz / DBGROWTH in KB select name,sum(a.dbsz)/1024 "Physical siZe KB",b.actsz/1024 "Actual Size in Kb" from (select sum(bytes) dbsz from dba_data_files union all select sum(bytes) dbsz from dba_temp_files union all select sum(bytes) dbsz from v$log) a , (select sum(bytes) actsz from dba_extents) b ,v$database group by name,b.actsz /

DBGROWTH in Bytes select name,sum(a.dbsz) "Physical siZe BYTES",b.actsz "Actual Size in bytes" from (select sum(bytes) dbsz from dba_data_files union all select sum(bytes) dbsz from dba_temp_files union all select sum(bytes) dbsz from v$log) a , (select sum(bytes) actsz from dba_extents) b ,v$database group by name,b.actsz /

P.R.P.R.

Page 330

Distribution of objects and data Which schemas are taking up all of the space
set pages 999 col "size MB" format 999,999,999 col "Objects" format 999,999,999 select obj.owner "Owner" , obj_cnt "Objects" , decode(seg_size, NULL, 0, seg_size) "size MB" from (select owner, count(*) obj_cnt from dba_objects group by owner) obj , (select owner, ceil(sum(bytes)/1024/1024) seg_size from dba_segments group by owner) seg where obj.owner = seg.owner(+) order by 3 desc ,2 desc, 1 /

Show the ten largest objects in the database


col col col col select , , , from owner format a15 segment_name format a30 segment_type format a15 mb format 999,999,999 owner segment_name segment_type mb ( select owner , segment_name , segment_type , bytes / 1024 / 1024 "MB" from dba_segments order by bytes desc ) rownum < 11

where /

Is java installed in the database?

This will return 9000'ish if it is...


select from where and / count(*) all_objects object_type like '%JAVA%' owner = 'SYS'

P.R.P.R.

Page 331

Display character set information


select * from nls_database_parameters /

Show all used features


select , from where / name detected_usages dba_feature_usage_statistics detected_usages > 0

Show all connected users


set lines 100 pages 999 col ID format a15 select username , sid || ',' || serial# "ID" , status , last_call_et "Last Activity" from v$session where username is not null order by status desc , last_call_et desc /

Time since last user activity


set lines 100 pages 999 select username , floor(last_call_et / 60) "Minutes" , status from v$session where username is not null order by last_call_et /

P.R.P.R.

Page 332

Sessions sorted by logon time


set lines 100 pages 999 col ID format a15 col osuser format a15 col login_time format a14 select username , osuser , sid || ',' || serial# "ID" , status , to_char(logon_time, 'hh24:mi dd/mm/yy') login_time , last_call_et from v$session where username is not null order by login_time /

Show user info including os pid


col "SID/SERIAL" format a10 col username format a15 col osuser format a15 col program format a40 select s.sid || ',' || s.serial# "SID/SERIAL" , s.username , s.osuser , p.spid "OS PID" , s.program from v$session s , v$process p Where s.paddr = p.addr order by to_number(p.spid) /

Show a users current sql


Select sql_text from v$sqlarea where (address, hash_value) in (select sql_address, sql_hash_value from v$session where username like '&username') /

P.R.P.R.

Page 333

Session status associated with the specified os process id


select , , , , , from , where and / s.username s.sid s.serial# p.spid last_call_et status V$SESSION s V$PROCESS p s.PADDR = p.ADDR p.spid='&pid'

All active sql


set feedback off set serveroutput on size 9999 column username format a20 column sql_text format a55 word_wrapped begin for x in (select username||'('||sid||','||serial#||') ospid = '|| process || ' program = ' || program username, to_char(LOGON_TIME,' Day HH24:MI') logon_time, to_char(sysdate,' Day HH24:MI') current_time, sql_address, sql_hash_value from v$session where status = 'ACTIVE' and rawtohex(sql_address) <> '00' and username is not null ) loop for y in (select sql_text from v$sqlarea where address = x.sql_address ) loop if ( y.sql_text not like '%listener.get_cmd%' and y.sql_text not like '%RAWTOHEX(SQL_ADDRESS)%' ) then dbms_output.put_line( '--------------------' ); dbms_output.put_line( x.username ); dbms_output.put_line( x.logon_time || ' ' || x.current_time || ' SQL#=' || x.sql_hash_value); dbms_output.put_line( substr( y.sql_text, 1, 250 ) ); end if; end loop; end loop; end; /

P.R.P.R.

Page 334

select user#,username from v$session;

Display any long operations


set lines 100 pages 999 col username format a15 col message format a40 col remaining format 9999 select username , to_char(start_time, 'hh24:mi:ss dd/mm/yy') started , time_remaining remaining , message from v$session_longops where time_remaining = 0 order by time_remaining desc /

List open cursors per user


set pages 999 select sess.username , sess.sid , sess.serial# , stat.value cursors from v$sesstat stat , v$statname sn , v$session sess where sess.username is not null and sess.sid = stat.sid and stat.statistic# = sn.statistic# and sn.name = 'opened cursors current' order by value /

Or alternatively
set lines 100 pages 999 select count(hash_value) cursors , sid , user_name from v$open_cursor group by sid , user_name order by cursors /

P.R.P.R.

Page 335

Show latent parameter changes


select , from where / name value v$parameter ismodified != 'FALSE'

Show non-default parameters


set pages 999 lines 100 col name format a30 col value format a50 select name , value from v$parameter where isdefault = 'FALSE' and value is not null order by name /

Or for name='parameter' style...


set pages 999 lines 100 select name || '=' || decode(type, 2, '''') || value || decode(type, 2, '''') parameter from v$parameter where isdefault = 'FALSE' and value is not null order by name /

Reset/Unset a spfile parameter

Setting a parameter to =' ' often isn't enough. Do this instead...


alter system reset <parameter> scope=spfile sid='*' /

P.R.P.R.

Page 336

List scheduled jobs


set lines 100 pages 999 col schema_user format a15 col fails format 999 select job , schema_user , to_char(last_date, 'hh24:mi dd/mm/yy') last_run , to_char(next_date, 'hh24:mi dd/mm/yy') next_run , failures fails , broken , substr(what, 1, 15) what from dba_jobs order by 4 /

Submit a job
dbms_job.submit('<code>', <start time>, <repeat time>, TRUE);

For example:
declare job_id number; begin dbms_job.submit( job_id , 'andy.daily_data_clense' , trunc(sysdate+1)+22/24 , 'sysdate+1' , true); end; /

Remove a job You need to be connected as the user who owns the job
exec dbms_job.remove(<job number>);

Reset a broken job You need to be connected as the user who owns the job P.R.P.R. Page 337

exec dbms_job.broken(<job number>, FALSE);

Add a program to the 10g scheduler (os program)


begin dbms_scheduler.create_program( program_name=>'ANDY.job_test', program_action=>'/home/oracle/andyb/job_test.sh', program_type=>'EXECUTABLE', comments=>'test job', enabled=>TRUE); end; /

Add a program to the 10g scheduler (stored procedure)


begin dbms_scheduler.create_program( program_name=>'ANDY.job_test', program_action=>'andy.job_test', program_type=>'STORED_PROCEDURE', comments=>'test program', enabled=>TRUE); end; /

Schedule a 10g job


begin dbms_sheduler.create_job( job_name=>'andy.andy_job_test', program_name=>'andy.job_test', start_date=> )

Invalid objects List invalid objects...


set lines 200 pages 999 col "obj" format a40 select owner || '.' || object_name "obj",

P.R.P.R.

Page 338

object_type from dba_objects where status = 'INVALID' /

Recompile all invalid objects...


@?/rdbms/admin/utlrp.sql

Show the size of an object


col segment_name format a20 select segment_name , bytes "SIZE_BYTES" , ceil(bytes / 1024 / 1024) "SIZE_MB" from dba_segments where segment_name like '&obj_name' /

All objects owned by a user


col object_name format a40 select object_name , object_type from dba_objects where owner = '&user' order by object_type, object_name /

Source code of a procedure


select text from dba_source where owner = 'ANDY' and name = 'FILE_TEST' and type = 'PACKAGE BODY' order by line /

Get an objects ddl (9i onwards) Note. Works for 9i and newer. Parameters: OBJECT_TYPE, OBJECT_NAME, SCHEMA
set pagesize 0 set long 90000 select dbms_metadata.get_ddl('TABLE','TABLE_A','ANDY') from dual;

P.R.P.R.

Page 339

Display compilation errors and warnings


show errors show errors view <veiw_name> show errors procedure <proc_name>

select * from dba_errors;

Find all tables containing the specified column


set pages 999 lines 100 col tab format a60 col column_name format a20 select owner || '.' || table_name as tab , column_name from dba_tab_columns where column_name like upper('&col') /

List all tables owned by a user sorted by size


set lines 100 pages 999 col segment_name format a40 col mb format 999,999,999 select segment_name , ceil(sum(bytes) / 1024 / 1024) "MB" from dba_segments where owner like '&user' and segment_type = 'TABLE' group by segment_name order by ceil(sum(bytes) / 1024 / 1024) desc /

Index info by table


select , , from , where and order / i.index_name i.tablespace_name ceil(s.bytes / 1048576) "Size MB" dba_indexes i dba_segments s i.index_name = s.segment_name table_name like '&table' by 2, 1

P.R.P.R.

Page 340

Show indexed columns


select from where order / column_name dba_ind_columns index_name = '&index' by column_position

Show currently exectuing sql


select sql_text from v$sqlarea where users_executing > 0 /

Session statistics
select , from , where and and order / sn.name st.value v$sesstat st v$statname sn st.STATISTIC# = sn.STATISTIC# st.VALUE > 0 st.SID = &SID by value desc

Resource intensive sql


change 8192 to match block size select sql_text , executions , to_char((((disk_reads+buffer_gets)/executions) * 8192)/1048576, '9,999,999,990.00') as total_gets_per_exec_mb , to_char((( disk_reads /executions) * 8192)/1048576, '9,999,999,990.00') as disk_reads_per_exec_mb , to_char((( buffer_gets /executions) * 8192)/1048576, '9,999,999,990.00') as buffer_gets_per_exec_mb , parsing_user_id from v$sqlarea where executions > 10 order by 6 desc /

P.R.P.R.

Page 341

File io stats
Requires timed_statistics=true set lines 80 pages 999 col fname heading "File Name" format a60 col sizemb heading "Size(Mb)" format 99,999 col phyrds heading "Reads" format 999,999,999 col readtim heading "Time" format 99.999 col phywrts heading "Writes" format 9,999,999 col writetim heading "Time" format 99.999 select lower(name) fname , (bytes / 1048576) sizemb , phyrds , readtim , phywrts , writetim from v$datafile df , v$filestat fs where df.file# = fs.file# order by 1 /

In session tracing
To switch it on: exec dbms_system.set_sql_trace_in_session (<sid>, <serial#>, true); To switch it off: exec dbms_system.set_sql_trace_in_session (<sid>, <serial#>, false);

Rows per block


select avg(row_count) avg , max(row_count) max , min(row_count) min from ( select count(*) row_count from &table_name group by substr(rowid, 1, 15) ) /

P.R.P.R.

Page 342

Show the buffer cache advisory


Note. The current setting is halfway down and has a read factor of one. set lines 100 pages 999 col est_mb format 99,999 col estd_physical_reads format 999,999,999,999,999 select size_for_estimate est_mb , estd_physical_read_factor , estd_physical_reads from v$db_cache_advice where name = 'DEFAULT' order by size_for_estimate /

db_cache_advice needs to be on for the above to work alter system set db_cache_advice=on;

Performance - Locks DML:

Show sessions that are blocking each other

select from where and and /

'SID ' || l1.sid ||' is blocking v$lock l1, v$lock l2 l1.block =1 and l2.request > 0 l1.id1=l2.id1 l1.id2=l2.id2

' || l2.sid blocking

hiprpr@gmail.com

P.R.P.R.

Page 343

Show locked objects


set lines 100 pages 999 col username format a20 col sess_id format a10 col object format a25 col mode_held format a10 select oracle_username || ' (' || s.osuser || ')' username , s.sid || ',' || s.serial# sess_id , owner || '.' || object_name object , object_type , decode( l.block , 0, 'Not Blocking' , 1, 'Blocking' , 2, 'Global') status , decode(v.locked_mode , 0, 'None' , 1, 'Null' , 2, 'Row-S (SS)' , 3, 'Row-X (SX)' , 4, 'Share' , 5, 'S/Row-X (SSX)' , 6, 'Exclusive', TO_CHAR(lmode)) mode_held from v$locked_object v , dba_objects d , v$lock l , v$session s where v.object_id = d.object_id and v.object_id = l.id1 and v.session_id = s.sid order by oracle_username , session_id /

Show which row is locked


select , , , , , from , where and / do.object_name row_wait_obj# row_wait_file# row_wait_block# row_wait_row# dbms_rowid.rowid_create (1, ROW_WAIT_OBJ#, ROW_WAIT_FILE#, ROW_WAIT_BLOCK#, ROW_WAIT_ROW#) v$session s dba_objects do sid=&sid s.ROW_WAIT_OBJ# = do.OBJECT_ID

P.R.P.R.

Page 344

Then select the row with that rowid...


select * from <table> where rowid=<rowid>;

List locks
column column column column column SELECT , , , , , FROM WHERE / lock_type format a12 mode_held format a10 mode_requested format a10 blocking_others format a20 username format a10 session_id lock_type mode_held mode_requested blocking_others lock_id1 dba_lock l lock_type NOT IN ('Media Recovery', 'Redo Thread')

Performance - Locks DDL:

How all ddl locks in the system


select decode(lob.kglobtyp, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER', 4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE', 7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE', 11, 'PACKAGE BODY', 12, 'TRIGGER', 13, 'TYPE', 14, 'TYPE BODY', 19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB', 22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE', 28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE', 32, 'INDEXTYPE', 33, 'OPERATOR', 34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION', 40, 'LOB PARTITION', 41, 'LOB SUBPARTITION', 42, 'MATERIALIZED VIEW', 43, 'DIMENSION', 44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN', 48, 'CONSUMER GROUP', 51, 'SUBSCRIPTION', 52, 'LOCATION',

P.R.P.R.

Page 345

, , , , , , from , , , where and and and and /

55, 'XML SCHEMA', 56, 'JAVA DATA', 57, 'SECURITY PROFILE', 59, 'RULE', 62, 'EVALUATION CONTEXT','UNDEFINED' ) object_type lob.kglnaobj object_name pn.kglpnmod lock_mode_held pn.kglpnreq lock_mode_requested ses.sid ses.serial# ses.username v$session_wait vsw x$kglob lob x$kglpn pn v$session ses vsw.event = 'library cache lock' vsw.p1raw = lob.kglhdadr lob.kglhdadr = pn.kglpnhdl pn.kglpnmod != 0 pn.kglpnuse = ses.saddr

Slightly more simple version of the above


select , , , , , from , where and / ses.username ddl.session_id ses.serial# owner || '.' || ddl.name object ddl.type ddl.mode_held dba_ddl_locks ddl v$session ses owner like '%userid%' ddl.session_id = ses.sid

Generate kill statement for ddl locking sessions


select 'alter system kill session ''' || ddl.session_id || ',' || ses.serial# || ''' immediate;' from dba_ddl_locks ddl , v$session ses where owner like '%userid%' and ddl.session_id = ses.sid /

P.R.P.R.

Page 346

Top ten hotest objects by touch count


col owner format a20 trunc col object_name format a30 col touches format 9,999,999 select * from ( select count(*) , sum(tch) TOUCHES , u.name OWNER , o.name OBJECT_NAME from x$bh x , obj$ o , user$ u where x.obj = o.obj# and o.owner# = u.user# group by u.name, o.name order by 2 desc ) where rownum < 11 /

Waits by file
col name format a60 select name , count from x$kcbfwait , v$datafile where indx + 1 = file# order by 2 /

Segment Waits

select , , , from where and and order , /

object_name obj# statistic_name value v$segment_statistics owner like '&owner' statistic_name like '%waits%' value > 0 by statistic_name value desc

P.R.P.R.

Page 347

Time waited for latches


col event format a30 select event , time_waited , round(time_waited*100/ SUM (time_waited) OVER(),2) wait_pct from ( select event , time_waited from v$system_event where event not in ( 'Null event' ,'client message' ,'rdbms ipc reply' ,'smon timer' ,'rdbms ipc message' ,'PX Idle Wait' ,'PL/SQL lock timer' ,'file open' ,'pmon timer' ,'WMON goes to sleep' ,'virtual circuit status' ,'dispatcher timer' ,'SQL*Net message from client' ,'parallel query dequeue wait' ,'pipe get') union ( select name , value from v$sysstat where name like 'CPU used when call started' ) ) order by 2 desc /

Identify hot blocks


Look at all waits for the instance col event format a30 select event , total_waits , time_waited from v$system_event where event like '%wait%' order by 2,3 /

P.R.P.R.

Page 348

If there are lots of 'data block' waits, get a break-down of them


select * from v$waitstat /

Then run this to identify the file, block and reason code...
select , , from where / p1 "File #" p2 "Block #" p3 "Reason Code" v$session_wait event = 'buffer busy waits'

Note. You might need to run this a few times before anything is displayed.

Look at the performance stats for the instance


select , from , where order , / n.name s.value v$statname n v$sysstat s n.statistic# = s.statistic# by n.class n.name

Performance - Statistics
Gather database statistics
Gather stats on the entire database...
execute dbms_stats.gather_database_stats;

Or...
execute dbms_stats.gather_database_stats( estimate_percent => 1, method_opt => 'FOR ALL COLUMNS SIZE 1',cascade => TRUE);

P.R.P.R.

Page 349

Gather stats for a single schema...


execute dbms_stats.gather_schema_stats('SCOTT');

Or...
execute dbms_stats.gather_schema_stats( ownname => 'SCOTT', estimate_percent => 1, method_opt => 'FOR ALL COLUMNS SIZE 1',cascade => TRUE);

You can let oracle come up with the estimate figure by using dbms_stats.auto_sample_size
or... execute dbms_stats.gather_schema_stats( ownname => 'SYS', cascade => TRUE);

Table statistics
exec dbms_stats.gather_table_stats('<owner>', '<table_name>');

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 system stats


execute dbms_stats.gather_system_stats('Start');

Wait for a while - idealy with the database under a typical workload
execute dbms_stats.gather_system_stats('Stop');

P.R.P.R.

Page 350

To see the current system statistics


select , from where / pname pval1 sys.aux_stats$ sname = 'SYSSTATS_MAIN'

Export/Import optimizer statistics


Create a table to hold the statistics...
exec dbms_stats.create_stat_table(ownname => 'SYS',stattab => 'prod_stats', tblspace => 'USERS');

Populate the table with the current stats...


exec dbms_stats.export_schema_stats(ownname => 'SCOTT',statown=>'SYS', stattab=>'prod_stats');

At this point you need to: 1) take an export of the 'prod_stats' table 2) import 'prod_stats' into the target database 3) load the statistics using this command...
exec dbms_stats.import_schema_stats(ownname => 'SCOTT',statown=>'SYS', stattab=>'prod_stats');

Old style analyze


analyze table employees compute statistics; analyze table employees estimate statistics sample 100 rows; analyze table employees estimate statistics sample 15 percent; analyze index employees_ind compute statistics;

P.R.P.R.

Page 351

Show a count of analyezed tables broken down by schema


set pages 999 lines 100 select a.owner , a.total_tables tables , nvl(b.analyzed_tables,0) analyzed from (select owner , count(*) total_tables from dba_tables group by owner) a , (select owner , count(last_analyzed) analyzed_tables from dba_tables where last_analyzed is not null group by owner) b where a.owner = b.owner (+) and a.owner not in ('SYS', 'SYSTEM') order by a.total_tables - nvl(b.analyzed_tables,0) desc /

Show tables that have analyze dates older than today This is useful if you are running an analyze and want to see how much is left to do
select from where and order / count(last_analyzed) left_to_do dba_tables owner = '&schema' trunc(last_analyzed) < trunc(sysdate) by 1

Performance - Query Tuning:


Create a plan table
@?/rdbms/admin/utlxplan.sql

Autotrace To switch it on:


column plan_plus_exp format a100

P.R.P.R.

Page 352

set set set set set

autotrace autotrace autotrace autotrace autotrace

on explain # Displays the execution plan only. traceonly explain # dont run the query on # Shows the execution plan as well as statistics of the statement. on statistics # Displays the statistics only. traceonly # Displays the execution plan and the statistics

To switch it off:
set autotrace off

Explain plan
explain plan for select ...

or...
explain plan set statement_id = 'bad1' for select...

Then to see the output...


set lines 100 pages 999 @?/rdbms/admin/utlxpls

Find a query's hash Put something unique in the like clause


select hash_value, sql_text from v$sqlarea where sql_text like '%TIMINGLINKS%FOLDERREF%' /

Grab the sql associated with a hash


select sql_text from v$sqlarea where hash_value = '&hash' /

P.R.P.R.

Page 353

Look at a query's stats in the sql area


select , , , , , from where / executions cpu_time disk_reads buffer_gets rows_processed buffer_gets / executions v$sqlarea hash_value = '&hash'

Performance Memory:
SGA breakdown
set lines 100 pages 999 col bytes format 999,999,999 compute sum of bytes on pool break on pool skip 1 select pool , name , bytes from v$sgastat order by pool , name /

PGA usage by username


select st.sid "SID", sn.name "TYPE", ceil(st.value / 1024 / 1024) "MB" from v$sesstat st, v$statname sn where st.statistic# = sn.statistic# and sid in (select sid from v$session where username like '&user') and upper(sn.name) like '%PGA%' order by st.sid, st.value desc /

P.R.P.R.

Page 354

Display pool usage


select name , sum(bytes) from v$sgastat where pool like 'shared pool' group by name /

Miscellaneous - Useful UNIX:


Find/Zip/Move/Delete files older than x days
find ./ -name "*.ARC" -mtime +1 -exec ls -l {} \; find ./ -name "*.ARC" -mtime +1 -exec rm {} \; find ./ -name "*.ARC" -mtime +1 -exec gzip {} \; find ./ -name "*.arch" -mtime +1 -exec mv {} /u01/andy/;

Delete the 500 oldest files


rm -f `ls -tr|head -500`

Remove 10 days before files Here . (dot) is nothing but current directory while excute this command u should be in correct location.. To fine 10days before how many files r there $ find . -name "*.xml" -mtime +10 |wc l To Remove 10days before files. $find . -name "*.xml" -mtime +10 -exec rm '{}' \;

P.R.P.R.

Page 355

Find and grep


find ./ -grep <what> {} \; -print 2>/dev/null Or... find ./ -exec grep -l "string" {} \;

list all files opened by a process


lsof -p <pid>

ls -l sorted by size
ls -l |sort -k 5 du -sk *|sort -n

cpio unzip syntax


cpio -idmv < <filename>

man commands
man -k <what> -displays the chapters containing the specified man <chapter> <what> -shows the page

pipes
mknod <name> p

Turn off auto indent and bracket matching in vi


:set noai nosm

P.R.P.R.

Page 356

Capture a control charater


ctl-v then press the control key (eg. backspace)

Configure ksh environment


To display the current settings
set -o To set HP/UX stylee... set -o vi set -o vi-esccomplete

Show routing tables


netstat -r

Check all logs for ORA- errors


grep ^ORA- *log |cut -f2 -d"-"|cut -f1 -d:|awk '{print "ORA-" $1}'|sort u

To see which query is running at present in the DB set pages 9999 lines 300 long 999 trimspool on echo off col username for a10 col machine for a30 col osuser for a20 select p.spid, s.username, s.sid, s.serial#, s.status,s.sql_hash_value, s.last_call_et/60 active_mins, to_char(s.logon_time,'dd-mon-yy hh24:mi') from v$session s, v$process p where s.status='ACTIVE' and s.username <> 'SYS' and s.paddr = p.addr and s.sid in ( select sid from v$session where (last_call_et < 60 or status <> 'INACTIVE') ) and s.username is not null order by

P.R.P.R.

Page 357

s.status desc / To see the query for a hashvalue

select sql_text from v$sql where hash_value='&hash_value' /

Script Find SQL being executed by a OS Process ID (PID)

prompt "Please Enter The UNIX Process ID" set pagesize 50000 set linesize 30000 set long 500000 set head off select s.username su, substr(sa.sql_text,1,540) txt from v$process p, v$session s, v$sqlarea sa where p.addr=s.paddr and s.username is not null and s.sql_address=sa.address(+) and s.sql_hash_value=sa.hash_value(+) and spid=&SPID;

SQL to view OS process and Oracle session info

Use this commands and sql query to show information about OS process and Oracle user session. Useful if for example you notice a single process is chewing up CPU on the server. At the Unix prompt (replace 22910 with the actual process id): $ ps -ef | grep 22910 oracle 22910 1 14 09:16:59 ? 32:09 oracleDBNAME (DESCRIPTION=(LOCAL=no)(ADDRESS=(PROTOCOL=BEQ))) P.R.P.R. Page 358

In sqlplus or TOAD run this query: SELECT s.saddr, s.sid, s.serial#, s.username, s.osuser, s.machine, s.program, s.logon_time, s.status, p.program, p.spid FROM v$session s, v$process p WHERE s.paddr = p.addr AND p.spid IN (22910); If otherwise you need to identify Unix process for a specific Oracle database session run SQL statement below (assuming SIDs are 39 and 24, can also put username or osuser etc in whe where clause):

SELECT p.program, p.spid, s.saddr, s.sid, s.serial#, s.username, s.osuser, s.machine, s.program, s.logon_time, s.status FROM v$session s, v$process p WHERE s.paddr = p.addr AND s.sid IN (39, 24) PROGRAM SPID ------------------------------ --------- ... oracle@hostname (TNS V1-V3) 590 oracle@hostname (TNS V1-V3) 6190

... ...

At the OS prompt get the process information ps -ef | egrep '590|6190' oracle 18232 14573 0 10:16:17 pts/4 0:00 egrep 590|6190 oracle 6190 1 0 Jul 28 ? 14:40 oracleDBNAME (DESCRIPTION=(LOCAL=no)(ADDRESS=(PROTOCOL=BEQ))) oracle 590 1 0 Jul 30 ? 12:10 oracleDBNAME (DESCRIPTION=(LOCAL=no)(ADDRESS=(PROTOCOL=BEQ)))

P.R.P.R.

Page 359

Determining Which Segments Have Many Buffers in the Pool


Method 1 The following query counts the number of blocks for all segments that reside in the buffer cache at that point in time. Depending on buffer cache size, this might require a lot of sort space. SQL> COLUMN OBJECT_NAME FORMAT A40 COLUMN NUMBER_OF_BLOCKS FORMAT 999,999,999,999 SELECT o.OBJECT_NAME, COUNT(*) NUMBER_OF_BLOCKS FROM DBA_OBJECTS o, V$BH bh WHERE o.DATA_OBJECT_ID = bh.OBJD AND o.OWNER != 'SYS' GROUP BY o.OBJECT_NAME ORDER BY COUNT(*); OBJECT_NAME NUMBER_OF_BLOCKS ---------------------------------------- ---------------SQLPLUS_PRODUCT_PROFILE 1 AQ$_QUEUES 2 BONUS 3 EMP 8 DEPT 8 SALGRADE 8

Access.sql
-- ----------------------------------------------------------------------------------- File Name : http://www.oracle-base.com/dba/monitoring/access.sql -- Author : DR Timothy S Hall -- Description : Lists all objects being accessed in the schema. -- Call Syntax : @access (schema-name) -- Requirements : Access to the v$views. -- Last Modified: 15/07/2000 -- ---------------------------------------------------------------------------------SET LINESIZE 255 SET VERIFY OFF COLUMN object FORMAT A30 SELECT a.object, a.type, a.sid, b.username, b.osuser, b.program

P.R.P.R.

Page 360

FROM

v$access a, v$session b WHERE a.sid = b.sid AND a.owner = UPPER('&1') ORDER BY a.object

Eliminate duplicate records from a table


SQL> delete from EMP where rowid not in (select max (rowid) from EMP group by ename);

To see the Session Timezone Select sessiontimezone from dual; Select dbtimezone from dual;

P.R.P.R.

Page 361

Error Lines in Files


You can return the error lines in a file using: root> cat alert_LIN1.log | grep -i ORAThe "grep -i ORA-" command limits the output to lines containing "ORA-". The "-i" flag makes the comparison case insensitive. A count of the error lines can be returned using the "wc" command. This normally give a word count, but the "-l" flag alteres it to give a line count: root> cat alert_LIN1.log | grep -i ORA- | wc -l

Useful Profile Settings


The following .profile settings rely on the default shell for the user being set to the Korn shell (/bin/ksh). The backspace key can be configured by adding the following entry: stty erase "^H" The command line history can be accessed using the [Esc][k] by adding the following entry: set -o vi Auto completion of paths using a double strike of the [Esc] key can be configured by adding the following entry: set filec

P.R.P.R.

Page 362

>> Excute DOS Commands from SQL prompt In linux Sql> !ls In Windows Sql> $dir OR Sql> host dir

P.R.P.R.

Page 363

Base Tables and Views:


V$timezone_names MGMT$RACDB_CONNECTS (To Check the RAC) SQL> show parameter CLUSTER_DATABASE

P.R.P.R.

Page 364

Oracle useful Links:

3) Scripts info: http://www.orafaq.com/wiki/Scripts


http://www.oracle-base.com/dba/DBACategories.php

4) This is for Free videos download:


http://dba-appsdba.blogspot.com/2009/08/oracle-dba-videos-with-download-links.html

5) Oracle Apps Scripts: http://oracle.anilpassi.com/some-scripts-contributed-by-ahmad-bilal16.html


6) All syntaxes & Views. http://ss64.com/

7) SET System Variable Summary

http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12040.ht m#SQPUG066
8) Oracle Database Performance Tuning Guide10g Release 2 (10.2)

http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/toc.htm

P.R.P.R.

Page 365

P.R.P.R.

Page 366

P.R.P.R.

Page 367

P.R.P.R.

Page 368

P.R.P.R.

Page 369

P.R.P.R.

Page 370

P.R.P.R.

Page 371

P.R.P.R.

Page 372

P.R.P.R.

Page 373

Oracle 11g new features:


http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/index.html

Virtual Columns in Oracle Database 11g Release 1


When queried, virtual columns appear to be normal table columns, but their values are derived rather than being stored on disc. The syntax for defining a virtual column is listed below.
column_name [datatype] [GENERATED ALWAYS] AS (expression) [VIRTUAL]

If the datatype is omitted, it is determined based on the result of the expression. The GENERATED ALWAYSand VIRTUAL keywords are provided for clarity only. The script below creates and populates an employees table with two levels of commission. It includes two virtual columns to display the commission-based salary. The first uses the most abbreviated syntax while the second uses the most verbose form.
CREATE TABLE employees ( id NUMBER, first_name VARCHAR2(10), last_name VARCHAR2(10), salary NUMBER(9,2), comm1 NUMBER(3), comm2 NUMBER(3), salary1 AS (ROUND(salary*(1+comm1/100),2)), salary2 NUMBER GENERATED ALWAYS AS (ROUND(salary*(1+comm2/100),2)) VIRTUAL, CONSTRAINT employees_pk PRIMARY KEY (id) ); INSERT INTO employees (id, first_name, last_name, salary, comm1, comm2) VALUES (1, 'JOHN', 'DOE', 100, 5, 10); INSERT INTO employees (id, first_name, last_name, salary, comm1, comm2) VALUES (2, 'JAYNE', 'DOE', 200, 10, 20); COMMIT;

Querying the table shows the inserted data plus the derived commission-based salaries.
SELECT * FROM employees; ID SALARY2 ----------1 110 2 240 FIRST_NAME LAST_NAME SALARY COMM1 COMM2 SALARY1

---------- ---------- ---------- ---------- ---------- ---------- -------JOHN JAYNE DOE DOE 100 200 5 10 10 20 105 220

2 rows selected. SQL>

P.R.P.R.

Page 374

The expression used to generate the virtual column is listed in the DATA_DEFAULT column of the [DBA|ALL|USER]_TAB_COLUMNS views.
COLUMN SELECT FROM WHERE data_default FORMAT A50 column_name, data_default user_tab_columns table_name = 'EMPLOYEES'; DATA_DEFAULT --------------------------------------------------

COLUMN_NAME -----------------------------ID FIRST_NAME LAST_NAME SALARY COMM1 COMM2 SALARY1 SALARY2 8 rows selected. SQL>

ROUND("SALARY"*(1+"COMM1"/100),2) ROUND("SALARY"*(1+"COMM2"/100),2)

Notes and restrictions on virtual columns include:


Indexes defined against virtual columns are equivalent to function-based indexes. Virtual columns can be referenced in the WHERE clause of updates and deletes, but they cannot be manipulated by DML. Tables containing virtual columns can still be eligible for result caching. Functions in expressions must be deterministic at the time of table creation, but can subsequently be recompiled and made non-deterministic without invalidating the virtual column. In such cases the following steps must be taken after the function is recompiled: o Constraint on the virtual column must be disabled and re-enabled. o Indexes on the virtual column must be rebuilt. o Materialized views that access the virtual column must be fully refreshed. o The result cache must be flushed if cached queries have accessed the virtual column. o Table statistics must be regathered. Virtual columns are not supported for index-organized, external, object, cluster, or temporary tables. The expression used in the virtual column definition has the following restrictions: o It cannot refer to another virtual column by name. o It can only refer to columns defined in the same table. o If it refers to a deterministic user-defined function, it cannot be used as a partitioning key column. o The output of the expression must be a scalar value. It cannot return an Oracle supplied datatype, a user-defined type, or LOB or LONG RAW.

Here is an example of Virtual Column-Based Partitioning.

P.R.P.R.

Page 375

http://www.oracle.com/technology/pub/articles/oracle-database-11g-topfeatures/11g-schemamanagement.html

Schema Management
Manage database objects more efficiently with new functionality that makes many common operations incredibly fast and simple. Download Oracle Database 11g Oracle Database 11g includes a ton of features that not only make jobs simplerbut in some cases, some common timeconsuming operations have also been reduced to virtually one line. In this installment you will learn about some of those features.

DDL Wait Option


Jill the DBA at Acme Retailers is trying to alter the table called SALES to add a column, TAX_CODE. It's pretty routine stuff; she issues the following SQL statement:

SQL> alter table sales add (tax_code varchar2(10));


But instead of getting something like "Table altered", she gets:

alter table sales add (tax_code varchar2(10)) * ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired
The error message says it all: the table is being used right now, probably by a transaction, so getting an exclusive lock on the table may be next to impossible. Of course, the rows of the table are not locked forever. When sessions perform commit the locks on those rows are released, but before that unlock period gets very far, other sessions may update some other rows of the tableand thus the slice of time to get the exclusive lock on the table vanishes. In a typical business environment, the window for locking the table exclusively does open periodically, but the DBA may not be able to perform the alter command exactly at that time. Of course, Jill can just keep on typing the same command over and over again until she gets an exclusive lockor goes nuts, whichever comes first. In Oracle Database 11g, Jill has a better option: the DDL Wait option. She issues:

SQL> alter session set ddl_lock_timeout = 10; Session altered.


Now, when a DDL statement in the session does not get the exclusive lock, it will not error out. Instead, it will wait for 10 seconds. In that 10 seconds, it continually re-tries the DDL operation until it's successful or the time expires, whichever comes first. When she issues:

SQL> alter table sales add (tax_code varchar2(10));


the statement hangs and does not error out. So, instead of Jill trying repeatedly to get the elusive fraction of time when the exclusive lock is available, she outsources repeated trials to Oracle Database 11g, somewhat like a telephone programmed to re-try a busy number. Now, Jill likes this feature so much that she shares it with all the other DBAs. As everyone faces the same issue when altering a table during busy system time, they all find this new feature very helpful. So Jill wonders, can this behavior be default so that they don't need to issue the ALTER SESSION statement every time? Yes, it can. If you issue ALTER SYSTEM SET DDL_LOCK_TIMEOUT = 10, the sessions automatically waits for that time period during DDL operations. Just like any other ALTER SYSTEM statement, this can be overridden by an ALTER SESSION statement.

P.R.P.R.

Page 376

Adding Columns with a Default Value


Although happy with this feature alone, Jill ponders another issue somewhat related to the first one. She wants to add the column TAX_CODE but it has to be NOT NULL. Obviously when she adds a not null column to a non-empty table, she has to also specify a default value, 'XX'. So she writes the following SQL:

alter table sales add tax_code varchar2(20) default 'XX' not null;
But she stops there. The table SALES is huge, about 400 million rows. She knows that when she issues the statement, Oracle will add the column alright but will update the value 'XX' in all rows before returning control back to her. Updating 400 million rows will not only take a very long time, it will also fill up the undo segments, generate a large amount of redo, and create massive performance overhead. So Jill has to ask for a "quiet period"an outageto make this change. But is there a better approach in Oracle Database 11g? There is. The above statement will not issue an update to all the records of the table. Well, that's not a problem for new records where the value of the column will be automatically set to 'XX', but when the user selects this column for an existing record, that will return NULL, right? Wrong, actually. When a user selects the column for an existing record, Oracle gets the fact about the default value from the data dictionary and returns it to the user. So, you kill two birds with one stone: you can define a new column as not null and with a default value and still not incur any penalty for redo and undo generation. Nice.

Virtual Columns
Acme's database contains a table called SALES, as you saw earlier. The table has the following structure: SALES_ID CUST_ID SALES_AMT NUMBER NUMBER NUMBER

Some users want to add a column called SALE_CATEGORY, which identifies the type of the sale: LOW, MEDIUM, HIGH and ULTRA, depending on the amount of sale and the customer in question. This column will help them identify the records for appropriate action and routing to the concerned employee for handling. Here are the logic for values in the column: If sale_amt is more than: 0 10001 100001 1000001 And sale_amt is less Then sale_category than or equal to: is: 1000 100000 1000000 Unlimited LOW MEDIUM HIGH ULTRA

Although this column is a crucial business requirement, the development team does not want to change the code to create the necessary logic. Of course, you could add a new column in the table called sale_category, and write a trigger to populate the column using the logic shown abovea fairly trivial exercise. But performance issues would arise due to context switching from and into the trigger code. In Oracle Database 11g, you do not need to write a single line of code in any trigger. All you have to do instead is add a virtual column. Virtual columns offer the flexibility to add columns that convey business sense without adding any complexity or performance impact. Here's how you would create this table:

SQL> create table sales 2 ( 3 sales_id number, 4 cust_id number, 5 sales_amt number, 6 sale_category varchar2(6)

P.R.P.R.

Page 377

7 8 9 10 11 12 13 14 15 16

generated always as ( case when sales_amt <= 10000 then 'LOW' when sales_amt > 10000 and sales_amt <= 100000 then 'MEDIUM' when sales_amt > 100000 and sales_amt <= 1000000 then 'HIGH' else 'ULTRA' end ) virtual );

Note lines 6-7; the column is specified as "generated always as", meaning the column values are generated at runtime, not stored as part of the table. That clause is followed by how the value is calculated in the elaborate CASE statement. Finally, in line 15,"virtual" is specified to reinforce the fact that this is a virtual column. Now, if you insert some records:

SQL> insert into sales (sales_id, cust_id, sales_amt) values (1,1,100); 1 row created. SQL> insert into sales (sales_id, cust_id, sales_amt) values (2,102,1500); 1 row created. SQL>insert into sales (sales_id, cust_id, sales_amt) values (3,102,100000); 1 row created. SQL> commit; Commit complete. SQL> select * from sales; SALES_ID CUST_ID SALES_AMT SALE_C ---------- ---------- ---------- -----1 1 100 LOW 2 102 1500 LOW 3 102 100000 MEDIUM 3 rows selected.
the virtual column values are all populated as usual. Even though this column is not stored, you can refer to it as any other column in the table. You can even create indexes on it.

SQL> create index in_sales_cat on sales (sale_category); Index created.


The result will be a function-based index.

SQL> select index_type 2 from user_indexes 3 where index_name = 'IN_SALES_CAT'; INDEX_TYPE --------------------------FUNCTION-BASED NORMAL SQL> select column_expression 2 from user_ind_expressions 3 where index_name = 'IN_SALES_CAT'; COLUMN_EXPRESSION

P.R.P.R.

Page 378

-------------------------------------------------------------------------------CASE WHEN "SALES_AMT"<=10000 THEN 'LOW' WHEN ("SALES_AMT">10000 AND "SALES_AMT" <=100000) THEN CASE WHEN "CUST_ID"<101 THEN 'LOW' WHEN ("CUST_ID">=101 AND "CUS T_ID"<=200) THEN 'MEDIUM' ELSE 'MEDIUM' END WHEN ("SALES_AMT">100000 AND "SALES _AMT"<=1000000) THEN CASE WHEN "CUST_ID"<101 THEN 'MEDIUM' WHEN ("CUST_ID">=101 AND "CUST_ID"<=200) THEN 'HIGH' ELSE 'ULTRA' END ELSE 'ULTRA' END
You can even partition on this column, as you saw in the Partitioning installment of this series. You can't, however, enter a value for this column. If you try to, you won't get far:

insert into sales values (5,100,300,'HIGH','XX') * ERROR at line 1: ORA-54013: INSERT operation disallowed on virtual columns

Invisible Indexes
Do you often wonder if an index will be truly beneficial to your users' queries? It might be helping one query but hurting 10 others. Indexes definitely affect INSERT statements negatively and potentially deletes and updates as well, depending on whether the WHERE condition includes the column in the index. A related question is, is the index being used at all and what happens to a query's performance if the index is dropped? Sure, you can drop the index and see the impact on the query, but that's easier said than done. What if the index actually did help the queries? You have to reinstate the index, and to do that, you will need to recreate. Until it is completely recreated, no one can use it. The recreation of the index is also an expensive process; it takes up a lot of database resources you would rather put to better use. What if you had some kind of option to make an index sort of unusable for certain queries while not affecting the others? Prior to Oracle Database 11g, issuing ALTER INDEX ... UNUSABLE is not an option as it will make all DML on that table fail. But now you have precisely that option via invisible indexes. Simply stated, you can make an index "invisible" to the optimizer so that no query will use it. If a query wants to use the index, it has to explicitly specify it as a hint. Here's an example. Suppose there is a table called RES and you created an index as shown below:

SQL> create index in_res_guest on res (guest_id);


After analyzing this table and index, if you

SQL> select * from res where guest_id = 101;


you'll find that the index is being used:

Execution Plan ---------------------------------------------------------Plan hash value: 1519600902 ------------------------------------------------------------------------------------------| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | ------------------------------------------------------------------------------------------| 0 | SELECT STATEMENT | | 1 | 28 | 3 (0)| 00:00:01 | | 1 | TABLE ACCESS BY INDEX ROWID| RES | 1 | 28 | 3 (0)| 00:00:01 | |* 2 | INDEX RANGE SCAN | IN_RES_GUEST | 1 | | 1 (0)| 00:00:01 | ------------------------------------------------------------------------------------------Predicate Information (identified by operation id): ---------------------------------------------------

P.R.P.R.

Page 379

2 - access("GUEST_ID"=101)
Now make the index invisible:

SQL> alter index in_res_guest invisible; Index altered.


The following now shows:

SQL> select * from res where guest_id = 101 2 / Execution Plan ---------------------------------------------------------Plan hash value: 3824022422 -------------------------------------------------------------------------| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | -------------------------------------------------------------------------| 0 | SELECT STATEMENT | | 1 | 28 | 140 (2)| 00:00:02 | |* 1 | TABLE ACCESS FULL| RES | 1 | 28 | 140 (2)| 00:00:02 | -------------------------------------------------------------------------Predicate Information (identified by operation id): --------------------------------------------------1 - filter("GUEST_ID"=101)
that the index is not being used. To make the optimizer use the index again, you have to explicitly name the index in a hint:

SQL> select /*+ INDEX (res IN_RES_GUEST) */ res_id from res where guest_id = 101; ------------------------------------------------------------------------------------------| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | ------------------------------------------------------------------------------------------| 0 | SELECT STATEMENT | | 1 | 28 | 3 (0)| 00:00:01 | | 1 | TABLE ACCESS BY INDEX ROWID| RES | 1 | 28 | 3 (0)| 00:00:01 | |* 2 | INDEX RANGE SCAN | IN_RES_GUEST | 1 | | 1 (0)| 00:00:01 | ------------------------------------------------------------------------------------------Presto! The index is used by the optimizer again. Alternatively, you can set a session-level parameter to use the invisible indexes:

SQL> alter session set optimizer_use_invisible_indexes = true;


This feature is very useful when you can't modify the code, as in third-party applications. When you create indexes, you can append the clause INVISIBLE at the end to build the index as invisible to the optimizer. You can also see the current setting for an index using the dictionary view USER_INDEXES.

SQL> select visibility 2 from user_indexes 3 where index_name = 'IN_RES_GUEST'; VISIBILITY --------INVISIBLE

P.R.P.R.

Page 380

Note that when you rebuild this index, the index will become visible. You have to explicitly make it invisible again. So, to "what" exactly is this index invisible? Well, it's not invisible to the user. It's invisible to the optimizer only. Regular database operations such as inserts, updates, and deletes will continue to update the index. Be aware of that when you create invisible indexes; you will not see the performance gain due to the index while at the same time you may pay a price during DML operations.

Read Only Tables


Robin, a developer for the Acme data warehouse system, ponders a classic problem. As a part of the ETL process, several tables are updated with different periodicities. When updated, the tables are opened up to the users per business rules, even though the users shouldn't modify them. So, revoking DML privilege from the users on these tables is not an option. What Robin needs is functionality that acts as a switch, to make a table update-able and then not so. The implementation of this trivial-sounding operation is actually quite difficult. What options does Robin have? One option is to create a trigger on the table that raises an exception on INSERT, DELETE, and UPDATE. Execution of a trigger involving context switching is not good for performance. The other option is to create a Virtual Private Database (VPD) policy that always returns a false string, such as "1=2". When a VPD policy on the table uses this function, it returns FALSE, and the DML fails. This may be more performant than the trigger option but definitely less desirable as the users will see an error message like "policy function returned error". In Oracle Database 11g, however, you have a much better way to achieve that goal. All you do is make the table read only as shown below:

SQL> alter table TRANS read only; Table altered.


Now when a user tries to issue a DML such as that shown below:

SQL> delete trans;


Oracle Database 11g throws an error right away:

delete trans * ERROR at line 1: ORA-12081: update operation not allowed on table "SCOTT"."TRANS"
The error message does not reflect the operation to the letter but conveys the message as intended, without the overhead of a trigger or VPD policy. When you want to make the table update-able, you will need to make it read/write, as shown below:

SQL> alter table trans read write; Table altered.


Now DMLs will be no problem:

SQL> update trans set amt = 1 where trans_id = 1; 1 row updated.


While a table is in read-only mode only DMLs are disallowed; you can perform all DDL operations (create indexes, maintain partitions, and so on). So, a very useful application of this feature is table maintenance. You can make the table read only, perform the necessary DDL, and then make it read/write again. To see the status of the table, look for the read_only column in the data dictionary view dba_tables.

SQL> select read_only from user_tables where table_name = 'TRANS'; REA ---

P.R.P.R.

Page 381

NO

Fine Grained Dependency Tracking


This feature is best explained through an example. Consider a table called TRANS, created as:

create table trans ( trans_id trans_amt store_id trans_type )

number(10), number(12,2), number(2), varchar2(1)

Users are not supposed to get the data from this table directly; they get it through a view, VW_TRANS, created as shown below:

create or replace view vw_trans as select trans_id, trans_amt from trans;


Now, the view VW_TRANS depends on the table TRANS. You can check the dependencies using this query:

select d.referenced_name, o.status from user_dependencies d, user_objects o where d.name = o.object_name and d.name = 'VW_TRANS' / REFERENCED_NAME STATUS ---------------------------------------------------------------- ------TRANS VALID
The status of the view VW_TRANS, as shown, is VALID. Then, modify the underlying table in some way, such as by adding a column:

alter table trans add (trans_date date);


Because the view depends on the table that was altered, the view now gets invalidated in Oracle Database 10g and previous releases. You can check the dependencies and status now using the query shown above:

REFERENCED_NAME STATUS ---------------------------------------------------------------- ------TRANS INVALID


The status shows as INVALID. Nothing has changed fundamentally that would cause the view to be permanently invalid, and it can be re-compiled easily by:

alter view vw_trans compile;


So, why was that view invalidated? The answer is simple: When a parent object changes, the child objects are automatically placed under scrutiny because something there may need to change as well. However, in this case, the change is the addition of a new column. The view does not use that column, so why should it be invalidated? It doesn't, in Oracle Database 11g. The dependency is still set to TRANS, of course, but the status is not INVALIDit's VALID now!

REFERENCED_NAME STATUS ---------------------------------------------------------------- ------TRANS VALID


Since the view is not invalidated, all the dependent objects of the view, such as another view or packages and procedures, are not invalidated either. This behavior adds tremendous value to the availability of the application, which in turn enhances the overall availability of the entire stack. You do not need to stop the apps while making some database changes. Had you altered a column used in the view, such as TRANS_AMT, the view would have been invalidated. That would be desirable too, since the alter column could affect the view.

P.R.P.R.

Page 382

But high availability does not stop at views and tables alone; you need them for other stored objects such as procedures and packages as well. Consider a package shown below:

create or replace package pkg_trans is procedure upd_trans_amt ( p_trans_id trans.trans_id%type, p_trans_amt trans.trans_amt%type ); end; / create or replace package body pkg_trans is procedure upd_trans_amt ( p_trans_id trans.trans_id%type, p_trans_amt trans.trans_amt%type ) is begin update trans set trans_amt = p_trans_amt where trans_id = p_trans_id; end; end; /
Now suppose you want to write a function that increases the amount of a transaction by a specified percentage. This function uses the package pkg_trans.

create or replace function adjust ( p_trans_id number, p_percentage number ) return boolean is l_new_trans_amt number(12); begin select trans_amt * (1 + p_percentage/100) into l_new_trans_amt from trans where trans_id = p_trans_id; pkg_trans.upd_trans_amt ( p_trans_id, p_percentage ); return TRUE; exception when OTHERS then return FALSE; end; /
If you check the status of the function, it should be valid:

select status from user_objects where object_name = 'ADJUST' /

P.R.P.R.

Page 383

STATUS ------VALID
Suppose you want to modify the package pkg_trans by adding a new procedure to update the vendor_name column. Here is the new package definition:

create or replace package pkg_trans is procedure upd_trans_amt ( p_trans_id trans.trans_id%type, p_trans_amt trans.trans_amt%type ); procedure upd_vendor_name ( p_trans_id trans.trans_id%type, p_vendor_name trans.vendor_name%type ); end; / create or replace package body pkg_trans is procedure upd_trans_amt ( p_trans_id trans.trans_id%type, p_trans_amt trans.trans_amt%type ) is begin update trans set trans_amt = p_trans_amt where trans_id = p_trans_id; end; procedure upd_vendor_name ( p_trans_id trans.trans_id%type, p_vendor_name trans.vendor_name%type ) is begin update trans set vendor_name = p_vendor_name where trans_id = p_trans_id; end; end;
After this package is recompiled, what will be the status of the function ADJUST? In Oracle Database 10g and below, the function, being a dependent one, will be invalidated, as shown in the status:

STATUS ------INVALID
If can be easily compiled by alter function ... recompile, but in Oracle Database 11g, the function will not be invalidated:

STATUS ------VALID
This is a tremendous boost to the notion of high availability. The function adjust does not call the changed portion of the package pkg_trans so there is no need for this function to be invalidated, and rightfully so it is not in Oracle Database 11g.

P.R.P.R.

Page 384

But that's not always the case. If the package were modified in such a way that the new sub-component is at the end, as shown in the above example, then the dependent stored code is not invalidated. If the sub-component is added at the beginning, as shown below:

create or replace package pkg_trans is procedure upd_vendor_name ... procedure upd_trans_amt ... end;
the dependent stored code, ADJUST, is invalidated, as is the case in Oracle Database 10g and below. This occurs because the new procedure, inserted before the existing ones, changes the slot numbers in the package, thereby triggering invalidations. When the procedure was inserted after the exiting ones, the slot numbers were not changed; a new slot number was merely added. Here are some common guidelines for reducing the dependent-related invalidations.

Add components such as functions and procedures to the end of a package. A common cause of invalidation is the change in data types. If you don't specify column names, all the columns are assumed by the procedure and any change will invalidate the procedure even if the column is not used. For instance, when you use select * from sometable, all the columns of the table are assumed. Avoid constructs like select *, datatypes likesometable%rowtype and insert into sometable values (...), where no column list is mentioned. If possible, use views on tables in the stored codes. This allows you to add columns to the table that are not used by stored codes. Since the view is not invalidated, as shown above, the stored code will not be invalidated as well. In case of synonyms, use

create or replace synonym ...;


Instead of

drop synonym ...; create synonym ...;


This does not invalidate procedures. Also, if you have used online redefinition before you might have seen that the redefinition makes some dependent objects invalid. No longer so in Oracle Database 11g. Now, online redefinition will not invalidate objects if columns referenced by them are of the same name and type. If a column was dropped during redef, but a procedure was not using the column, the procedure is not invalidated.

Conclusion
As you can see, not only are previously laborious commands radically simpler, but in some cases, completely new avenues have opened up in terms of how you conduct day-to-day operations. I have seen many changes in Oracle Database functionality over the course of my career, and there are some landmark ones that redefine how business is done. The ones described here belong in that category.

P.R.P.R.

Page 385

Flashback Data Archive (Demo)


http://uhesse.wordpress.com/2009/10/23/total-recall-brief-introduction-into-flashback-dataarchive/#comment-332

We can now designate particular tables for being able to track back all the changes on them even after years. This option addresses especially legal requirements to keep history for certain data for several years. With Total Recall resp. Flashback Data Archive, this can be achieved quite comfortable and efficient. In order to demonstrate that, I create a demo user, giving him the DBA role (kind of quick & dirty of course, but makes the demo easier):
SQL> grant dba to quaid identified by quaid; Grant succeeded. SQL> connect quaid/quaid Connected. SQL> create tablespace flatbs datafile '/u01/app/oracle/oradata/orcl/flatbs01.dbf' size 50m; Tablespace created.

This tablespace is just an ordinary tablespace, but I am going to use it to hold the Flashback Archive, created now:
SQL> create flashback archive fla_10y tablespace flatbs retention 10 year; Flashback archive created.

If I designate a table to fla_10y, I will be able to do Flashback Query on that table even after 10 years provided I have the space to hold that history in the tablespace(s), associated to that Flashback Archive. Following creates two ordinary tables with ordinary rows in them:
SQL> create table norecall (id number, name varchar2(50)); Table created. SQL> create table totalrecall (id number, name varchar2(50)); Table created. SQL> insert into norecall values (1,'QUAID');

P.R.P.R.

Page 386

1 row created. SQL> insert into 1 row created. SQL> commit; Commit complete. totalrecall values (1,'QUAID');

I want to be able to keep the history of the second table for 10 years:
SQL> alter table totalrecall flashback archive fla_10y; Table altered. SQL> select to_char(systimestamp,'yyyy-mm-dd:hh24:mi:ss') from dual; TO_CHAR(SYSTIMESTAM ------------------2009-10-21:10:55:47

I will do DML on the two tables now. As you probably know, this leads to the creation of before images in the undo tablespace, which we can use to look into the past of the tables but most likely not after 10 years, because the before images in the undo tablespace are getting overwritten somewhen.
SQL> delete from norecall; 1 row deleted. SQL> commit; Commit complete. SQL> select * from norecall as of timestamp to_timestamp('2009-10-21:10:55:47','yyyy-mm-dd:hh24:mi:ss'); ID NAME ---------- -------------------------------------------------1 QUAID SQL> delete from totalrecall;

1 row deleted. SQL> commit; Commit complete.

The select above is a Flashback Query, as it is possible since 9i. I will now make sure, that there are no before images left in the undo tablespace by creating a new one and dropping the old one.

P.R.P.R.

Page 387

SQL> create undo tablespace undonew datafile '/u01/app/oracle/oradata/orcl/undonew01.dbf' size 50m; Tablespace created. SQL> alter system set undo_tablespace='UNDONEW'; System altered. SQL> select * from norecall as of timestamp to_timestamp('2009-10-21:10:55:47','yyyy-mm-dd:hh24:mi:ss'); ID NAME ---------- -------------------------------------------------1 QUAID

As long as the old undo tablespace is still there, it may still get used for a conventional Flashback Query. But no longer after the drop tablespace. The before images of the history-tracked table, though, are saved into the Flashback Archive (getting compressed during the transfer), which would be the same, if the content of the old undo tablespace gets overwritten by new before images. Thats why I still can do Flashback Query with totalrecall:
SQL> connect / as sysdba Connected. SQL> shutdown immediate SQL> startup SQL> drop tablespace undotbs1 including contents and datafiles; Tablespace dropped. SQL> connect quaid/quaid Connected. SQL> select * from norecall as of timestamp to_timestamp('2009-10-21:10:55:47','yyyy-mm-dd:hh24:mi:ss'); select * from norecall as of timestamp * ERROR at line 1: ORA-01555: snapshot too old: rollback segment number with name "" too small SQL> select * from totalrecall as of timestamp to_timestamp('2009-10-21:10:55:47','yyyy-mm-dd:hh24:mi:ss'); ID NAME ---------- -------------------------------------------------1 QUAID

I will insert a new row into the ordinary table to demonstrate further differences between it and the history tracked table:
SQL> insert into norecall values (2,'John Doe'); 1 row created. SQL> commit; Commit complete. SQL> select to_char(sysdate,'yyyy-mm-dd:hh24:mi:ss') from dual; TO_CHAR(SYSDATE,'YY -------------------

P.R.P.R.

Page 388

2009-10-23:02:14:28

Upto this point of the story, the shown features are the same in 11g release 1 already available. Following are new features of 11g release 2: We are now able to do DDL statements on the historytracked tables and can still do Flashback Query!
SQL> alter table norecall drop column name; Table altered. SQL> select * from norecall as of timestamp 2 to_timestamp('2009-10-23:02:14:28','yyyy-mm-dd:hh24:mi:ss'); select * from norecall as of timestamp * ERROR at line 1: ORA-01466: unable to read data - table definition has changed SQL> select to_char(sysdate,'yyyy-mm-dd:hh24:mi:ss') from dual; TO_CHAR(SYSDATE,'YY ------------------2009-10-23:02:17:06 SQL> truncate table norecall; Table truncated. SQL> select * from norecall as of timestamp 2 to_timestamp('2009-10-23:02:17:06','yyyy-mm-dd:hh24:mi:ss'); select * from norecall as of timestamp * ERROR at line 1: ORA-01466: unable to read data - table definition has changed

Above demonstrated that DDL on an ordinary table makes Flashback Query behind the DDL impossible. That was nothing new. New is:
SQL> alter table totalrecall drop column name; Table altered. SQL> select * from totalrecall as of timestamp to_timestamp('2009-10-21:10:55:47','yyyy-mm-dd:hh24:mi:ss'); ID NAME ---------- -------------------------------------------------1 QUAID SQL> truncate table totalrecall; Table truncated.

P.R.P.R.

Page 389

SQL> select * from totalrecall as of timestamp to_timestamp('2009-10-21:10:55:47','yyyy-mm-dd:hh24:mi:ss'); ID NAME ---------- -------------------------------------------------1 QUAID

With 11g release 2, we can do Flashback Query behind DDL on tables in the Flashback Archive! In 11g release 1, DDL on history-tracked tables was prohibited, which was a show-stopper for many customers. One DDL, we still cant get through is of course:
SQL> drop table totalrecall; drop table totalrecall * ERROR at line 1: ORA-55610: Invalid DDL statement on history-tracked table

P.R.P.R.

Page 390

TROUBLESHOOT:
1) While inserting the records user getting a error: SQL> insert into DRC_PRODUCTS_L0DATA (market) values('AUS'); insert into DRC_PRODUCTS_L0DATA (market) values('AUS') * ERROR at line 1: ORA-01536: space quota exceeded for tablespace 'HYPDATA'

SQL> !oerr ora 01536 01536, 00000, "space quota exceeded for tablespace '%s'" // *Cause: The space quota for the segment owner in the tablespace has // been exhausted and the operation attempted the creation of a // new segment extent in the tablespace. // *Action: Either drop unnecessary objects in the tablespace to reclaim // space or have a privileged user increase the quota on this // tablespace for the segment owner.

Sol: Grant Unlimited tablespace Privilege to that User Sys> grant unlimited tablespace to <user>;

P.R.P.R.

Page 391

P.R.P.R.

Page 392

P.R.P.R.

Page 393

Potrebbero piacerti anche