Monday, December 29, 2008

Oracle 10g New Features

  • Flash Recovery Area
  • Recycle Bin (logical structure for locally managed, non-system tablespaces)
  • Bigfile Tablespace
  • Oracle Easy Connect : New net service connection resolution technique in 10g
  • PL/SQL compiler warnings
  • Data Pump
  • Flashback Table
  • Two new background processes: MMON (Memory Monitor) and MMNL (Memory Monitor Light)
  • Compressed backup set regardless of whether blocks in the datafiles are used or unused in RMAN. Works with only backupsets, not image copies
  • Block change tracking in RMAN. CTWR (Change Tracking Writer) is a new process which works with the new block changing tracking feature in 10g for fast RMAN incremental backups. Is automatically used by RMAN. This improves performance because RMAN doesn't have to scan the whole datafile during backup.
  • RMAN has introduced control file autobackup
  • Flashback Database: Database should be in ACHIVELOG mode and logging should be enabled. Uses flashback logs that are stored in flash recovery area to perform the recovery. However, other flashback technologies use undo data for recovery operation.
  • Automatic Storage Management: The Migrate Database to ASM job uses RMAN to convert your database to ASM.
  • Automatic Shared Memory Management (ASMM) : Oracle recommends using ASMM over the use of Memory Advisor. In OEM, Administration --> Memory Parameters --> Under SGA you can see if ASMM is enabled or disabled . MMAN (Memory Manager) process takes care of this.
  • SQL_ID new in 10g, is a hash value that uniquely identifies a single SQL statement within a database.
  • Data Dicitonary Statistics, OS statistics, System statistics
  • DBMS_ADVISOR package
  • Automatic SQL tuning desined into the new query optimizer that totally replaces the need for manual SQL tuning.
  • Sorted Hash Clusters
  • Automated Channel failover in RMAN. In order to use this feature multiple channels must be allocated.

Oracle 10g Database Shutdown

  • shutdown normal: Default type of shutdown that Oracle performs if no shutdown options are provided. No new Oracle connections are allowed from the time the SHUTDOWN NORMAL command is issued. Database will wait until all users are disconnected to proceed with the shutdown process. Also called “clean” shutdown because no recovery is necessary.
  • shutdown transactional: No new Oracle connections are allowed, No new transactions are allowed to start from the time this command is issued. Once all active transactions on the database have completed, all client connections are disconnected. Also called “clean” shutdown because no recovery is necessary.
  • shutdown immediate: No new Oracle connections are allowed, Any uncommitted transactions are rolled out i.e. a user in the middle of a transaction will lose all the uncommitted work. Oracle does not wait for clients to disconnect. Any unfinished transactions are rolled back and their database connections are terminated. Also called “clean” shutdown because no recovery is necessary.
  • shutdown abort: No new Oracle connections are allowed, Any SQL statements currently in progress are terminated, Uncommitted work is not rolled back, Disconnects all client connections immediately. Not a clean shutdown and requires recovery when the database is subsequently started.

Oracle 10g Database Startup

Oracle uses parameter initialization files to store information about initialization parameters used when an Oracle instance starts. Parameter file can either be a plain text file i.e. PFILE or a binary file i.e. SPFILE. Oracle uses a search hierarchy when a startup command is issued without specifying either a PFILE or an SPFILE.
  • startup nomount: parameter file is read and the background processes and memory structures are initiated, but they are not attached or communicating with the disk structures of the database. We can run the script that creates the underlying database.
  • startup mount: does all the work as above and also attaches and interacts with the database structures. At this point it will obtain the information from the control file and attach to the main database structures. Tasks that can be performed in this state include recovery, changing file locations, or place the database in archive log mode.
  • startup open: is the default startup mode if no mode is specified on the startup command line. Performs all the steps of startup nomount, startup mount, and startup open. This option makes the database available to all the users.
  • startup force: use this option if you are experiencing difficulty starting the database in a normal fashion. Ex: If a database sever lost power and the database has stopped abruptly, it can leave the database in a state in which a startup force is necessary. Startup force does a shutdown abort and restarts the database.
  • startup restrict: starts up the database and places it in the open mode, but gives access only to users who have the RESTRICTED SESSION privilege. You may want to open a database in the RESTRICT mode when you want to perform maintenance on the database while it is open but ensure that no users cannot connect and perform work on the database. Can also be used during exports and imports. After you are done with your activities, you can disable the restricted session using ALTER SYSTEM DISABLE RESTRICTED SESSION, so that everyone can connect to the database.

