6588667 oracle dba ppt

173
Oracle Database Administration I 1 Oracle Database Administration I Lesson 1 Oracle Server Architecture 2 Overview Set of data to store and access information Based on a relational model of rows and columns stored in tables Also Object-oriented (OO) structures Abstract datatypes and methods Contains these components: Physical Memory Process 3 Oracle’s Overall Role Retrieve data File I/O Space Management Change Management Access Management

Upload: gjaggu

Post on 24-Oct-2014

159 views

Category:

Documents


21 download

TRANSCRIPT

Oracle Database Administration ILesson 1 Oracle Server Architecture

Overviewu u u

Set of data to store and access information Based on a relational model of rows and columns stored in tables Also Object-oriented (OO) structuresn

Abstract datatypes and methods

u

Contains these components:n

Physical Memory Process

n

n

2

Oracles Overall Roleu u u u u

Retrieve data File I/O Space Management Change Management Access Management

3

Oracle Database Administration I 1

Database Structureu u u u u u u

Data file(s) Control file(s) Redo logs Init.ora (spfile.ora 9i) Trace Alert log Password

4

Instance Structureu

Memory structures are allocatedn

Collectively known as System Global Area. 95% defined by data block buffer cache, Shared SQL Pool, Large Pool and Java Pool.

n

u u

Oracle background processes are started. Single database accessible by multiple instances RAC (Real Application Cluster) a.k.a. parallel server

5

Instance Definedu

Defined by initialization parameter(s) that determine the size and composition Can be dynamically altered initSID.ora (ascii file) spfileSID.ora (binary file) configSID.ora (usually only used to create a database notwidely used)

u u u u

6

Oracle Database Administration I 2

Oracle Instanceu

Composed of:n

SGA (System Global Area) PGA (Program Global Area) Oracle BACKGROUND processes

n

n

7

System Global Area (SGA)u

Shared memory region allocated by Oracle for an Oracle database Allocated when the Oracle database is started The SGA should be in non-paged, non-swapped memory

u u

8

SGA Compositionu u u u u u u

Buffer cache Shared SQL Pool Large pool (optional) Java pool Redo log buffer Dictionary cache Other miscellaneous items

9

Oracle Database Administration I 3

PGA Compositionu

Non-shared memory area to which a process (server or background) can write Allocated by Oracle when a user connects to an Oracle database and a session is created

u

10

Oracle Instanceu

Required Background Processes:n

DBWn LGWR SMON PMON CKPT (9i)

n

n

n

n

11

Oracle Instanceu

Optional Background Processes:(not all inclusive)n

ARCn CKPT (prior to 9i) RECO Lock (LCK0) Job Queue (SNPn) Queue Monitor (QMNn) Dispatcher (Dnnn) Server (Snnn for dedicated MTS servers)

n

n

n

n

n

n

n

12

Oracle Database Administration I 4

Oracle Instance More Details

SGAu u u u

Buffer Cache Redo Log BUFFER Shared SQL Pool Dynamic (as of Oracle 9i)

14

Dynamic SGAu

Defined in Granulesn

SGA < 128mb SGA > 128mb

4mb size 16mb size

n

u u u

Can be modified on the fly (9i) Establish an overall maximum Initially allocated 4 for small, 3 for large (fixed SGA, buffer cache, Shared pool)

15

Oracle Database Administration I 5

Data Buffer Cache Structureu

Can be defined in two ways:n

By block db_block_buffers By byte db_cache_size

n

u

Was divided into blocks the same size as the blocks in the datafiles As of 9i, multiple buffer cache introduced (depends on block size of each tablespace) Size and number defined in the initialization Parameter File Holds copies of data blocks read from disk

u

u u

16

Data Buffer Cache Contentsu u

Stores the most recently accessed BLOCKS OF DATA Contains PINNED buffersn

Data being accessed Data that has been MODIFIED, but not written to disk

u

Contains DIRTY buffersn

u u

FREE buffers Two lists, write and LRU

17

REDO Log Buffersu u u

Stores the REDO ENTRIES (changes to the database) Default is four times the OS block size Larger reduces log I/O and uncommented redo to online redo logs Changed data is moved from the database buffer cache to the redo log buffer then to the redo log files

u

18

Oracle Database Administration I 6

Shared Poolu u

Can be dynamically modified (9i) Must be an integer multiple of the granule sizeu

Oracle will round up if not

u u

Managed by LRU algorithm Contains:n

Library Cache Data Dictionary Cache Control structures Reusable Runtime Memory

n

n

n

19

Shared Pool

20

Shared Poolu

Library Cachen

SHARED by all users for commonly used SQL statements Shared and Private SQL areas for executed statements PL/SQL Procedures and Packages Allocation and Reuse of Memory

n

n

n

21

Oracle Database Administration I 7

Library Cacheu

Shared SQLn

PARSE TREES for SQL statements EXECUTION plans for SQL statements Size dependent on complexity

n

n

u

Private SQLn

Each session has one Persistent and Runtime areas Cursors

n

n

22

Library Cacheu

PL/SQL Program Unitsn

Procedures, functions, Packages, anonymous blocks and database triggers

u

Allocation and Reuse of Memoryn

Every SQL statement submitted, Oracle automatically allocates memoryu u u

Checks for existence Allocate private SQL area May flush the shared pool

23

PGA

24

Oracle Database Administration I 8

PGAu

Varies depending if dedicated or Shared servers (MTS) are used Stack space Session information (PGA verses Shared Pool) Memory allocated to hold a sessions variables and arrays Automatically managed in 9i with the SQL memory management

u u u u

25

Questionsu u u u u

What is the name of Oracles memory structure? What are its contents? How is it divided? If I have 150 mb SGA, why does Oracle change the size? Can you vary sizes of Oracle blocks?n

If so, how?

26

Oracle Databaseu

Composed of two structures:n

Physical (Operating System view) Logical (Oracles view)

n

27

Oracle Database Administration I 9

Physical View Files

Physical Structureu

Made up of:n

Data files Redo Log Files two or more with members One or more Control Files One Parameter File Trace and alert log files One Password file

n

n

n

n

n

29

Datafileu u u u

Disk space for a tablespace One or more per tablespace Associated with only one tablespace Consists of segments:n

UNDO, Temporary, Data, index, undo, LOB and cache (for the most part)

30

Oracle Database Administration I 10

Redo Log Filesu

Characteristicsn

Record changes made to the data by various transactions Help RECOVER the data in case of a failure Streamline the process of how data is written to disk

n

n

31

Control Filesu

u u

Record of the overall architecture and status of the database Easily moved and recovered Contain the following:n n n

Database NAME Datafiles NAMES and LOCATIONS Redo log file NAMES, Log sequence number and LOCATIONS

32

Parameter Fileu

Attributes of an instance are defined through an Oracle Parameter File Determines the size and characteristics of the instance Stored in an ASCII file or housed with the database in a binary file

u

u

33

Oracle Database Administration I 11

Parameter Fileu

The only Oracle file that is ASCII All other files are binary and not directly changeable by the DBA Read-only when the instance startsn

u

u

Most changes require a stop and restart of the instance

34

Trace and Alert Logsu

Trace files contain information about significant events Alert log records the commands and results of major events in the life of the databasen

u

Monitor daily Rename for historical purposes

n

35

Logical View Structures

Oracle Database Administration I 12

Logical View Structuresu u u u u

Tablespace(s) Schema objects Segments Extents Data blocks

37

Tablespace(s)u u u

Logically divides a database One or more datafiles are explicity created for each one Logically divided into segments that are further divided into extents and blocks Can be defined as read-only A unit of space to store a schemas objects

u u

38

Object(s)u

Schema(s)n

A collection of objects owned by one Oracle user Tables, indexes, views, sequences, stored procedures, functions, packages, UNDO segments

u

Object(s)n

39

Oracle Database Administration I 13

Extents and Blocksu u u u

A collection of the smallest object in a database An extent can be of a varying size Extents MUST be contiguous Blocks are the finest collection of space in an Oracle database

40

Questionsu u u u u

What are the physical files of a database system? What are the logical entities of a database? What is the smallest structure? Which structure MUST be contiguous? Which structure will tell you event information?

41

Background Processes Review

Oracle Database Administration I 14

Background Processesn

Every instance has BACKGROUND PROCESSES BACKGROUND PROCESSES perform I/O, handle process cleanup and monitor the ORACLE database Provide support, increase performance, assist in recovery and make the database more reliable

n

n

43

Background Processesu u u u u u

DBW0 (DBWn) LGWR PMON SMON CKPT ARCn

44

Database Bufferu

After the changed data (redo entries) are written to the online redo log files, the changed data will be written to disk These changed data are called dirty Dirty data are moved to the write list Dirty data can be on the write list and on the LRU list

u u u

45

Oracle Database Administration I 15

DBWnu

At some time after the redo entries have been written into the online redo logs, the database writer (DBWn) writes the dirty buffer back to the database This is called delayed write and is based on initialization parameters

u

46

DBWn (Database Writer)u

Can have one or more runningn

Only available on systems with Asynch I/O Can use I/O slaves to duplicate the above on systems without itKeeps the BUFFER CACHE clean and free

n

u

Performs all WRITES to the databasen

47

When does the DBWR write?u u u

The dirty list reaches a threshold length A DBWR timeout LGWR issues a checkpoint

48

Oracle Database Administration I 16

LGWR (Log Writer)u

Writes the REDO log entries (located in the REDO LOG BUFFER) to the REDO LOG files Only the changed data, not the entire Oracle block(s) is written to the redo logs Issues checkpoints

