Tuesday, January 26, 2010

Partition Table In Oracle

What is Partition Table?


Decompose a table or index into smaller, more manageable pieces, called partitions. Each partition of a table or index must have the same logical attributes, such as column names, datatypes, and constraints, but each partition can have separate physical attributes such as pctfree, pctused, and tablespaces.

Partition Key


Each row in a partitioned table is unambiguously assigned to a single partition. The partition key is a set of from 1 to 16 columns that determines the partition for each row.

Sub Partition


Partitions created within partitions. They are just partitions themselves and there is nothing special about them.

Composite Partitioning


Composite partitioning is a combination of other partitioning methods. Oracle currently supports range-hash and range-list composite partitioning.

Interval Partitioning


Interval partitioning is an extension to range partitioning in which, beyond a point in time, partitions are defined by an interval. Interval partitions are automatically created by the database when data is inserted into the partition.

Partitioning Methods


There are several partitioning methods offered by Oracle Database:
1.    Range partitioning
2.    Hash partitioning
3.    List partitioning
4.    Composite range-hash partitioning
5.    Composite range-list partitioning

Range partitioning


Must specify the following three things when range partitions in created:
· Partitioning method: range
· Partitioning column(s)
· Partition descriptions identifying partition bounds

SQL Code:
CREATE TABLE sales
    (
        invoice_no NUMBER,
        sale_year  INT NOT NULL,
        sale_month INT NOT NULL,
        sale_day   INT NOT NULL
    )
PARTITION BY RANGE (sale_year, sale_month, sale_day)
    (
        PARTITION sales_pA VALUES LESS THAN (1999, 04, 01) TABLESPACE tsa,
        PARTITION sales_pB VALUES LESS THAN (1999, 07, 01) TABLESPACE tsb,
        PARTITION sales_pC VALUES LESS THAN (1999, 10, 01) TABLESPACE tsc,
        PARTITION sales_pD VALUES LESS THAN (2000, 01, 01) TABLESPACE tsd
    );

In this example there is a table creates four partitions, one for each quarter of sales.

Partitioning column(s): sale_year, sale_month, and sale_day

Partition descriptions identifying partition bounds:

The VALUES LESS THAN clause determines the partition bound: rows with partitioning key values that compare less than the ordered list of values specified by the clause are stored in the partition.























Portion NameTablespace
sales_pAtsa
sales_pBtsb
sales_pCtsc
sales_pDtsd

Use range partitioning to map rows to partitions based on ranges of column values. This type of partitioning is useful when dealing with data that has logical ranges into which it can be distributed; for example, months of the year. Performance is best when the data evenly distributes across the range. If partitioning by range causes partitions to vary dramatically in size because of unequal distribution, you may want to consider one of the other methods of partitioning.

To get Information about the portion table run the following query
select partition_position, partition_name, high_value
from dba_tab_partitions
where table_name = 'SALES' order by 1;
 

Adding a Partition to a Range-Partitioned Table


ALTER TABLE sales
ADD PARTITION jan2010 VALUES LESS THAN ( '01-FEB-2010' )
TABLESPACE tsx;

Hash partitioning


Must specify the following three things when range partitions in created:
· Partitioning method: hash
· Partitioning column(s)
· Number of partitions or individual partition descriptions


SQL Code:
create table customer (
        customer_id            number,
        customer_name          varchar2(20)
)
partition by hash (customer_id)
partitions 4
store in (gear1, gear2, gear3, gear4);
 

The above example creates a hash-partitioned table. The partitioning column is customer_id, four partitions are created and assigned system generated names, and they are placed in four named tablespaces (gear1, gear2, gear3, gear4)

Adding a Partition to a Hash-Partitioned table


ALTER TABLE customer
ADD PARTITION customer_id TABLESPACE gear5;


List partitioning


Must specify the following three things when range partitions in created:
· Partitioning method: List
· Partitioning column(s)
· Partition descriptions, each specifying a list of literal values (a value list),
   Which are the discrete values of the partitioning column
   that qualify a row to be included in the partition