Reference: Sybex Oracle Admin I Study Guide

Friday, December 26, 2008

Optimal Flexible Architecture (OFA)

The OFA (Optimal Flexible Architecture) is useful for establishing a manageable directory structure for a new Oracle Server. The OFA model recommends mount point, directory, and file-naming conventions.

Ex: The file naming convention for a redo log members in a redo log group 1 can be:
redo1a.log
redo1b.log

When Does LGWR Write?

Log Writer writes from redo log buffer to the redo log files when one of the following occurs:
  • Every 3 seconds
  • A user commits a transaction
  • A redo Log Buffer is one-third full
  • Redo Log Buffer contains 1 MB worth of redo information
  • Before DBWn process whenever a database checkpoint occurs

When Does DBWR Write?

Database Writer (DBWR) writes from the database buffer cache to the data files when one of the following occurs:
  • No free buffer space in the cache
  • Number of modified and committed, but unwritten, buffers in the cache is too large
  • At a database checkpoint event
  • The instance shutdown (other than shutdown abort)
  • A tablespace in backup mode or offline mode or read only mode
  • A segment is dropped

Wednesday, December 24, 2008

Oracle Server Architecture Explained

Oracle Server Architecture can be described in 3 categories:
  • User-related process
  • Logical memory structures (Oracle instance)
  • Physical file structures (Database files)
User Processes:
At the user level, two processes allow a user to interact with the instance, and ultimately with the database: the User Process and the Server Process.

In addition to User and Server processes that are associated with each user connection, an additional memory structure called Program Global Area (PGA) is also created for each user. PGA stores user-specific information such as bind variables and session variables.

Oracle Instance:
Made up of Oracle’s main memory structure called System Global Area (SGA) and Oracle background processes. It is with the SGA that the Server Process communicates when the user accesses the data in the database.
Required SGA Components:
Shared Pool: caches most recently used SQL statements
Database Buffer Cache: caches the data that has been most recently accessed by the database users.
Redo Log Buffer: Stores transaction information for recovery purposes

Optional SGA Components:
Java Pool: caches most recently used Java objects
Large Pool: caches data for large operations such as RMAN backup and restore activities
Streams Pool: caches the data associated with queued message requests

Oracle Background Processes:
Each Oracle background process performs a specific job in helping to manage the instance

Required Oracle Background Processes:
  • SMON: System Monitor --> Performs instance recovery following a instance crash, coalesces free space in the database
  • PMON: Process Monitor --> Cleans up failed user database connections
  • DBWn*: Database Writer --> Writes modified database blocks from SGA’s Database Buffer Cache to the datafiles on disk
  • LGWR: Log Writer --> Writes transaction recovery information from the SGA’s Redo Log Buffer to the online redo log files on disk
  • CKPT: Checkpoint --> Updates database file and control file headers following a checkpoint event
The Oracle Database
An instance is a temporary memory structure, but the Oracle database is made up of physical files that reside on server’s disk drives. These files are called Control Files, Datafiles, and Redo Logs. Additional files include PFILE, SPFILE, archived logs.

Control Files: Critical components of database. The following information is stored in the control file:
  • The name of the database
  • The names, locations, and sizes of the datafiles and redo log files
  • Information used to recover the database in case of disk failure

Datafiles: Physical files that actually store the data that has been inserted into each table in database. Datafiles are behind another database storage area called a tablespace. A tablespace is a logical storage area within the database. Tablespaces group logically related segments. Required tablespace include SYTEM, SYSAUX and TEMP. Optional tablespaces include USERS, TOOLS, UNDOTBS1

Redo Log Files: The information needed to recover a transaction in the event of database failure is automatically recorded in the Redo Log Buffer. The contents of the Redo Log Buffer are ultimately written to the redo logs by the LGWR background process. Because of the important role that the redo logs play in the recovery mechanism, they are usually multiplexed or copied. Sets of redo logs are referred to as redo log groups. Each multiplexed file within the group is called a redo log group member.