u

u

49

Online Redo Log Filesu

The online redo log files hold the redo entries Only the changed bytes are written to the online redo log file The entire data block is not written to these logs

u

u

50

Online Redo Log Filesu

There is a fixed number of online redo log file groups Defined at database creation time Can add or drop groups or members (discussed later)

u u

51

Oracle Database Administration I 17

Online Redo Log Filesu u

Redo log file groups cycle If there are three redo log file groups:n

When the first group is full, LGWR starts writing to the second group When the second group is full, LGWR writes to the third group When the third group is full, LGWR writes to the first group

n

n

52

LGWR (Log Writer)u

What causes the LGWR to clear the REDO LOG BUFFER and transfer the transactions to disk?n

When a user process COMMITS a TRANSACTION TIME-OUT (caused every three seconds) When the redo log buffer becomes 1/3 FULL When the DBWR writes the dirty buffers to disk

n

n

n

53

LGWR (Log Writer)u

LGWR can be bypassedn

Use the UNRECOVERABLE key word This is to be used very carefully. No redo entries will ever exist after this point Best used for temporary object creation

n

n

54

Oracle Database Administration I 18

PMONu

Cleans up after failed server processes by releasing system resources FREEs resource locks Rolls back aborted processes Restarts dispatchers and shared-server processes

u u u

55

SMONu

INSTANCE RECOVERY performed at startup CLEANS up temp segment(s) no longer in use Can coalesce fragmented tablespaces

u

u

56

CKPTu

Updates the header record of the data files with a SCN (System Change Number) This SCN is used for synchronization of all files Does this on behalf of the LGWR Can be a source of I/O contention with the LGWR

u u u

57

Oracle Database Administration I 19

Archive Modeu

Saves the online redo log files as archived redo log files A database in archive log mode can be restored to the last committed transaction Production databases are run in archive log mode

u

u

58

ARCnu

Copies the REDO logs to the ARCHIVE storage when the REDO logs become filledn

Process was optional before 9i, but now is automatically started when archivelog mode is set. Must be turned on

n

59

ARCnu

ARCn copies a filled online redo log file to an archived redo log file ARCn gives each archived redo log file a unique name ARCn must be finished copying the online redo log before it is overwritten

u

u

60

Oracle Database Administration I 20

Process Questionsu

Which process can cause the DBWR to write to disk? Which process can coalesce the free space in a tablespace? Which process wakes up to take care of shared servers?

u

u

61

How does this all fit together?

Instance and Databaseu u u

The instance is started The instance mounts the database The database opensn

Users may now use the database

63

Oracle Database Administration I 21

User Processu

In network access mode (web or client/server), a user process utilizes the Transparent Network Substrate (TNS) that allow the client applications (i.e., ORACLE tools) to communicate with the server processes Initiates a session on the PC that connects to a dedicated server process

u

64

Sessionu

The activity of a user from the time the user connects to the database to the time the user disconnects from the database Can execute multiple transactions

u

65

User Starts Transactionu u u

A user application on the PC talks to SQL*Net SQL*Net talks to the user server process The server process parses the SQL statement and validates it

66

Oracle Database Administration I 22

A Transaction is Startedu

A logical unit of workn

One or more SQL statements that must all be saved (committed) or discarded (rolled back) as a group

u

Begins with the first executable SQL statement

67

A Transaction is Startedu

Ends with a COMMIT or ROLLBACK SQL statementn

Explicitly with a COMMIT or ROLLBACK Implicitly when a DDL statement is issued

n

u

The EXIT statement will do a commit by default

68

Dedicated Server

Assume for now that we have a Dedicated Server Architecture(Multi Threaded Server, MTS will be discussed later)n

Each user has one server process Each server process works for only one user Session information is stored in the PGA

n

n

69

Oracle Database Administration I 23

Dedicated Serveru

The user process on the PC communicates to the server through Oracles SQL*NET A network listener process is created A dedicated server process is created

u u

70

Server Processu u u

An OS process that works on behalf of the user Reads the data from disk into the buffer cache Communicates with the database for the usern

User processes do not connect directly to the database

71

What does the server process do?

Oracle Database Administration I 24

SGA Activityu

The server process reads data from the database datafiles and stores it into the data buffer cache The user SQL statement changes the data in the data buffer cache

u

73

PGA (Program Global Area)u

An area in memory that contains data and controls information for a single usern

Memory is ALLOCATED when a user process connects to the database Extra memory is allocated for session management if in dedicated server mode

n

74

PGA (Program Global Area)u

What does the PGA hold?n

Variables Arrays Other User information for a particular user

n

n

75

Oracle Database Administration I 25

Physical and Logical readsu u

Physical reads get data from the datafiles Logical reads get data from memory (The SGA data buffer cache) All managed by the server process(es)

u

76

The SQL Statementu

The server process receives the SQL statement. Processed either by:n

If an identical SQL statement is found in the shared pool, it uses it If not found in the shared pool, a new shared SQL area is allocated

n

u

There are three phases to a SQL statement:n

PARSE, EXECUTE and FETCH

77

PARSEu

CHECKS the statement for syntactic and semantic validityn

Data Dictionary

u

Ensures the processes issuing the command has the RIGHTS to execute the command ALLOCATES a private SQL area for the statement ( PGA ) SCANS existing SQL area for matching statement

u u

78

Oracle Database Administration I 26

PARSE TREEu

Method Oracle uses to find the specific data in the databasen

Two Typesu u

Cost Optimization Rule Optimizationn

Banner uses rule

79

EXECUTEu

Will only execute if the PARSE is successful APPLIES the PARSE TREE to the data PERFORM physical and logical reads

u

u

80

EXECUTEu

CHANGES data where necessary Performs constraint CHECKING FETCH RETURNS rows of data for a SELECT statement

u

u

81

Oracle Database Administration I 27

UNDO Segmentsu

The data before it was changed is written to the UNDO segmentsn

These segments are in a tablespace

u

If the user rolls back the data, the UNDO segments are used to restore the old data

82

Redo Log Bufferu u

The changed data is placed in the redo log buffer If the data is committed, the LGWR writes the changed data to the online redo log files The commit is completed after the data is written to the redo log

u

83

SGA ReviewBuffer Cache Shared Pool Redo Log Buffer

Oracle Database Administration I 28

Buffer Cacheu

Consists of buffers the size of the data blocks (only option prior to 9i) or in bytes Two purposes:n

u

To improve performance for repeated statements usage To allow users to make changes quickly in memory

n

u

Contains two lists:n

LRU WRITE

n

85

LRU (Least Recently Used)u

Data retained in SGA is by time ordern

Newest to oldest information Longer it sits, older it becomes When new space is needed or a CKPT (checkpoint) has occurred:u u

n

n

DIRTY buffers are written to disk and removed from memory Oldest data in the SGA can be written over

86

Parts of the Buffer listsu

FREEn

Empty section of memory ready for data

u

DIRTYn

Section of memory that CONTAINS data that has been modified, but not yet written to disk

u

PINNEDn

Data that is currently in use and has been locked

87

Oracle Database Administration I 29

Redo Log Bufferu u

Written to when a user modifies data The server process moves the changed data from user memory to this buffer Contains only the redo entries LGWR writes the redo entries to the online redo log file

u u

88

Shared Poolu

Has two mandatory structures:n

Library Cache Dictionary Cache

n

u

One optional structuren

Large Pool

89

Mandatory Contentsu

Data Dictionary cache (also called row cache)n

Dictionary row information recently accessed

u

Library cachen

Parsed statements Execution plans

n

90

Oracle Database Administration I 30

Read ConsistencyHow Oracle maintains a Consistent view of the data for each transaction

UNDO Segmentsu

Main purposen

Read consistency Transaction rollbacku u u

n

User initiated ROLLBACK Abnormal termination Abnormal database termination

92

UNDO Segmentsu

Containsn

Block Information File names and block ID Data as it existed before a transaction Transaction numbers

n

n

n

93

Oracle Database Administration I 31

UNDO (Rollback) Segmentsu

Stores the data before it was changed by a transaction If the user cancels a transaction (rolls back the data), the UNDO segments are used to restore the old data Discussed in a later section

u

u

94

UNDO Segmentsu

Record the transaction that occurred on the datan

Should an error occur during a modification of data, the record retained by the UNDO SEGMENT will restore the data prior to the modification attempt

95

Read Consistencyu

Ensures data seen by a statement is consistent with respect to a point-in-time Even data changed by another transaction is not seen during the transaction

u

96

Oracle Database Administration I 32

Read Consistencyu

Basic principlesn

Readers can not lock data blocks Readers can not block other readers Readers can not block writers Writers can not block readers Writers can block writers

n

n

n

n

97

COMMITu u u u

When a statement is executed and saved Can be explicitly or implicitly commited Ends the current transaction Generates a System Change Number (SCN)

98

COMMITu

What happens when a COMMIT is made?n

Modification becomes PERMANENT A copy of the transaction is placed in the REDO BUFFER Redo buffer is FLUSHED to the REDO LOGS

n

n

99

Oracle Database Administration I 33

COMMITu

When a COMMIT is made:n

User is NOTIFIED Resource locks are RELEASED DBW0 may WRITE the data back to the database fileu

n

n

Note: Issuing a COMMIT does not guarantee that a transaction has been written back to the DATAFILE

100

Redo Log Filesu

When a REDO BUFFER is flushed, its information is stored in the REDO LOG FILESn