SQL Code:
create table sales (
        product_id     number,
        trans_amt      number,
        sales_dt       date,
        state_code     varchar2(2)
)
partition by list (state_code)
(
partition ct            values ('CT'),
partition ca            values ('CA'),
partition ny_vm_nj       values ('NY', 'VM', 'NJ'),
partition def            values (default)
);

Use list partitioning when you require explicit control over how rows map to partitions. You can specify a list of discrete values for the partitioning column in the description for each partition. This is different from range partitioning, where a range of values is associated with a partition, and from hash partitioning, where the user has no control of the row to partition mapping.

Adding a Partition to a List-Partitioned Table


The following statement illustrates adding a new partition to a list-partitioned table. In this example physical attributes and NOLOGGING are specified for the partition being added.
ALTER TABLE sales
ADD PARTITION hi VALUES ('HI')
STORAGE (INITIAL 20K NEXT 20K) TABLESPACE tbs_3
NOLOGGING;

Composite range-hash partitioning


Must specify the following three things when range partitions in created:
· Partitioning method: range
· Partitioning column(s)
· Partition descriptions identifying partition bounds
 
· Subpartitioning method: hash
· Subpartitioning column(s)
· Number of subpartitions for each partition or descriptions of subpartitions


SQL Code:
CREATE TABLE scubagear (
        equipno NUMBER,
        equipname VARCHAR(32),
        price NUMBER
        )
PARTITION BY RANGE (equipno) SUBPARTITION BY HASH(equipname)
    SUBPARTITIONS 8 STORE IN (ts1, ts2, ts3, ts4)
        (
       PARTITION p1 VALUES LESS THAN (1000),
       PARTITION p2 VALUES LESS THAN (2000),
       PARTITION p3 VALUES LESS THAN (MAXVALUE)
        );

In this example, three range partitions are created, each containing eight subpartitions. Because the subpartitions are not named, system generated names are assigned, but the STORE IN clause distributes them across the 4 specified tablespaces (ts1, ts2, ts3, ts4).

Range-hash partitioning partitions data using the range method, and within each partition, subpartitions it using the hash method. These composite partitions are ideal for both historical data and striping, and provide improved manageability of range partitioning and data placement, as well as the parallelism advantages of hash partitioning.

The partitions of a range-hash partitioned table are logical structures only, as their data is stored in the segments of their subpartitions. As with partitions, these subpartitions share the same logical attributes. Unlike range partitions in a range-partitioned table, the subpartitions cannot have different physical attributes from the owning partition, although they are not required to reside in the same tablespace

Adding a Partition to a range-hash Table


ALTER TABLE sales
ADD PARTITION q1_2000 VALUES LESS THAN (2000, 04, 01)
SUBPARTITIONS 8 STORE IN tbs5;

Composite range-list partitioning


Must specify the following three things when range partitions in created:
· Partitioning method: range
· Partitioning column(s)
· Partition descriptions identifying partition bounds
 
· Subpartitioning method: list
· Subpartitioning column
· Subpartition descriptions, each specifying a list of literal values (a value list),
  which are the discrete values of the subpartitioning
  column that qualify a row to be included in the subpartition

SQL Code:
CREATE TABLE quarterly_regional_sales
      (deptno number, item_no varchar2(20),
       txn_date date, txn_amount number, state varchar2(2))
  TABLESPACE ts4
  PARTITION BY RANGE (txn_date)
    SUBPARTITION BY LIST (state)
      (PARTITION q1_1999 VALUES LESS THAN (TO_DATE('1-APR-1999','DD-MON-YYYY'))
         (SUBPARTITION q1_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q1_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q1_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q1_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q1_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q1_1999_southcentral VALUES ('OK', 'TX')
         ),
       PARTITION q2_1999 VALUES LESS THAN ( TO_DATE('1-JUL-1999','DD-MON-YYYY'))
         (SUBPARTITION q2_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q2_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q2_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q2_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q2_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q2_1999_southcentral VALUES ('OK', 'TX')
         ),
       PARTITION q3_1999 VALUES LESS THAN (TO_DATE('1-OCT-1999','DD-MON-YYYY'))
         (SUBPARTITION q3_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q3_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q3_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q3_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q3_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q3_1999_southcentral VALUES ('OK', 'TX')
         ),
       PARTITION q4_1999 VALUES LESS THAN ( TO_DATE('1-JAN-2000','DD-MON-YYYY'))
         (SUBPARTITION q4_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q4_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q4_1999_northeast VALUES ('NY', 'VM', 'NJ'),
         SUBPARTITION q4_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q4_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q4_1999_southcentral VALUES ('OK', 'TX')
         )
      );

