You are on page 1of 187

Oracle Database Maintenance Training

Integrated Product Dept.


Oracle Architecture
Objectives
After learning this part, you will be expected to learn:

Describe the architecture and main components of an


Oracle server;
List the structures involved in establishing a connection to
Oracle instances
Cluster mode: RAC/HOT STANDBY

3
List of Main Components

Instance
Client process
Shared pool SGA

Library cache
Redo
Database Buffer
Data dict. log buffer
Cache
Server process cache

PMON SMON DBWR LGWR CKPT Others


Program global area

Parameter file Data file Control file Redo data File log file
file

Password file
Database

4
Oracle Server

One Oracle server:


Oracle server
Is a database management system that
provides open, exhaustive and
comprehensive management services;
Consists of an Oracle database and an
Oracle instance

5
Oracle Instance

An Oracle instance:
A basic way of access to the Oracle database
Always opens and uses only one database at a time
Consists of the memory structure and the background processes

Instance

Shared pool SGA


Memory structure
Library cache
Database Redo log
Data Dict. buffer cache buffer cache
cache
Background process
PMON SMON DBWR LGWR CKPT Others

6
Create a Connection and Session

Create a connection Server process

Create a session

User process Oracle server

Database user

7
Oracle Database

Oracle database:
Is data set treated as a unit
Consists of three file types

Oracle database

Data Control Redo log Archived log file


Parameter file file file file

Password file

8
Physical Structure

The physical storage of an Oracle database is dependent


on actual operating system files:

Control files

Title
Data files Control
files
Data files
Redo log files (including data
Online redo
dictionary)
log files

9
Memory Structure

The Oracle memory consists of the following two areas:

System global area (SGA): a basic element in the Oracle instance


allocated on system startup

Program global area (PGA): allocated while the server process is


starting

10
System Global Area (SGA)

The system global area (SGA) consists of the following


memory areas:
Shared pool
Database Buffer Cache
Redo log buffer cache
Two optional memory structures can be configured
within the SGA:
Large pool
JAVA pool

11
SGA

The upper limit of the SGA size is based on the value of


SGA_MAX_SIZE.
The principles of SGA allocation rely on its components:
Contiguous virtual memory allocation
Allocation size is based on the parameter SGA_MAX_SIZE

12
Shared Pool
The shared pool is used to store the most recently
executed SQL statements and the most recently used data
definitions.
It consists of mainly of two memory structures:
Library cache
Data dictionary cache
Its size is determined by the value of the parameter
Shared pool
SHARED_POOL_SIZE.
Library
cache
ALTER SYSTEM SET Data dictionary
SHARED_POOL_SIZE = 64M; cache

13
Library Cache

The library cache stores the most recent SQL and PL/SQL
statements:
It allows commonly used statements to be shared
It is managed by LRU (least recently used) algorithm
It consists of two structures:

Shared SQL area


Shared PL/SQL area
Their respective size is determined by the shared pool internally

14
Data Dictionary Cache

Data dictionary cache is a set defined as the most frequently objects


in the database.
It consists of such information as data filename, table, index, column, user
privilege and other database objects.
During the parsing, the server process will look up the data dictionary to
obtain information about relation objects permitted for access.
The information in the data dictionary cached in the memory area helps
quicken the response to data inquiry.
Its size is determined by the size of the shared pool.

15
Database Buffer Cache

The database buffer cache stores the copies of data blocks previously
extracted from the data file.

When you get or modify data, this buffer cache helps improve the
performance.
It is managed by LRU algorithm.
DB_BLOCK_SIZE determines the primary block size.

Database buffer
cache

16
Database Buffer Cache

It consists of independent sub-caches:


DB_CACHE_SIZE
DB_KEEP_CACHE_SIZE
DB_RECYCLE_CACHE_SIZE

The database buffer cache can be resized dynamically.


ALTER SYSTEM SET DB_CACHE_SIZE = 96M;

DB_CACHE_ADVICE can be configured to collect


statistics used to predict the size of different caches.

17
Redo Log Buffer Cache

The redo log buffer cache contains all the changes made
to data blocks.
This cache is primary used for recovery.
The records can be used to redo changes.
Its size is defined by LOG_BUFFER.

Redo log
buffer cache

18
Large Pool

As an optional storage area in the SGA, the large pool is only


configured on a shared server.
It helps relieve the burn on the shared pool.
It is used for operations like UGA, backup and recovery.
It does not use LRU algorithm.
Its size is determined by the value of LARGE_POOL_SIZE.

ALTER SYSTEM SET LARGE_POOL_SIZE = 64M;

19
Java Pool

Java pool is intended to release Java commands:

It is required if installing and using Java.

It is stored in database tables a way very similar to PL/SQL.

Its size depends on the value of the JAVA_POOL_SIZE parameter.

20
Program Global Area

PGA is an area allocated for every user process to connect the Oracle database.

PGA Dedicated server Shared server


Server
process Session information
Stack sort area, cursor Stack sort area, cursor
space information space information

User SGA SGA


process
Session
information

Shared SQL areas Shared SQL areas

21
Process Structure

As a program, the Oracle process performs a series of steps or a specific


task depending on the information type it requires.

User process: It gets started when a database user requires a


connection to the Oracle server.
Server process: Connect Oracle instance, started when the user
establishes a session.
Background process: Used when Oracle instance gets started.

22
User Process

The user process requires interaction between Oracle servers:


It must set up a connection first.
It does not interact with the Oracle server directly

Server
process
User
process
Connection
established

Database user

23
Service Process

A service process is a program that directly interacts with the Oracle server.

In response to user requests, it makes a call to the server, and returns the
result to the user.
A session can be created in either the dedicated or shared server mode.

Server
process
Connection
established Session created

User Oracle server


process

Database user

24
Background Processes

The relationship between the physical and memory