Hold records of all transactions that have been applied to the database With these entries, a database can be reconstructed during a database crash

n

101

Redo Log Filesu

REDO LOG FILESn n

REDO LOG FILES are circular When a transaction is COMMITTED (data modified), the LGWR transfers the statement from the REDO LOG BUFFER to the REDO LOG FILES A SCN (System Change Number) is also associated to each COMMITTED transaction that is written to a REDO LOG FILE

n

102

Oracle Database Administration I 34

Redo Log Filesu

When a REDO LOG FILE becomes full, the LGWR moves to the next filen

If there are no new REDO LOG FILES, the old files are reused If these other files were not archived, all data before this point can no longer be recovered

n

103

Archiving Redo Logsu

If ARCHIVELOG is ENABLED, redo log files can be stored Archiving can be duplexed Standby databases can use these same archives

u u

104

Checkpoint Variables in Parameter Fileu

LOG_CHECKPOINT_INTERVAL (will be obsoleted in 10i)n

Number of filled REDO LOG FILE blocks written between consecutive CHECKPOINTS (OS-dependent)u

NOTE: Do not make this value larger than the REDO LOG FILE. If it is larger, the CKPT only occurs when switching logs

u

LOG_CHECKPOINT_TIMEOUTn

Maximum amount of time before another CHECKPOINT occurs (default 900 sec)

u

LOG_CHECKPOINT_TO_ALERTn

Puts the checkpoint information in the alert_SID.ora file.

105

Oracle Database Administration I 35

SWITCHING LOG FILESu

Occur in Two waysn

Filled REDO LOG Forced by DBA with the ALTER SYSTEM SWITCH LOGFILE command

n

106

Multiplexing Redo Log Filesu

Increase the security of the Oracle databasen

Groups must contain identical sets of logfiles (names should be different) Place on different disks to help increase the REDO LOG files chances of survival should there be a computer failure When the REDO buffers are flushed to the REDO LOG files, the information to be stored is mirrored to a log file in both groups

n

n

107

Multiplexing Redo Log Files

1,3,5,.. A_LOG1 A_LOG2 2,4,6,.. LGWR B_LOG1 B_LOG2 Group 1 Group 2

108

Oracle Database Administration I 36

CONTROL FILEu

A binary file that is necessary for the database to runn

Should remain read/write to the database File is constantly updatedu

n

NOTE: It is an excellent idea to have backup copies of this file, in case something should happen to it

109

CONTROL FILEu

Containsn

DATABASE NAME TIMESTAMP of database creation TIMESTAMP of last access NAMES and LOCATIONS of databases and redo log files Current LOG SEQUENCE number

n

n

n

n

110

TRANSACTIONu

Logical unit of workn

One or more SQL statements executed by a single user

111

Oracle Database Administration I 37

TRANSACTIONu

A TRANSACTION starts when a user executes a SQL statement The TRANSACTION ends when:n

u

SQL statement is COMMITTED A user ends the session unexpectedly A user EXITS the database

n

n

112

TRANSACTIONu

The TRANSACTION is aborted when:n

A ROLLBACK occurs User TERMINATES ABNORMAL user exit Processor FAILURE Media FAILURE

n

n

n

n

113

Parameter Fileu u

initSID.ora configSID.ora

114

Oracle Database Administration I 38

Data Buffer Cache Parametersu

DB_CACHE_SIZE (9i)u

Number of blocks in the data block buffer cache (3000 to 10,000) Can have five different block sizes DB_#K_CACHE_SIZE Cannot exceed the MAX_SGA_SIZE Specifies the size of a Oracle block Cannot be changed except by rebuilding the database/tablespace (2k, 4k or 8k)

u u uu

DB_BLOCK_SIZE (bytes)u u

115

Log Buffer Parametersu

log_buffer (bytes)n

Default value is:u

256k

116

Shared Pool Parameteru

Shared_pool_size (bytes)n

75,000,000 is minimum for Banner 250,000,000 or more for production is suggested

n

117

Oracle Database Administration I 39

Archiving Parametersu

log_archive_start (true / false)n

Starts automatic archiving

u

log_archive_dest (directory path)n

The disk location of the archived redo log files

u

log_archive_format (format of the name of the archive redo log files)

118

Archiving Parametersu u

Standby_archive_dest Log_archive_dest_nn

As of 9i can be up to 10 locations (SERVICE=tns_service | LOCATION= local location) MANDATORY | OPTIONAL Used for managing the 1-10 archive destinations

n

n

u

Log_archive_dest_state_nn

119

Archiving Parametersu u

Log_archive_duplex_dest Log_archive_min_succeed_destn

V$archive_dest V$archive V$logs

n

n

120

Oracle Database Administration I 40

Checkpoint Parameteru

Checkpoints should be avoided in an OLTP system like Banner Larger redo log files will reduce checkpoints Longer checkpoint intervals, larger redo gapsn

u u

How much are you willing to lose?

u

Parametersn

log_checkpoint_interval (blocks) log_checkpoint_timeout (seconds)u

n

0 value will turn it off

121

CKPT Background Processu u u

Background Process that helps LGWR at log switch This process updates the data file header files CKPT_PROCESS = TRUEn

Used only in Oracle systems prior to 9i In 9i, remove this parameter from any init.ora. It will cause an error. Automatically started in 9i

n

n

122

Other Banner Parametersu u

dml_locks (1500 to 2000) processes (number of user plus oracle background processes) open_cursors = 1024 (2048 is better) optimizer_mode = rule (Banner requirement)

u u

123

Oracle Database Administration I 41

More to life than a DEDICATED server

Server Configurationsu

Three typesn

DEDICATED server MULTITHREAD server COMBINED user/server process

n

n

125

DEDICATED serveru

Two tasksn

USER process and SERVER process If the two processes are on the same machine, the program interface is handled by the LOCAL MACHINE'S I/O If the two processes are on different machines, the program interface is handled by a COMMUNICATION MECHANISM (SQL*Net/Net80)

n

n

126

Oracle Database Administration I 42

DEDICATED server

127

MULTITHREADED serveru

Allows many user processes to share a server processn

This allows the system resources to be freed, but can cause decreased response time for heavy users

128

MULTITHREADED ServerApplication Code

Client Workstation Database Server

Dispatcher Processes

Oracle Server Code

System Global AreaRequest queue Response Queues

129

Oracle Database Administration I 43

DISPATCHERu

The USER process connects to a DISPATCHERn

The DISPATCHER routes the USER request to the Request Queue The SERVER process checks the queue for new requests (FIFO) The SERVER process then places the response on the calling dispatcher's response queue, and then back to the application

n

n

130

Parameter Settings - MTSu u u

Mts_servers = n Mts_max_servers = n Mts_dispatchers =

(protocol=ipc/tcp) (dispatchers=N)u

Mts_max_dispatchers = n

131

Summaryu

Oracle databasen

Data, redo log, control, trace, alert log and parameter files

u

Oracle Instancen

The set of background processes which access data, log, and control files. An Oracle Instance is defined by one or more Parameter Files that is read at startup time

n

132

Oracle Database Administration I 44

Oracle INSTANCEu

Processes that controln

DATAFILES REDO LOG FILES CONTROL FILES

n

n

133

Physical structureu

One or more DATA files that contain data Two or more REDO files One or more CONTROL files One or more Parameter Files

u

u

u

134

DATAFILEu

How is a DATAFILE used?n

Data is read into stored memory cache Can manipulate, view, or change the data After you complete the transaction, the data is written back to the DATAFILE

n

n

135

Oracle Database Administration I 45

REDO log filesu

When do they help?n

n n

When a system failure has prevented Oracle from updating DATA Allows the transaction to be recalled Prevents existing data from becoming corrupted through an incomplete transaction by restoring the original information

136

CONTROL FILESu

Why does Oracle need them?n

When an Oracle database is started, the CONTROL file that is listed first in the parameter file is read Identifies the database Opens the redo logs to allow the database to function

n

n

137

SETTING BUFFERSu u

Parameter File Data buffersn

DB_CACHE_SIZEu

Cannot be used with db_block_buffers

u

Redo logn

LOG_BUFFER

138

Oracle Database Administration I 46

PGA (Program Global Area)u

MULTITHREADED PGAn

The SGA is responsible for allocating the memory to the user sessions

u

DEDICATED PGAn

PGA allocates the memory to the user sessions as needed

139

BACKGROUND PROCESSESu

DBWn (Database Writer) LGWR (Log Writer) CKPT (Check Point) SMON (System Monitor) S### (Server)

u u u u u

PMON (Process Monitor) ARCn (Archiver) RECO (Recover) Dnnn (Dispatcher) LCKn (Lock)

u

u

u

u

140

RECOu

Resolves in-doubt transactions in distributed database systems

141

Oracle Database Administration I 47

Dnnnu

Used for MULTITHREADED servern

An optional feature The Dispatcher is used to TRANSLATE communications from one protocol to another

n

142

LCKnu

Used with the PARALLEL (RAC 9i) server optionn

It instantly LOCKS data to prevent data corruption caused by simultaneous access of data by different processes

143

CKPTu

Primary goaln

Make sure all modified data buffers get written to files FORCES DBWR to clean the BUFFER CACHE CAUSES the switching of REDO LOG FILES FLUSHES the REDO LOG BUFFER to disk

n

n

n

144

Oracle Database Administration I 48

CKPTu

PROBLEMSn

The CKPT processes will put more overhead on the server May cause a considerable slowdown In 9i, the CKPT process is predefined and started. In earlier version, to activate CKPT:u