Every database must have at least two redo log files, which may or may not be multiplexed.

Reference: Sybex Oracle Administration I Study Guide

PFILE Vs SPFILE

Two types of parameter initialization files: PFILE and SPFILE

PFILE
  • Text file that can be edited.
  • When changes are made to PFILE then the instance must be shutdown and restarted before it takes effect.
  • init.ora
  • Can be created from an SPFILE using create pfile from spfile command

SPFILE
  • Binary file and cannot be edited
  • Most changes can be made dynamically when the instance is open and running
  • spfile.ora
  • Can be created from an PFILE using create spfile from pfile command

Data Dictionary Views Vs Dynamic Performance Views

Oracle 10g contains two types of metadata views:
  • Data Dictionary Views (Ex: DBA_TABLES, DBA_USERS, DBA_VIEWS)
  • Dynamic Performance Views (Ex: V$DATBASE, V$VERSION)
Data dictionary views have names that begin with DBA_, ALL_, and USER_

DBA_TABLES: All tables in the entire database reserved for user accounts that have DBA privileges
DBA_USERS: Shows information about all the users in the database
DBA_VIEWS: Shows information about all the views in the database
ALL_TABLES: All tables owned by a particular database user plus all tables to which the user has been granted access
USER_TABLES: All tables owned by a particular database user

NOTE:
  • DBA_ views are available only when the database is open and running.
  • Data contained in DBA_ views is static and is not cleared when the database is shutdown
  • V$ views are available even when the database is not fully open and running.
  • V$ views contain dynamic statistical data that is lost each time when the database is shutdown
Reference: Sybex Oracle Admininstration I Study Guide

Tuesday, December 23, 2008

ORAPWD utility

The orapwd password file is required for all remote database administrative connections to an Oracle database using SYSDBA or SYSOPER. ORAPWD is an Oracle utility that generates a password file for remote connections.

When using ORAPWD, one should use appropriate naming convention, which includes orapw$ORACLE_SID. The password file must be located in $ORACLE_HOME/dbs in UNIX and in $ORACLE_HOME\database in Windows. The init.ora file must also contain REMOTE_LOGIN_PASSWORDFILE parameter, set to SHARED or EXCLUSIVE.


Example:
orapwd file=orapwdTEST password=systestpass entries=20

The entries option determines how many users can be stored in password file. To see what users are utilizing the password file,

SQL> select * from v$pwfile_users;


Reference: Sybex OCP 10g Admin Study Guide

About oratab File

oratab file can be used to set oracle homes for multiple instances, and also has options to start the database at system boot time. This file is located at /var/opt on Unix box.

[oracle@localhost etc]$ vi oratab

# This file is used by ORACLE utilities. It is created by root.sh
# and updated by the Database Configuration Assistant when creating a database.

# A colon, ':', is used as the field terminator. A new line terminates
# the entry. Lines beginning with a pound sign, '#', are comments.
#
# Entries are of the form:
# $ORACLE_SID:$ORACLE_HOME::
#
# The first and second fields are the system identifier and home
# directory of the database respectively. The third filed indicates
# to the dbstart utility that the database should , "Y", or should not,
# "N", be brought up at system boot time.
#
# Multiple entries with the same $ORACLE_SID are not allowed.
#

Example Entry:
vinay:/u01/app/oracle/product/10.2.0/db_1:N

Set Environment Variables

You can set these variables in .bash_profile file on Unix systems or .profile on Linux

[oracle@localhost ~]$ vi .bash_profile

# User specific environment

export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/lib:/usr/local/lib
export ORACLE_SID=test

export PATH=$PATH:$HOME/bin:$ORACLE_HOME/bin

[oracle@localhost ~]$. ./.bash_profile

Sunday, December 21, 2008

Using Statspack Performance Monitoring Tool

Statspack was used before Oracle 10g. In Oracle 10g version AWR and ADDM are used to monitor the performance of database.

The default level of collection, level 5, is adequate for most applications. At this level the normal performance statistics are captured along with the high-resource-usage SQL statements. Parameters can be used to set the limits for the SQL statement collection, which will be highly system dependent.