Like the composite range-hash partitioning method, the composite range-list partitioning method provides for partitioning based on a two level hierarchy. The first level of partitioning is based on a range of values, as for range partitioning; the second level is based on discrete values, as for list partitioning. This form of composite partitioning is well suited for historical data, but lets you further group the rows of data based on unordered or unrelated column values.

Dropping a Table Partition


Use one of the following statements to drop a table partition or subpartition:

  • ALTER TABLE ... DROP PARTITION to drop a table partition

  • ALTER TABLE ... DROP SUBPARTITION to drop a subpartition of a range-list partitioned table


Partition Indexes


There is two types of indexes on partitioned tables:

  • Local Index

  • Global Index


Local Index: The index is partitioned in exactly the same way as the base table. For instance, you can create a local index on the TRANS_AMOUNT column of the TRANS table as follows:
create index in_trans_01
on trans (trans_amount)
local;

This creates a range-partitioned index, on the TRANS_DT column, the same way the TRANS table is partitioned. All the index entries for a specific partition, such as Y05Q1, will exist only inside the corresponding partition of the index.

Global Index: The index can span all partitions in the base table. For example, suppose there is a primary key on TRANS, on the TRANS_ID column. The primary key can be anywhere inside the table, across all the partitions. In this case, the index entries of a partition of the table may exist outside the corresponding partition of the index. For such a situation, create a global index, as follows:
alter table trans
add constraint pk_trans
primary key (trans_id)
using index global;

Reference:
http://www.oracle.com/technology/oramag/oracle/06-sep/o56partition.html
http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10739/partiti.htm

Oracle 10g Enterprise Manager

Oracle 10g on Windows 2003 Server:


Having set the ORACLE_SID variable, I am trying to start the dbconsole using following command.

Problem 01:


emctl start dbconsole

The errors Message :
OC4J Configuration issue. c:\oracle\product\10.2.0\db_1/oc4j/j2ee/OC4J_DBConsole
_192.168.1.41_cjdb not found.

Solution:


Step 01: Find the hostname of Oracle Server and set the ORACLE_HOSTNAME Environment variable
$ hostname

Run these commands For Linux:
$ ORACLE_HOSTNAME=myhost.domainname.com
$ export ORACLE_HOSTNAME

Run these commands For Windows:
> Set ORACLE_HOSTNAME=myhost.domainname.com

It's good idea to drop & recreate Enterprise Manager Repository with correct listener/port

Step 02: Now configure the em Repository following way

Drop and then create em repository for single instance
emca -deconfig   dbcontrol db
emca -config     dbcontrol db

For Cluster (drop and create and RAC EM)
emca -deconfig   dbcontrol db
emca -config     dbcontrol db

Example:
emca -config dbcontrol db
 
STARTED EMCA at Jan 26, 2010 10:14:19 AM
EM Configuration Assistant, Version 10.2.0.1.0 Production
Copyright (c) 2003, 2005, Oracle.  All rights reserved.
 
Enter the following information:
Database SID: cjdb
Listener port number: 1521
Password for SYS user:
Password for DBSNMP user:
Password for SYSMAN user:
Email address for notifications (optional): tamim@cyberjahan.com
Outgoing Mail (SMTP) server for notifications (optional): 25
-----------------------------------------------------------------
 
You have specified the following settings
 