structures is maintained and enforced by Oracles background
processes.
Mandatory background processes
DBWn PMON CKPT
LGWR SMON RECO
Optional background processes
ARCn LMON Snnn
QMNn LMDn
CJQ0 Pnnn
LCKn Dnnn

25
Database Writer

DBWn begins to write:


Instance
Checkpoint implementation
SGA
The number of dirty blocks
Database reaches a threshold value.
buffer The cache has no free space
cache
Timeout
DBWn AC connection request
Tablespace offline
Tablespace in ready only mode
Data Control Redo log Dropping or Truncating a table
files files files
Tablespace BEGIN BACKUP
Database

26
Log Writer

Instance
SGA
LGWR begins to write:
Redo log When a transaction
buffer commits
When one third of the
DBWn LGWR buffer cache is full
When there is an 1MB
log
Data
files
Control
files
Redo log
files
Every 3 seconds
Before DBWn writes
Database

27
System Monitor Process
Instance Used for:
Instance recovery:
SGA
Rolling forward changes
made to the log file
Opening the database
so that users can log on
Rolling back
SMON uncommitted
transactions
It coalesces free space every 3
Data Control Redo log seconds
files files files It de-allocates temporary
segments
Database

28
Process Monitor
Instance
SGA
Clean up after failed
processes by:
Rolling back a transaction
Releasing a lock
Freeing other resources
PMON
Restarting dead
dispatches

PGA area

29
Checkpoint

Instance Used for:


SGA Sending signals to
Redo Log
DBWn
Buffer Modifying data file
block headers
DBWn
DWW0 LGWR
LGWR CKPT
Modifying control
file information
Data Control Redo log
files files files

30
Archiver Process

An optional background process


Automatically archiving online redo log files when
ARCHIVELOG mode is configured
Saving all database changes

ARCn
ARCn
Data Control Redo log Archived
files files files Redo log
files

31
Logical Structure

An Oracle logical structure hierarchy describes how the physical space of


a database is used, including tablespaces, segments, extents and blocks.

Tablespace
Data file
Segment Segment

Extent Blocks

32
RAC Mode

Schematic Diagram

33
RAC Mode

Advantages
Good scalability
High availability
State-of-the-art Cache Fusion technology
Lower hardware cost
Brief switching
Disadvantages
Difficult to manage
High demand on the network

34
HOTSTANDBY (Failover)

Schematic Diagram

35
HOTSTANDBY( Failover)
Advantages
Easy to manage
Running steadily
Disadvantages
Lengthy switching
During system switching, the database connection
between the client and the server will go down, and
thus a reconnection attempt is required.
The standby system is idle, making it impossible to
achieve a load balance.

36
Summary

After learning this part, you are expected to know:


Database file: Data file, control file, online redo log
SGA memory structure: Database Buffer Cache, shared pool, redo
log buffer cache.
Main background processes:
DBWn, LGWR, CKPT, PMON, SMON, and ARCn
Cluster: RAC/HOT STANDBY

37
Managing Tablespaces and Data Files
Objectives

After learning this part, you are expected to know:


Logical structure of the database
Create tablespace
Resize the tablespace
Allocate space for temporary segments
Change the status of tablespace
Change tablespace storage parameter settings

39
Overview

Database

Data Control Redo log


files files files

40
Database Architecture

Database

Tablespace Data file

Logically Segment Physically

Extent

Oracle
OS block
block

41
System and Non-System Tablespaces

System tablespace:
Created with the database
Contains the data dictionary
Contains the SYSTEM undo segment
Non-System Tablespaces:
Different segments stored separately (e.g., undo
segments, temporary segments, application data)
Control the amount of space allocated to users objects

42
Tablespace Management
Locally managed tablespaces:
Free extents are contained in their own bitmap
Each bit in the bitmap corresponds to a block or a group of
blocks
Flag bit in the bitmap shows the free or used status of
blocks.
Dictionary-Managed Tablespaces:
Default tablespace management method
Free extents recorded in the data dictionary

43
Locally Management Tablespaces

CREATE TABLESPACE userdata


DATAFILE '/u01/oradata/userdata01.dbf' SIZE 500M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 256K;

Simplifying the content contained in the data dictionary


Space allocation and recycle do not generate undo
information
Eliminating the need to coalesce adjacent extents

44
Dictionary Managed Tablespaces

CREATE TABLESPACE userdata


DATAFILE '/u01/oradata/userdata01.dbf' SIZE 500M
EXTENT MANAGEMENT DICTIONARY
DEFAULT STORAGE ( initial 1M NEXT 1M );

Extents are managed in the data dictionary


Each segment stored on the tablespace can have
different storage parameters
Required to coalesce adjacent extents

45
Undo Tablespace

Used to restore undo information


Cannot contain other objects
Extents managed locally
DATAFILE and EXTENT MANAGEMENT are only limited to
creation

CREATE UNDO TABLESPACE undo1


DATAFILE '/u01/oradata/undo101.dbf' SIZE 40M;

46
Temporary Tablespaces

Used for sorting


Cannot contain fixed objects
Local tablespace management is preferred.
CREATE TEMPORARY TABLESPACE temp
TEMPFILE '/u01/oradata/temp01.dbf' SIZE 500M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 10M;

47
Restrictions on Default Temporary Tablespaces

You cannot:
Drop the default temporary tablespace until after a new
default is made available
Take the default temporary tablespace offline.
Can not change the default temporary tablespace to a
permanent tablespace

48
Drop Tablespace

Remove a tablespace from the data dictionary


Use AND DATAFILES to drop a tablespace data file from the
operating system:

DROP TABLESPACE userdata


INCLUDING CONTENTS AND DATAFILES;

49
Resize Tablespaces

Increase data files


Resize a data file:
Automatically
Manually

Tablespace APP_DATA

100M
100M 200M
100M
app_data_01.dbf app_data_02.dbf app_data_03.dbf

50
Manually Resize Data Files