n

u

Parameter Filen n

CHECKPOINT_PROCESS=TRUE

145

Oracle Database Administration ILesson 2 Starting and Stopping an Oracle Instance

Starting and Stopping an Oracle Databaseu

Agendan

Application(s) used in starting a database Required environment settings to startup a database Various levels of a database startup and shutdown

n

n

147

Oracle Database Administration I 49

Starting an Oracle Databaseu

After the installation of Oracle, the DBA configures, creates and starts a database for user access Before you can create a database, you must start an application to begin

u

148

Packages to Use for Startupu u

SQLPLUS Use a database management tool (Enterprise Manager, TOAD) Scripts Oracle Universal Installer RMAN (Recovery Manager not discussed in this course)

u u u

149

SQLPLUSu

The replacement for Server Manager (svrmgrl) starting with release 8.1.5 With Password filen

u

Sqlplus /nologn

Then issue connect / as sysdba (9i) Connect internal as sysdba (8i to be desupported after 9i)

n

u

Without password filen

Sqlplus / as sysdba

150

Oracle Database Administration I 50

Database Management toolsu

Oracle Enterprise Manager (OEM)n

Has become more sophisticated Comes with the Enterprise Edition Use the Instance Manager as INTERNAL or AS SYSDBA

n

n

u

TOADn

Downloadable version - minimal

u

Many other types

151

Starting an Oracle Databaseu

Scriptsn

Unix: csh, sh, perl VMS: dcl, perl NT: perlu

n

n

All require several environment variables to be set prior to running any Oracle application

152

Environment Variable - UNIXu

$ORACLE_HOMEu

Set to the directory that Oracle is installed under

u

$ORACLE_SIDu

Set to the name of the database the DBA wants to startup/shutdown

u

$LD_LIBRARY_PATHu

Set to $ORACLE_HOME/lib

u

(optional) $PATHu

Should include $ORACLE_HOME/bin

153

Oracle Database Administration I 51

Setting Environment - UNIXu

Executing the script oraenv, typically located in /usr/local/bin, automatically sets all environment variables Or manually at the command promptn

u

Examplesn

ORACLE_HOME = /u01/app/oracle/9.0.1/bin ORACLE_SID=TEST

n

u

NOTE: Oracle account should set variables in $ORACLE_HOME/bin with no application-specific definitions

154

Environment Variable - VMSu

ORA_DBu

Directory location for database parameter, configuration and dump files

u

ORA_SIDu

Set to the name of the database the DBA wants to startup/shutdown

u

ORA_ROOTDIRu

Oracles home directory

155

Setting Environment -VMSu

Running the command file ORAUSER_.COM, located under ORA_ROOT:[db_], automatically sets all logicals and symbols correctlyu

@orauser_.com

156

Oracle Database Administration I 52

Environment Variable - NTu

Registry values are defined and a service entry is created when the database is created Registry values are automatically set when you use OEM or during installationn

u

Run regeditu

HKEY_LOCAL_MACHINE/SOFTWARE/ORACLE

157

Setting Environment - NTu

ORADIM can be used to create itn

Oradim NEW SID sid SRVC serviceu

Please refer to the documentation for full syntax

u

CMD at the DOS prompt settingn

SET ORACLE_HOME=d:\oracle\ora91\bin SET ORACLE_SID=TEST

n

158

Local Database Startupu

Once the proper environment variables are set, the DBA then needs to invoke the local database management utilitysqlplus /nolog connect / as sysdba Or connect / as sysdban

NT has other options:u u

MANUAL or AUTOMATIC service ORADIM

159

Oracle Database Administration I 53

Connection ExampleC:\Documents and Settings\vdevore>sqlplus /nolog SQL*Plus: Release 9.2.0.1.0 - Production on Fri Apr 4 21:07:52 2003 Copyright (c) 1982, 2002, Oracle Corporation. reserved. SQL> connect sys/systest as sysdba Connected to an idle instance. SQL> All rights

160

Startup by OSu

User must have OS PRIVILEGES:n

Unix: group DBA(defined in /etc/groups) VMS: Rights identifier ORA__DBA (defined in sys$system:authorize) NT: be in the group ORA_DBA

n

n

161

Startup using ORAPWDu u

As of 8i, Oracle introduced the password file Grant sysdba, sysoper for remote or local connection More in DBA II

u

162

Oracle Database Administration I 54

Why use AS SYSDBA/INTERNAL?u

When the database is shut down, there is no way to verify username and password is necessary to find a way for an individual to log onto the database connected, the user has sys privileges

u It

u Once

163

What Options are there?u

Once the DBA has connected to the database, he/she can proceed to:u u u

Startup the database in several modes Shutdown the database in several modes Or create a database

164

Lets Start a databaseu u

There are several ways to start the database's instance We will look at:n

Nomount Mount Open Restrict Force

n

n

n

n

165

Oracle Database Administration I 55

Start the Instanceu

Starting the instance involves:n n n n

n

Reading a parameter file (text - init.ora, binary spfile.ora) Allocating SGA (system global area) in memory Creating background processes Reading the control files for system information (for existing databases only) Open files for read and/or read-write

166

NOMOUNTu u

Typically used during database creation Starts the background processes and allocates memory Also used in recovery

u

167

Nomount - exampleC:\Documents and Settings\vdevore>sqlplus /nolog SQL*Plus: Release 9.2.0.1.0 - Production on Fri Apr 4 21:07:52 2003 Copyright (c) 1982, 2002, Oracle Corporation. SQL> connect sys/systest as sysdba Connected to an idle instance. SQL> startup nomount ORACLE instance started. Total System Global Area Fixed Size Variable Size Database Buffers Redo Buffers SQL> 135338868 bytes 453492 bytes 109051904 bytes 25165824 bytes 667648 bytes All rights reserved.

168

Oracle Database Administration I 56

MOUNTu

Mounting the database involves:n

Associating the database with the started instance Opening the control file, reading it, obtaining the names of the redo log and data files Verify checksum value (if enabled) and/or SCN synchronization

n

n

169

Mount - exampleC:\Documents and Settings\vdevore>sqlplus /nolog SQL*Plus: Release 9.2.0.1.0 - Production on Fri Apr 4 21:07:52 2003 Copyright (c) 1982, 2002, Oracle Corporation. SQL> connect sys/systest as sysdba Connected to an idle instance. SQL> startup mount ORACLE instance started. Total System Global Area Fixed Size Variable Size Database Buffers Redo Buffers Database mounted. SQL> 135338868 bytes 453492 bytes 109051904 bytes 25165824 bytes 667648 bytes All rights reserved.

170

OPENu

Opening the database involves:n

Opening the data file(s) and online redo logs for read-write Allowing regular users to connect to the database Attempts to acquire one or more UNDO segments Performs automatic crash recovery if database was shutdown abnormally

n

n

n

171

Oracle Database Administration I 57

OPEN -ExampleSQL> startup open ORACLE instance started.

Total System Global Area Fixed Size Variable Size Database Buffers Redo Buffers Database mounted. Database opened. SQL>

135338868 bytes 453492 bytes 109051904 bytes 25165824 bytes 667648 bytes

172

STARTUP No Argumentsu

Oracle assumes that STARTUP with no arguments implies a STARTUP OPEN It is also assumed that the current SID environment variable is what will be used.n

u

DBAs must ALWAYS be sure that the proper environment is set

u

PFILE or SPFILE must be defined and accessible or it will fail DBA must have SYSDBA or OSDBA

u

173

Starting an instanceu

NOMOUNT, MOUNT, and OPEN are different stages of an Oracle database startupn

When a STARTUP OPEN is issued, the database first startups in a NOMOUNT state, then proceeds to a MOUNT state, and finally proceeds to an OPEN state

174

Oracle Database Administration I 58

RESTRICTu u

STARTUP RESTRICT Opens the database, but only allows users with RESTRICTED SESSION privilege to access the database Why start a database in a restricted mode?u u

u

Maintenance (database upgrades) Exporting and importing data

175

RESTRICT - ExampleSQL> startup restrict ORACLE instance started. Total System Global Area Fixed Size Variable Size Database Buffers Redo Buffers Database mounted. Database opened. SQL> 4199600 bytes 42028 bytes 4026500 bytes 122880 bytes 8192 bytes

176

FORCEu

STARTUP FORCE is used for troubleshooting a failed or failure to open database If the database is closed, forces the database open If the database is open, it will abort the database and then open itExample: To shutdown the current instance, restart it without mounting or opening and allow only DBA access:STARTUP FORCE NOMOUNT RESTRICT

u u

177

Oracle Database Administration I 59

Other Startup Optionsu

Parallel/Shared (RAC 9i)(Shared is a synonym for Parallel)n

Allows multiple instances to access the database Cannot be used with EXCLUSIVE or NOMOUNT Invalid if initialization parameter SINGLE_PROCESS is set to TRUE Automatically restarts every five seconds if the instance is busy being recovered Will not retry for any other reason - parallel mode only

n

n

u

Retryn

n

178

Other Startup Optionsu

STARTUP RECOVERn

Specifies that media recovery be performed Has same effect as issuing RECOVER DATABASE The recovery processesu u u

n

n

Enable log archiving for media recovery Perform complete database recovery Perform partial database recovery

179

Other Startup Commandsu

Pfile = parameterfilenamen

A site-specific parameter file to initialize an instance at startup. If not specified, Oracle searches for it in:u

n

UNIX -$ORACLE_HOME/dbs/init.ora VMS - ORA_ROOT:[db_]__init.ora NT - HOME#\admin\\init.ora