It is also possible to capture statistics from an individual session as part of a snapshot by using the i_session_id parameter to the procedure. The example below will capture session level statistics for the session with a session id (Oracle sid) of 32.
SQL> execute statspack.snap(i_session_id=>32);

There are currently five different levels of statspack snapshots, defined as follows in the table stats$level_description (9i version):


SNAP_LEVEL DESCRIPTION
---------- -----------------------------------------------------------
0 This level captures general statistics, including rollback
segment, row cache, SGA, system events, background events,
session events, system statistics, wait statistics, lock
statistics, and Latch information

5 This level includes capturing high resource usage SQL
Statements, along with all data captured by lower levels

6 This level includes capturing SQL plan and SQL plan usage
information for high resource usage SQL Statements, along
with all data captured by lower levels

7 This level captures segment level statistics, including
logical and physical reads, row lock, itl and buffer busy
waits, along with all data captured by lower levels

10 This level includes capturing Child Latch statistics, along
with all data captured by lower levels

Using Statspack: Performance monitoring tool
----------------------------------------------
1) Run the scripts to install statspack
SQL> @?/rdbms/admin/spcreate.sql

2) Enter password for perfstat, enter default_tablespace (USERS), enter temporary tablespace (TEMP)

3) conn perfstat/perfstat

4) execute statspack.snap

5) Again repeat step 4 after sometime to get another snap

6) @?/rdbms/admin/spreport.sql

7) Enter a value for begin_snap and end_snap

8) Give a name for the report

9) host vi .lst to view the report
Resolving Your Wait Events

DB File Scattered Read
This generally indicates waits related to full table scans. As full table scans are pulled into memory, they rarely fall into contiguous buffers but instead are scattered throughout the buffer cache. A large number here indicates that your table may have missing or suppressed indexes. Although it may be more efficient in your situation to perform a full table scan than an index scan, check to ensure that full table scans are necessary when you see these waits. Try to cache small tables to avoid reading them in over and over again, since a full table scan is put at the cold end of the LRU (Least Recently Used) list.

DB File Sequential Read
This event generally indicates a single block read (an index read, for example). A large number of waits here could indicate poor joining orders of tables, or unselective indexing. It is normal for this number to be large for a high-transaction, well-tuned system, but it can indicate problems in some circumstances. You should correlate this wait statistic with other known issues within the Statspack report, such as inefficient SQL. Check to ensure that index scans are necessary, and check join orders for multiple table joins. The DB_CACHE_SIZE will also be a determining factor in how often these waits show up. Problematic hash-area joins should show up in the PGA memory, but they're also memory hogs that could cause high wait numbers for sequential reads. They can also show up as direct path read/write waits.

Free Buffer
This indicates your system is waiting for a buffer in memory, because none is currently available. Waits in this category may indicate that you need to increase the DB_BUFFER_CACHE, if all your SQL is tuned. Free buffer waits could also indicate that unselective SQL is causing data to flood the buffer cache with index blocks, leaving none for this particular statement that is waiting for the system to process. This normally indicates that there is a substantial amount of DML (insert/update/delete) being done and that the Database Writer (DBWR) is not writing quickly enough; the buffer cache could be full of multiple versions of the same buffer, causing great inefficiency. To address this, you may want to consider accelerating incremental checkpointing, using more DBWR processes, or increasing the number of physical disks.

Buffer Busy
This is a wait for a buffer that is being used in an unshareable way or is being read into the buffer cache. Buffer busy waits should not be greater than 1 percent. Check the Buffer Wait Statistics section (or V$WAITSTAT) to find out if the wait is on a segment header. If this is the case, increase the freelist groups or increase the pctused to pctfree gap. If the wait is on an undo header, you can address this by adding rollback segments; if it's on an undo block, you need to reduce the data density on the table driving this consistent read or increase the DB_CACHE_SIZE. If the wait is on a data block, you can move data to another block to avoid this hot block, increase the freelists on the table, or use Locally Managed Tablespaces (LMTs). If it's on an index block, you should rebuild the index, partition the index, or use a reverse key index. To prevent buffer busy waits related to data blocks, you can also use a smaller block size: fewer records fall within a single block in this case, so it's not as "hot." When a DML (insert/update/ delete) occurs, Oracle Database writes information into the block, including all users who are "interested" in the state of the block (Interested Transaction List, ITL). To decrease waits in this area, you can increase the initrans, which will create the space in the block to allow multiple ITL slots. You can also increase the pctfree on the table where this block exists (this writes the ITL information up to the number specified by maxtrans, when there are not enough slots built with the initrans that is specified).