ALTER DATABASE
DATAFILE '/u03/oradata/userdata02.dbf'
RESIZE 200M;

Tablespace APP_DATA

100M
100M 200M 200M
100M

app_data_01.dbf app_data_02.dbf app_data_03.dbf app_data_04.dbf

51
Add a Data File to the Tablespace

ALTER TABLESPACE app_data


ADD DATAFILE '/u01/oradata/userdata03.dbf'
SIZE 200M;

Tablespace APP_DATA

100M 100M 200M


100M
app_data_01.dbf app_data_02.dbf app_data_03.dbf

52
Move Data Files (Modify Tablespace)

The tablespace must be online.


The destination data file must be present.

ALTER TABLESPACE userdata


RENAME
DATAFILE '/u01/oradata/userdata01.dbf'
TO '/u01/oradata/userdata01.dbf';

53
Obtain Tablespace Information

Tablespace info:
DBA_TABLESPACES
V$TABLESPACE
Data file info:
DBA_DATA_FILES
V$DATAFILE
Temporary file info:
DBA_TEMP_FILES
V$TEMPFILE

54
Summary

After learning this part, you are expected to know:


How to store data separately using tablespaces
Resize tablespaces:
Add data files
Extend data files
Use locally managed tablespaces
Use temporary tablespaces

55
Practice

The practice in this part covers the following:


Create tablespaces
Resize tablespaces
Please refer to Oracle Database Hands-on Practice
Tablespace Management

56

56
Managing Redo Log Files
Objectives

After learning this part, you are expected to know:


The functions of an online redo log file
The structure of an online redo log file
Control log files switching and checkpoint
implementation
Multiplex online redo log files

58
Use the Redo Log Files

Redo log files record all data changes and provide the means to redo
transactions in the event of a database failure.
Manage redo log files in groups.
An Oracle database requires a minimum of two groups of redo log files.
Each log file in the group is called a group member.

Database

Redo log
files

59
Structure of a Redo Log File

Group 1 Group 2 Group 3


Disk 1

Member Member Member

Member Member Member Disk 2

60
How Redo Logs Work

Redo logs are used in a cyclic fashion.


When the current online redo log group is filled, LGWR
begins writing to the next group.
This is called a log switch.
Checkpoint is triggered.
Related information is written into control files.

61
Forcing Log Switches and Checkpoints

Force a log switch using the command ALTER SYSTEM


SWITCH LOGFILE.
A checkpoint can be forced using:
FAST_START_MTTR_TARGET parameter
ALTER SYSTEM CHECKPOINT command

ALTER SYSTEM CHECKPOINT;

62
Adding Redo Log Groups

ALTER DATABASE ADD LOGFILE GROUP 3


('$HOME/ORADATA/u01/log3a.rdo',
'$HOME/ORADATA/u02/log3b.rdo')
SIZE 1M;

log1a.rdo log2a.rdo log3a.rdo

log1b.rdo log2b.rdo log3b.rdo

Group 1 Group 2 Group 3

63
Adding Online Redo Log Group Members

ALTER DATABASE ADD LOGFILE MEMBER


'$HOME/ORADATA/u04/log1c.rdo' TO GROUP 1,
'$HOME/ORADATA/u04/log2c.rdo' TO GROUP 2,
'$HOME/ORADATA/u04/log3c.rdo' TO GROUP 3;

log1a.rdo log2a.rdo log3a.rdo


log2a.rdo
log1b.rdo log2b.rdo log3b.rdo
log2c.rdo
log1c.rdo log2c.rdo log3c.rdo

Group 1 Group 2 Group 3

64
Dropping a Redo Log Group

ALTER DATABASE DROP LOGFILE GROUP 3;

log1a.rdo log2a.rdo log3a.rdo

Group 1 Group 2 Group 3

65
Dropping an Online Redo Log Group Member

ALTER DATABASE DROP LOGFILE MEMBER


'$HOME/ORADATA/u04/log3c.rdo';

log1a.rdo log1a.rdo

log1b.rdo log1b.rdo

log1c.rdo log2c.rdo

Group 1 Group 2

66
Clearing, Relocating or Renaming Online Redo Log Files

Clear an online redo log file:

ALTER DATABASE CLEAR LOGFILE '$HOME/ORADATA/u01/log2a.rdo';

The relocation or renaming of the online redo log files


can be changed by adding new log files and dropping
the old log files

67
Obtaining Log Group and Member Information

Obtaining log group and member information by querying the


following data dictionaries
V$LOG
V$LOGFILE

68
Archived Redo Log Files

Filled online redo log files can be archived.


There are two advantages of archiving online redo log files:
Restore: If the database is configured to run in ARCHIVELOG mode,
inactive groups of filled online redo log files must be archived. Because
all changes made to the database are recorded in the online redo log
files, the database administrator can use the physical backup and the
archived online redo log files to recover the database without losing any
committed data.
Backup: Performed when the database is open.
A default database is created in NOARCHIVELOG mode.

69
Archived Log Files

Archived logs can be obtained from ARCn or by manually archiving


SQLs.
A control file contains archived log name, log sequence number, the
highest and lowest SCNs.
A filled online log file cannot be reused until a checkpoint occurs,
and the online log file is archived by ARCn. Otherwise, please wait.
Archived log files can be multiplexed.

70
Summary

After learning this part, you are expected to know:


The use of online redo log file
How to obtain online redo log files
Control log switch and checkpoint
Manage multiple online redo log files in redundant mode

71
Practice

The practice in this part covers:


Create and add a redo log file group and its members.
Delete a redo log file group and its members.
Please refer to Oracle Database Hands-on Practice
Manage Redo Log Files

72
Managing Users and Privileges
Objectives

After learning this part, you are expected to know:


Create a database user
Modify and delete an exiting user
Monitor existing user information
Identify system and object privileges
Grant and revoke privileges