u

u

180

Oracle Database Administration I 60

Changing the startup state of a databaseu

The DBA can change the current state of a database using the ALTER DATABASE SQL command The syntax is on the next slide

u

181

Changing the startup state of a databaseALTER DATABASE [MOUNT | OPEN]SQL> startup nomount ORACLE instance started. Total System Global Area Fixed Size Variable Size Database Buffers Redo Buffers SQL> alter database mount; Statement processed. SQL> alter database open; Statement processed. SQL> 4199600 42028 4026500 122880 8192 bytes bytes bytes bytes bytes

182

Changing the startup state of a databaseu

The ALTER DATABASE SQL command only moves the startup state of the database to a higher leveln

For example, the ALTER DATABASE SQL command cannot change the startup state from OPEN to MOUNTu

In this case, the DBA must first shutdown the database and then issue a STARTUP MOUNT command

183

Oracle Database Administration I 61

Database shutdownu

A database shutdown stops an instance and makes the database unavailable to users SyntaxSHUTDOWN [ABORT|IMMEDIATE|NORMAL|TRANSACTIONAL]

u

184

Commonly Used Shutdown Optionsu

SHUTDOWN NORMALn

Flushes all buffered writes to the disk, waits for all sessions to disconnect and then terminates the instance

u

SHUTDOWN IMMEDIATEn

Flushes all buffered writes to the disk, kills all user connections, performs a rollback on all uncommitted transactions, then terminates the instance

185

Shutdown Immediate - exampleC:\Documents and Settings\vdevore>sqlplus /nolog SQL*Plus: Release 9.2.0.1.0 - Production on Sun Apr 6 13:16:30 2003 Copyright (c) 1982, 2002, Oracle Corporation. SQL> connect sys/systest as sysdba Connected. SQL> shutdown immediate Database closed. Database dismounted. ORACLE instance shut down. SQL> All rights reserved.

186

Oracle Database Administration I 62

Database shutdownu

SHUTDOWN ABORTn

Should only be used in emergency situations, such as when the DBA detects a media failure, power failure, or security breach to the database

187

Shutdown Abortu

SHUTDOWN ABORTn

Immediately terminates the Oracle instance All buffered writes are NOT flushed to disk Does not perform a rollback on uncommitted transactions An instance recovery is required on the next database startup (performed automatically)

n

n

n

188

Database shudownu

SHUTDOWN TRANSACTIONAL(new with Oracle 8i)n

All current sessions in a transaction are allowed to complete No new sessions are allowed to start Any connected sessions are disconnected either by issuing a new transaction or once all transactions are committed or aborted

n

n

189

Oracle Database Administration I 63

Database shutdownu

SHUTDOWN NORMAL, SHUTDOWN TRANSACTIONAL and SHUTDOWN IMMEDIATE are either the usual or safest shutdown commandsn

The following steps occur during a shutdown (See next slide)

190

Database shutdownu

(SHUTDOWN IMMEDIATE) USER CONNECTIONS ARE TERMINATED All database data in the SGA is written back to the database files All redo log buffer data is written back to the redo log files Database is dismounted The control files are closed The SGA is removed from memory and the background processes are closed

u u u u u

191

Shutdown States illustrated

192

Oracle Database Administration I 64

Viewsu

V$databasen

Contains database information from the control file

u

V$instancen

Gives the state of the current instance

193

Questions?u u u

Which OEM manager can use to start up a database? How must you connect to startup a database? Which shutdown command satisfies these conditions?u u

The database shuts down when the last user logs off Force the database to close with users connected and disconnects their transactions midstream Force the database to close with users connected, but let transactions complete

u

194

Summaryu

Start an Oracle DATABASEn

Log onto the host O/S, set up the proper environment and then run sqlplus /nolog

u

A database startup proceeds in three stages:n

Starting the instance (NOMOUNT) Opening the controlfile(s) (MOUNT) Opening the datafiles and redo logfiles (OPEN)

n

n

u

Ways to shutdown a database:n

Abort, Immediate, Normal and transactional

195

Oracle Database Administration I 65

Oracle Database Administration ILesson 3 Creating and Managing Tablespaces

Creating and Managing Tablespacesu

Agendan

Describe Oracle tablespaces Create and modify tablespaces Manage tablespaces by querying the appropriate data dictionary views

n

n

197

Creating and Managing Tablespacesu

All schema objects within the database (tables, views, packages, functions) are stored in segments and collectively stored in tablespacesn

A tablespace is a logical unit of storage that is defined within Oracle Each tablespace corresponds to one or more operating-system level datafiles Each segment is contained in a single tablespace

n

n

198

Oracle Database Administration I 66

Creating and Managing Tablespaces

199

Creating and Managing Tablespacesu

A tablespace can be in several states while the database is openn

Online or Offline Read-only or read-write

n

u

A tablespace can be altered back and forth between these options as neededn

Conditions must be tested before each alter (no current transactions may be active)

200

Creating and Managing Tablespacesu

Each database must be created with at least one tablespace (SYSTEM).n

This holds all data dictionary objects and built-in PL/SQL program units (procedures, functions, packages and triggers)

u

Each tablespace can contain one or more schemas and each schema can have one or more objectsn

Each object can span more than one datafile per tablespace

201

Oracle Database Administration I 67

Creating and Managing Tablespacesu

When the Oracle Universal Installer (OUI) or OEM creates a database, it creates several tablespaces by default. For example:n

SYSTEM - contains system definitions (Required) TEMP - used for sorting RBS/UNDO - used for rollback/UNDO segments TOOLS - used for storing PL/SQL program units USERS - used as default tablespace for users

n

n

n

n

202

Creating and Managing Tablespacesu

Prior to creating a tablespace, the DBA will need to consider (covered extensively in Lesson 5):n

Tablespace storageu

This includes the type of data file to create

n

Segment storage Disk contention Free space and segment fragmentation

n

n

203

Tablespace Storageu

Tablespace Storage considerationsn

System limitation on datafile size Database limitation when database is created (maxdatafiles) Data file managementu

n

n

Autoextend feature on an existing datafile Manually adding a datafile

u

204

Oracle Database Administration I 68

Data File Types and Behavioru u u u

Permanent Temporary Oracle Managed Files (OMF) Extent managementn

Dictionary Locallyu u

n

Uniform extent autoallocated

205

Tablespace Storageu

Each tablespace contains object segment(s) Each segment is subdivided into logical units of storage called EXTENTSu

u

When a user creates an object (such as tables, views, sequences) within the database, Oracle allocates an extent(s) within a tablespace in which to store the objects segment(s)

206

Tablespace Storage

207

Oracle Database Administration I 69

Segment Storageu

Segments can span across datafiles, but extents cannot Each segment can be composed of one or more extents Each extent is further subdivided into units of storage called DATABASE BLOCKS Extents must be made up of contiguous DATABASE BLOCKS

u

u

u

208

Database Blocksu

Not identical to operating system-level file blocks A logical database block may span multiple system level blocks Should be created to either fit into an OS-level file block or be the same

u

u

209

Database Blocksu

The size of each database block is determined by the parameter DB_BLOCK_SIZE in the initialization parameter file This size is fixed during database creation time. Cannot be changed unless the database is re-created The default DB_BLOCK_SIZE is 2048 bytes

u

u

210

Oracle Database Administration I 70

Tablespace Storageu

Logical storage hierarchy:n

Tablespaceu

Object segmentu

Extentsu

Oracle Blocks

211

Dictionary vs. Localu

Starting with 8i, you can now create tablespaces that are managed locally within the header file of the tablespace If you specify local in a create tablespace, you cannot specify default storage, minextents, nor temporary clause Local allows two types of management: uniform extent or autoallocate

u

u

212

Create Tablespace (dictionary)u

Create a tablespace using the CREATE TABLESPACE SQL command. The syntax for dictionary managed is:CREATE TABLESPACE datafile 'size [M|K] [autoextend_clause] DEFAULT STORAGE () [online|offline];

u

213

Oracle Database Administration I 71

Create Tablespace (local)u

Create locally managed tablespace syntax:CREATE TABLESPACE datafile '' size [M|K] EXTENT MANAGEMENT LOCAL UNIFORM SIZE [M|K];

214

Create Tablespace (OMF)u

Create an Oracle Managed File in a default location for datafile creation with defaults of 100M size and unlimited autoextensible maximum size:alter system set db_create_file_dest CREATE TABLESPACE ;

=

215

Datafile Namingu

The datafile name must contain the absolute pathn

No UNIX/NT variable names nor VMS logicals should be specified in the datafile name

u

The directory that contains the datafile MUST have write permissions for the Oracle software owner

216

Oracle Database Administration I 72

UNIX Namingu

Examplen

Create a tablespace called DEVELOPMENT Specify a datafile '/u01/oradata/SEED/SEED_DEVELOPMENT_01.dbf' with a size of 300 Megabytes Make this tablespace available to all users immediately

n

n

217

UNIX Naming Exampleu

The answer is:2> 3> datafile '/u01/oradata/SEED/SEED_DEVELOPMENT_01.dbf' size 300M;

SQL> create tablespace development

Tablespace created.

218

VMS Namingu

Example:n

Create a tablespace called RBS Specify a datafile 'dka300:[oradata.seed]seed_rbs_01.dbf' with a size of 300 Megabytes Make this tablespace available to all users immediately and autoextensible at 500k increments to a maximum of 400 megabytes

n

n

219

Oracle Database Administration I 73

VMS Naming Exampleu