Database ORACLE_HOME ................ c:\oracle\product\10.2.0\db_1
 
Database hostname ................ 192.168.1.41
Listener port number ................ 1521
Database SID ................ cjdb
Email address for notifications ............... tamim@cyberjahan.com
Outgoing Mail (SMTP) server for notifications ............... 25
 
-----------------------------------------------------------------
Do you wish to continue? [yes(Y)/no(N)]: Y
Jan 26, 2010 10:15:45 AM oracle.sysman.emcp.EMConfig perform
INFO: This operation is being logged at c:\oracle\product\10.2.0\db_1\cfgtoollog
s\emca\cjdb\emca_2010-01-26_10-14-19-AM.log.
Jan 26, 2010 10:15:57 AM oracle.sysman.emcp.util.PlatformInterface executeComman
d
WARNING: Error executing CMD /C c:\oracle\product\10.2.0\db_1\bin\emctl.bat depl
oy dbconsole c:\oracle\product\10.2.0\db_1\192.168.1.41_cjdb 192.168.1.41:3938 1
92.168.1.41 cjdb
Jan 26, 2010 10:15:57 AM oracle.sysman.emcp.EMConfig perform
SEVERE: Error instantiating EM configuration files
Refer to the log file at c:\oracle\product\10.2.0\db_1\cfgtoollogs\emca\cjdb\emc
a_2010-01-26_10-14-19-AM.log for more details.
Could not complete the configuration. Refer to the log file at c:\oracle\product
\10.2.0\db_1\cfgtoollogs\emca\cjdb\emca_2010-01-26_10-14-19-AM.log for more deta
ils.

To configure the enterprise manager database control for your database, issue the following commands as oracle user in Linux Platform:
[oracle@dbsrv oracle]$ export ORACLE_HOME=<ORACLE_HOME>
[oracle@dbsrv oracle]$ export ORACLE_SID=<ORACLE_SID>
[oracle@dbsrv bin]$ cd $ORACLE_HOME/bin
[oracle@dbsrv bin]$ ./emca -config dbcontrol db -repos create
Now just follow the instructions on the screen… you’ll need the SYS, DBSNMP and SYSAUX passwords.

Sometimes you already have the SYSMAN, DBSNMP and SYSAUX accounts, and the previous EMCA command can fail to create the DBConsole repository the error ORA-20001 occurs.
ORA-20001 Sysman Already Exists While Running EMCA

If the previous drop procedure fails and by checking the logs we see ORA-01031 insufficient privileges, this may be because we don’t have a password file created. Just go to $ORACLE_HOME/dbs and check if we have a file called pwd<sid>.ora. If not, create it…
[oracle@dbsrv oracle]$ cd $ORACLE_HOME/bin
[oracle@dbsrv bin]$ ./orapwd file=$ORACLE_HOME/dbs/pwd<sid>.ora password=oracle entries=5

Problem 02:


emctl status dbconsole
Unable to determine local host from URL REPOSITORY_URL=http://192.168.1.41:%EM_U
PLOAD_PORT%/em/upload/

Solution:


Change the value of REPOSITORY_URL in following way
%ORACLE_HOME%\<hostname_sid>\sysman\config\emd.properties
REPOSITORY_URL=http://xxxx:5500/em/upload/

Example:
#REPOSITORY_URL=http://192.168.1.41:%EM_UPLOAD_PORT%/em/upload/
REPOSITORY_URL=http://192.168.1.41:5500/em/upload/



Create Database Console

To create the configuration files and repository for Database Console, run:
$ emca -config dbcontrol db -repos create

Drop Database Console

To drop (remove) the configuration files and repository for Database Console, run:
$ emca -deconfig dbcontrol db -repos drop

Recreate Database Console

To recreate the configuration files and repository for Database Console, run:
$ emca -config dbcontrol db -repos recreate

Using EMCA with Real Application Clusters

In this section, I will be using two Database Control consoles running; one on linux1 and the other on linux2. From either of these consoles, you can manage and monitor all targets in the cluster.