74
Database Schema

A schema is a named collection of


objects Schema Objects
Tables
When a user is created, a
corresponding schema is created Triggers
for that user. Constraints
A user can be associated only with Indexes
a schema of the same name. Views
Sequences
Username and schema are used
interchangeably Stored program units
Synonyms
User-defined data types
Database links

75
About Creating a User

Determine in which tablespace the user needs to store objects


Determine the maximum amount of space the user can use in
each tablespace.
Allocate default tablespace and temporary tablespace.
Create a user.
Grant privileges and roles to users.

76
Creating a User: Database Level Identification

Set an initial password:

CREATE USER aaron


IDENTIFIED BY soccer
DEFAULT TABLESPACE data
TEMPORARY TABLESPACE temp
QUOTA 15m ON data
PASSWORD EXPIRE;

77
Dropping a User

DROP USER aaron;

Drop a user and all objects in the schema using


CASCADE option.

DROP USER aaron CASCADE;

A user who is currently connected to the Oracle server


cannot be dropped.

78
Obtaining User Information

Use the following query to obtain user information.


DBA_USERS
DBA_TS_QUOTAS

79
System Privileges

More than 100 privileges


ANY means privileges in any schema
GRANT is used to grant privileges
REVOKE is used to revoke privileges

80
System Privileges: Examples

Category Examples
INDEX CREATE ANY INDEX
ALTER ANY INDEX
DROP ANY INDEX
TABLE CREATE TABLE
CREATE ANY TABLE
ALTER ANY TABLE
DROP ANY TABLE
SELECT ANY TABLE
UPDATE ANY TABLE
DELETE ANY TABLE
SESSION CREATE SESSION
ALTER SESSION
RESTRICTED SESSION
TABLESPACE CREATE TABLESPACE
ALTER TABLESPACE
DROP TABLESPACE
UNLIMITED TABLESPACE

81
Granting System Privileges

GRANT CREATE SESSION TO emi;

GRANT CREATE SESSION TO emi WITH ADMIN OPTION;

82
Revoking System Privileges

REVOKE CREATE TABLE FROM emi;

83
Granting Object Privileges

GRANT EXECUTE ON dbms_output TO jeff;

GRANT UPDATE ON emi.customers TO jeff WITH GRANT


OPTION;

84
Revoking Object Privileges

REVOKE SELECT ON emi.orders FROM jeff;

85
Obtaining Privileges Information

Query data dictionaries


DBA_SYS_PRIVS
SESSION_PRIVS
DBA_TAB_PRIVS
DBA_COL_PRIVS

86
Summary

After learning this part, you are expected to know:


Specify an appropriate password mechanism while
creating users
Control the amount of space used by users
Control system and object privileges

87
Practice

The practice in this part covers the following:


Create a user
Display the information on user from the data dictionary
Remove users tablespace quota
Please refer to Oracle Database Hands-on Practice
Managing Users and Privileges

88
Managing an ORACLE Instance
Objectives

After learning this part, you are expected to know:


Create and manage initialized parameter files
Start and close instances
Monitor and use diagnostic files

90
Initialization Parameter Files

Oracle Instance

Shared pool SGA


Library
cache Data buffer Redo log
Data dict. cache buffer
cache

PMON SMON DBW0 LGWR CKPT Others

spfiledb01.ora

SQL> CONNECT / AS SYSDBA


SQL> STARTUP

91
Initialization Parameter Files

Instance access entry


There are two types of parameters:
Explicit: There is an entry in the file
Implicit: There is no entry in the file, but it is assigned a default
value
Different initialization files can be used in different environments to
optimize the execution of a single database.
Changing parameter settings in a file and validating the change
depend on the type of initialization parameter file.
Static initialization parameter file (PFILE)
Persistent initialization parameter file (SPFILE)

92
PFILE
initSID.ora

The PFILE is a text file that can be maintained using a


standard operating system editor.
Modify the file manually.
The modification will take effect the next time when the
database is started.
The default path is $ORACLE_HOME/dbs.

93
An Example of PFILE
# Initialization Parameter File: initdb01.ora
db_name = db01
instance_name = db01
control_files = ( /u03/oradata/db01/control01db01.ctl,
/u03/oradata/db01/control02db01.ctl)
db_block_size = 4096
db_block_buffers = 500
shared_pool_size = 31457280 # 30M Shared Pool
db_files = 1024
max_dump_file_size = 10240
background_dump_dest = /u05/oracle9i/admin/db01/bdump
user_dump_dest = /u05/oracle9i/admin/db01/udump
core_dump_dest = /u05/oracle9i/admin/db01/cdump
undo_management = auto
undo_tablespace = undtbs
...

94
SPFILE
spfileSID.ora

The SPFILE file is a binary file in which the modification can take
effect without the need of restarting the database.
The file resides on the ORACLE server side.
The ALTER SYSTEM command can be used to change the value of
parameters directly.
It can determine whether the modification will take effect
temporarily in the memory or the modification will take effect
persistently from now on.
Modified values can be deleted and reset to default value of
instances.

ALTER SYSTEM SET undo_tablespace = 'UNDO2';

95
Creating an SPFILE File

An SPFILE is created from an initSID.ora file using the CREATE


SPFILE command. This can be executed before or after the
database is open.

CREATE SPFILE FROM PFILE;

96

96
An Example of SPFILE

*.background_dump_dest='$ORACLE_HOME/admin/db01/bdump'
*.compatible='9.0.0'
*.control_files='/u03/oradata/db01/ctrl01db01.ctl','/u03/oradata/db01/ctrl02db01.ctl'
*.core_dump_dest='$ORACLE_HOME/admin/db01/cdump'
*.db_block_buffers=500
*.db_block_size=4096
*.db_files=40
*.db_name='db01'
*.instance_name='db01'
*.remote_login_passwordfile='exclusive'
*.shared_pool_size=31457280 # 30M Shared Pool
*.undo_management='AUTO'
db01.undo_tablespace='UNDOTBS01'
db02.undo_tablespace='UNDOTBS02'
...

