Professional Documents
Culture Documents
DBA Demos
DBA Demos
Page 1
P.R.P.R.
Page 2
ORACLE 10g
P.R.P.R.
DBA Demos
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
... 132
1)
2)
P.R.P.R.
Page 4
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
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.
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
KK
/disk1/oradata/good/KK.dbf
RESIZE:
>> alter database datafile < file_id> resize 20m;
>> alter tablespace bigts resize 30m;
1 OS BLOCK
P.R.P.R.
= 512 BYTES
Page 12
WITH 2K:
IN PFILE
MENTION 1 PARAMETER
db_2k_cache_size=12m
Page 13
TEMPORARY TABLESPACE:
Page 14
Group name is g1
Create 2 more temporary table spaces with name
NOW
HOW TO ADD A TEMPOARY TABLESPACE TO A GROUP
P.R.P.R.
Page 15
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
NOW
>> alter database default temporary tablespace TEMP1;
>> select * from Database_properties;
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
,
/
Page 19
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
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
/
Page 21
P.R.P.R.
Page 22
Below query will tell you how much (upto what extend) you can resize your all
datafile and how.
hiprpr@gmail.com
Page 23
P.R.P.R.
Page 24
LINUX.. 2K
WINDOWS .4K
IN 10g BLOCKSIZE IS
LINUX..8K
WINDOWS..8K
NOTE:
BLOCKSIZE
2K
P.R.P.R.
SMALLFILE
*4
BIGFILE
8 GB
8tb
4K
16 GB
16tb
8K
32 GB
32tb
Page 25
16K
64 GB
64tb
32K
128 GB
128tb
VIEWS:
P.R.P.R.
DBA_TABLESPACES
DBA_DATA_FILES
DBA_TEMP_FILES
DBA_TABLESPACE_GROUPS
DBA_FREE_SPACE
V$TABLESPACE
V$DATAFILE
DBA_TS_QUOTAS
USER_TS_QUOTAS..
Page 26
P.R.P.R.
Page 27
USER MANAGEMENT
P.R.P.R.
Page 28
Page 29
>> 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;
Page 30
New password: xy
U4>> connect / as sysdba
DEF
--YES
YES
P.R.P.R.
Page 31
GRANTEE
------------------USER
PRIVILEGE
--------------------------------UNLIMITED TABLESPACE
ADM
--NO
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;
Page 32
from dba_ts_quotas
where tablespace_name not in ('TEMP')
/
@@@@@@@
$$$$$$$$$$$$
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
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.
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.
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
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
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)
6)
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.
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));
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
P.R.P.R.
Page 42
SYS
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).
DBSNMP
dbsnmp
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.
P.R.P.R.
Page 43
% lsnrctl dbsnmp_stop
Oracle9i
% agentctl stop
3.
4.
5.
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.
OUTLN
outln
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
P.R.P.R.
Page 44
ORDSYS
ordsys
ORDPLUGINS ordplugins
CTXSYS
ctxsys
DSSYS
dssys
PERFSTAT
perfstat
WKPROXY
P.R.P.R.
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.
Page 45
WKSYS
change_on_install
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
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
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
ODM
odm
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
ODM_MTR
mtrpw
OLAPSYS
mtrpw
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
TRACESVR
trace
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
P.R.P.R.
Page 47
REPADMIN
P.R.P.R.
Page 48
P.R.P.R.
Page 49
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>
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.
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.
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
If the value of this column is TRUE, then the user can log on with SYSDBA
system privileges.
SYSOPER
If the value of this column is TRUE, then the user can log on with
SYSOPER system privileges.
P.R.P.R.
Page 54
Expand the number of password file users if the password file becomes full
Remove the password file
hiprpr@gmail.com
@@@@@@@@@@@@$$$$$$$$$$$$$$$$$$$$$$$$&&&&&&&&&&&&&&
P.R.P.R.
Page 55
ROLES
CREATE A ROLE
>> create role <role name>;
>> create role r1;
>> Desc dba_roles;
P.R.P.R.
Page 56
>>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
P.R.P.R.
Page 57
Page 58
rows selected
kk> select * from pp.pp;
rows selected..
P.R.P.R.
Page 59
PRIVILEGES
System privileges
Object privileges
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
P.R.P.R.
USER_TAB_PRIVS
USER_COL_PRIVS
ALL_COL_PRIVS
USER_TAB_PRIVS_MADE
USER_TAB_PRIVS_RECD
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
....
(composite_limit)
In order to enforce kernel limits, resource_limit must be set to true.
Password limits
Page 63
???
(password_grace_time)
P.R.P.R.
Page 64
P.R.P.R.
Page 65
STORAGE PARAMETERS
LMTS
DMTS
INITIAL
64k
40k
NEXT
__
40K
MIN
505
2147483645
MAX
2147483645
PCT
__
50%
UNIFORM
1m
__
0%
>> save sp
>> create tablespace lmts datafile location size 10m;
>> @sp
P.R.P.R.
Page 66
initial
Lmts
65536
next
min
1
max
pct
2147483645
O/p
Tsname
Lmts1
initial
65536
next
min
1
max
pct
2147483645
Page 67
Initial
40
next
min
max
pct
40
505
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
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
P.R.P.R.
DMTS
MANUAL
Page 70
DMTS
LMTS
>Exec dbms_space_admin.tablespace_migrate_to_local
(TABLESPACENAME);
P.R.P.R.
next
min
1
max
pct
2147483645
Page 71
Initial
35184
next
min
1
max
2147.
pct
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
Initially extent size
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.}
-
P.R.P.R.
Page 74
P.R.P.R.
Page 75
ROLLBACK SEGMENTS.
Page 76
>> create rollback segment rbs2 tablespace roll storage (optimal 150k);
@@@@
>> create rollback segment rbs3 tablespace roll
Storage (initial 20k optimal 100k);
@@@@
>> 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
NOTE:
1)
2)
Page 79
UNDOTBS
UNDO1
What's in undo
select
,
,
from
group
,
/
P.R.P.R.
tablespace_name
status
count(*) as HOW_MANY
dba_undo_extents
by tablespace_name
status
Page 80
P.R.P.R.
Page 81
###########@@@@@@%%%%&&&&&&&&&&&&&
P.R.P.R.
Page 82
Undotbs
Undo1
SNP
SNP
SNP SNP
P.R.P.R.
Page 83
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
undotbs
undo1;
hiprpr@gmail.com
=====####=====#####=====######
P.R.P.R.
Page 85
...
1.
2.
3.
4.
FLASH BACK
FLASHBACK TABLE:
>> Cr8 a tablespace
>> Cr8 a user
FLB
FLB
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
P.R.P.R.
Page 86
@@@@@#######$$$$$$$$
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
table
timestamp
########################
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
(USE UNDO)
For each commit point ORACLE will gives one XID (transaction id)
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
(USE UNDO)
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%
P.R.P.R.
SPFILE
1. Semi Binary Format
2. 1st preference
3. Dynamic -- 80%
Static -- 20%
Page 94
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
DIS ADVANTAGES:
We cant trace the control file
We cant recreate the control file
We cant rename the database
Page 95
(DYNOMIC)
(SEMI DYNOMICSESSION DEPENDENT)
(STATIC)
Page 96
P.R.P.R.
Page 97
OMF
(ORACLE MANAGED FILES)
P.R.P.R.
Page 98
#control_files
#undo_tablespace
Create required directory structure
Startup nomount
Create database;
P.R.P.R.
Page 99
CONTROLFIILE MANAGEMENT
P.R.P.R.
Page 100
V$CONTROLFIILE
V$CONTROLFILE_RECORD_SECTION
MIN
MAX
1
8
P.R.P.R.
Page 101
~] $ vi cont.trc
] $ edit that trace file
dgg removing
Up to beginning of the
Page
Startup nomount
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:
>> @cont.trc
Control file created ..
Open
>> Sho parameter cont_
P.R.P.R.
Page 103
RENAME A DATABASE
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
hiprpr@gmail.com
P.R.P.R.
Page 104
P.R.P.R.
Page 105
REDOLOGFILE MANAGEMENT
P.R.P.R.
Page 106
MIN
GROUPS
MEMBERS
MAX
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
P.R.P.R.
Page 108
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
P.R.P.R.
Page 109
DROP A GROUP
To drop the redolog file, its status should be INACTIVE
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
P.R.P.R.
Page 111
P.R.P.R.
Page 112
NETWORKING
SERVER SIDE
CLIENT SIDE
LISTENER.ORA
1.
2.
3.
4.
TNSNAMES.ORA
Listener name
Protocol
Port number
SID names
In .bash_profile
1.Alias name
2.Protocal
3.Port number
(Same as server Port)
4. SID names
(Same as server SID)
TNS_ADMIN=$HOME
DEFAULT LOCATION
$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
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
SERVER SIDE;
My Listener name is
SID: ram
Port: 6666
Protocol: TCP/IP
RED
CLIENT SIDE:
My Tnsname (alias name) is
GREEN
SID: ram
(Same as server side)
Port: 6666
(Same as server side)
Protocol: TCP/IP (Same as server side)
P.R.P.R.
Page 116
In pfile
Remote_login_passwordfile=exclusive
P.R.P.R.
Page 117
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
RED
CLIENT SIDE:
My Tnsname (alias name) is
SID: ram
Port: 6666
Protocol: TCP/IP
GREEN
P.R.P.R.
Page 120
(CLIENT SIDE)
in parameter file.
global_names=FALSE
Page 121
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
P.R.P.R.
Page 123
hiprpr@gmail.com
P.R.P.R.
Page 124
MATERIALIZED VIEWS
P.R.P.R.
Page 125
Complete
Fast
Force
P.R.P.R.
Page 126
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
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;
Page 128
KK> /
(Some times then observe)
P.R.P.R.
Page 129
NOTE:
Syntax:
>> EXECUTE DBMS_MVIEW.RFRESH
(materialized viewname,refresh_option)
U1> Exec dbms_mview.refresh (MVN,COMPLETE);
(M.view name)
(Option)
VIEWS:
P.R.P.R.
DBA_MVIEWS
DBA_MVIEW_COMMENTS
DBA_MVIEW_DETAILS_RELATIONS
DBA_MVIEW_LOGS
DBA_MVIEW_REFRESH_TIMES
DBA_MVIEW_LOG_FILTER_COLS
Page 130
log_owner
log_table
dba_mview_logs
P.R.P.R.
Page 131
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)
P.R.P.R.
PHYSICAL BACKUPS
1. COLD BACKUP
2. HOT BACKUP
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)
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}
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
P.R.P.R.
Page 138
@@@
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
}
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
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
P.R.P.R.
Page 143
P.R.P.R.
Page 144
NOTE: If u want to import at a time both users tables then use FULL=Y option
P.R.P.R.
Page 145
SCHEMA LEVEL:
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
@@@
>> 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
14 rows
4 rows
Page 148
P.R.P.R.
Page 149
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):
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
.
.
.
.
.
.
.
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
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'
P.R.P.R.
Page 153
DATABASE REORG.
STEPS:
P.R.P.R.
Page 154
P.R.P.R.
Page 155
COMPLETE BACKUP:
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
"EMP"
17 rows imported
sys>>
pp>> select count (*) from emp;
17 rows....
@@@@@@@@@
Pr>> Demobld
Pr>> select count (*) from tab;
P.R.P.R.
Page 157
Page 158
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
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.
Page 164
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
P.R.P.R.
Page 165
Username: / as sysdba
REMAP_SCHEMA
KB
KB
KB
KB
4
14
5
0
rows
rows
rows
rows
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
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
Page 167
rows
rows
rows
rows
Username: / as sysdba
Export> stop_job=immediate
Are you sure you wish to stop this job ([yes]/no): y
(Job Name)
Username: / as sysdba
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
******************************************************************************
P.R.P.R.
Page 169
P.R.P.R.
Page 170
P.R.P.R.
Page 171
COLD BACLUPS
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/
(For backup)
(Take a backup)
Good] $ cd cold
Cold] $ ls
All files are in backup
P.R.P.R.
Page 174
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
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
P.R.P.R.
Page 179
SCENARIO.3
Sys>>
Kk>> select count (*) from emp;
14 rows
Kk>> select count (*) from dept;
4 rows
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
Page 181
SCENARIO.4
LOSS OF NON SYSTEM DATAFILE
Page 182
~] $ 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:
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
Sys>> kk tablespace
Sys>> kk
user
Sys>> kk kk (as a default)
kk>> Demobld
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>>
P.R.P.R.
Page 186
STATUS
GROUP#
---------------- ---------INACTIVE
1
INACTIVE
3
CURRENT
2
P.R.P.R.
STATUS
GROUP#
Page 187
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'
STATUS
GROUP#
---------------- ---------INACTIVE
1
INACTIVE
3
CURRENT
2
P.R.P.R.
Archive Mode
Enabled
USE_DB_RECOVERY_FILE_DES
1
1
Page 188
STATUS
GROUP#
---------------- ---------CURRENT
1
UNUSED
2
UNUSED
3
>> http://www.lazydba.com/oracle/0__66824.html
@@@
P.R.P.R.
Page 189
SCENARIO.6
Page 190
P.R.P.R.
Page 191
P.R.P.R.
Page 192
SCENARIO.7
PTR>>
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}
Page 193
{A}
EXPORT
TABLE EMP
{B}
P.R.P.R.
{A}
Page 194
SCENARIO.8
<FILE ID>
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
:20,40 W /oraeng/app/oracle/product/10.2.0/dbs/initram.ora
Append the 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
P.R.P.R.
Page 197
P.R.P.R.
Page 198
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
P.R.P.R.
Page 200
P.R.P.R.
Page 201
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
###
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
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
P.R.P.R.
Page 207
SCENARIO.1
DATABASE CRASH
(LOSS OF C/R/D/
FILES) :
Page 208
P.R.P.R.
Page 209
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)
P.R.P.R.
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
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
SID: ram
(Same as server side)
Port: 6666
(Same as server side)
Protocol: TCP/IP (Same as server side)
Location: /disk2/oradata/bad
~] $ 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;
Page 213
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;
Page 215
Delete all backups, copies and archived redo log files based on the
configured Retention policy:
RMAN>>delete obsolete;
Page 216
O/p
Youll get two status
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
P.R.P.R.
recid=2
recid=6
recid=7
recid=8
Page 217
recid=3
recid=4
recid=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
P.R.P.R.
recid=2
recid=6
recid=7
recid=8
Page 218
RMAN>
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>
RMAN>>delete backupset;
Delete a specific Backupset
RMAN>> delete backupset 120;
Page 220
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
E.g.:
SHOW CHANNEL;
SHOW DEVICE TYPE;
SHOW DEFAULT DEVICEC TYPE;
SHOW MAXSETSIZE
SHOW ALL;
P.R.P.R.
Page 222
RMAN>
(complete)
(cumulative)
(incremental)
P.R.P.R.
Page 223
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;
###
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
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
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
Control Files:
RC_BACKUP_CONTROLFILE
RC_PROXY_CONTROLFILE
RC_CONTROLFILE_COPY
hiprpr@gmail.com
P.R.P.R.
Page 228
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
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
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
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
Page 237
---------Data
Index
Other
-------------0
0
0
---------------5838
5081
8
Page 238
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
SCENARIO. 2
SCENARIO. 3
Page 242
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;
SCENARIO. 5
Loss of Redologs:
RMAN> shutdown abort
RMAN> startup nomount
RMAN> restore controlfile
P.R.P.R.
Page 243
Incremental
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
http://download.oracle.com/docs/cd/B19306_01/backup.102/b14192/setup00
5.htm
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>";
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>);
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;
}
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';
P.R.P.R.
Page 248
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;
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;
P.R.P.R.
Page 250
Page 251
P.R.P.R.
Page 252
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
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)
(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.
Page 258
Sys>>
Tts>> select * from tab;
T
Tts>> select * from t;
hiprpr@gmail.com
P.R.P.R.
Page 259
P.R.P.R.
Page 260
WINDOWS
Page 261
P.R.P.R.
Page 262
CLONING
dba11 Source
dba15 Target
SID: Ram
DBNAME: Ram
LOCATION: /disk1/oradata/good
SID: Prasad
DBNAME: Prasad
LOCATION: /disk2/oradata/bad
*.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
clone.ctl
Page 265
}
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:
TIME
SCN
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
Page 268
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
P.R.P.R.
Page 270
P.R.P.R.
Page 271
http://arjudba.blogspot.com/2008/04/how-to-get-back-dropped-tablespace.html
P.R.P.R.
Page 272
Backup Flashback:
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'
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
or...
flashback database to timestamp to_timestamp('22/04/2007 19:30:00','dd/mm/yyyy
hh24:mi:ss');
P.R.P.R.
Page 275
LOG MINER
2S
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
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)
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
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
IMPLEMENTING AUDITING
Page 282
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)
ACTION
---------103
OWNER
----KK
Page 283
kk> @aud
USER OBJ_NAME
---- ---TT
EMP
ACTION
---------103
OWNER
----KK
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
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
OBJ_NAME
-------EMP
EMP
EMP
EMP
DEPT
DEPT
ACTION
---------103
103
103
103
3
3
OWNER
----KK
KK
KK
KK
KK
KK
Page 285
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
2nd session
P.R.P.R.
Page 286
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
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>;
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.
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)
...
[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.
P.R.P.R.
:
:
:
:
:
:
:
:
:
:
:
:
256
133
0
0
0
30
0
0
93
0
0
849517 (0.849517)
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).
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
P.R.P.R.
:
:
:
:
:
:
:
:
:
:
:
:
128
118
0
0
0
9
1
0
0
0
0
849517 (0.849517)
Page 294
Performance Tuning
P.R.P.R.
Page 295
P.R.P.R.
Page 296
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
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
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
1st
SQL> /
112 rows created.
SQL> /
224 rows created
2nd
P.R.P.R.
Page 300
OWNER
----STR
STR
STR
STR
STR
STR
STR
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
P.R.P.R.
Page 301
P.R.P.R.
Page 302
P.R.P.R.
Page 303
Application Tunning
(1) Tkprof (Trace Kernel profile)
(2) Explain Plan
(3) SQL trace
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
********************************************************************************
$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
********************************************************************************
$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
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.
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>
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
P.R.P.R.
Page 310
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>
Library Cache:
SQL> select sum(pinhits)/sum(pins) "LC Hit Ratio" from v$librarycache;
LC Hit Ratio
-----------.767868371
SQL>
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
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
P.R.P.R.
Page 315
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
) (PORT = 1521))
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
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.
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
text
P.R.P.R.
Page 320
48
49
50
51
52
53
54
10
10
10
10
11
11
11
Aug
Aug
Aug
Aug
Aug
Aug
Aug
2010
2010
2010
2010
2010
2010
2010
20:30
21:30
22:30
23:30
00:30
01:30
02:30
1
1
1
1
1
1
1
55
56
57
58
59
60
61
62
63
11
11
11
11
11
11
12
12
12
Aug
Aug
Aug
Aug
Aug
Aug
Aug
Aug
Aug
2010
2010
2010
2010
2010
2010
2010
2010
2010
18:01
19:30
20:30
21:30
22:30
23:30
00:30
01:30
02:30
1
1
1
1
1
1
1
1
1
64
65
66
67
12
12
12
12
Aug
Aug
Aug
Aug
2010
2010
2010
2010
20:53
21:31
22:30
23:30
1
1
1
1
1
1
P.R.P.R.
Page 321
End
Snapshot Id specified: 69
Begin
End
---------- ---------Buffer Cache:
48M
48M
Shared Pool Size:
160M
160M
.
.
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:
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
Eg:
exec dbms_stats.gather_table_stats(ownname => 'KK',tabname => 'DEPT',cascade=> TRUE);
Eg:
exec dbms_stats.gather_schema_stats
(ownname => 'KK',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 :
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
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
STATUS
--------------Production
64bi
10.2.0.1.0
10.2.0.1.0
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
/
/ 1024 /
/ 1024 /
1024) ||
1024) ||
DB size in KB
col "Database Size" format a20
col "Free space" format a20
col "Used space" format a20
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
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
where
/
P.R.P.R.
count(*)
all_objects
object_type like '%JAVA%'
owner = 'SYS'
Page 331
name
detected_usages
dba_feature_usage_statistics
detected_usages > 0
P.R.P.R.
Page 332
P.R.P.R.
Page 333
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'
P.R.P.R.
Page 334
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
name
value
v$parameter
ismodified != 'FALSE'
P.R.P.R.
Page 336
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>);
Page 337
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'
/
P.R.P.R.
Page 339
P.R.P.R.
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
Page 340
column_name
dba_ind_columns
index_name = '&index'
by column_position
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
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);
P.R.P.R.
Page 342
select
from
where
and
and
/
hiprpr@gmail.com
P.R.P.R.
Page 343
P.R.P.R.
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
Page 344
List locks
column
column
column
column
column
SELECT
,
,
,
,
,
FROM
WHERE
/
P.R.P.R.
Page 345
,
,
,
,
,
,
from
,
,
,
where
and
and
and
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
P.R.P.R.
Page 346
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
,
/
P.R.P.R.
object_name
obj#
statistic_name
value
v$segment_statistics
owner like '&owner'
statistic_name like '%waits%'
value > 0
by statistic_name
value desc
Page 347
P.R.P.R.
Page 348
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.
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
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');
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
pname
pval1
sys.aux_stats$
sname = 'SYSSTATS_MAIN'
P.R.P.R.
Page 351
count(last_analyzed) left_to_do
dba_tables
owner = '&schema'
trunc(last_analyzed) < trunc(sysdate)
by 1
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...
P.R.P.R.
Page 353
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
/
P.R.P.R.
Page 354
P.R.P.R.
Page 355
ls -l sorted by size
ls -l |sort -k 5
du -sk *|sort -n
man commands
man -k <what> -displays the chapters containing the specified
man <chapter> <what> -shows the page
pipes
mknod <name> p
P.R.P.R.
Page 356
P.R.P.R.
Page 357
s.status desc
/
To see the query for a hashvalue
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
...
...
P.R.P.R.
Page 359
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
P.R.P.R.
Page 361
P.R.P.R.
Page 362
P.R.P.R.
Page 363
P.R.P.R.
Page 364
3) Scripts info:
http://www.orafaq.com/wiki/Scripts
http://www.oracle-base.com/dba/DBACategories.php
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
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
DOE
100
10
105
JAYNE
DOE
200
10
20
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
COLUMN_NAME
-----------------------------ID
FIRST_NAME
LAST_NAME
SALARY
COMM1
COMM2
SALARY1
SALARY2
DATA_DEFAULT
--------------------------------------------------
ROUND("SALARY"*(1+"COMM1"/100),2)
ROUND("SALARY"*(1+"COMM2"/100),2)
8 rows selected.
SQL>
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.
P.R.P.R.
Page 376
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:
1000
LOW
10001
100000
MEDIUM
100001
1000000
HIGH
1000001
Unlimited
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:
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:
P.R.P.R.
Page 378
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:
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> 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:
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.
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:
P.R.P.R.
Page 381
NO
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:
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:
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:
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:
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:
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
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.
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
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
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'
P.R.P.R.
Page 391
P.R.P.R.
Page 392
P.R.P.R.
Page 393