For information on the current cluster configuration, you can run:
$ emca -displayConfig dbcontrol –cluster 



Create Database Console
 
$ emca -config dbcontrol db -repos create –cluster



Drop Database Console
 
$ emca -deconfig dbcontrol db -repos drop -cluster

Troubleshooting EMCA

If you have any problems when running emca, check the log file under:
ORACLE_HOME/cfgtoollogs/emca/<ORACLE_SID>/
 
Log Directory:
$ORACLE_HOME/cfgtoollogs/emca
For Linux:
u01/app/oracle/product/10.2.0/db_1/cfgtoollogs/emca 
For Windows:
C:\oracle\product\10.2.0\db_1\cfgtoollogs\emca

Sunday, January 3, 2010

Create directory in Oracle

Directories must be created if external tables are used. Created directories are shown in either dba_directories or all_directories. There is no user_directories. When a directory has been created, the read and write object privileges can be granted on it

Related Data Dictionary Objects


dir$    all_directories         ku$_directory_t
        dba_directories         ku$_directory_view

System Privileges
GRANT create any directory TO <user_name>;
GRANT drop any directory TO <user_name>;

Syntax: CREATE OR REPLACE DIRECTORY <directory_name> AS '<operating_system_path>';

SQL Code:
create or replace directory attachment_dir as '/u02';

Select * from  all_directories
Where directory_name = 'ATTACHMENT_DIR'

Granting Privileges to a Directory


grant read, write on directory attachment_dir to cpdb;

SELECT grantor, grantee, table_schema, table_name, privilege
FROM all_tab_privs
WHERE table_name = 'ATTACHMENT_DIR';

Set UTL_FILE_DIR using ALTER SYSTEM command


alter system set UTL_FILE_DIR = '/u02/attachment_dir' scope=spfile;

OS Commend to create a directory


[oracle@vasdbsrv u02]$ mkdir /u02/attachment_dir
[oracle@vasdbsrv u02]$ ls -la
total 36
drwxrwxr-x   5 oracle oinstall  4096 Dec  8 13:08 .
drwxr-xr-x  26 root   root      4096 Dec  7 09:10 ..
drwxr-xr-x   2 oracle oinstall  4096 Dec  8 13:08 attachment_dir
drwxrwxr-x   2 oracle oinstall 16384 Nov 12 15:35 lost+found
drwxr-x---   3 oracle oinstall  4096 Nov 12 10:50 oradata

PLSQL Code to read or write a file to the directory


Source: {ORACLE_HOME}/rdbms/admin/utlfile.sql

declare
  f utl_file.file_type;