97
Starting Up a Database
NOMOUNT

OPEN
STARTUP

MOUNT

NOMOUNT

Starting the
Instance
SHUTDOWN
SHUTDOWN

98
Starting Up a Database
MOUNT

OPEN
STARTUP

MOUNT

Opening the
Control File
NOMOUNT

Starting the
Instance
SHUTDOWN
SHUTDOWN

99
Starting Up a Database
OPEN

OPEN
STARTUP Opening All Files Described in
the Control File of the Instance
MOUNT

Opening the
Control File
NOMOUNT

Starting the
Instance
SHUTDOWN
SHUTDOWN

100
STARTUP Command

Start up an instance and open a database:

STARTUP

STARTUP PFILE=$ORACLE_HOME/dbs/initdb01.ora

101
The ALTER DATABASE Command

Change the Status of the Database (UNMOUNT TO MOUNT):

ALTER DATABASE db01 MOUNT;

Open an database:
ALTER DATABASE db01 OPEN;

102
Shutting Down the Database

Shutdown mode A I T N
Allowing new access x x x x
Waiting till all current sessions are terminated
x x x o
Waiting till all current transactions are terminated
x x o o
Forced execution of checkpoint and closing all files
x o o o

Shutdown Mode:
NORMAL
x NO
TRANSACTIONAL
o YES
IMMEDIATE
ABORT

103
Shutting Down an Object

During a
Shutdown Normal,
Shutdown Transactional
In this shutdown mode: or After that, restarting
Shutdown Immediate
the database:
Data block buffer
content written into Instance recovery
data file not required
Un-submitted
transactions rolled
back
Resource released

Consistent Database
(Clean Database)

104
Shutting Down an Object

During a
Shutdown Abort
After that, restarting the
or database:
In this shutdown mode: Instance Failure
or
Startup Force Modified information is
Modified data block
written to the redo log
buffer content are not
file
written into data file
Uncommitted changes
Uncommitted
must be rolled back with
transactions are not
the rollback segment
rolled back
Resource released

Inconsistent Database
(Dirty Database)

105
Managing Instances by Checking Diagnostic Files

A diagnostic file covers the information of important events


that occurred while an instance is running.
Diagnostic files are the basis for daily management of
databases and help solve problems.
There are following types of diagnostic files:
Alert log file (alertSID.log)
Background trace file
User trace file

106
Alert Log File

The alert log file keeps a record of some operating


commands and results of major events while the database
is running.
It is used for diagnosis of error messages in daily database
running.
Each file has corresponding timestamp information.
Its path is defined in the initialization parameter
BACKGROUND_DUMP_DEST.

107
Background Trace File

The background trace file keeps a record of error messages


detected by background processes.
The background trace file is created only when the
background process detects an error.
Its path is defined in the initialization parameter
BACKGROUND_DUMP_DEST.

108
User Trace File

The user trace file is created when user process is connected to the
Oracle server through the server process.
A user trace file contains traced SQL statements or user
communication error messages.
A user trace file is created when an error occurs during a user
session.
Its path is defined in the initialization parameter USER_DUMP_DEST.
It size is defined in the parameter MAX_DUMP_FILE_SIZE and the
default value is 10M.

109
Opening or Closing a User Trace File

The following commands and parameters can be used to open or close a


user trace file at the session or instance level:
At the session level, use the ALTER SESSION command: ALTER
SESSION SET SQL_TRACE = TRUE
At the session level, execute the DBMS package:
dbms_system.SET_SQL_TRACE_IN_SESSION
At the instance level, set the following parameter in the initialization file:
SQL_TRACE = TRUE

110
Summary

After learning this part, you are expected to know:


How to create and manage initialization parameter files
How to start up and shut down instances and databases
How to monitor and use diagnostic files

111
Practice

The practice in this part covers the following:


Creating an SPFILE file
Starting up and shutting down an database in different
ways
Please refer to Oracle Database Hands-on Practice.
Classroom practice- Managing an Oracle Instance

112

ctice
112
Introduction to the Use of SQL*Plus
Objectives

After learning the course, you shall learn:


How to log in to the SQL*Plus environment
How to edit SQL commands
How to format SQL*Plus commands and output results
Execute with scripts

114
Main Contents of SQL*Plus

Log in to SQL*Plus.
Describe table structure.
Edit SQL statements.
Execute SQL in the SQL*Plus.
Save or insert SQL statements to or into a file

115
Logging In to SQL*Plus

Through a Windows environment:

Through a command line environment:

sqlplus [username[/password
[@database]]]

116
Displaying Table Structure

SQL> DESCRIBE departments

Name Null? Type


----------------------- -------- ------------
DEPARTMENT_ID NOT NULL NUMBER(4)
DEPARTMENT_NAME NOT NULL VARCHAR2(30)
MANAGER_ID NUMBER(6)
LOCATION_ID NUMBER(4)

117
SQL*Plus Editing Commands

A[PPEND] text
C[HANGE] / old / new
C[HANGE] / text /
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n

118
SQL*Plus Editing Commands

I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
n text
0 text

119
Using LIST, n, and APPEND

SQL> LIST
1 SELECT last_name
2* FROM employees

SQL> 1
1* SELECT last_name

SQL> A , job_id
1* SELECT last_name, job_id

SQL> L

1 SELECT last_name, job_id


2* FROM employees

120
Using the CHANGE Command

SQL> L
1* SELECT * from employees

SQL> c/employees/departments
1* SELECT * from departments

SQL> L
1* SELECT * from departments

121
SQL*Plus File Commands

SAVE filename
GET filename
START filename
@ filename
EDIT filename
SPOOL filename
EXIT

122
Using the SAVE and START Commands