Uninstall Statspack:
---------------------
1) Drop the user perfstat
drop user perfstat cascade; [cascade will drop all objects in user's schema]

2) @?/rdbms/admin/spdrop.sql;

RMAN Tablespace Backup

RMAN> backup tablespace users;

Above command will execute successfully in the following conditions:
1) The databse is in NOARCHIVELOG mode and the tablespace is offline
2) The database is in ARCHIVELOG mode and the tablespace is offline
3) The database is in ARCHIVELOG mode and the tablespace is online

About Checkpoints

A checkpoint is an event that flushes the modified data from buffer cache to the disk and updates the control file and datafiles. The CKPT process updates the headers of datafiles and control files. A checkpoint is initiated automatically when one of the following occurs:

1) When the redo log file is filled and a log switch occurs
2) When the instance is shutdown with NORMAL, TRANSACTIONAL, or IMMEDIATE
3) When a tablespace status is changed to read-only or put into BACKUP mode

Commands for issuing Checkpoint manually:
--------------------------------------------
ALTER SYSTEM CHECKPOINT;

ALTER SYSTEM SWITCH LOGFILE;

Saturday, December 13, 2008

Restore critical Datafile (system, undo, sysaux) using RMAN

1) shutdown abort;

2) startup mount pfile =

3) RMAN> restore database;

4) RMAN> recover database;

5) RMAN> sql 'alter database open';

Restore Non-critical Datafile using RMAN

1) See for which tablespace the datafile belongs.
SQL> select file_name, tablespace_name from dba_data_files;

2) alter tablespace offline;

3) RMAN> restore tablespace ;

4) RMAN> recover tablespace ;

5) RMAN> sql 'alter tablespace online';

RMAN Backup (when db is online)

1) Check the ORACLE_SID. The target database will be the value stored in it.

2) Make sure that the database is in archive_log mode
select log_mode from v$database;

3) Add these parameters in init.ora file
db_recovery_file_dest=/.../.../flash_recovery_area
db_recovery_file_dest_size= 2147483648

4) startup pfile =

5) > rman target / nocatalog

6) RMAN> backup database plus archivelog;

Friday, December 12, 2008

Database Security

Creating a user:

SQL>
create user test identified by testpass default tablespace users temporary tablespace temp;
SQL> grant create session to test;

Check to see what roles are granted for a user:

SQL> select * from user_role_privs;
[OR]
SQL
> select * from session_roles;

SQL> conn scott/tiger;

SQL> password


[OR]

Reset to old password:

SQL> alter user uname identified by values 'GSKBHU8768BKJ';

get the value before from dba_users

ALTER USER:




















Drop a user:

SQL> conn system/manager;

SQL> drop user scott;


Check to see what system privileges are granted to user:

SQL> conn scott/tiger;

SQL> select * from user_sys_privs;


Revoking system privileges:
You can revoke system privileges using REVOKE command.
Ex: revoke create table from scott;

Creating Roles:
SQL> create role dept_manager;
SQL> grant select, insert, update, delete on dept_pay to dept_manager;

Granting Roles:
SQL> grant dept_manager to scott;

Check roles granted to a user:
SQL> select * from user_role_privs;

Revoking privileges from a role:
SQL> revoke all on dept_pay from dept_manager;

Dropping a role:
SQL>
drop role dept_manager;

Import Data Pump Utility (impdp)

The following sample shows you how to import a table using data pump utility. Similarly, you can import either a tablespace or full database.

SQL> conn system/manager@sample
Connected.

SQL> grant create any directory to scott;
Grant succeeded.

SQL> conn scott/tiger@sample
Connected.

SQL> create directory dump_dir as 'E:\ORACLE\PRODUCT\10.2.0\ADMIN\SAMPLE\DPDUMP';
Directory created.