begin
  f := utl_file.fopen('ATTACHMENT_DIR', myfile.txt', 'w');
  utl_file.put_line(f, 'line test 1: text-1');
  utl_file.put_line(f, 'line test 2: text-2');
  utl_file.fclose(f);
end;
/

Drop Directory
Syntax: DROP DIRECTORY <directory_name>;
SELECT *
FROM dba_directories;

DROP DIRECTORY 'ATTACHMENT_DIR;

Saturday, January 2, 2010

Optimize Oracle UNDO Parameters

Data Concurrency and Read Consistency


ROLLBACK or UNDO is the backbone of the READ CONSISTENCY mechanism provided by Oracle. Multi-User Data Concurrency and Read Consistency mechanism make Oracle stand tall in Relational Database Management Systems (RDBMS) world.

Starting in Oracle9i, rollback segments are re-named undo logs. Traditionally transaction undo information was stored in Rollback Segments until a commit or rollback statement was issued, at which point it was made available for overlaying.

Best of all, automatic undo management allows the DBA to specify how long undo information should be retained after commit, preventing "snapshot too old" errors on long running queries.

This is done by setting the UNDO_RETENTION parameter.  The default is 900 seconds (5 minutes), and you can set this parameter to guarantee that Oracle keeps undo logs for extended periods of time.

Rather than having to define and manage rollback segments, you can simply define an Undo tablespace and let Oracle take care of the rest. Turning on automatic undo management is easy.  All you need to do is create an undo tablespace and set UNDO_MANAGEMENT = AUTO.

UNDO_RETENTION is a parameter in the init.ora initialization parameters file that specifies the time period in seconds for which a system retains undo data for committed transactions. The flashback query can go upto the point of time specified as a value in the UNDO_RETENTION parameter.

The properties of the UNDO_RETENTION parameter are mentioned below:

  • Parameter type – Integer

  • Default value – 900

  • Range of values – 0 to 232 – 1

  • Syntax – ALTER SYSTEM SET UNDO_RETENTION = < seconds >;


However it is worth to tune the following important parameters
1. The size of the UNDO tablespace
2. The
UNDO_RETENTION parameter

Calculate UNDO_RETENTION for given UNDO Tabespace


You can choose to allocate a specific size for the UNDO tablespace and then set the UNDO_RETENTION parameter to an optimal value according to the UNDO size and the database activity. If your disk space is limited and you do not want to allocate more space than necessary to the UNDO tablespace, this is the way to proceed. The following query will help you to optimize the UNDO_RETENTION parameter:
Optimal Undo Retention =
           Actual Undo Size / (DB_BLOCK_SIZE
× UNDO_BLOCK_REP_ESC)

Because these following queries use the V$UNDOSTAT statistics, run the queries only after the database has been running with UNDO for a significant and representative time.

Actual Undo Size


SELECT SUM(a.bytes) "UNDO_SIZE"
FROM v$datafile a,
       v$tablespace b,
       dba_tablespaces c
WHERE c.contents = 'UNDO'
AND c.status = 'ONLINE'
AND b.name = c.tablespace_name
AND a.ts# = b.ts#;

Undo Blocks per Second


SELECT MAX(undoblks/((end_time-begin_time)*3600*24)) "UNDO_BLOCK_PER_SEC"
FROM v$undostat;

DB Block Size


SELECT TO_NUMBER(value) "DB_BLOCK_SIZE [KByte]"
FROM v$parameter
WHERE name = 'db_block_size';

Optimal Undo Retention Calculation


Formula:
Optimal Undo Retention =
           Actual Undo Size / (DB_BLOCK_SIZE × UNDO_BLOCK_REP_ESC)

Using Inline Views, you can do all calculation in one query


SQL Code:
SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",
    SUBSTR(e.value,1,25)    "UNDO RETENTION [Sec]",
    ROUND((d.undo_size / (to_number(f.value) *
    g.undo_block_per_sec)))"OPTIMAL UNDO RETENTION [Sec]"
  FROM (
       SELECT SUM(a.bytes) undo_size
          FROM v$datafile a,
               v$tablespace b,
               dba_tablespaces c
         WHERE c.contents = 'UNDO'
           AND c.status = 'ONLINE'
           AND b.name = c.tablespace_name
           AND a.ts# = b.ts#
       ) d,
       v$parameter e,
       v$parameter f,
       (
       SELECT MAX(undoblks/((end_time-begin_time)*3600*24))undo_block_per_sec
       FROM v$undostat
       ) g
WHERE e.name = 'undo_retention'
AND f.name = 'db_block_size'

Calculate Needed UNDO Size for given Database Activity


If you are not limited by disk space, then it would be better to choose the UNDO_RETENTION time that is best for you (for FLASHBACK, etc.). Allocate the appropriate size to the UNDO tablespace according to the database activity:
Formula:
Undo Size = Optimal Undo Retention × DB_BLOCK_SIZE × UNDO_BLOCK_REP_ESC

Using Inline Views, you can do all calculation in one query


SQL Code:
SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",
       SUBSTR(e.value,1,25) "UNDO RETENTION [Sec]",
       (TO_NUMBER(e.value) * TO_NUMBER(f.value) *
       g.undo_block_per_sec) / (1024*1024)
      "NEEDED UNDO SIZE [MByte]"
  FROM (
       SELECT SUM(a.bytes) undo_size
         FROM v$datafile a,
              v$tablespace b,
              dba_tablespaces c
        WHERE c.contents = 'UNDO'
          AND c.status = 'ONLINE'
          AND b.name = c.tablespace_name
          AND a.ts# = b.ts#
       ) d,
      v$parameter e,
      v$parameter f,
       (
       SELECT MAX(undoblks/((end_time-begin_time)*3600*24))
         undo_block_per_sec
         FROM v$undostat
       ) g
WHERE e.name = 'undo_retention'
  AND f.name = 'db_block_size'


Automatic Undo Retention Tuning


Oracle 10g automatically tunes undo retention to reduce the chances of "snapshot too old" errors during long-running queries. The UNDO_RETENTION parameter is used to set a low retention time threshold which the system will attempt to achieve. In the event of any undo space constraints the system will prioritize DML operations over undo retention meaning the low threshold may not be achieved. If the undo retention threshold must be guaranteed, even at the expense of DML operations, the RETENTION GUARANTEE clause can be set against the undo tablespace during or after creation:



Reset the undo low threshold.


ALTER SYSTEM SET UNDO_RETENTION = 2400;

Guarantee the minimum threshold is maintained.


ALTER TABLESPACE undotbs1 RETENTION GUARANTEE;
 
SELECT tablespace_name, retention FROM dba_tablespaces;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       GUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

Switch back to the default mode.


ALTER TABLESPACE undotbs1 RETENTION NOGUARANTEE;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       NOGUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.


The Undo Advisor PL/SQL Interface


Oracle Database provides an Undo Advisor that provides advice on and helps automate the establishment of your undo environment. You activate the Undo Advisor by creating an undo advisor task through the advisor framework. The following example creates an undo advisor task to evaluate the undo tablespace. The name of the advisor is 'Undo Advisor'. The analysis is based on Automatic Workload Repository snapshots, which you must specify by setting parameters START_SNAPSHOT and END_SNAPSHOT. In the following example, the START_SNAPSHOT is "1" and END_SNAPSHOT is "2".



DECLARE
   tid    NUMBER;
   tname  VARCHAR2(30);
   oid    NUMBER;
   BEGIN
   DBMS_ADVISOR.CREATE_TASK('Undo Advisor', tid, tname, 'Undo Advisor Task');
   DBMS_ADVISOR.CREATE_OBJECT(tname, 'UNDO_TBS', null, null, null, 'null', oid);
   DBMS_ADVISOR.SET_TASK_PARAMETER(tname, 'TARGET_OBJECTS', oid);
   DBMS_ADVISOR.SET_TASK_PARAMETER(tname, 'START_SNAPSHOT', 1);
   DBMS_ADVISOR.SET_TASK_PARAMETER(tname, 'END_SNAPSHOT', 2);
   DBMS_ADVISOR.execute_task(tname);
end;

Source : http://www.oracle.com/technology/oramag/code/tips2004/032904.html


Automatic Undo Retention Tuning


Oracle 10g automatically tunes undo retention to reduce the chances of "snapshot too old" errors during long-running queries. The UNDO_RETENTION parameter is used to set a low retention time threshold which the system will attempt to achieve. In the event of any undo space constraints the system will prioritize DML operations over undo retention meaning the low threshold may not be achieved. If the undo retention threshold must be guaranteed, even at the expense of DML operations, the RETENTION GUARANTEE clause can be set against the undo tablespace during or after creation:


Reset the undo low threshold.



ALTER SYSTEM SET UNDO_RETENTION = 2400;

Guarantee the minimum threshold is maintained.



ALTER TABLESPACE undotbs1 RETENTION GUARANTEE;
 
SELECT tablespace_name, retention FROM dba_tablespaces;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       GUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

Switch back to the default mode.



ALTER TABLESPACE undotbs1 RETENTION NOGUARANTEE;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       NOGUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

How to backup and restore the Oracle Control File

There are two approaches to take Backup of control file in Oracle:



  • Backing it up in a binary format

  • Backing it up in a human readable format


Syntax: 
alter database backup controlfile to ['filename' | trace]

This command comes in two versions. One backs up the control file in a binary format while the other backs it up in a human readable form. It is required if the database is running in archive log mode and a structural change was made to the database.

Backing it up in a binary format:


You can generate a binary image of the Control File
SQL Code: 
alter database backup controlfile
               to '/some/arbitrary/path';
alter database backup controlfile
               to '/some/arbitrary/path' reuse;

Backing it up in a human readable format:


You generate a text file script which will re-generate a Control File when run as a SQL script. The file name will be something like 'ora_<some numbers>.trc'
SQL Code:
alter database backup controlfile to trace;

Check udump directory for text based controlfile.
Syntax:
alter database backup controlfile to trace
               as '/some/arbitrary/path';
alter database backup controlfile to trace
               as '/some/arbitrary/path' reuse;

If the human readable form is chosen, the file can be made usable if the comments at the beginning are removed and replaced with a connect / as sysdba. If the init.ora file is not at its default location, it has to be appended with a pfile=.... in the line containing a startup.

Restore the control file


The trouble starts when you attempt to restore the binary version of the Control File backup. Because it was an exact, binary copy of a Control File, its SCN number will not agree with the SCN in the headers of all the data files -basically, the Master Clock is out of whack. You therefore have to issue the following command
RECOVER DATABASE USING BACKUP CONTROLFILE;

It tells the system not to pay too much attention to the SCN of the Control File. Unfortunately, after you issue that command (and following any recovery that it might cause to take place), you must open the database with the following command:
ALTER DATABASE OPEN RESETLOGS;

You can also use RMAN script to restore and recover control file to all locations specified in the parameter file then restore the database, using that control file:
SQL Code
STARTUP NOMOUNT;
RUN
{
  ALLOCATE CHANNEL c1 DEVICE TYPE sbt;
  RESTORE CONTROLFILE;
  ALTER DATABASE MOUNT;
  RESTORE DATABASE;
}

Restore control file to default location:


The default location is defined by CONTROL_FILES parameter of pfile/spfile. If you don't specify any location while restoring your control file then the control file will be restored to the location set by CONTROL_FILES parameter.
RMAN Code: 
RMAN> SET DBID 7887865467
RMAN> RUN {
      RESTORE CONTROLFILE FROM AUTOBACKUP;
     }

Restore of the Control File from Control File Autobackup


For the use who are using  recovery catalog, you can restore your control file from an autobackup. The database must be in a NOMOUNT state. And you have to set DBID. RMAN uses the autobackup format and DBID to determine where to find for the control file autobackup.
RMAN Code:
RMAN> SET DBID 7887865467
RMAN> RUN {
        SET CONTROLFILE AUTOBACKUP FORMAT
        FOR DEVICE TYPE DISK TO 'autobackup_format';
        RESTORE CONTROLFILE FROM AUTOBACKUP;
      }

Restoring a Control File When Using a Recovery Catalog


The recovery catalog contains a complete record of the backups of Database, including backups of the control file. Therefore, It is not necessary to mention the DBID or control file autobackup format.
RMAN Code:
$rman TARGET / CATALOG cpdb/cpdb
RMAN> RESTORE CONTROLFILE;

Restore of the Control File From a Known Location


If you know the backuppiece of controlfile or any copy then simply you can use,
RMAN Code: 
RMAN> RESTORE CONTROLFILE from 'filename';

Restore of the Control File to a New Location


In prior cases RMAN restore the control file to the location specified by CONTROL_FILES parameter of the spfile or pfile.If you want to restore the control file to another location use,
RMAN Code:
RMAN> RESTORE CONTROLFILE TO '<new_location>';

It is also possible to change CONTROL_FILES parameter and then perform RESTORE CONTROLFILE to change location.

Limitations When Using a Backup Control File


After Complete the restore and recover the control file  using a backup control file, It is mandatory  run RECOVER DATABASE and perform an OPEN RESETLOGS on the database. Where SCN is change.