SQL> L
1 SELECT last_name, manager_id, department_id
2* FROM employees
SQL> SAVE my_query

Created file my_query

SQL> START my_query


LAST_NAME MANAGER_ID DEPARTMENT_ID
------------------------- ---------- -------------
King 90
Kochhar 100 90
...
20 rows selected.

123
Summary

In the SQL*Plus environment:


Execute SQL statements
Edit SQL statements
Format and output
Interact with script files

124
Exercise

The practice in this part covers the following:


Please refer to Oracle Database Hands-on Practice
Classroom Practice - Sqlplus Utility

125
Introduction to Logical Backup and Recovery
Objectives

Concept of logical backup


Tools used in logical backup of Oracle database
Forms of logical backup of Oracle database

127
Database Backup and Recovery
Two backup modes for ORACLE database:
Physical backup: It supports full recovery of database, but the database
must run in archivelog mode. Moreover, the backup is rather complicated,
and it requires the assistance of the recovery manager RMAN in backup
and recovery as well as mass external storage devices, for example, tape
library.
Logical backup: It does not require that the database run in the archivelog
mode. The backup work is simple, and no mass external storage devices
are required.
Logical backup of ORACLE database consists of three modes: table mode,
user mode, and full-database mode.
Closely related to backup, the recovery also consists of three modes: table
mode, user mode, and full-database mode.

128
Backup Tools

Backup Tool
EXPORT (Using the EXP command)
Recovery Tool
IMPORT (Using the IMP command)

129
Database Backup and Recovery
EXPORT Backup
In principle, the version of the backup program and recovery program (exp
and imp) must be same with the version of Server. We recommend the
backup shall be performed on the Server to ensure the consistency of
character set and software version. The following sample backup and
recovery statements directly run on the database server.
The backup or recovery operation cannot happen at the time when any
timing task of the database is going on; otherwise, the contention of
rollback segment or temp segment may lead to the failure of backup or
recovery operation.
We recommend that the backup operation be performed on the time when
the system is not busy to avoid the period when database writing
operations are frequent, for example, the backup operation can be
performed at 2:00 in the morning.

130
The Export Command

Syntax
exp keyword = (value, value2, ,valuen)

Example
exp hr/hr TABLES=(employees,departments) rows=y
file=exp1.dmp

exp system/manager OWNER=hr direct=y


file=expdat.dmp

exp system/manager TRANSPORT_TABLESPACE=y


TABLESPACES=(ts_emp) log=ts_emp.log

exp system/manager FULL=y inctype=cumulative


file=expcum1.dmp

131
Database Backup and Recovery

Table Mode
Table mode is used to back up a designated object in a certain user
mode (such as table, index, constraint, and so on).
To back up the object to the local hard disk of the host, use the
following command:
exp ring/ring rows=y indexes=n compress=n buffer=1024000
direct=y feedback=100000 file=exp_ring_tables_yyyymmdd.dmp
log=exp_ring_tables_yyyymmdd.log
tables=RBT_ADMININFO,RBT_CONFIG

132
Database Backup and Recovery

User Mode
User mode is used to back up all objects under a certain
user mode.
To back up the objects to the local hard disk of the host,
use the following command:
exp ring/ring rows=y indexes=n compress=n
buffer=1024000 direct=y feedback=100000
file=exp_ring_yyyymmdd.dmp
log=exp_ring_yyyymmdd.log

133
Command Line of the Import Tool

Syntax
imp keyword = value or keyword = (value, value2, value n)

Example
imp hr/hr TABLES=(employees,departments) rows=y
file=exp1.dmp

imp system/manager FROMUSER=hr file=exp2.dmp

imp system/manager TRANSPORT_TABLESPACE=y


TABLESPACES=ts_employees

134
Database Backup and Recovery

IMPORT Recovery
Table Mode
It is to recover from the data backed up in the table
mode.
To recover from a local file, use the following command:
imp ring/ring rows=y indexes=n ignore=n commit=y
buffer=1024000 feedback=100000
file=exp_ring_tables_yyyymmdd.dmp
log=imp_ring_tables_yyyymmdd.log
tables=RBT_ADMININFO,RBT_CONFIG

135
Database Backup and Recovery

IMPORT Recovery
User Mode
It is to recover from the data backed up in the user
mode.
To recover from a local file, use the following command:
imp ring/ring rows=y indexes=n ignore=n commit=y
buffer=1024000 file=exp_ring_yyyymmdd.dmp
log=imp_ring_yyyymmdd.log

136
Database Backup and Recovery
IMPORT Recovery
The ignore parameter
During the recovery of Oracle database, if it is to recover a table that
already exists, the Oracle server will then determine the operation
according to the settings of the ignore parameter.
If ignore=y, Oracle server will not execute the CREATE TABLE
statement, and it will insert data in the table instead. If records to be
inserted are against the constraints, for example, primary key
constraint, the error record will not be inserted, but conforming
records will be added to the table.
If ignore=n, Oracle server will not execute the CREATE TABLE
statement, nor will it insert data in the table. It will ignore the table
error and recover the next table.
The indexes parameter
During data recovery, if indexes=n the indexes of the table will
not be recovered, but the unique index corresponding to the primary
key will be recovered unconditionally to ensure data integrity.

137
Database Backup and Recovery
Regular Backup of cron Scripts
Set the backup time for the cron scripts to 2:00 each morning. It will
perform backup for all application data.
Definition steps:
Assign timing task authority to an Oracle user
Execute the crontab e command as an Oracle user to add a timing
task
Create the task script exp_cron.sh in the backup directory and note
to set such environment variables as ORACLE_HOME,
ORACLE_SID and PATH
Add execution authority to exp_cron.sh
Check whether the setting is correct with the crontab l command
after modification

138
Summary

Concept of Export and Import Tools


Use of Export and Import Tools
Some Principles of Using the Export and Import Tools

139
Practice