SQL> grant read,write on directory dump_dir to public;
Grant succeeded

Now issue the command impdp in command prompt to import a dump file. Following screen shot will help you with the command:

Export Data Pump Utility (expdp)

Following sample shows you how to export tables using data pump utility in Oracle 10g. Similarly you can export tablespace or full database.

SQL> grant create any directory to scott;

Grant succeeded.


SQL> conn scott/tiger@sample

Connected.


SQL> create directory dump_dir as 'E:\ORACLE\PRODUCT\10.2.0\ADMIN\SAMPLE\DPDUMP';

Directory created.


SQL> grant read,write on directory dump_dir to public;

Grant succeeded

SQL> select * from dba_directories;

Now, use the command expdp to use the Data Pump utility. The following screen shot will help you with the command.


Monitoring progress of Data Pump job:

SELECT owner_name,job_name, operation, job_mode, state

FROM dba_datapump_jobs;

Thursday, December 11, 2008

Tablespace Commands, Views and Transportable Tablespaces

Commands used to create a tablespace and alter a tablespace:

create tablespace datafile '/../../.dbf' size 10M;

SQL> create tablespace test datafile '/database/test1/files/test.dbf'
size 10m autoextend on next 64K
maxsize 25M
extent management local autoallocate
segment space management auto;

Temporary tablespaces ARE NOT a candidate for automatic segment-space management:

CREATE TEMPORARY TABLESPACE temp
TEMPFILE '/u07/app/oradata/ORA901/temp01.dbf' SIZE 500M REUSE
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 500K
SEGMENT SPACE MANAGEMENT AUTO;

ERROR at line 4:
ORA-30573: AUTO segment space management not valid for this
type of tablespace

SQL> CREATE TABLESPACE lmtbsb DATAFILE '/u02/oracle/data/lmtbsb01.dbf' SIZE 50M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K;

alter tablespace add datafile '/../../.dbf' size 10M;

To see the tablespace and files:
---------------------------------

select file#,ts#,name,status from v$datafile;

Modifying Tablespaces:
  • ALTER TABLESPACE old_name RENAME TO new_name;
  • ALTER TABLESPACE tbs_name ADD DATAFILE '/oradata/sample.dbf' SIZE 2G;
  • ALTER TABLESPACE tbs_name OFFLINE;
  • ALTER TABLESPACE tbs_name RENAME DATAFILE '/oradata/sample.dbf' TO '/optware/oradata/sample.dbf';
  • ALTER TABLESPACE tbs_name ONLINE;
  • ALTER TABLESPACE tbs_name READ ONLY;
  • ALTER TABLESPACE tbs_name READ WRITE;
  • ALTER TABLESPACE tbs_name BEGIN BACKUP;
  • ALTER TABLESPACE tbs_name END BACKUP;
  • alter tablespace TEST drop datafile '/database/test1/files/test02.dbf'; //only when the datafile is empty
NOTE: If you drop a datafile that is non-empty, you will get ORA-03262 error, saying that the file is non-empty.

Data dictionary and dynamic performance views























































Transportable Tablespaces:

more

Using SQL-Loader

There are four stages to loading data using SQL-Loader:

1. Create a data file. The data file contains the data that you wish to load. There is one record per line and each attribute value is separated by a comma.
2. Create the relation for the data.
3. Create a control file. The control file tells Oracle how to load data from the data file.
4. Run SQL-Loader. SQL-Loader reads the control file and loads the data. A log file is produced that describes what happened and describes any errors that may have occurred.

Ex:
1. Create a data file

The data file is a text file that contains the data. Create a text file by running the text editor and typing the following data:

10, Finance, MA
11, Arts, NJ
12, Science, WA
13, Research, IL

Save the file as sample.dat

2. Create the relation

Create a relation testtab in your Oracle account using the following command:

CREATE TABLE testtab
(deptno NUMBER(3) NOT NULL,
deptname VARCHAR2(15),
deptloc VARCHAR2(15));

The data in sample.dat will be loaded into the relation testtab using SQL-Loader. The relation testtab must exist in the database before SQL-Loader can load data into it.

3. Create a control file

The control file describes the structure of the data and indicates the relation into which the data should be loaded. Create a text file containing the following:

LOAD DATA
INFILE 'E:\sample.dat'
INTO TABLE testtab
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
(deptno, deptname, deptloc)

Save the file as sample.ctl

4. Execute SQL-Loader

The command to execute the SQL-Loader is:

sqlldr userid=tester@test control=E:\sample.ctl log=E:\sample.log

Creating Symbolic Links

Symbolic links lets you to create a link to the actual file. i.e. The link created will point to the file that is present at different location.

Ex:

[oracle@localhost dbs]$ ln -s $ORACLE_BASE/admin/PROD/pfile/initPROD.ora initPROD.ora

In the above example, a symbolic link is created in the 'dbs' folder that will actually point to the initPROD.ora file present at different location. Advantage is that you keep seperated the init files from where the software is present.

i.e [oracle@localhost dbs]$ ln -s {source} {destination}

Database Cloning (Hot backup)

See that the source database is shutdown, and add these parameters in source init file

log_archive_dest=
log_archive_format="log_s%_t%_r.arc"

1) Set the source database in archive log mode;
a) startup pfile=
b) alter database archivelog;

2) To see whether the source database is in archive log mode or not
select log_mode from v$database;

3) Set each tablespace in backup mode and copy all the datafiles needed and end backup mode
alter tablespace begin backup;
cp
alter tablespace end backup;

4) To see what tablespaces you have in ur database
select * from v$tablespace;

Command to create archive logs in source database:
alter system switch logfile; [database should be open]

alter system archive log current;

5) Make a copy of the init.ora and make changes to parameters and save it as init.ora [needed for destination database]

6) Create a control file from the source database
alter database backup controlfile to trace; [stores trace file to udump, if specified in init.ora of source i.e. udump_file_dest]
[OR]
alter database backup controlfile to trace as /u02/.../.../create_control.sql;

7) Use Set#2 i.e ResetLogs option. Delete all the lines related to Set#1 and the script should contain only lines related to create control file.
a) Startup nomount pfile=
b) Create control file set database
c) Delete all the commented lines
d) Save the trace file as .sql file

8) Add the destination database entry in oratab(/var/opt/oracle)

9) Use the destination instance

10) Run the script generated by step 7

11) Control file will be generated

12) Now, apply archive logs of source database
recover database using backup controlfile until cancel;

13) alter database open resetlogs;

14) Above step will open the database in resetlogs mode and creates a new Global database name

15) Reuse the temp file
alter tablespace temp add tempfile 'copied location' reuse;

16) select * from dba_temp_files;

Perform a few checks
If the last couple of steps went smoothly, the database should be open. It is advisable to perform a few checks at this point:


Check that the database has opened with:
select status from v$instance;
The status should be 'OPEN'

17) Make sure that the datafiles are all ok:
select distinct status from v$datafile;
It should return only ONLINE and SYSTEM.


18) Take a quick look at the alert log too.


19) Set the databases global name
The new database will still have the source databases global name. Run the following to reset it:

alter database rename global_name to
/
Note. no quotes!


20) Create a spfile
From sqlplus:
create spfile from pfile;

21) Change the database ID
If RMAN is going to be used to back-up the database, the database ID must be changed. If RMAN isn't going to be used, there is no harm in changing the ID anyway - and it's a good practice to do so.

From sqlplus:

shutdown immediate
startup mount
exit
From unix:

nid target=/
NID will ask if you want to change the ID. Respond with 'Y'. Once it has finished, start the database up again in sqlplus:

shutdown immediate
startup mount
alter database open resetlogs
/

22 )Configure TNS
Add entries for new database in the listener.ora and tnsnames.ora as necessary.

23) Finished

Database Cloning (Cold backup)

1) Copy all tha datafiles, redo files from source database to a different location

2) Make a copy of the init.ora and make changes to parameters and save it as init.ora

3) Startup the source database

3) Create a control file from the source database
alter database backup controlfile to trace; [stores trace file to udump, if specified in init.ora]
[OR]
alter database backup controlfile to trace as /u02/.../.../create_control.sql;

4) Shutdown the source database

5) Add the destination database entry in oratab(/var/opt/oracle)

6) Edit the control file that is generated as a trace file in step 3