The answer is:

SQL> create tablespace rbs 2> 3> 4> datafile 'dka300:[oradata.seed]seed_rbs_01.dbf size 300M autoextend on next 500k maxsize 400M;

Tablespace created.

220

NT Namingu

Examplen

Create a tablespace called NEWDATA Specify a datafile d:\oradata\seed\seed_newdata_01.dbf' with a size of 900 Kilobytes Make this tablespace unavailable to users.u

n

n

Extra credit what is missing with the final statement and assumed?

221

NT Naming Exampleu

The answer is:

SQL> create tablespace newdata 2> 3> datafile d:\oradata\seed\seed_newdata_01.dbf size 900K offline;

Tablespace created.

222

Oracle Database Administration I 74

Creating and Managing Tablespacesu

When creating datafiles for tablespaces, adopt a common file naming convention Most Oracle file types are named as follows (see next slides)

u

223

Creating and Managing Tablespacesu

DATAFILES__.dbf

u

Examplen

The third datafile of the SYSTEM tablespace belonging to the SEED database system_SEED_03.dbf

224

Creating and Managing Tablespacesu

Use the ALTER DATABASE SQL command to modify the characteristics of an existing tablespacen

Add/rename/change the state of a datafile Change a tablespace to read-only Take a tablespace offline/online Change the storage parameters To begin/end online hot backups Coalesce free space

n

n

n

n

n

225

Oracle Database Administration I 75

Alter Tablespace Syntax

226

Datafile Options

227

Creating and Managing Tablespacesu

Example:n

Add a second 100 MB datafile to the system tablespace Place the datafile under/u01/oradata/SEED/SYSTEM_SEED_02.dbf

n

n

Make it readily available

228

Oracle Database Administration I 76

Example Alter TablespaceSQL> alter tablespace system 2 add datafile '/u01/oradata/SEED/system_SEED_02.dbf 3 size 100M; Tablespace altered.

229

Creating and Managing Tablespacesu

Examplen

Change the development tablespace to read-only mode The syntax is:

n

SQL> alter tablespace development read only; Tablespace altered.

230

Creating and Managing Tablespacesu

Adding a datafile to a tablespacen

Space from the new file is automatically allocated to the tablespace The new datafile can reside on a separate disk Oracle treats this and all datafiles belonging to a tablespace as a single logical entity

n

n

231

Oracle Database Administration I 77

Creating and Managing Tablespaces

Tablespace

Datafile #1

Datafile #2

n

Once a datafile is added to a tablespace, you cannot delete it unless the tablespace is first dropped

232

Creating and Managing Tablespacesu

To drop any tablespace (except SYSTEM) use the DROP TABLESPACE SQL command The syntax is:

u

DROP TABLESPACE [INCLUDING CONTENTS [CASCADE CONSTRAINTS]]

233

Creating and Managing Tablespacesu

A tablespace that contains data cannot be dropped unless the INCLUDING CONTENTS option is specifiedn

If constraints exist between objects in the tablespace to be dropped and objects in another tablespace, the CASCADE CONSTRAINTS option must be specified along with the INCLUDING CONTENTS option

234

Oracle Database Administration I 78

Creating and Managing Tablespacesu

Once a tablespace is dropped, the datafile(s) associated with the tablespace must be deleted on the operating system leveln

The DROP command only removes that tablespace from the data dictionary Cannot drop the SYSTEM tablespace because it contains the data dictionary Once a drop is executed, it cannot be undone

n

n

235

Creating and Managing Tablespacesu

Examplen

Drop the DEVELOPMENT tablespace, including all contents The syntax is:

n

SQL> drop tablespace development including contents; Tablespace dropped.

236

OEM

237

Oracle Database Administration I 79

Summaryu

Steps to creating and managing tablespacesn

Prepare the operating system Determine storage options Execute the CREATE TABLESPACE SQL and ALTER TABLESPACE command Ways to manage the stored data

n

n

n

238

Oracle Database Administration ILesson 4 Creating an Oracle Database

Creating an Oracle Databaseu

Agendan

Methods of creation Set up the proper operating system environment prior to creating a database Execute the CREATE DATABASE SQL command Execute the proper scripts that build the data dictionary and PL/SQL procedures

n

n

n

240

Oracle Database Administration I 80

Creation Methodsu u u

OEM Database configuration assistant When the Oracle software is installed Manually, either with scripts or by command line

241

Creating an Oracle Databaseu

Six general steps to creating a databasen

Preparing the Operating System Creating a parameter file Starting the instance Creating the database Building the data dictionary Building the system PL/SQL procedures

n

n

n

n

n

242

Creating an Oracle Databaseu

Preparing the Operating Systemn

An Oracle database consists of datafiles, redo log files, and control files Prior to creating a database, the location(s) of these files should be thought out carefully Space will need to be allocated for the files The system administrator will need to create the appropriate directories and set the proper permissions for these files

n

n

n

243

Oracle Database Administration I 81

Creating an Oracle databaseu

All systemsn

The owner of the directories should be the Oracle software owner (typically "oracle").u

On Unix systems, the dba group will also be the group owner of the directory. On VMS, the user must have the ORA_DB rights identifier ON NT, the user must be in the group ORA_DBA

u un

The Oracle software owner should be the only user that has write access to these directories

244

Create the Oracle User environment UNIXu

Unixn

(as root)

Bash# cd /u01 bash# mkdir oradata bash# chown oracle:dba oradata bash# chmod 755 oradata

245

Create the Oracle User Environment VMSu

VMSn

(as SYSTEM)

$ Set default dka300:[000000] $ create/dir [.oradata] $ set file/own=oracle oracle.dir $ set prot=(S:RWED,O:RWED,G:RE,O:RE) oracle.dir

246

Oracle Database Administration I 82

Create the Oracle User Environment NTu

NTn

(As administrator) Use Administrative tools in 'Settings' or the Manage option in 'My Computer'u u

n

Create the partitions Define a user with administrative privileges.

247

Setting the Database Nameu

Setting the name of the database:n

UNIX Enter the new name in /var/opt/oracle/oratab VMS Run ora_find_sid.com to register the database NT Run oradim to create a new database service Labels each database with a unique identifieru u

n

n

n

Known as the ORACLE SYSTEM IDENTIFIER Referred to as the ORACLE SID

248

Defining the Oracle SIDu

Identifies which database a user will connect to upon executing an Oracle applicationu

Unix/NT - ORACLE SID is designated by an environment variable, $ORACLE_SID VMS Oracle SID is a logical, ORA_SID

u

249

Oracle Database Administration I 83

Setting the Oracle SIDu

Now that a SID is defined:n

Set the SID in the proper manner for the OSu u u

UNIX VMS NT

export ORACLE_SID=TRNG define ora_sid trng set ORACLE_SID=TRNG

n

Once the ORACLE SID is set, all subsequent Oracle I/O affects the associated database

250

Creating the Parameter fileu

Defines and configures the parameters that configure the database All parameters are customizable by the DBA Read at instance startup First created as an ASCII file (initSID.ora) As of 9i, a binary (spfileSID.ora) file can be created and be managed once the instance is started

u u u u

251

Parameter Fileu

Great care should be taken in the sizing of each parameter If a parameter is not defined, Oracle will provide defaultsn

u

To view all defined and defaulted values, run sqlplus as sys or system and issue:Show parameters

or

view v$parameter

u

See example in the workbook.

252

Oracle Database Administration I 84

Default Parameter File Locationu

Unixn

Oracle looks for the associated parameter file under $ORACLE_HOME/dbs/init.orau

This is usually a link to the real init.ora

u

VMSn

Oracle looks for the associated parameter file underORA_ROOT:[db_]__init.ora

u

NTn

Oracle looks under$ORACLE_HOME\database\init.ora

253

Creating an Oracle databaseu

Oracle provides a template init.ora located under:n n n

$ORACLE_HOME/dbs (Unix) ORA_RDBMS (VMS) $ORACLE_HOME\admin\sample\pfile (nt)

u

For example,n

If you have a database with a SID of SEED, Oracle looks for the associated parameter file under:u u

$ORACLE_HOME/dbs/initSEED.ora (Unix) ORA_ROOT:[db_seed]PLUTO_SEED_init.ora (VMS)

254

Questions?u

Refer to the workbook for a sample init.ora filen

What is the default block size? Is the buffer cached defined in blocks or bytes? Can you have more than one value for the service_names value? Which control file is read when the database is opened?

n

n

n

255

Oracle Database Administration I 85

Creating an Oracle databaseu

Most associated parameters take default values if they are not explicitly defined The values that MUST be defined in each file are:n

u

db_name (set to the same value as the ORACLE SID) control_files (should point to the location of the control files)

n

256

Which type of Data File?u

Dictionary managedn

Default storage clause used Uniform extent Autoallocate Oracle manages the allocation, growth and removal Default file location defined in the init.ora

u

Locally managedn n

u

Oracle managed files (OMF)n n

257

Creating an Oracle databaseu

Invoke Oracle as: sqlplus /nolog Connect to the database as the sysdba user Start the Oracle instance (nomount)n

u

u

Only allowable startup level since control files, redo log files, and datafiles do not exist at this point

258

Oracle Database Administration I 86

Creating an Oracle databaseThe workbook illustrates how to start a database in nomount mode

u

259

Creating an Oracle databaseu

Once the Oracle instance is started, execute a CREATE DATABASE SQL command. Below is an abridged syntax:

CREATE DATABASE DATAFILE '' size M LOGFILE GROUP '' size M