The practice in this part covers the following:


Please refer to Oracle Database Hands-on Practice
Classroom practice- Logical backup

140
Daily Database Check
Objectives

Check Database Status


Check Database Version
View SGA
Check rollback section competition
Check Log File
Check tablespace
Check Job Status

142
Daily Database Check

Check Database Status


Confirm whether the database is in open status and provides
service normally.
oracle% sqlplus "/as sysdba"
SQL> select status, instance_role from v$instance;
STATUS INSTANCE_ROLE
------------ ------------------
OPEN PRIMARY_INSTANCE

143
Daily Database Check

Check Database Version


The database must be patched with the latest patchset;
8i requires 8.1.7.4;
9i requires 9.2.0.5 or later patch version.
SQL>select * from v$version;

144
Daily Database Check
View SGA
The sum of individual buffers in the SGA must be less than half the physical memory
of the system.
Check the SGA of the database:
SQL>show sga
Check physical memory of the system:
Solaris:
$ /usr/sbin/prtconf |grep -i "Memory size"
HP:
$ grep Physical /var/adm/syslog/syslog.log
AIX:
$ /usr/sbin/lsattr -E -l sys0 -a realmem

145
Daily Database Check
Check rollback section competition
8i: The return value must be less than 2%. If this value is excessively
high, 8i needs manual creation of more rollback segments.
SQL> select 'The average of waits/gets is '||
round((sum(waits) / sum(gets)) * 100,2)||'%'
From v$rollstat;
9i: The Nospace value must be 0. If the non-zero values exist
continuously, it is recommended that the size of the rollback tablespace
be increased.
SQL>select distinct nospaceerrcnt as nospace
From v$undostat
Where begin_time>sysdate-(1/12);

146
Daily Database Check
Check Log File
During database running, query v$log_history to observe the
switching time of the log switch.
It is recommended that the online log be better switched every one
hour at non-peak period, and be switched every 20 minutes at
service summit.
SQL>select to_char(first_time,'yyyy-mm-dd hh24:mi:ss') change_time
from v$log_history;
CHANGE_TIME
-------------------
2004-04-06 10:02:52
2004-04-06 10:10:45
2004-04-06 10:17:01

147
Daily Database Check
Check tablespace
Check such information as the size, left space and used space
percentage of each tablespace
Especially when the left space of the service tablespace is less than
50M or the used space percentage is greater than 90%, consider
increasing the size of the tablespace.
SQL> select a.tablespace_name, a.bytes totalbytes, sum(b.bytes)
freebytes
from dba_data_files a, dba_free_space b
where a.file_id = b.file_id
group by a.tablespace_name, a.bytes ;
TABLESPACE_NAME TOTALBYTES FREEBYTES
-----------------------------------------
CWMLITE 20971520 11141120

148
Daily Database Check

Check Job Status


The Broken column must be N. If the Broken column is Y, check the
oracle alarm log and analyze the job failure cause. After the fault is
cleared, run exec dbms_job.run(:job);
SQL>select job,what,to_char(next_date,yyyy/mm/dd
hh24:mi:ss),broken,failures
from dba_jobs;

149
Daily Database Check

View Users Connected to Database


View the specific information of user process connected to the
current database, including the connected database user name,
computer name, running program name, and process status.
select username,machine,program,status from v$session where osuser
<> 'oracle';
USERNAME MACHINE PROGRAM STATUS
--------------- -------------------- -------------------- --------
CORPRING CHINA\MENGWEI INACTIVE
SYSTEM CHINA\H36922 dbsnmp.exe INACTIVE

150
Summary

Check Database Status


Check Database Version
View SGA
Check rollback section competition
Check Log File
Check tablespace
Check Job Status

151
Practice

The practice in this part covers the following:


Please refer to "Oracle Database Hands-on Practice"
Classroom practice-> Daily Database Check

152
Network Configuration
Objectives

Listener Management
Local Service Name Configuration
Handle Simple Connection Faults

154
Listener Process

Client Server

Listener

tnsnames.ora

sqlnet.ora
listener.ora

155
Configuring the listener.org File

Default Configuration of listener.ora:


Listener name LISTENER
Port 1521
Protocols TCP/IP and IPC
SID name Default example
Host name Default host name

156
Example of listener.ora

1. LISTENER =
2. (ADDRESS_LIST =
3. (ADDRESS= (PROTOCOL= TCP)(Host= stc-sun02)(Port= 1521))
)
4. SID_LIST_LISTENER =
5. (SID_LIST =
6. (SID_DESC =
7. (ORACLE_HOME= /home/oracle)
8. (GLOBAL_DBNAME = ORCL.us.oracle.com)
9. (SID_NAME = ORCL)
)

10. ...sample additional SID description ...


)

157
Listener Tool (LSNRCTL)

The tool can be used by running the following command


UNIX command syntax:
$ lsnrctl <command name>

DOS prompt:

LSNRCTL> <command name>


Manage non-default listener

LSNRCTL> set current_listener listener02

158
Listener Program Management

View status of listener program:


% lsnrctl status
Test listener program from other cluster node:
% tnsping tns_alias
Start listener program process:
% lsnrctl start
Stop listener program process:
% lsnrctl stop
If the listener name configured in the database configuration file
listener.ora is not a default LISTENER, the listener name must be
provided upon starting/stopping listener. For example, lsnrctl start
listener_rac1

159
Configuring Local Network Service Name

160
Adding Service Name

161
Specifying Oracle Version

162
Inputting Database Service name

163
Network Protocol

164
Host Name and Listener Port

165
Test and Connection

166
Connection Test Result

167
Name Network Service

168
Saving

169
tnsnames.ora

# TNSNAMES.ORA Network Configuration File:/u03/ora9i/rel12/network/admin/tnsnames.ora


# Generated by Oracle configuration tools.

MY_SERVICE.US.ORACLE.COM =