7) Use Set#2 i.e ResetLogs option. Delete all the lines related to Set#1 and the script should contain only lines related to create control file.
a) Startup nomount pfile=
b) Create control file set database
c) Delete all the commented lines
d) Save the trace file as .sql file

8) Use the destination instance

9) Run the script generated by step 7

10) Control file will be generated

11) alter database open resetlogs;

12) Above step will open the database in resetlogs mode and creates a new Global database name

Wednesday, December 10, 2008

Upgrade Database

Steps to upgrade your database:

1) Check to see that no processes are running currently
ps -ef | grep pmon

2)Shutdown the processes that are running

3) sqlplus / as sysdba

4) startup upgrade

5)@?/rdbms/admin/catupgrd.sql

6)shutdown immediate

7)startup

8)@?/rdbms/admin/utlrp.sql

9)Upgrade completed

Upgrading Oracle Software

Steps to be performed to upgrade your Oracle software:

1) Check to see that no processes are running currently
ps -ef | grep pmon

2)Shutdown the processes that are running

3) unzip the folder of the upgrade

4)Execute runInstaller

5)Upgrade completed

Applying Patches to Oracle

Follow these steps to apply patches to Oracle software:

1) Check to see that no processes are running currently
ps -ef | grep pmon

2)Shutdown the processes that are running

3)unzip the patch you had downloaded

4)Go to the unzipped folder and apply the patch
/u01/app/oracle/product/10.2.0/db_1/OPatch/opatch apply

5)To check the patch applied
/u01/app/oracle/product/10.2.0/db_1/OPatch/opatch lsinventory

Oracle 10g Silent Installation

Command to install Oracle 10g database using response file:

$/runInstaller -silent -noconfig -responseFile

NOTE: Response files can be found in $ORACLE_HOME/assistants/dbca/templates folder

Database Silent Installation Using Response File

Path of templates for dbca: $ORACLE_HOME/assistants/dbca/templates/

Use either of the three commands to create database in Oracle 10g using dbca silent installation:

1. dbca -progress_only -responseFile
## Display a progress bar depicitng progress of database creation process. ##

2. dbca -silent -responseFile
## Creates database silently. No user interface is displayed. ##

3. dbca -silent -createDatabase -cloneTemplate -responseFile
## Creates database silently with clone template. The template in reponsefile is a clone template ##

Database Creation Script

This is a sample script to create a database in Oracle 10g. Before you use this script, make sure you have the initialization parameter file (init.ora) or server parameter file (spfile)

SQL> startup nomount pfile= #if using pfile

(or) SQL> startup nomount #if using spfile

SQL> create database test
logfile group 1 ('/optware/oradata7/suresh/files/redofiles/redo01.log') size 10M,
group 2 ('/optware/oradata7/suresh/files/redofiles/redo02.log') size 10M,
group 3 ('/optware/oradata7/suresh/files/redofiles/redo03.log') size 10M
character set WE8ISO8859P1
national character set utf8
datafile '/optware/oradata7/test/files/system.dbf'
size 200M
autoextend on
next 10M maxsize unlimited
extent management local
sysaux datafile '/optware/oradata7/test/files/sysaux.dbf'
size 200M
autoextend on
next 10M
maxsize unlimited
undo tablespace undo
datafile '/optware/oradata7/test/files/undo.dbf'
size 200M
default temporary tablespace temp
tempfile '/optware/oradata7/test/files/temp.dbf'
size 200M;

SQL> @?/rdbms/admin/catalog.sql # '?' represents ORACLE_HOME
SQL> @?/rdbms/admin/catproc.sql

catalog.sql creates the data dictionary. catproc.sql creates all structures required for PL/SQL.

The user system might also want to run ?/sqlplus/admin/pupbld.sql. pupbld.sql creates a table that allows to block someone from using sql plus.

SQL> connect system/manager
SQL> @?/sqlplus/admin/pupbld

Tuesday, December 9, 2008

Welcome Message

A warm welcome to all the new members.

This blog is intended for audience who want to share their knowledge, experience, and get some help in Oracle Database Administration. This blog will help us to share knowledge and communicate well with others in this subject. You are welcome to drop any comment or suggestion.

Thanks & Regards,
Vinay