260

Creating an Oracle databaseu

The datafile defined becomes the first datafile of the SYSTEM TABLESPACE Each database MUST have at least two logfile groups For additional options of the CREATE DATABASE SQL command, consult the ORACLE SERVER ADMINISTRATOR'S GUIDE

u u

261

Oracle Database Administration I 87

Creating an Oracle databaseSQL> create database SEED 2> datafile '/oradata/SEED/system_SEED_01.dbf' size 200M 3> logfile group 1 '/oradata/SEED/log_SEED_01.rdo' size 3M, 4> group 2 '/oradata/SEED/log_SEED_02.rdo' size 3M 5> / Statement processed.

262

Creating an Oracle databaseu

Once the CREATE DATABASE command is executed, a new database is createdn

The control files associated with this database are also created in the location(s) designated in the parameter file

263

Creating an Oracle databaseu

Now the data dictionary and PL/SQL packages need to be built The scripts catalog.sql, catproc.sql need to run against the databasen

u

The former script MUST be run first

264

Oracle Database Administration I 88

Creating an Oracle databaseu

These scripts are located under:n

$ORACLE_HOME/rdbms/admin (unix/NT) ORA_ROOT:[rdbms] (VMS)

n

SQL> @?/rdbms/admin/catalog SQL> @?/rdbms/admin/catproc

265

Creating an Oracle databaseu

Once these scripts have run, two default users are created in the databasen

SYS (initial password change_on_install) SYSTEM (initial password MANAGER)

n

u

Both users have DBA authority over the databasen

These users should NEVER be deleted from the database

266

Data dictionaryu

Composed of a set of tables and views Read-only Provides information about the associated database Created by SQL script catalog.sql

u

u

u

267

Oracle Database Administration I 89

Data dictionaryu

Data dictionary contains the following:n

Usernames of the associated database Security Names and definitions of scheme objects Space allocation for database objects Auditing information Triggers, functions, packages, and stored procedures

n

n

n

n

n

268

Data dictionaryu

Scripts that construct the data dictionaryn

CATALOG.SQLu

Commonly used data dictionary views

n

CATPROC.SQLu

Scripts for PL/SQL on server

n

NOTE: The owner of the data dictionary is SYS

269

Data dictionary viewsu

Display basic information about Oracle accountsn

SQL> select * from all_users;

u

Display DBA informationn

SQL> select * from dba_users;

u

Rollback segments and their statusn

SQL> select segment_name, status 2> from dba_rollback_segs;

n

270

Oracle Database Administration I 90

Summaryu

Steps to creating an Oracle databasen

Preparing the O/S Determining the ORACLE SID Creating a parameter file Starting the instance Executing the CREATE DATABASE SQL command Building the data dictionary and PL/SQL packages

n

n

n

n

n

271

Oracle Database Administration ILesson 5 Space Management

Basics of Storageu

Tablespace - Logical storage area within an Oracle Database that subdivides the databasen

The placement and composition of a tablespace are critical for optimization

u

Data File - Physical files that make up a tablespacen

Size and structure should be well planned out

273

Oracle Database Administration I 91

Space Componentsu

Database block - smallest unit of storage within an Oracle database Extent - Contiguous allocation of database blocks Segment - Logical collection of extents that make up a table, cluster, index, temporary segment, or UNDO segment

u u

274

Segment Storage Attributesu

Each of these extent options should be reviewed individuallyn

Initial Next Minextents Maxextents -

Allocates the first extent of space Size of the extent allocated after the initial Number of extents allocated during the initial creation of the segment Limits the total number of extents the segment can create

n

n

n

275

Additional Storage Optionsu

Pctincrease - controls the rate of growth of extents beyond the secondn

If UNDO segments are being configured, this is not an option

u

PCTFREE - reserved portion of the data block that is used for later updates to rows in that block PCTUSED- percentage of space in a data block used before allocating another block A block is kept on the free list until it reaches PCTFREE A block stays off the free list until PCTUSED is reached

u

u

u

276

Oracle Database Administration I 92

Segment Creation Optionsu u

Tablespace - The tablespace to store the segments Partitioning - Feature of Oracle8 that allows a segment to be separated into multiple segments, each existing in a single or multiple tablespaces Optimal - sets the optimal size in bytes for a rollback segment (not used with UNDO)

u

277

ExampleCreate table EMP ( EMPID NUMBER, F_Name L_Name MI SSN VARCHAR2(25), VARCHAR2(25), VARCHAR2(1), VARCHAR2(11)

) Pctfree 10 Pctused 40 storage (Initial 2K Next 2K Pctincrease 0 unlimited) Tablespace USERS; Maxextents

278

Storage Considerationsu

Object creation parameters override tablespace default storage parameters with the exception of locally managed tablespaces as of Oracle8i Locally managed tablespaces enforce the use of uniform extent size or the size that has been autoallocated by Oraclen

u

One exception -- import (discussed in DBAII)

279

Oracle Database Administration I 93

Local vs. Dictionary Managedu

Two DBA philosophies:n

Dictionary managedu u

Grouping of tables are by schema, not table Can take schema offline (ie, bad blocks, recovery)

n

Locally managedu u

Never have tablespace fragmentation with uniform extents Never have to worry about extent growth with autoallocate

280

Physical Database Attributesu

Autoextend vs adding datafilesn

Both can be executed when the database is up Both can extend the tablespace and be ready for use immediately

n

u

Autoextending an existing datafile can alleviate DBA worries, but adversely can waste space Adding a datafile is under your controlAlter tablespace add datafile /u01/oradata/seed/newfile_seed_02.dbf size 500M;

u

281

RAIDu

RAIDn

Important to have for an Oracle system Jbod Lowest data cost low overhead 0 low data cost load balancing 1, 0+1 high data cost most expensive 5 Highest data cost safeu

n

n

n

n

It takes four I/Os for one write (read data, read parity,write data, write parity) Minimum of three disks, plus 66-87% of space The more disks, the higher the gain

u u

282

Oracle Database Administration I 94

Questionsu

What are the two ways to use the autoextend clause? Which segment type does not use the pctincrease storage clause? What would you think would be less problematic in regards to objects needing extents?

u

u

283

Storage issuesu

Disk contentionn

Background process content for data access

u

Segment fragmentationn

Seek time is reduced

u

Free space fragmentationn

Cannot allocate a contiguous extent

284

Disk Contentionu

Too many heavily used segments on a single disk slows down access time and causes degradation in database performance System (Data Dictionary), TEMP and UNDO segment tablespaces are used constantlyu

u

Keeping these tablespaces on separate disks ensures the best access time

285

Oracle Database Administration I 95

Fragmentation Issuesu

Fragmentationn

Frequent writes to a tablespace lead to greater fragmentation Fragmented tablespaces run slower and require more disk activity then non-fragmented tablespaces Thus, objects should be grouped into tablespaces based on their activity and size

n

n

286

Levels of Fragmentationu

Levels of fragmentationn

Application Interim Segmentu

Data changes are moderate, allowing for some fragmentation

n

UNDO Segmentsu

Used regularly with constant changes to data. Fragmentation is high

n

Temporary Segmentsu

Data is swapped in and out constantly. Fragmentation is highest

287

Free Space vs. Segmentu

Free space fragmentation is determined by the number of contiguous free space chunks within a tablespace Segment fragmentation is determined by the number of extents relative to the number of segments within a tablespace

u

288

Oracle Database Administration I 96

Free Space Fragmentationu u

Caused by dropping or truncating segments Categorized as usable or unusablen

A usable free space chunk is large enough to be used by the growth of an existing segment An unusable free space chunk is too small to be used by an existing segment

n

289

Segment Fragmentationu u

Caused by segments requiring multiple extents Using a uniform extent size (i.e. locally managed tablespaces) will alleviate this Manage this by monitoring dba_segments and dba_free_space

u

290

Common Methodologiesu

Uniform Extent sizesn

Eliminates unusable free space fragmentation Does not eliminate segment fragmentation Minimizes maintenance efforts Extent sizes should be carefully chosen to achieve best performance

n

n

n

291

Oracle Database Administration I 97

Common Methodologiesu

Appropriate sizing of segmentsn

Often complicated and time-consuming Bound to a finite period of time for growing tables

n

u

Rebuilds (imp/exp)n

Eliminate existing fragmentation by using imp/exp (discussed further in DBAII)

292

Common Methodologiesu

Using Pctincrease 100n

Minimizes segment fragmentation Minimizes maintenance efforts Extent sizes grow exponentially Requires large free space chunks to be available

n

n

n

293

Dictionary Viewsu

DBA_FREE_SPACEn

How much free space is available

u

DBA_SEGMENTSn

Information about all segments

u

DBA_EXTENTSn

Describes the extents of all objects

294

Oracle Database Administration I 98

Summaryu u u u u

Basics of Space Storage Storage Parameters Default Storage Parameters Fragmentation Methodologies for maintaining

295

Oracle Database Administration ILesson 6 Creating and Managing UNDO Segments

Creating and Managing Rollback/UNDO Segmentsu

Agendan

Theory behind rollback/UNDO segments Rollback/UNDO segments within an Oracle Database Rollback/UNDO segments used in transactions Rollback/UNDO segments used in read-consistency

n

n

n

297

Oracle Database Administration I 99

UNDO Segmentsu

Database objects that record old values of data before the data are modified by transactions Used to recover the database Provide read consistency Allow certain transactions to be undone (rolled back)

u u u

298

UNDO Segmentsu u

Undo management is new term for rollback Two options under 9in