(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = stc-sun02.us.oracle.com)(PORT = 1521))

)
(CONNECT_DATA =
(SERVICE_NAME = TEST.us.oracle.com)

)
)

170
sqlnet.ora

# SQLNET.ORA Network Configuration File: /u03/ora9i/rel12/network/admin/sqlnet.ora


# Generated by Oracle configuration tools.

NAMES.DEFAULT_DOMAIN = us.oracle.com
NAMES.DIRECTORY_PATH= (TNSNAMES, HOSTNAME)
SQLNET.EXPIRE_TIME=0

sqlplus system/manager@MY_SERVICE
SQL*Plus: Release 9.0.0.0.0 - Beta on Tue Feb 27 10:11:00 2001
(c) Copyright 2000 Oracle Corporation. All rights reserved.
Connected to:
Oracle9i Enterprise Edition Release 9.0.0.0.0 - Beta
JServer Release 9.0.0.0.0 - Beta
SQL>

171
Troubleshooting for Client

Common Faults:

ORA-12154 TNS:could not resolve service name


ORA-12198 TNS:could not find path to destination
ORA-12203 TNS:unable to connect to destination
ORA-12533 TNS:illegal ADDRESS parameters
ORA-12541 TNS:no listener

172
Summary

Listener Management
Local Service Name Configuration
Three important configuration files:
listener.ora
Tnsnames.ora
Sqlnet.ora

173
Practice

The practice in this part covers the following:


Please refer to "Oracle Database Hands-on Practice"
Classroom practice-> Network Configuration

174
Emergency Database Fault Handling
Objectives

Error Information View Tool (oerr)


Common Oracle Errors
Manually Collect Onsite Information
RDA collects on-site information

176
Emergency Database Fault Handling

Error Information View Tool (oerr)


Oracle provides a practical program oerr. This program can
be used to obtain the description of oracle error information.
On UNIX platform, the oerr tool can quickly obtain the
detailed description of oracle error information.
Specific syntax of the oerr tool: oerr error type error code
For example: To query ORA-2336, input "oerr ora 2236" .

177
Emergency Database Fault Handling

Common Oracle Errors


ORA-1652 to ORA-1655
ORA-165X error information indicates that the tablespace does not have
enough allocable space, including ora-1652, ora-1653, ora-1654 and ora-
1655.
ORA-01555 (snapshot too old)
Undotablespace is introduced in 9i.If undo tablespace is set enough high,
and also undo_retention is set enough high, (greater than the time
necessary for completing major events), it is possible to completely solve
the ORA-1555 error problem (however, an excessively high value may
cause degradation of system performance).

178
Emergency Database Fault Handling

Common Oracle Errors


ORA-04031
If the value of the parameter shared_pool_size is very high (greater than 350M),
the possible cause of an ORA-4031 error is possibly bug of the Oracle database or
that the application does not better use the bind variable.
Empty the current shared_pool, and the Ora-4031 error can be cleared temporarily.

Internal ORA-600 Error


The first parameter provides the actual error information (for example, 1579
indicates block interruption error), while other parameters provide other related
information (for example, in the above block interruption error, the block number to
be read and the block number actually ready by the Oracle are indicated. )
An ORA-600 error may cause that the system generates one or multiple trace files.

179
Emergency Database Fault Handling

Service Recovery Handling


If a fault occurs to the RAC database, check the alarm log file of the
database rapidly to locate the fault cause, influence range and fault
phenomenon. For example:
Whether the database fault occurs once or repeatedly
Whether the database fault can be recovered easily, rounded or cleared
Whether services can run normally after the fault occurs to the database.
If a node database of the RAC database terminates services abnormallys,
but other nodes run normally, attempt to manually start the faulty
database and recover the database to running status.

180
Emergency Database Fault Handling

Manually Collect Onsite Information


Detailed Description of Error Phenomenon
Database alarm log file: alert_{ORACLE_SID}.log
Database trace file: *.TRC
Initialization parameter file: SPFILE cannot be read directly and needs to
be converted into a text file.
Network configuration file: listener.ora, tnsnames.ora,sqlnet.ora
Database version
Type and version of the operating system

181
Emergency Database Fault Handling
Use ORACLE RDA to collect on-site information
RDA is a shell program developed by ORACLE. It is used to completely collect
environmental information of Oracle software, for reference of engineers in remote
fault diagnosis.
RDA installation: Set up an independent directory for RDA. Do not include the RDA of
the old version in the same directory.
After script execution, pack information reports in htm and txt form under the
RDA_Output directory and a .tar.Z of these files.
Precautions on the Use of RDA:
Confirm whether the database is started and can be connected.
Confirm the FTP process is in BIN mode, and no error occurs to download.
Confirm whether the sell file after decompression of tar has executable right.

182
Summary

Error Information View Tool (oerr)


Common Oracle Errors
Manually Collect Onsite Information
RDA collects on-site information

183
Practice

The practice in this part covers the following:


Please refer to "Oracle Database Hands-on Practice"
Classroom practice-> Emergency Database Fault Handling

184
Questions and Answers

185
Recommended Database References

Recommended Good Books about Oracle Introduction


Oracle8i Backup and Recovery Manual
Guide to Oracle8i Learners
Oracle8i PLSQL Program Design
Oracle8 Database Administrator Manual
Oracle9 statspack High-Performance Adjustment
OCP Teaching Materials
ORACLE Delivery-Attached Manual

186
Recommended Database Websites

http://tahiti.oracle.com: Official documentation website of Oracle


http://metalink.oracle.com/: Technical support website of Oracle, with a
vast Knowledge Base and experience on solution of various problems.
http://www.itpub.net: The most hottest forum on such IT technologies
as database in China
http://www.cnoug.org: Official forum of Oracle in China
http://www.orafaq.org/faq2.htm orafaq: Famous overseas Oracle FAQ
forum, with detailed categories.

187