Manual undo managementu

Oracle7/8i/9i rollback segments

n

Automatic undo managementu

AKA Automatic Undo Management (AUM) or System Managed Undo (SMU)

299

What are UNDO segments for?u

Three purposes for undon

Read consistency Transaction rollback Transaction recoveryu

n

n

New purpose in 9i

300

Oracle Database Administration I 10 0

Types of Undo Segmentsu

SYSTEMn

Used for objects in SYSTEM tablespace

u

Non-SYSTEMn

Used for objects in other tablespacesu u

Automatic (UNDO) Manual (rollback segments)

u

Deferredn

Used for offline tablespace

301

Why Use AUM?u

Easier to administern

In a recent Oracle benchmark, 400 rollback segments were replaced by one undo tablespace

u

Reduced chance of common errorsn

snapshot too oldu

DBA selected retention period Dynamic extent transfer

n

unable to extend rollback segmentu

302

Dynamic Extent Transferu

Extents within undo tablespace may switch ownership from one segment to another Prevents single large transaction from affecting other users Space reuse is more efficient, so errors are less likely Eliminates need for managing rollback space for online and batch differently

u u u

303

Oracle Database Administration I 10 1

Automatic Undo Managementu

New initialization parameters UNDO_MANAGEMENTn

AUTOu u u

Undo segments managed internally No CREATE, DROP, ALTER Automatic creation, shrinking, etc.

n

MANUALu

Default; DBA-managed rollback segments

304

UNDO valuesu

UNDO_TABLESPACEn

Defines the name of the tablespace used to hold the undo segments

u

UNDO_RETENTIONn

Controls amount of undo data to retainu u

Specify in seconds Read consistency and Oracle Flashback

305

UNDO Segmentsu

Discrete database objectsn

Reside within a specific tablespace

u

Each segment allocates extents within a tablespace to store table data before the data are modified

306

Oracle Database Administration I 10 2

UNDO Segmentsu

Can hold data for multiple transactions A single transaction must be contained in a single segment Provided maximum number of extents has not been reached

u

u

307

Creating UNDO Tablespaceu u

The tablespace is all that needs to be created with AUM. Usually created at database creation time as part of the CREATE DATABASE statement: UNDO TABLESPACE undotbs datafile'/u02/oradata/SEED/undodbs_seed_01.dbf' size 200m autoextend off

308

SYSTEM Rollback Segmentu

Default rollback segment is automatically created during database creation Cannot be deleted Segment resides in the SYSTEM tablespace Can only be used for SYSTEM objects Create a second one for creating the tablespaces during creation of a database

u

u

u

u

309

Oracle Database Administration I 10 3

SYSTEM Rollback Segmentu

Additional rollback/UNDO segments must be created to hold rollback data for objects in nonSystem tablespaces The size and number of segments must be monitored:n

u

v$rollstat, dba_segments

310

Create a Rollback Segmentu

CREATE ROLLBACK SEGMENT SQL command syntax:

CREATE ROLLBACK SEGMENT TABLESPACE [STORAGE |OPTIMAL]

NOTE: this is not required with 9i

311

Storage clauseu

Allows the DBA to set the sizing of the rollback segment(s) The DBA may allow Oracle to size the rollback segment automatically MINEXTENTS for rollback segments must be 2

u

u

312

Oracle Database Administration I 10 4

Create a Rollback Segmentu

Must reside in a rollback tablespacen

Example with Default storage parameters chosen:

SQL >create rollback segment rbs1 2 >tablespace rbs / Rollback segment created.

313

ALTER ROLLBACK SEGMENTu

Once the rollback segment is created, It must be brought online before it can store transaction information An entry must be made in the initSID.ora file to be brought online each time the instance is start Use the rule of four to estimate:n

u

u

# rollback = transactions/4

314

ALTER ROLLBACK SEGMENTALTER ROLLBACK SEGMENT ONLINE|OFFLINEu

ONLINEn

Brings rollback segment online Available for subsequent transactions Takes rollback segment offline Unavailable for subsequent transactions Will not go offline until all transactions have completed

n

u

OFFLINEn n

n

315

Oracle Database Administration I 10 5

When the database is shut down and restartedu u

Only the SYSTEM rollback segment is brought online Only the segment names in the ROLLBACK_SEGMENTS parameter in the initialization parameter file are brought onlineROLLBACK_SEGMENTS=(RBS1,RBS2)

u

Query the data dictionary view to check the status of all rollback segments:sys.dba_rollback_segs

316

Rollback Information Storedu

Each time a transaction is executed against the database, Oracle automatically allocates an available UNDO segment Unchanged data is stored for transaction and session rollback To ensure that each user has a consistent view of the data they are working on.

u

u

317

Request a Rollback Segmentu

Programmatically, you can specify the rollback segment to usen

Prior to executing the SQL statement, execute: SET TRANSACTION USE ROLLBACK SEGMENT Example:

n

SQL>SET TRANSACTION USE ROLLBACK SEGMENT RBS1; Transaction set.

318

Oracle Database Administration I 10 6

ExampleEMPNO | ENAME 00100 | John Doe 00200 | Sue Smith 00300 | Jane Goodall 00400 | Sam Tyson 00500 | Mike Jones | DEPTNO | | 001 | 001 | 001 | 001 | 001 | | | | | SAL 15000 15000 15000 15000 15000 -----------------------------------------

u u

The Emp table holds this information prior to the transaction Before the statement is applied, a free UNDO segment is obtained

319

Statement is ExecutedSQL> update emp set sal=30000 where empno=0500; 1 row updated.

u u

The user executes this SQL statement If the user commits, the rollback/UNDO segment is released

320

Rollback Statementu

To undo changesn

Execute a ROLLBACK SQL statement This undoes the update statement and copies information back into the table

n

SQL> rollback; Statement processed.

321

Oracle Database Administration I 10 7

Oracle Flashbacku

Consistent view of database at past pointn

Read-only Export and query Protection against user erroru

n

n

Uh, I just deleted 1,000 rows from SPRIDEN. Can you restore it for me? UNDO_RETENTION parameter

n

Must be using AUM in order to use Flashbacku

322

Using Flashbacku u u

User needs execute on DBMS_FLASHBACK Retention time must be long enough to be useful Query as usual after enabling FlashbackCALL dbms_flashback.enable_AT_time ('25-MAR-02:08:00:00'); SELECT * FROM emp; CALL dbms_flashback_disable();

323

Dictionary Viewsu

V$rollstatn

Number of times a rollback segment has wrapped Number of times it has extended Number of times it has shrunk

n

n

u

V$rollnamen

Maps the rollback segment to its name by USN

324

Oracle Database Administration I 10 8

Data Dictionary Language (DDL) statementsu

Change the internal structure of the database They do not use rollback/UNDO segments during processing Once SQL statements are executed, they cannot be rolled back!

u

u

325

Summaryu

UNDO segments provide the user the ability to undo DML statements within the database UNDO segments also provide read-consistency within the database UNDO is a special type of segment Rollback segments are kept for backwards compatiblity

u

u

u

326

Oracle Database Administration ILesson 7 Creating and Managing Database Users

Oracle Database Administration I 10 9

Creating and Managing Database Usersu

Agendan

Create new Database Users Modify existing Database Users Monitor information about Database Users Drop Database Users Terminate user sessions

n

n

n

n

328

Creating and Managing Database Usersu

Creating users under Oraclen

Created within the database or OEM Not defined in the underlying operating system

n

u

Oracle stores internal user account information within the data dictionary in an encrypted format

329

CREATE USER SQL

330

Oracle Database Administration I 11 0

Create User Considerationsu

If you do not specify a default tablespace, the user is assigned to SYSTEM If not explicitly specified, users have a QUOTA of 0 on all tablespaces By default, the account is not locked and the password is not pre-expired

u

u

331

Default Temporary Tablespaceu

If you do not specify a temporary tablespace, temporary segments default to the SYSTEM tablespace In 9i, if you create the default temporary tablespace for everyone you do not need to worry about this To use this new feature, create it at database creation time or later It must be of type temporary

u

u

u

332

Create a Useru

Example:n

Create a user SAISUSR with a password of u_pick_it Assign a default tablespace of USERS and a quota of 100KB on the DEVELOPMENT tablespace Specify the temporary tablespace to be TEMP (Syntax is on the next slide.)

n

n

n

333

Oracle Database Administration I 11 1

Example of Creating a UserSQL> create user saisusr identified by u_pick_it 2> default tablespace USERS 3> temporary tablespace TEMP 4> quota 100K on development 5> / Statement Processed.

334

User Passwordsu

During the CREATE USER command, the assigned password echoes on the screenu u

Note that the password is stored in encrypted form The encryption algorithm is DES-128 bit

u

Oracle passwords are NOT case-sensitive

335

Password Agingu

You can use Password Managementn

Run the script utlpwmg.sql to start

u

You can setu u u u

Password attempts Grace periods History Many more!

336

Oracle Database Administration I 11 2

Object Ownershipu

As with an OS account, Oracle assigns an ownership to all database objects that you create in the databasen

This ownership is known as a user's SCHEMA

u

When a user creates an object in the database, it is created under that user's SCHEMA

337

Joe Creates a Tableu

Examplen

User joe creates a table dept within the database This table is created under joe's ownership or schema

n

SQL> create table dept 2> (deptno number(25), 3> dname varchar2(100)) / Table created.

338

Creating and Managing Database Usersu

Now, connect to the database as chris. SQL> connect chris/u_pick_it Connected.