arabic oracle

43
GnanaSekar. A DBA - 1 TABLE OF CONTENTS 1. ORACLE ARCHITECTURAL COMPONENTS.......................................................................3 Physical Files ................................ ................................ ................................ ................................ ................... 3 Backgroung Processes ................................ ................................ ................................ ................................ .... 3 Memory Area (SGA) ................................ ................................ ................................ ................................ ........ 4 How Oracle processes a query ................................ ................................ ................................ ...................... 4 How Oracle processes a DML statement ................................ ................................ ................................ .... 4 How Oracle processes a COMMIT statement ................................ ................................ ............................ 5 2. STARTUP AND SHUTDOWN A DATABASE .......................................................................5 Parameter File ................................ ................................ ................................ ................................ ................. 5 STARTUP Command ................................ ................................ ................................ ................................ ....... 6 SHUTDOWN Command ................................ ................................ ................................ ................................ . 6 Basic Dynamic Performance View ................................ ................................ ................................ ............... 7 How to terminate a user session ................................ ................................ ................................ ................... 7 3. CREATE A DATABASE ....................................................................................................7 STEP 1 . Set the operating system variables. ................................ ................................ .............................. 7 STEP 2. Prepare the parameter file. ................................ ................................ ................................ ............. 8 STEP 3. Start the instance in NOMOUNT stage. ................................ ................................ ....................... 8 STEP 4. Create the database ................................ ................................ ................................ ......................... 8 STEP 5. Run scripts to generate the data dictionary and accomplish postcreation steps. ................. 8 Troubles Shooting of Create Database ................................ ................................ ................................ ........ 9 What you get after the database is created ................................ ................................ ................................ . 9 4. MAINTAINING THE CONTROL FILE .................................................................................9 Features and Contents of Control File ................................ ................................ ................................ ........ 9 Multiplex the Control File ................................ ................................ ................................ .............................. 9 5. MAINTAINING REDO LOG FILES.....................................................................................9 Features and Contents of Redo Log Files ................................ ................................ ................................ ... 9 Views about Redo Log Files ................................ ................................ ................................ ........................ 11 Maintenance Operations on Redo Log files ................................ ................................ .............................. 11 6. TABLESPACES AND DATA FILES...................................................................................12 Logical and Physical Structure of a database ................................ ................................ .......................... 12 SYSTEM and Non-SYSTEM Tablespaces ................................ ................................ ................................ .. 13 Creating Tablespaces ................................ ................................ ................................ ................................ ... 13 Four Methods to increase the size of tablespaces ................................ ................................ .................... 13 READ-ONLY Tablespace ................................ ................................ ................................ ............................. 14 Dropping Tablespaces ................................ ................................ ................................ ................................ .. 15 Dictionary Views about tablespaces and data files ................................ ................................ ................. 15 7. STORAGE STRUCTURE AND RELATIONSHIPS ................................................................16 Storage Clause Precedence ................................ ................................ ................................ ......................... 16 Extent Allocation and Deallocation ................................ ................................ ................................ ........... 16 Block Space Utilization Parameters ................................ ................................ ................................ ........... 16 Dictionay Views about storage ................................ ................................ ................................ ................... 17 8. ROLLBACK SEGMENT...................................................................................................18 Purpose of Rollback Segment ................................ ................................ ................................ ...................... 18 How transactions use Rollback Segment ................................ ................................ ................................ ... 18 Creating Rollback Segment ................................ ................................ ................................ ......................... 19 Offline and Drop Rollback Segment ................................ ................................ ................................ ........... 20 Dictionary Views about Rollback Segment ................................ ................................ ............................... 20 9. TEMPORARY S EGMENT ................................................................................................21 Temporary Segments in a Temporary Tablespace ................................ ................................ ................... 21 Views about temporary segments ................................ ................................ ................................ ................ 21 This watermark does not appear in the registered version - http://www.clicktoconvert.com

Upload: eldeebnet

Post on 10-Apr-2015

563 views

Category:

Documents


0 download

DESCRIPTION

Arabic introduction to oracle

TRANSCRIPT

Page 1: Arabic Oracle

GnanaSekar. A

DBA - 1

TABLE OF CONTENTS

1. ORACLE ARCHITECTURAL COMPONENTS.......................................................................3Physical Files ................................ ................................ ................................ ................................ ................... 3Backgroung Processes ................................ ................................ ................................ ................................ .... 3Memory Area (SGA) ................................ ................................ ................................ ................................ ........ 4How Oracle processes a query ................................ ................................ ................................ ...................... 4How Oracle processes a DML statement ................................ ................................ ................................ .... 4How Oracle processes a COMMIT statement ................................ ................................ ............................ 5

2. STARTUP AND SHUTDOWN A DATABASE .......................................................................5Parameter File ................................ ................................ ................................ ................................ ................. 5STARTUP Command ................................ ................................ ................................ ................................ ....... 6SHUTDOWN Command ................................ ................................ ................................ ................................ . 6Basic Dynamic Performance View ................................ ................................ ................................ ............... 7How to terminate a user session ................................ ................................ ................................ ................... 7

3. CREATE A DATABASE ....................................................................................................7STEP 1 . Set the operating system variables. ................................ ................................ .............................. 7STEP 2. Prepare the parameter file. ................................ ................................ ................................ ............. 8STEP 3. Start the instance in NOMOUNT stage. ................................ ................................ ....................... 8STEP 4. Create the database ................................ ................................ ................................ ......................... 8STEP 5. Run scripts to generate the data dictionary and accomplish postcreation steps. ................. 8Troubles Shooting of Create Database ................................ ................................ ................................ ........ 9What you get after the database is created ................................ ................................ ................................ . 9

4. MAINTAINING THE CONTROL FILE .................................................................................9Features and Contents of Control File ................................ ................................ ................................ ........ 9Multiplex the Control File ................................ ................................ ................................ .............................. 9

5. MAINTAINING REDO LOG FILES.....................................................................................9Features and Contents of Redo Log Files ................................ ................................ ................................ ... 9Views about Redo Log Files ................................ ................................ ................................ ........................ 11Maintenance Operations on Redo Log files ................................ ................................ .............................. 11

6. TABLESPACES AND DATA FILES...................................................................................12Logical and Physical Structure of a database ................................ ................................ .......................... 12SYSTEM and Non-SYSTEM Tablespaces ................................ ................................ ................................ ..13Creating Tablespaces ................................ ................................ ................................ ................................ ... 13Four Methods to increase the size of tablespaces ................................ ................................ .................... 13READ-ONLY Tablespace ................................ ................................ ................................ ............................. 14Dropping Tablespaces ................................ ................................ ................................ ................................ ..15Dictionary Views about tablespaces and data files ................................ ................................ ................. 15

7. STORAGE STRUCTURE AND RELATIONSHIPS ................................................................16Storage Clause Precedence ................................ ................................ ................................ ......................... 16Extent Allocation and Deallocation ................................ ................................ ................................ ........... 16Block Space Utilization Parameters ................................ ................................ ................................ ........... 16Dictionay Views about storage ................................ ................................ ................................ ................... 17

8. ROLLBACK SEGMENT...................................................................................................18Purpose of Rollback Segment ................................ ................................ ................................ ...................... 18How transactions use Rollback Segment ................................ ................................ ................................ ... 18Creating Rollback Segment ................................ ................................ ................................ ......................... 19Offline and Drop Rollback Segment ................................ ................................ ................................ ........... 20Dictionary Views about Rollback Segment ................................ ................................ ............................... 20

9. TEMPORARY SEGMENT ................................................................................................21Temporary Segments in a Temporary Tablespace ................................ ................................ ................... 21Views about temporary segments ................................ ................................ ................................ ................ 21

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 2: Arabic Oracle

GnanaSekar. A

DBA - 2

10. MANAGING TABLES ...................................................................................................21ROWID in Oracle 8 ................................ ................................ ................................ ................................ ....... 21High Water Mark ................................ ................................ ................................ ................................ ........... 22ANALYZE TABLE command ................................ ................................ ................................ ........................ 23DBMS_ROWID Package ................................ ................................ ................................ .............................. 23

11. MANAGING INDEXES..................................................................................................24B-Tree Index ................................ ................................ ................................ ................................ ................... 24Reverse Key Index ................................ ................................ ................................ ................................ .......... 24Bitmap Index ................................ ................................ ................................ ................................ ................... 24When we need to rebuild indexes? ................................ ................................ ................................ ............. 25ANALYZE INDEX command ................................ ................................ ................................ ........................ 25

12. MAINTAINING DATA INTEGRITY ................................................................................25Types of Constraints ................................ ................................ ................................ ................................ ...... 25Three States of Constraints ................................ ................................ ................................ .......................... 26Deferred and non-deferred constraints ................................ ................................ ................................ ..... 27

13. CLUSTERS AND INDEX-ORGANIZED TABLES ..............................................................28Creating Index Cluster ................................ ................................ ................................ ................................ .28Creating Hash Clusters ................................ ................................ ................................ ................................ 28Index-Organized Tables ................................ ................................ ................................ ............................... 29

14. SQL*LOADER, IMPORT/EXPORT.........................................................................30SQL*Loader Features ................................ ................................ ................................ ................................ ... 30Files Used by SQL*Loader ................................ ................................ ................................ .......................... 30Comparing Direct and Conventional Path Loads ................................ ................................ ................... 31Uses of Export and Import ................................ ................................ ................................ ........................... 31

15. MANAGING DATABASE USERS...................................................................................32Checklist for Creating Users ................................ ................................ ................................ ........................ 32Examples and Guidelines about users ................................ ................................ ................................ ....... 32Dictionary Views about Users ................................ ................................ ................................ ..................... 33

16. MANAGING USER PROFILES.......................................................................................33User Profiles and resource limits ................................ ................................ ................................ ............... 33How to enforce resource limit using profiles ................................ ................................ ............................ 34Password Management ................................ ................................ ................................ ................................ 35Dictionary Views about user profiles ................................ ................................ ................................ ......... 35

17. MANAGING PRIVILEGES.............................................................................................36SYSTEM Privileges ................................ ................................ ................................ ................................ ........ 36Examples about system privileges ................................ ................................ ................................ .............. 36Dictionary Views about system privileges ................................ ................................ ................................ .37Object Privileges ................................ ................................ ................................ ................................ ............ 38Examples about object privileges ................................ ................................ ................................ ............... 40Dictionary Views about object privileges ................................ ................................ ................................ ..40

18. MANAGING ROLES.....................................................................................................40What is role? ................................ ................................ ................................ ................................ ................... 40Manapulating Roles ................................ ................................ ................................ ................................ ...... 41

FREQUENTLY ASKED QUESTIONS IN ORACLE 8 DATABASE ADMINISTRATION................42

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 3: Arabic Oracle

GnanaSekar. A

DBA - 3

1. Oracle Architectural Components

Physical Files

Data files

store the data dictionary, user objects, and before-images of data that are modified bycurrent transactions. A database has at least one data file.

Redo logfiles

contain a record of changes made to the database to ensure reconstruction of the datain case of failures. A database requires at least two redo log files.

Control files

contain the information needed to maintain and verify database integrity. A databaseneeds at least one control file.

Backgroung Processes

The background processes in an instance perform common functions that are needed to service therequests from several concurrent users, without compromising the integrity and performance of thewhole system. Each Oracle instance may use several background processes, depending on theconfiguration, but every instance comprises these five background processes by default:

DBWR

The server process records changes to rollback and data blocks in the buffer cache.The database writer (DBWR) writes the dirty buffers from the database buffer cacheto the data files. It ensures that sufficient number of free buffers—buffers that can beoverwritten when server processes need to read in blocks from the data files—areavailable in the database buffer cache. Database performance is improved becauseserver processes only make changes in the buffer cache, and the DBWR deferswriting to thedata files until one of the following events occur:

· The number of dirty buffers reaches a threshold value· A process scans a specified number of blocks when scanning for free buffers and

cannot find any

· A timeout occurs· A DBWR checkpoint can be triggered by various events such as closing· of the database, (Checkpoint is a means of synchronizing the database buffer

cache with the data file.)LGWR

The Log Writer (LGWR) is a background process that writes entries from the redolog buffer into the redo log files. The LGWR performs sequential writes to the redolog file under the following situations:· When the redo log buffer is one-third full

· When a timeout occurs (every three seconds)· Before DBWR writes modified blocks in the database buffer cache to the· data files

· When a transaction commits

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 4: Arabic Oracle

GnanaSekar. A

DBA - 4

SMON

· Performs automatic instance recovery.· Reclaims space used by temporary segments no longer in use.

· Merges contiguous areas of free space in the datafiles. PMON

· Cleans up abnormally terminated connections.

· Rolls back uncommitted transactions.· Releases locks held by a terminated process.· Frees SGA resources allocated to the failed process.

CKPT

Checkpoint Process is responsible for updating the database status informationwhenever changes in the buffer cache are permanently recorded in the database.

Memory Area (SGA)

Shared Pool

· Size defined by SHARED_POOL_SIZE in parameter file

· Library cache contains statement text, parsed code, and an execution plan. Sincethe library cache stores this information, if a query is reexecuted before itsexecution plan is aged out by other statements, the server process does not needto parse the statement. Thus the library cache helps improve the performance ofapplications.

· Data dictionary cache stores the most recently used data dictionary information,such as table and column definitions, usernames, passwords, and privileges.During the parse phase, the server process looks for the information in thedictionary cache to resolve the object names specified in the SQL statement andto validate the access privileges. If necessary, the server process initiates theloading of this information from the data files.

Database BufferCache

· Number of buffers defined by DB_BLOCK_BUFFERS· Size of a buffer based on DB_BLOCK_SIZE

· Stores the most recently used blocksRedo LogBuffer

· Size defined by LOG_BUFFER· Records changes made through the instance

· Used sequentially· Circular buffer

How Oracle processes a query

1. Parse: In this stage, the user process sends the query to the server process with a request to parseor compile the query. The server process checks the validity of the command and uses the area inthe SGA known as the shared pool to compile the statement. At the end of this phase, the serverprocess returns the status—that is, success or failure of the parse phase—to the user process.

2. Execute: During this phase in the processing of a query, the server process prepares to retrieve thedata.

3. Fetch: The rows that are retrieved by the query are returned by the server to the user during thisphase. Depending on the amount of memory used for the transfer, one or more fetches are requiredto transfer the results of a query to the user.

How Oracle processes a DML statement

1. The server process reads the data and rollback blocks from the data files, if they are not already inthe buffer cache.

2. Copies of the blocks that are read are placed in the buffer cache.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 5: Arabic Oracle

GnanaSekar. A

DBA - 5

3. The server process places locks on the data.

4. The server process records the changes to be made to the rollback (before-image) and to the data(new value) in the redo log buffer.

5. The server process records the before-image to the rollback block and updates the data block, bothin the database buffer cache. Both the changed blocks in the buffer cache are marked as dirtybuffers —that is, buffers that are not the same as the corresponding blocks on the disk.

How Oracle processes a COMMIT statement

1. The server process places a commit record, along with the SCN, in the redo log buffer.

2. LGWR performs a contiguous write of all the redo log buffer entries up to and including thecommit record to the redo log files. After this point, the Oracle server can guarantee that thechanges will not be lost even in case of failures.

3. The user is informed that the COMMIT is complete.

4. The server process records information to indicate that the transaction is complete and thatresource locks can be released.

2. Startup and Shutdown a Database

Parameter FileThe parameter file, commonly referred to as the init<SID>.ora file, is a text file that can be maintainedusing a standard operating system editor. By default, it is located in the $ORACLE_HOME/dbsdirectory on a UNIX machine and in the %ORACLE_HOME%\database directory on NT. Theparameter file is only read during instance startup. If the file is modified, shut down and restart theinstance to make the new parameter values effective. The uses of parameter file are :· Size the System Global Area (SGA) components to optimize performance.· Set database and instance defaults.

· Set database limits.· Define (on database creation only) various physical attributes of the database, such as the database

block size.

· Specify control files, archived log files, and trace file locations.

Parameter File Example

# Initialization Parameter File: initDB1.oradb_name = DB1control_files = (/DISK1/control01.con, /DISK2/control02.con)db_block_size = 8192db_block_buffers = 2000shared_pool_size = 30000000log_buffer = 65536processes = 50max_dump_file_size = 10240background_dump_dest =(/home/disk3/user15/BDUMP)user_dump_dest =(/home/disk3/user15/UDUMP)rollback_segments = (r01,r02,r03,r04)...

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 6: Arabic Oracle

GnanaSekar. A

DBA - 6

STARTUP Command

Example

SVRMGR> CONNECT / AS SYSDBASVRMGR> STARTUP PFILE=/DISK1/initDB1.ora

Startup Stages

Parameter file is readInstance is started

(Memory/SGA is allocated, Background Processes started)

------------------------NOMOUNT

Control file is readDatabase configuration is loaded into SGA

------------------------MOUNT

Datafiles and redo log files are located

Verify all the datafiles and redo log files can beopened

Check the consistency of the database

Database opened ------------------------OPENUsers can access the database

SHUTDOWN Command

Syntax

SHUTDOWN [NORMAL | TRANSACTIONAL | IMMEDIATE | ABORT ]

Shutdown Mode ABORT IMMEDIATE TRANSACTIONAL NORMALAllow new connections X X X XWait until current sessions end X X X symbol 252

\f"Wingdings" \s 10ü}

Wait until current transactions end X X symbol 252 \f"Wingdings" \s 10ü}

symbol 252\f

"Wingdings" \s 10ü}

Force a checkpoint and closefiles

X symbol 252 \f"Wingdings"

\s 10ü}

symbol 252 \f"Wingdings" \s 10ü}

symbol 252\f

"Wingdings" \s 10ü}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 7: Arabic Oracle

GnanaSekar. A

DBA - 7

Basic Dynamic Performance View

Dynamic Performance View(accessible in the NOMOUNT stage or above)

Description

V$PARAMETER Contains information about the initialization parameterV$SGA Contains summary information on the SGAV$OPTION Lists options that are installed with the Oracle server

V$PROCESS Contains information about the currently active processV$SESSION Lists current session informationV$VERSION Lists the version number and the components

V$INSTANCE Displays the state of the current instance

Dynamic Performance View ( accessible in the MOUNT stage or above)

Description

V$THREAD Contains thread information, for example about theredo log groups

V$CONTROLFILE Lists the names of the control files (Even thoughavailable, this view returns no rows in NOMOUNTstate.)

V$DATABASE Contains database informationV$DATAFILE Contains data file information from the control fileV$LOGFILE Contains information about the online redo log files

How to terminate a user session

Example : To kill scott’s session

SVRMGR> SELECT sid, serial# FROM v$session WHERE 2> username=‘SCOTT’;

SID SERIAL#------ --------- 7 15

SVRMGR> ALTER SYSTEM KILL SESSION ‘7,15’;

3. Create a Database

STEP 1 . Set the operating system variables.

On UNIX set the following environment variables:

Variable DescriptionORACLE_HOME Set to the directory where the Oracle software will be

installed (Example: /u01/app/oracle/product/8.0.3)

ORACLE_SID Specifies the instance name and must be unique forOracle instances running on the same machine.

PATH Search path which must include $ORACLE_HOME/bin

On NT Set the variable ORACLE_SID to use SVRMGR30. Create the service and the passwordfile with ORADIM80.

C:\> ORADIM80 -NEW -SID u16

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 8: Arabic Oracle

GnanaSekar. A

DBA - 8

-INTPWD password -STARTMODE auto-PFILE ORACLE_HOME\DATABASE\initU16.ora

STEP 2. Prepare the parameter file.

Create parameter file using any editor in the operation system.

# Initialization Parameter File: initDB1.oradb_name = DB1control_files = (/DISK1/control01.con, /DISK2/control02.con)db_block_size = 8192db_block_buffers = 2000shared_pool_size = 30000000log_buffer = 65536processes = 50max_dump_file_size = 10240background_dump_dest =(/home/disk3/user15/BDUMP)user_dump_dest =(/home/disk3/user15/UDUMP)rollback_segments = (r01,r02,r03,r04)......

STEP 3. Start the instance in NOMOUNT stage.

SVRMGR> CONNECT / AS SYSDBASVRMGR> STARTUP NOMOUNT PFILE=initDB1.oraORACLE instance started.

STEP 4. Create the database

Issue the CREATE DATABASE command in server manager

CREATE DATABASE DB1 MAXLOGFILES 5 MAXLOGMEMBERS 5 MAXDATAFILES 100LOGFILE GROUP 1 '/DISK3/log1a.rdo' SIZE 1 M, GROUP 2 ’/DISK3/log2a.rdo' SIZE 1 MDATAFILE '/DISK1/system01.dbf' size 50M

STEP 5. Run scripts to generate the data dictionary and accomplishpostcreation steps.After database creation, the catalog.sql and catproc.sql scripts must be run as the user SYS. Theyare located in the $ORACLE_HOME/rdbms/admin directory on UNIX and in the%ORACLE_HOME%\rdbms80\admin directory on NT.

Script Purposecatalog.sql Creates commonly used data dictionary viewscatproc.sql Runs all scripts required for PL/SQL on the server

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 9: Arabic Oracle

GnanaSekar. A

DBA - 9

Troubles Shooting of Create Database

Creation of the database fails if:

· There are syntax errors in the SQL script· Files that should be created already exist· Operating system errors such as file or directory permission or insufficient space errors occur

What you get after the database is created

· Data files which make up the SYSTEM tablespace

· Control files and redo log files· User SYS/change_on_install· User SYSTEM/manager· Rollback segment SYSTEM

· Internal tables (but no data dictionary views) So you need to run catalog.sql

4. Maintaining the Control File

Features and Contents of Control File

· Is a binary file that is necessary for the database to start and operate successfully.· Every time an instance mounts an Oracle database, it reads the control file to locate the data files

and online redo log files.· Is updated continuously during database use and must be available whenever the database is

mounted or opened.

· Provides information about database consistency used during recovery.· If any of the control files currently being used by the database becomes unavailable, then the

database cannot function properly.

· In summary, control file contains the following information¾ Database name¾ Data file location¾ Redo log file location

¾ Tablespace names¾ Current log sequence number¾ Checkpoint information

¾ Log history¾ Backup information

Multiplex the Control File

To add an additional control file to play use the following steps:

1. Shut down the database.

2. Make a copy of the existing control file to a different device using operating system commands.

3. Edit or add the CONTROL_FILES parameter and specify names for all the control files.

4. Start up the database.

5. Maintaining Redo Log Files

Features and Contents of Redo Log Files

· Used to store the ‘transaction history’· The Oracle server maintains online redo log files to minimize the loss of data in the database. The

redo log files record all changes made to data in the database buffer cache.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 10: Arabic Oracle

GnanaSekar. A

DBA - 10

· Redo log files are used in a situation such as an instance failure to recover committed data that has

not been written to the data files. The redo log files are only used for recovery.

Group 2 Group 3Group 1

Member

Member

Disk 1

Disk 2Member

Member Member

Member

· A set of identical copies of online redo log files is called an online redo log group .· The background process LGWR concurrently writes the same information to all online redo log

files in a group.

· The Oracle server needs a minimum of two online redo log file groups for the normal operation ofa database.

· Each online redo log file in a group is called a member .

· Each member in a group has identical log sequence numbers and the same size. The log sequencenumber is assigned each time the Oracle server starts writing to a log group to identify each redolog file uniquely. The current log sequence number is stored in the control file and in the header ofall data files.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 11: Arabic Oracle

GnanaSekar. A

DBA - 11

Views about Redo Log Files

SVRMGR> SELECT group#,sequence#,bytes,members,status2> FROM v$log;

GROUP# SEQUENCE# BYTES MEMBERS STATUS------ --------- ------- ------- -------- 1 688 1048576 1

CURRENT 2 689 1048576 1

INACTIVE2 rows selected.

SVRMGR> SELECT * 2> FROM v$logfile;

GROUP# STATUS MEMBER------ ------ ----------------------- 1 /DISK3/log1a.rdo 2 /DISK4/log2a.rdo2 rows selected.

Maintenance Operations on Redo Log files

Example 1 : Adding Online Redo Log Groups

SVRMGR> ALTER DATABASE ADD LOGFILE 2> (‘/DISK3/log3a.rdo’) size 1M;

Example 2 : Adding Online Redo Log Members

SVRMGR> ALTER DATABASE ADD LOGFILE MEMBER 2> ‘/DISK4/log1b.rdo’ TO GROUP 1, 3> ‘/DISK4/log2b.rdo’ TO GROUP 2;

Example 3 : Dropping Online Redo Log Groups

SVRMGR> ALTER DATABASE DROP LOGFILE GROUP 3;

Example 4 : Dropping Online Redo Log Members

SVRMGR> ALTER DATABASE DROP LOGFILE MEMBER 2> ‘/DISK4/log2b.dbf’;

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 12: Arabic Oracle

GnanaSekar. A

DBA - 12

6. Tablespaces and Data Files

Logical and Physical Structure of a database

Database

Logical Physical

Tablespace Data file

O/S BlockOracle block

Segment

Extent

Tablespaces

· A tablespace can belong to only one database.· Each tablespace consists of one or more operating system files.· Tablespaces can be brought online while the database is running.· Except for the SYSTEM tablespace or a tablespace with an active rollback segment, tablespaces

can be taken offline, leaving the database running.· Tablespaces can be switched between read-write and read-only status.· Controlling space allocation and assigning space quotas to users

· Controlling availability of data by taking individual tablespaces online or offline· Distributing data storage across devices to improve I/O performance and to reduce I/O contention

against a single disk

· Performing partial backup and partial recovery operations· Keeping large amounts of static data on read-only devices

Data Files· Each tablespace in an Oracle database consists of one or more files called data file s. These are

physical structures that conform with the operating system on which the Oracle server is running.· A data file can belong to only one tablespace.

· An Oracle server creates a data file for a tablespace by allocating the specified amount of diskspace plus a small overhead.

· The database administrator can change the size of a data file after its creation or can specify that adata file should dynamically grow as objects in the tablespace grow.

Segments

· A segment is the space allocated for a specific type of logical storage structure within a tablespace.The following are examples of segments:

¾ Table segment

¾ Index segment¾ Temporary segment¾ Rollback segment

· A segment such as a data segment may span multiple files that belong to the same tablespace.

Extents· An extent is a set of contiguous number of blocks.

· Each type of segment is made up of one or more extents.· An extent may not span a data file, but must exist in one data file.

Data Blocks

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 13: Arabic Oracle

GnanaSekar. A

DBA - 13

· At the finest level of granularity, the data in an Oracle database is stored in data blocks.

· One data block corresponds to one or more physical file blocks allocated from an existing data file.· Data block size is specified for each Oracle database by the initialization parameter

DB_BLOCK_SIZE when the database is created.· The smallest unit of input-output.

SYSTEM and Non-SYSTEM Tablespaces

SYSTEM Tablespace· Automatic created after the database is created· Required in all databases for database operation· Contains data dictionary information, definitions of stored procedures, packages, and database

triggers· Contains the SYSTEM rollback segment· Should not contain user data although it is allowed

Non-SYSTEM Tablespace· Enable more flexibility in database administration

· Can store rollback segments, temporary segments, application data, and application indexes

Creating Tablespaces

Example

CREATE TABLESPACE app_dataDATAFILE ‘/DISK4/app01.dbf’ SIZE 100M, ‘/DISK5/app02.dbf’ SIZE 100MMINIMUM EXTENT 500KDEFAULT STORAGE ( INITIAL 500K

NEXT 500K MINEXTENTS 3

MAXEXTENTS 500 PCTINCREASE 50);

· INITIAL defines the size of the first extent. The minimum size of the first extent is two blocks,that is (2*DB_BLOCK_SIZE). The default size is 5 blocks, that is (5* DB_BLOCK_SIZE).

· NEXT refers to the size of the second extent. The minimum size of the next extent is one block.The default size is 5 blocks, that is (5* DB_BLOCK_SIZE).

· MINEXTENTS is the number of extents allocated when the segment is created. The minimumand default is 1.

· PCTINCREASE is the percent by which the extent size grows. The size of an extent is calculatedusing the following formula:

· MAXEXTENTS determines the maximum number of extents that a segment can have. Theminimum value is 1. The default maximum value depends on the data block size. The maximumsize can also be specified by the keyword UNLIMITED, which is equivalent to a value of2147483645.

Four Methods to increase the size of tablespaces

Method 1 : Adding Data Files to a Tablespace

ALTER TABLESPACE app_data ADD DATAFILE‘/DISK5/app03.dbf’ SIZE 200M;

Method 2 : Enabling Automatic Extension of new created Data Files

ALTER TABLESPACE app_data ADD DATAFILE

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 14: Arabic Oracle

GnanaSekar. A

DBA - 14

‘/DISK6/app04.dbf’ SIZE 200MAUTOEXTEND ON NEXT 10M MAXSIZE 500M;

Method 3 : Enabling Automatic Extension of existing Data Files

ALTER DATABASEDATAFILE ‘/DISK5/app03.dbf’AUTOEXTEND ON NEXT 10M MAXSIZE 500M;

Method 4 : Changing the Size of Data Files Manually

ALTER DATABASE DATAFILE ‘/DISK5/app02.dbf’RESIZE 200M;

READ-ONLY Tablespace

Making tablespaces read-only prevents further write operations on the data files. The purpose of read-only tablespaces is to ensure that no changes are made and to eliminate the need to perform backup andrecovery of large, static portions of a database. The Oracle server never updates the files of a read-onlytablespace, and therefore the files can reside on read-only media, such as CD ROMs or WORM drives.

Example : Make tablespace APP_DATA only available for read operations.

ALTER TABLESPACE app_data READ ONLY;

To make a tablespace READ-ONLY

· The tablespace must be online.· No active transactions are allowed.· The tablespace must not contain active rollback segments.

· The tablespace must not currently be involved in an online backup

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 15: Arabic Oracle

GnanaSekar. A

DBA - 15

Dropping Tablespaces

· A tablespace that still contains data cannot be dropped without the INCLUDING CONTENTSoption.

· Once a tablespace has been dropped, its data is no longer in the database.

· When a tablespace is dropped, only the file pointers in the control file of the associated databaseare dropped. The database files still exist and must be deleted explicitly at the operating systemlevel.

· Even if a tablespace is switched to read-only it can still be dropped, along with segments within it.This is possible because the DROP command only updates the data dictionary (which has to beread-write), but not the physical files that make up the tablespace.

· It is recommended that you take the tablespace offline before dropping it to ensure that notransactions access any of the segments in the tablespace.

Example : Removes the APP_DATA tablespace and all its contents

DROP TABLESPACE app_dataINCLUDING CONTENTS;

Dictionary Views about tablespaces and data files

SVRMGR> SELECT tablespace_name, contents,status 2 > FROM dba_tablespaces;

TABLESPACE_NAME CONTENTSSTATUS

--------------- ---------- ------SYSTEM PERMANENT

ONLINERBS PERMANENT

ONLINETEMP TEMPORARY

ONLINEDATA01 PERMANENT

ONLINE4 rows selected.

SVRMGR> SELECT tablespace_name, initial_extent, next_extent, 2 > max_extents, pct_increase, min_extlen 3 > FROM dba_tablespaces;

TABLESPACE INITIAL_EX NEXT_EXT MIN_EXTENT MAX_EXTENT PCT_I---------- ---------- -------- ---------- ---------- -----SYSTEM 10240 10240 1 121 50RBS 10240 10240 1 121 50TEMP 262144 262144 1 999 50DATA01 204800 204800 1 999 504 rows selected.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 16: Arabic Oracle

GnanaSekar. A

DBA - 16

SVRMGR> SELECT file_name, tablespace_name, bytes, 2 > autoextensible, maxbytes, increment_by 3 > FROM dba_data_files;

FILE_NAME TABLESPACE_NAME BYTES AUT MAXBYTES INCR------------------- --------------- -------- ---- -------- -----/DISK1/system01.dbf SYSTEM 31457280 NO 0 0/DISK2/rbs01.dbf RBS 5242880 NO 0 0/DISK3/temp01.dbf TEMP 5242880 NO 0 0/DISK4/data01.dbf DATA01 5242880 NO 0 0/DISK5/data02.dbf DATA01 512000 YES 15728640 5125 rows selected.

7. Storage Structure and Relationships

Storage Clause Precedence

· Any storage parameter specified at the segment level overrides the corresponding option set at thetablespace level, except for the MINIMUM EXTENT tablespace parameter.

· When storage parameters are not explicitly set at the segment level, they default to those at thetablespace level.

· When storage parameters are not explicitly set at the tablespace level, the Oracle server systemdefaults apply.

· If storage parameters are altered, the new options apply only to the extents not yet allocated.

· Some parameters cannot be specified at the tablespace level. These parameters need to be specifiedat the segment level only.

· If minimum extent size has been specified for the tablespace, this size will apply to all extents thatare subsequently allocated for segments in the tablespace.

Extent Allocation and Deallocation

· Allocated when the segment is

¾ Created¾ Extended¾ Altered

· Deallocated when the segment is¾ Dropped¾ Altered¾ Truncated

¾ Automatically resized (rollback segments only)

Block Space Utilization Parameters

INITRANS

Which defaults to 1 for a data segment, and 2 for an indexs segment, guaranteesminimum level of concurrency. For example, if set to 3, INITRANS ensures that atleast three transactions can concurrently make changes to the block. If necessary,additional transaction slots can be allocated from the free space in the block, topermit more concurrent transactions to modify rows in the block.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 17: Arabic Oracle

GnanaSekar. A

DBA - 17

MAXTRANS

Which has a default value of 255, sets the limit for the number of concurrenttransactions that can make changes to a data or an index block. When set, this valuerestricts use of space for transaction slots and therefore guarantees that there issufficient space in the block for use by row or index data.

PCTFREE

For a data segment specifies the percentage of space in each data block reserved forgrowth resulting from updates to rows in the block. The default for PCTFREE is 10percent.

PCTUSED

For a data segment represents the minimum percentage of used space that OracleServer tries to maintain for each data block of the table. A block is put back on thefree list when its used space falls below PCTUSED. The free list of a segment is alist of blocks that are candidates for accommodating future inserts. A segment, bydefault, is created with one free list. Segments can be created with a higher numberof free lists by setting the FREELISTS parameter of the storage clause. The defaultfor PCTUSED is 40 percent.

Dictionay Views about storage

SVRMGR> SELECT segment_name,tablespace_name,extents,blocks 2> FROM dba_segments

3> WHERE owner='SCOTT';

SEGMENT_NAME TABLESPACE_NAME EXTENTS BLOCKS------------ --------------- ------- -------EMP DATA01 5 55DEPT DATA01 1 5BONUS DATA01 1 5SALGRADE DATA01 1 5DUMMY DATA01 1 55 rows selected.

SVRMGR> SELECT extent_id,file_id,block_id,blocks 2> FROM dba_extents 3> WHERE owner='SCOTT' AND segment_name='EMP';

EXTENT_ID FILE_ID BLOCK_ID BLOCKS--------- -------- --------- ------- 0 4 2 5 1 4 27 5 2 4 32 10 3 4 42 15 4 4 57 205 rows selected.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 18: Arabic Oracle

GnanaSekar. A

DBA - 18

SVRMGR> SELECT tablespace_name, count(*), 2> max(blocks), sum(blocks) 3> FROM dba_free_space 4> GROUP BY tablespace_name;

TABLESPACE_NAME COUNT(*) MAX(BLOCKS SUM(BLOCKS--------------- -------- ----------- ----------DATA01 2 1284 1533RBS 3 2329 2419SORT 1 1023 1023SYSTEM 1 5626 5626TEMP 1 2431 24315 rows selected.

8. Rollback Segment

Purpose of Rollback Segment

Transaction Rollback

When a transaction makes changes to a row in a table, the old image is saved in the rollback segment.If the transaction is rolled back, the value in the rollback segment is written back to the row, restoringthe original value.

Read Consistency

When transactions are in progress, other users in the database should not see any uncommitted changesmade by these transactions. In addition, a statement should not see any changes that were committedafter the statement commences execution. The old values in the rollback segments are also used toprovide the readers a consistent image for a given statement.

Transaction Recovery

If the instance fails when transactions are in progress, Oracle server needs to rollback the uncommittedchanges when the database is opened again. This rollback is known as transaction recovery and is onlypossible if changes made to the rollback segment are also protected by the redo log files.

How transactions use Rollback Segment

Transaction 14 3

1 2

Transaction 2

1. When a transaction begins, a rollback segment needs to be assigned to this transaction.

2. A transaction may request a specific rollback segment using the following command: SET TRANSACTION USE ROLLBACK SEGMENT rollback_segment

3. If no such request is made, the Oracle server chooses the rollback segment with the fewesttransactions, and assigns it to the transaction.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 19: Arabic Oracle

GnanaSekar. A

DBA - 19

4. Transactions use extents of a rollback segment in an ordered circular fashion, moving from one to

the next after the current extent is full. A transaction writes a record to the current location in therollback segment and advances the current pointer by the size of the record.

1 2

4 3

1 2

3

4

5

5. The pointer or the head of the rollback segment moves to the next extent when the current extent isfull. When the last extent that is currently available is full, the pointer can only move back to thebeginning of the first extent if that extent is free. The pointer cannot skip over an extent and moveto the second or any other extent. If the first extent is being used, the transaction will allocate anadditional extent for the rollback segment. This is called an extend. Similarly, if the head tries tomove into an extent and that extent is active, the rollback segment will allocate an additionalextent. A rollback segment may grow in this manner until it reaches the maximum number ofextents specified by the MAXEXTENTS parameter.

6. The OPTIMAL parameter specifies the size in bytes that a rollback segment must shrink to, ifpossible. Specifying OPTIMAL minimizes the waste of space in a rollback segment. If theOPTIMAL parameter is specified, a rollback segment can release space on completion oftransactions that caused the growth.

Creating Rollback Segment

Example :

SVRMGR> CREATE ROLLBACK SEGMENT rbs01 2> TABLESPACE rbs 3> STORAGE ( INITIAL 100K 4> NEXT 100K 5> OPTIMAL 4M 6> MINEXTENTS 20 7> MAXEXTENTS 100);

SVRMGR> ALTER ROLLBACK SEGMENT rbs01 ONLINE;

Specify the following initialization parameter to ensure rollback segments are brought online atSTARTUP:

ROLLBACK_SEGMENTS=(rbs01)

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 20: Arabic Oracle

GnanaSekar. A

DBA - 20

Offline and Drop Rollback Segment

Take a rollback segment offline:

· To prevent new transactions from using a rollback segment· If the rollback segment needs to be dropped

ALTER ROLLBACK SEGMENT rbs01 OFFLINE;

· A rollback segment may need to be dropped if it is no longer needed or if it needs to be recreatedwith different storage settings like INITIAL, NEXT, and MINEXTENTS.

· A rollback segment needs to be offline before it can be dropped.

DROP ROLLBACK SEGMENT rbs01;

Dictionary Views about Rollback Segment

SVRMGR> SELECT segment_name, tablespace_name, owner, status 2> FROM dba_rollback_segs;

SEGMENT_NAME TABLESPACE_NAME OWNER STATUS------------ ---------------- ----- -------SYSTEM SYSTEM SYS ONLINERBS1 RBS SYS ONLINERBS2 RBS SYS ONLINERBS3 RBS SYS OFFLINE4 rows selected.

SVRMGR> SELECT usn, extents, rssize, optsize, hwmsize, xacts, status 2> FROM v$rollstat

USN EXTENTS RSSIZE OPTSIZE HWMSIZE XACTS STATUS--- -------- ------- -------- -------- ----- ----------------0 43 2199552 2199552 0 ONLINE1 20 202752 204800 417792 0 ONLINE2 4 38912 38912 0 PENDING OFFLINE3 rows selected.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 21: Arabic Oracle

GnanaSekar. A

DBA - 21

9. Temporary Segment

· Temporary segments are used when statements such as the following are executed and the Oracleserver cannot perform the sorting needed in memory because it is bigger than SORT_AREA_SIZE

¾ SELECT. . . ORDER BY

¾ CREATE INDEX¾ SELECT DISTINCT¾ SELECT. . . GROUP BY

· The amount of memory used by a process for sorting is determined by the SORT_AREA_SIZEinitialization parameter. If the sort volume exceeds this size, several sort runs are needed, andintermediate results are stored on disk.

· Temporary segments are created and used by the Oracle server in the tablespace that has beenassigned to the user for sorting.

Temporary Segments in a Temporary Tablespace

· Known as sort segments

· Only one segment per tablespace per instance· Created when the first disk sort occurs in the instance after startup· Reused by several transactions based on information in the Sort Extent Pool

· Released on instance shutdown

Views about temporary segments

· DBA_SEGMENTS Query this view to get information on both types of temporary segments.

· V$SORT_SEGMENT This view gives the status of the sort extent pool used by the instance.

· V$SORT_USAGEThis view only shows currently active sorts for the instance.

10. Managing Tables

ROWID in Oracle 8

OOOOOO BBBBBBFFF RRR

Data objectnumber

Relative filenumber

Row numberBlock number

ROWID Format

ROWID is a pseudo-column that can be queried along with other columns ina table. It has the following characteristics:· ROWID is a unique identifier for each row in the database.

· ROWID is not stored explicitly as a column value.· Although the ROWID does not directly give the physical address of a row, it can be used to locate

the row.· ROWID provides the fastest means of accessing a row in a table.

· ROWIDs are stored in indexes to specify rows with a given set of key values.

ROWID needs 10 bytes of storage on disk and is displayed using 18characters. It consists of the following components:· Data Object Number is assigned to each data object, such as table or index when it is created, and

it is unique within the database.· Relative File Number is unique to each file within a tablespace.· Block Number represents the position of the block, containing the row, within the file.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 22: Arabic Oracle

GnanaSekar. A

DBA - 22

· Row Number identifies the position of the row directory slot in the block header.

Example :

SVRMGR> SELECT deptno, ROWID2> FROM scott.dept;3>

DEPTNO ROWID------ ------------------10 AAAArsAADAAAAUaAAA20 AAAArsAADAAAAUaAAB30 AAAArsAADAAAAUaAAC40 AAAArsAADAAAAUaAAD4 rows selected.

In this example:· AAAArs is the data object number.

· AAD is the relative file number.· AAAAUa is the block number.· AAA is the row number for the department with DEPTNO=10.

High Water Mark

Extent ID 0 1 2 3 4

· The high water mark for a table indicates the last block that was ever used for the table.

· As data is inserted into the table, the high water mark is moved to mark the last block used.· The high water mark is not reset when rows are deleted from the table.· The high water mark is stored in the segment header of the table.

· When the Oracle server performs full table scans, it reads all the blocks up to the high water mark.· If large extents have been allocated to a table, but have not been used fully, it is possible to

manually deallocate space from the table by the following command. The space thus released isavailable for use by other segments in the tablespace.

ALTER TABLE scott.employeesDEALLOCATE UNUSED;

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 23: Arabic Oracle

GnanaSekar. A

DBA - 23

ANALYZE TABLE command

Example 1 : To verify the integrity of each data block of scott’s employees table.

ANALYZE TABLE scott.employees VALIDATESTRUCTURE;

Example 2 : Gather statistics on scott’s employees table

ANALYZE TABLE scott.employees COMPUTESTATISTICS;

· The statistics generated by the ANALYZE command will be stored in the data dictionary. E.g.dba_tables.

· The COMPUTE STATISTICS option will generate statistics based on a full table scan, while theESTIMATE STATISTICS will generate statistics based on a sample.

· When statistics are generated, the CHAIN_CNT column of the data dictionary viewDBA_TABLES is updated with the number of rows that are chained or migrated. If a large numberof rows are migrated, then the table needs to be reorganized to eliminate migration.

DBMS_ROWID Package

Function Name DescriptionROWID_CREATE Creates a ROWID from individual componentsROWID_OBJECT Returns the object identifier for a ROWID

ROWID_RELATIVE_FNO Returns the relative file number for a ROWIDROWID_BLOCK_NUMBER Returns the block number for a ROWIDROWID_ROW_NUMBER Returns the row number for a ROWID

ROWID_TO_ABSOLUTE_FNO Returns the absolute file number for a ROWIDROWID_TO_EXTENDED Converts a ROWID from restricted to extendedROWID_TO_RESTRICTED Converts a ROWID from extended to restricted

Example : To obtain the physical location of the rows in a table.

SVRMGR> SELECT deptno, ROWID, 2> DBMS_ROWID.ROWID_OBJECT(ROWID) AS OBJECT, 3> DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID) AS "RELATIVE FILE", 4> DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID) AS BLOCK

5> FROM scott.departments;

DEPTNO ROWID OBJECT RELATIVE F BLOCK------ ------------------- ------ ----------- ------10 AAAArsAADAAAAUaAAA 2796 3 130620 AAAArsAADAAAAUaAAB 2796 3 130630 AAAArsAADAAAAUaAAC 2796 3 130640 AAAArsAADAAAAUaAAD 2796 3 13064 rows selected.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 24: Arabic Oracle

GnanaSekar. A

DBA - 24

11. Managing Indexes

B-Tree Index

Index entry header

Key column length

Key column value

ROWID

Root

Branch

Leaf

Index entry

· At the top of the index is the root, which contains entries that point to the next level in the index.

· At the next level are branch blocks, which in turn point to blocks at the next level in the index.· At the lowest level are the leaf nodes, which contain the index entries that point to rows in the

table. The leaf blocks are doubly linked to facilitate scanning the index in an ascending as well asdescending order of key values.

Example : Create a normal B-Tree index on the last_name column of scott’s employees table

CREATE INDEX scott.emp_lname_idxON scott.employees(last_name)PCTFREE 30STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)TABLESPACE indx01;

Reverse Key Index

· A reverse key index reverses the bytes of each column indexed (except the ROWID) whilekeeping the column order. When inserting records on an ascending key, such as a system-generated employee number, I/O bottlenecks can occur on the index because all index updatesoccur at the same place in the index tree. Reverse key indexes spread the distribution of indexupdates across the index tree by reversing the data value of the index key.

· For example, on insert of employee number 7698 in the table, a key value of 8967 is stored in theindex. As the next employee number 7782 is entered, an index entry is made for 2877, therebyspreading the work load across multiple index blocks.

· Reverse key indexes are useful only for queries that contain equality predicates. Because lexicallyadjacent keys are not stored next to each other in a reverse key index, range searches cannot beperformed using such an index.

Example : Create a reverse key index on the ord_no column of scott’s ord tableCREATE UNIQUE INDEX scott.ord_ord_no_idxON scott.ord(ord_no) REVERSEPCTFREE 30STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)TABLESPACE indx01;

Bitmap Index

A bitmap index is also organized as a B-tree, but the leaf node stores a bitmap for each key valueinstead of a list of ROWIDS. Each bit in the bitmap corresponds to a possible ROWID, and if the bit isset, it means that the row with the corresponding ROWID contains the key value.

Example : Create a bitmap index on the region_id column of scott’s ord table

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 25: Arabic Oracle

GnanaSekar. A

DBA - 25

CREATE BITMAP INDEX scott.ord_region_id_idxON scott.ord(region_id)PCTFREE 30STORAGE(INITIAL 200K NEXT 200K

PCTINCREASE 0 MAXEXTENTS 50)TABLESPACE indx01;

Comparing B-Tree and Bitmap Indexes

B-tree BitmapSuitable for high-cardinality columns Suitable for low-cardinality columns

Updates on keys relatively inexpensive Updates to key columns very expensiveInefficient for queries using OR predicates Efficient for queries using OR predicatesUseful for OLTP Useful for DSS

When we need to rebuild indexes?

· Move an index to a different tablespace· Improve space utilization by removing deleted entries

· When the index becomes unbalanced/skewed· Change a reverse key index to a normal B-tree index and vice versa

ALTER INDEX scott.ord_region_id_idx REBUILDTABLESPACE indx02;

Index rebuilds have the following characteristics:· A new index is built using an existing index as the data source.· Sorts are not needed when an index is built using an existing index, resulting in better

performance.· The old index is deleted after the new index is built. During the rebuild, sufficient space is needed

to accommodate both the old and the new index in their respective tablespaces.

· The resulting index does not contain any deleted entries. Therefore this index uses space moreefficiently.

· Queries can continue to use the existing index while the new index is being built.

ANALYZE INDEX command

Analyze the index to perform the following:

· Check all the index blocks for block corruption. Note that this command does not verify whetherindex entries correspond to data in the table.

· Populate the INDEX_STATS view with information about the index.

ANALYZE INDEX scott.ord_region_id_idxVALIDATE STRUCTURE;

12. Maintaining Data Integrity

Types of Constraints

Constraint DescriptionNOT NULL Specifies that a column cannot contain null valuesUNIQUE Designates a column or combination of columns as uniquePRIMARY KEY Designates a column or combination of columns as the table’s primary keyFOREIGN KEY Designates a column or combination of columns as the foreign key in a referential

integrity constraint

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 26: Arabic Oracle

GnanaSekar. A

DBA - 26

CHECK Specifies a condition that each row of the table must satisfy

Three States of Constraints

Disabled Constraints

A constraint that is disabled is not checked, even though the constraint definition is still stored in thedata dictionary. Data in the table as well as new data that is entered or updated may not conform to therules defined by the constraint.

ALTER TABLE scott.departmentsDISABLE CONSTRAINT dept_pk CASCADE;

· Disable before bulk load, especially self-referencing foreign keys.· Disable referencing foreign keys before disabling parent keys.· Unique indexes are dropped, but nonunique indexes are retained.

Enabled Novalidate Constraints

If a constraint is enabled novalidate, new data that violates the constraint cannot be entered. However,the table may contain data that is invalid—that is, data that violates the constraint. This is usually anintermediate stage that ensures that all new data is checked before being accepted into the table.

ALTER TABLE scott.departmentsENABLE NOVALIDATE CONSTRAINTdept_pk;

· No locks on table· Primary/unique keys must use nonunique indexes

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 27: Arabic Oracle

GnanaSekar. A

DBA - 27

Enabled Constraints

If a constraint is in this state, then all data in the table is guaranteed to adhere to the constraint. Inaddition, this state prevents any invalid data from being entered. This is the normal state of operation ofa constraint for online transaction processing.

ALTER TABLE scott.employeesENABLE VALIDATE CONSTRAINTemp_dept_fk;

· Locks table· Can use unique or nonunique indexes· Needs valid table data

How to use the EXCEPTIONS table

The EXCEPTIONS clause helps to identify any row that violates aconstraint that is being enabled.

1. Create EXCEPTIONS table (utlexcpt.sql ).

2. Execute ALTER TABLE with EXCEPTIONS clause.

3. Use subquery on EXCEPTIONS to locate rows with invalid data.

4. Rectify the errors.

5. Reexecute ALTER TABLE to enable the constraint.

Deferred and non-deferred constraints

Nondeferred or Immediate Constraints

Nondeferred constraints, also known as immediate constraints, are enforcedat the end of every DML statement. A constraint violation causes thestatement to be rolled back.

Deferred Constraints

Deferred constraints are constraints that are checked only when a transactioncommits. If any constraint violations are detected at commit time, the entiretransaction is rolled back. These constraints are most useful when both theparent and child rows in a foreign key relationship are entered at the sametime, as in the case of an order entry system, where the order and the itemsin the order are entered at the same time.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 28: Arabic Oracle

GnanaSekar. A

DBA - 28

13. Clusters and Index-Organized tables

For example, there are two tables, ORD and ITEM. If they were stored as regular tables, ORD andITEM are placed in different segments. This means that the tables use their own set of blocks—a blockthat is used to store a row from the ORD table does not contain data from the ITEM table, and viceversa.If the tables ORD and ITEM are stored in a cluster, they share the same cluster segment. A block inthis segment can store rows from both tables. If a table is stored in a cluster, the cluster becomes thephysical unit of storage and the table is a logical entity—that is, part of the cluster.

Clusters have the following characteristics:

· Clusters have a cluster key, which is used to identify the rows that need to be stored together.· The cluster key may consist of one or more columns.· Tables in a cluster have columns that correspond to the cluster key.

· Clustering is a mechanism that is transparent to the applications using the tables. Data in aclustered table can be manipulated as though it were stored in a regular table.

· Updating one of the columns in the cluster key may entail physically relocating the row.· The cluster key is independent of the primary key. The tables in a cluster can have a primary key,

which may be the cluster key or a different set of columns.· Clusters are usually created to improve performance. Random access to clustered data may be

faster, but full table scans on clustered tables are generally slower.

Creating Index Cluster1. Create a cluster

CREATE CLUSTER scott.ord_clu(ord_no NUMBER(3))SIZE 200 TABLESPACE DATA01STORAGE(INITIAL 5M NEXT 5M PCTINCREASE0);

2. Create a cluster index

CREATE INDEX scott.ord_clu_idxON CLUSTER scott.ord_cluTABLESPACE INDX01STORAGE(INITIAL 1M NEXT 1M PCTINCREASE0);

3. Create tables in the cluster

CREATE TABLE scott.ord(ord_no NUMBER(3)CONSTRAINT ord_pk PRIMARY KEY,ord_dt DATE, cust_cd VARCHAR2(3))CLUSTER scott.ord_clu(ord_no);

CREATE TABLE scott.item(ord_no NUMBER(3) CONSTRAINT item_ord_fk REFERENCES scott.ord,prod VARCHAR2(5), qty NUMBER(3),CONSTRAINT item_pk PRIMARY KEY(ord_no,prod))CLUSTER scott.ord_clu(ord_no);

Creating Hash Clusters

1. Create a cluster

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 29: Arabic Oracle

GnanaSekar. A

DBA - 29

CREATE CLUSTER scott.off_clu(country VARCHAR2(2),postcode VARCHAR2(8))SIZE 500 HASHKEYS 1000TABLESPACE DATA01STORAGE(INITIAL 5M NEXT 5M PCTINCREASE 0);

2. Create tables in a cluster

CREATE TABLE scott.office(office_cd NUMBER(3), cost_ctr NUMBER(3), countryVARCHAR2(2), postcode VARCHAR2(8))CLUSTER scott.off_clu(country,postcode);

Index-Organized Tables

Storage StructureAn index-organized table keeps all data for a table within a B-treestructure. The B-tree index, which is based on the primary key of thetable, is organized like an index. The leaf blocks in this structurecontain the nonkey columns, instead of the ROWID, as the secondelement of the index leaf entry. Therefore, the use of an index-organized table eliminates the need to have two separate segments, thetable and the index.

Accessing an Index-Organized TableIndex access to a regular table requires that one or more index blocksare read to retrieve the ROWID and the I/O on the table based on theROWID. In contrast, reading an index-organized table requires onlyindex block reads because the whole row is available in the leaf node.An index-organized table can be accessed using either the primary keyor a combination of columns that constitute the leading part of theprimary key. Changes to the table data, such as adding new rows,updating rows, or deleting rows, result only in updating the index.

Index-Organized Tables Compared with Regular Tables

Regular Table Index-Organized TableUnique identifier–ROWID Identified by primary keyROWID implicitSupports several indexes

No ROWIDNo secondary indexes

FTS returns rows in no specific order Full index scans return rows in PK orderUnique constraints allowed No support for unique constraints

Distribution, replication, and partitioningsupported

Distribution, replication, and partitioning notsupported

Accessing index-organized table

Non-key columns

Key column

Row header

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 30: Arabic Oracle

GnanaSekar. A

DBA - 30

Example

CREATE TABLE scott.sales( office_cd NUMBER(3), qtr_end DATE, revenue NUMBER(10,2), review VARCHAR2(1000), CONSTRAINT sales_pk

PRIMARY KEY(office_code, qtr_end)) ORGANIZATION INDEX TABLESPACE data01 PCTTHRESHOLD 20 OVERFLOW TABLESPACE data02;

where

ORGANIZATION INDEX : specifies that it is an index-organized tablePCTTHRESHOLD : specifies the percentage of space reserved in the index block for an index-

organized table row (If a row exceeds the size calculated based on thisvalue, all columns after the column named in the INCLUDING clause aremoved to the overflow segment. If OVERFLOW is not specified, then rowsexceeding the threshold are rejected. PCTTHRESHOLD defaults to 50 andmust be a value from 0 to 50.)

INCLUDING column : specifies a column at which to divide an index-organized table row intoindex and overflow portions (All columns that follow column are stored inthe overflow data segment. If this is not specified and a row size exceedsPCTTHRESHOLD, all columns except the primary key columns will bemoved to the overflow area. The column is either the name of the lastprimary key column or any nonprimary key column.)

OVERFLOW : specifies that index-organized table data rows exceeding the specifiedthreshold are placed in the data segment defined bysegment_attributes_clause, which specifies the tablespace, storage, andblock utilization parameters

14. SQL*Loader, IMPORT/EXPORT

SQL*Loader loads data from external files into tablesin an Oracle database.

SQL*Loader Features

· One or more input files can be used.

· Several input records can be combined into one logical record for loading.· Input fields can be fixed or variable length.· Input data can be in any format—character, binary, packed decimal, date, and zoned decimal.· Data can be loaded from different types of media such as disk, tape, or named pipes.

· Data can be loaded into several tables in one run.· Options are available to either replace or to append to existing data in the tables.· SQL functions can be applied on the input data before the row is stored in the database.

· Column values can be autogenerated based on rules. For example, a sequential key value can begenerated and stored in a column.

· Data can be loaded directly into the table, bypassing the database buffer cache.

Files Used by SQL*Loader

· Control file: specifies the input format, output tables, and optional conditions that may be used toload only part of the records found in the input data files

· Data files: contain the data in the format defined in the control file· Parameter file: is an optional file that can be used to define the command line parameters for the

load

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 31: Arabic Oracle

GnanaSekar. A

DBA - 31

· Bad file: is used by the utility to write the records that are rejected during the load (This can occur

during input record validation by the utility or during record insertion by the Oracle server.)· Log file: is created by SQL*Loader and contains a record of the load· Discard file: is a file that can be created, if necessary, to store all records· that did not satisfy the selection criteria

Comparing Direct and Conventional Path Loads

Conventional Load Direct Path LoadUses COMMITs to make changes permanent Uses data savesRedo log entries always generated Generates redo only under specific conditions

Enforces all constraints Enforces only primary key, unique, and NOT NULLINSERT triggers fire INSERT triggers do not fireCan load into clustered tables Cannot load into clustered tables

Other users can make changes to tables Other users cannot make changes to tables

Example :

$sqlldr scott/tiger control=ulcase6.ctl \> log=ulcase6.log direct=true

Uses of Export and Import

· Reorganize tables· Move data owned by one user to another user

· Move data between databases:· Development to production· OLTP system to a data warehouse

· Migrate to a different platform or release of Oracle· Repeat test runs during development or upgrade· Perform a logical backup

Example 1 : Export scott’s EMP and DEPT tables with direct path export.Name the exported file as emp.dmp and the log file as exp.log.

$exp scott/tiger tables=(dept,emp) \> file=emp.dmp log=exp.log direct=y

Example 2 : Import the data from example 1 back to the database

$imp scott/tiger tables=(dept,emp) \> file=emp.dmp log=imp.log

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 32: Arabic Oracle

GnanaSekar. A

DBA - 32

Import Behavior

· Order of Import Table symbol 224 \f "Wingdings" \s 10à} Data symbol 224 \f "Wingdings" \s 10à}B-tree Indexes

symbol 224 \f "Wingdings" \s 10à}Constraints, Triggers, Bitmap indexes· Tablespace used for the object Same tablespace as in the source database, if possible

User’s default tablespace

15. Managing Database Users

Checklist for Creating Users

1. Choose a username and authentication mechanism. (E.g. login and password)

2. Identify tablespaces in which the user needs to store objects. (Don’t assign SYSTEM tablespace)

3. Decide on quotas for each tablespace.

4. Assign default tablespace and temporary tablespace.

5. Create a user. (Using the CREATE USER command)

6. Grant privileges and roles to the user.

Examples and Guidelines about users

Example 1 : Create a new user called PETER and assign tablespace quota to him.

CREATE USER peterIDENTIFIED BY my1stsonDEFAULT TABLESPACE data01TEMPORARY TABLESPACE tempQUOTA 15m ON data01QUOTA 20M on data02QUOTA 10M on INDX01PASSWORD EXPIRE;

Guidelines

· Choose a standard password initially

· Use the EXPIRE keyword to force users to reset their passwords during their first login.· Always assign temporary tablespace.· Restrict quotas to few users use QUOTA UNLIMITED with caution.

· Educate users:¾ To connect¾ To change password

Example 2 : Revoke PETER’s quota on tablespace data01

ALTER USER peter QUOTA 0 ON data01;

Once a quota of 0 is assigned, the objects owned by the user remain in the revoked tablespace but theycannot be allocated any new space. For example, if a table that is 10 MB exists in tablespace data01,and the tablespace data01 quota is altered to 0, no more new extents can be allocated for that table.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 33: Arabic Oracle

GnanaSekar. A

DBA - 33

Example 3 : Drop the database user PETER

DROP USER peter;

or

DROP USER peter CASCADE;

Guidelines

· When the user is dropped, all his objects(all tables, indexes, views.......) are dropped

· The CASCADE option drops all objects in the schema before dropping the user. This must bespecified if the schema contains any objects.

· A user who is currently connected to the Oracle server cannot be dropped.

Dictionary Views about Users

DBA_USERS DBA_TS_QUOTAS

USERNAME USERNAMEUSER_ID TABLESPACE_NAMECREATED BYTES

ACCOUNT_STATUS MAX_BYTESLOCK_DATE BLOCKSEXPIRY_DATE MAX_BLOCKS

DEFAULT_TABLESPACETEMPORARY_TABLESPACE

SVRMGR> SELECT tablespace_name, blocks, max_blocks,bytes, max_bytes 2> FROM dba_ts_quotas 3> WHERE username = 'SCOTT';

TABLESPACE_NAME BLOCKS MAX_BLOCKS BYTES MAX_BYTES--------------- ------ ----------- ------ ---------DATA01 10 -1 20480 -11 row selected.

A value of -1 in MAX_BLOCKS or MAX_BYTES column indicates that the user has unlimited quotaon a tablespace.

SVRMGR> SELECT username, account_status, temporary_tablespace2> FROM dba_users;

USERNAME DEFAULT_TABLESPACE TEMPORARY_TABLESPACEACCOUNT_STATUS

-------- ------------------- --------------------- --------------SYS SYSTEM TEMP OPENSYSTEM DATA01 TEMP OPENDBSNMP DATA01 TEMP OPENSCOTT DATA02 TEMP LOCKED4 rows selected.

16. Managing User Profiles

User Profiles and resource limits

· Are named sets of resource and password limits

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 34: Arabic Oracle

GnanaSekar. A

DBA - 34

· Are assigned to users by the CREATE/ALTER USER command

· Can be enabled or disabled· Can relate to the DEFAULT profile· Can limit system resources on session or call level

Resource Limits at Session Level

Resource Description

CPU_PER_SESSION Total CPU time measured in hundredths of secondsSESSIONS_PER_USER Number of concurrent sessions allowed for each usernameCONNECT_TIME Elapsed connect time measured in minutes

IDLE_TIME Periods of inactive time measured in minutesLOGICAL_READS_PER _SESSION Number of data blocks (physical and logical reads)PRIVATE_SGA Private space in the SGA measured in bytes (for MTS only)

Resources Limits at Call Level

Resource DescriptionCPU_PER_CALL CPU time per call in hundredths of secondsLOGICAL_READS_PER _CALL Number of data blocks

How to enforce resource limit using profiles

STEP 1 : Create profiles

CREATE PROFILE developer_prof LIMITSESSIONS_PER_USER 2CPU_PER_SESSION 10000IDLE_TIME 60CONNECT_TIME 480;

STEP 2 : Assign profiles to the user.

For new user :

CREATE USER user3 IDENTIFIED BY user3DEFAULT TABLESPACE data01TEMPORARY TABLESPACE tempQUOTA unlimited ON data01PROFILE developer_prof;

For existing user :

ALTER USER scottPROFILE developer_prof;

STEP 3 : Enabling Resource Limits

Set the initialization parameter RESOURCE_LIMIT to TRUE in the parameter file. Then restart thedatabse.

or

Enforce the resource limits by enabling the parameter with the ALTER SYSTEM command so that youdo not need to restart the database

ALTER SYSTEM SET RESOURCE_LIMIT=TRUE;

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 35: Arabic Oracle

GnanaSekar. A

DBA - 35

Password Management

Parameter DescriptionFAILED_LOGIN_ATTEMPTS Number of failed login attempts before lockout of the

accountPASSWORD_LOCK_TIME Number of days for which the account remains locked

upon password expiration

PASSWORD_LIFE_TIME Lifetime of the password in days after which thepassword expires

PASSWORD_GRACE_TIME Grace period in days for changing the password after thefirst successful login after the password has expired

PASSWORD_REUSE_TIME Number of days before a password can be reusedPASSWORD_REUSE_MAX Maximum number of times a password can be reused

PASSWORD_VERIFY_FUNCTION PL/SQL function that makes a password complexitycheck before a password is assigned

Example :

CREATE PROFILE grace_5 LIMIT FAILED_LOGIN_ATTEMPTS 3 PASSWORD_LIFE_TIME 30 PASSWORD_REUSE_TIME 30 PASSWORD_VERIFY_FUNCTION verify_function PASSWORD_GRACE_TIME 5;

Dictionary Views about user profiles

SVRMGR> SELECT username, password, account_status, 2> lock_date, expiry_date

3> FROM dba_users;

USERNAME ACCOUNT_STATUS LOCK_DATEEXPIRY_DATE

-------- --------------- ---------- -----------SYS OPEN 19-DEC-97SYSTEM OPEN 19-DEC-97SCOTT OPEN 19-DEC-97DBSNMP OPEN 19-DEC-974 rows selected.

SVRMGR> SELECT p.profile, p.resource_name, p.limit 2> FROM dba_users u, dba_profiles p 3> WHERE p.profile=u.profile AND username=’SCOTT’ AND p.resource_type=’KERNEL’;

PROFILE RESOURCE_NAME LIMIT-------------- -------------------------- --------DEVELOPER_PROF COMPOSITE_LIMIT DEFAULTDEVELOPER_PROF SESSIONS_PER_USER 2DEVELOPER_PROF CPU_PER_SESSION 10000DEVELOPER_PROF CPU_PER_CALL DEFAULTDEVELOPER_PROF LOGICAL_READS_PER_SESSION DEFAULTDEVELOPER_PROF LOGICAL_READS_PER_CALL DEFAULTDEVELOPER_PROF IDLE_TIME 60DEVELOPER_PROF CONNECT_TIME 480DEVELOPER_PROF PRIVATE_SGA DEFAULT9 rows selected.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 36: Arabic Oracle

GnanaSekar. A

DBA - 36

SVRMGR> SELECT * FROM dba_profiles 2> WHERE resource_type='PASSWORD' and profile=’DEVELOPER_PROF’

PROFILE RESOURCE_NAME LIMIT-------------- -------------------------- -------DEVELOPER_PROF FAILED_LOGIN_ATTEMPTS DEFAULTDEVELOPER_PROF PASSWORD_LIFE_TIME DEFAULTDEVELOPER_PROF PASSWORD_REUSE_IME DEFAULTDEVELOPER_PROF PASSWORD_REUSE_MAX DEFAULTDEVELOPER_PROF PASSWORD_VERIFY_FUNCTION DEFAULTDEVELOPER_PROF PASSWORD_LOCK_TIME DEFAULTDEVELOPER_PROF PASSWORD_GRACE_TIME DEFAULT7 rows selected.

17. Managing Privileges

SYSTEM Privileges

· System privileges enable users to perform particular actions in the database

· There are about 80 system privileges.· The ANY-keyword in the privileges signifies that users have the privilege in every schema.· The GRANT command adds a privilege to a user or a group of users.· The REVOKE command deletes the privileges.

Examples of system privileges

Category ExamplesINDEX CREATE ANY INDEX

ALTER ANY INDEXDROP ANY INDEX

TABLE CREATE TABLECREATE ANY TABLEALTER ANY TABLEDROP ANY TABLESELECT ANY TABLEUPDATE ANY TABLEDELETE ANY TABLE

SESSION CREATE SESSIONALTER SESSIONRESTRICTED SESSION

TABLESPACE CREATE TABLESPACEALTER TABLESPACEDROP TABLESPACEUNLIMITED TABLESPACE

Examples about system privileges

Example 1 : Allow user1 to connect to the database and create his own tables

GRANT CREATE SESSION, CREATE TABLE TO user1;

Example 2 : Allow scott to connect to the database and to further grant the privilege toother users or roles

GRANT CREATE SESSION TO scottWITH ADMIN OPTION;

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 37: Arabic Oracle

GnanaSekar. A

DBA - 37

Example 3 : Do not allow user1 to create table

REVOKE CREATE TABLE FROM user1;

Interesting example about WITH ADMIN OPTION

1. The DBA grants the CREATE TABLE system privilege to USER 1 with the ADMIN OPTION.

2. USER 1 creates a table.

3. USER 1 grants the CREATE TABLE system privilege to SCOTT.

4. SCOTT creates a table.

5. The database administrator revokes the CREATE TABLE system privilege from USER 1. The result:

1. The table of USER 1 still exists but the user cannot create any new tables.

2. SCOTT still has the table and the CREATE TABLE system privilege.

Dictionary Views about system privilegesQuery the DBA_SYS_PRIVS to list system privileges granted to users and roles:

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 38: Arabic Oracle

GnanaSekar. A

DBA - 38

SVRMGR>SELECT * FROM DBA_SYS_PRIVS;

GRANTEE PRIVILEGE ADM------- ------------------- ----...SCOTT SELECT ANY TABLE NOSYS DELETE ANY TABLE NOSYS EXECUTE ANY TYPE NOSYS INSERT ANY TABLE NOSYS SELECT ANY SEQUENCE NOSYS SELECT ANY TABLE YESSYS UPDATE ANY TABLE NOSYSTEM UNLIMITED TABLESPAC YES...

The view SESSION_PRIVS lists the privileges that are available for the current session to auser—in our example, for the user SCOTT.

SVRMGR> SELECT * FROM session_privs;

PRIVILEGE-------------------------CREATE SESSIONALTER SESSIONCREATE TABLESELECT ANY TABLECREATE CLUSTERCREATE SYNONYMCREATE VIEWCREATE SEQUENCECREATE PROCEDURE9 rows selected.

Object Privileges

· Object privileges enables users to access and manipulate a specific object

· Each object privilege that is granted authorizes the grantee to perform someoperation on theobject.

· The table below summarizes the object privileges that can be granted on each type of object.

Object priv. Table View Sequence ProcedureALTER symbo

l 252\f

"Wingdings"

\s10ü}

symbol252 \f

"Wingdings" \s 10ü}

DELETE symbol 252

\f"Wingdings"

\s10ü}

symbol 252

\f"Wingdings" \s10ü}

EXECUTE symbol252 \f

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 39: Arabic Oracle

GnanaSekar. A

DBA - 39

"Wingdings" \s 10ü}

INDEX symbol 252

\f"Wingdings"

\s10ü}

symbol 252

\f"Wingdings" \s10ü}

INSERT symbol 252

\f"Wingdings"

\s10ü}

REFERENCES symbol 252

\f"Wingdings"

\s10ü}

SELECT symbol 252

\f"Wingdings"

\s10ü}

symbol 252

\f"Wingdings" \s10ü}

symbol252 \f

"Wingdings" \s 10ü}

UPDATE symbol 252

\f"Wingdings"

\s10ü}

symbol 252

\f"Wingdings" \s10ü}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 40: Arabic Oracle

GnanaSekar. A

DBA - 40

Examples about object privileges

Example 1 : Allow all users to execute the package dbms_pipe

GRANT EXECUTE ON dbms_pipe TO public;

Example 2 : Allow user1 to update ename and sal columns of the emp table and also allowuser1 to grant the object privileges to other users or roles

GRANT UPDATE(ename,sal) ON emp TO user1WITH GRANT OPTION;

Example 3 : Do not allow scott to use the package dbms_pipe

REVOKE execute ON dbms_pipe FROM scott;

Interesting example about WITH GRANT OPTION

1. USER 1 is granted the SELECT object privilege with the GRANT OPTION.

2. USER 1 grants the SELECT privilege on EMP to USER 2. The result:

3. Later, the SELECT privilege is revoked from USER 1. This revoke is cascaded to USER 2 as well.

Dictionary Views about object privileges

Query DBA_TAB_PRIVS to return all object privileges granted to the specified user.

svrmgr> SELECT * FROM dba_tab_privs 2> WHERE GRANTEE=’SCOTT’

GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE GRANTABLE------- ----- ---------- ------- --------- ---------SCOTT SYS RESUMES SYS READ NO1 row selected.

Query DBA_COL_PRIVS to list all the column specific privileges that have been granted use thefollowing query:

svrmgr> SELECT * FROM dba_col_privs;

GRANTEE OWNER TABLE_NAME COLUMN_NAME GRANTOR PRIVILEGEGRANTABLE

------- ----- ---------- ----------- ------- --------- ---------SYSTEM SCOTT EMP EMPNO SCOTT INSERT NOSYSTEM SCOTT EMP SAL SCOTT UPDATE NO2 rows selected.

18. Managing Roles

What is role?

Roles are named groups of related privileges that are granted to users or other roles. They are designedto ease the administration of privileges in the database.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 41: Arabic Oracle

GnanaSekar. A

DBA - 41

Role Characteristics· Granted to and revoked from users with the same commands used to grant and revoke system

privileges

· May be granted to any user or role, except to itself (even indirectly)· Can consist of both system and object privileges· May be enabled or disabled for each user granted the role· Can require a password to enable

· Each role name must be unique among existing usernames and role names· Are not owned by anyone; are not in any schema· Have their descriptions stored in the data dictionary

Benefits of Roles· Reduced granting of privileges

· Dynamic privilege management· Selective availability of privileges· Granted through the OS· No cascading revokes

· Improved performance

Manapulating Roles

Example 1 : Creat a role without password

CREATE ROLE sales_clerk;

Example 2 : Create a role with password

CREATE ROLE hr_clerkIDENTIFIED BY bonus;

Example 3 : Grant privileges to the role

Grant create session, create table, select onemp to sales_clerk;

Example 4 : Assigning Roles to users

GRANT sales_clerk TO scott, peter;

Example 5 : Grant a role to another role

GRANT hr_clerk TO hr_manager;

Example 6 : Grant the role to scott and enable him to grant the role to other users

GRANT hr_manager TO scottWITH ADMIN OPTION;

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 42: Arabic Oracle

GnanaSekar. A

DBA - 42

Frequently Asked Questions in Oracle 8 Database Administration

Q1. How can I coalesce free space?

SMON coalesces free space (extents) into larger, contiguous extentsevery 2 hours and even then only for a short period of time.

SMON will not coalesce free space if a tablespace's default storageparameter "pctincrease" is set to 0. One can manually coalesce atablespace using the ALTER TABLESPACE ... COALESCE; command.

Q2 . How can I prevent tablespace fragmentation?

Always set PCTINCREASE to 0 or 100.

Bizarre values for PCTINCREASE will contribute to fragmentation. Forexample if you set PCTINCREASE to 1 you will see that your extentsare going to have weird and wacky sizes: 100K, 100K, 101K, 102K, etc.Such extents of bizarre size are rarely re-used in their entirety.PCTINCREASE of 0 or 100 gives you nice round extent sizes that caneasily be reused. Eg. 100K, 100K, 200K, 400K, etc.

Q3. Can one rename a tablespace's name?

No

Workaround:Export all of the objects from the tablespaceDrop the tablespace including contentsRecreate the tablespaceImport the objects back in

Q4. Can one rename a database user (schema)?

No

Workaround:Do a user-level export of user Acreate new user Bimport system/manager fromuser=A touser=Bdrop user A

Q5. What database block size should I use?

Oracle recommends that your database block size match, or bemultiples of your operating system block size. One can go smaller,but the performance cost is significant. Your choice should depend onthe type of application you are running. If you have lots of smalltransaction like with OLTP, use a small block size. With fewer butlarger transactions, like with a DSS application, use a large blocksize.

Q6. Can one resize tablespaces and data files?

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Page 43: Arabic Oracle

GnanaSekar. A

DBA - 43

You can manually increase the size of a datafile

ALTER DATABASE DATAFILE 'filename2' RESIZE 100M;

Because you can change the sizes of datafiles, you can add more spaceto your database without adding more datafiles. This is beneficial ifyou are concerned about reaching the maximum number of datafilesallowed in your database.Manually reducing the sizes of datafiles allows you to reclaim unusedspace in the database. This is useful for correcting errors inestimates of space requirements.Also, datafiles can be allowed to automatically extend if more spaceis required. Look at the following command:

CREATE TABLESPACE pcs_data_ts DATAFILE 'c:\ora_apps\pcs\pcsdata1.dbf' SIZE 3M AUTOEXTEND ON NEXT 1M MAXSIZE UNLIMITED DEFAULT STORAGE ( INITIAL 10240 NEXT 10240 MINEXTENTS 1 MAXEXTENTS UNLIMITED PCTINCREASE 0) ONLINE PERMANENT;

Q7. Can one improve the performance of SQL*Loader?

1. A very simple but easily overlooked hint, do not have any indexesand/or constraints (primary key) on your load tables during theload process. This will significantly slowdown load times.

2. Add the following option in the command line: DIRECT=TRUE. Thiswill effectively bypass most of the RDBMS processing.

3. Turn off database logging by specifying the NOLOGGING option. Thisoption can only be used with direct data loads.

4. Run multiple load jobs concurrently.

Q8. Common Import/ Export problems

ORA-01555: Snapshot too old - Ask you users to STOP working while youare exporting or use CONSISTENT=NOORA-01562: Failed to extend rollback segment - Set COMMIT=Y whileimporting

This watermark does not appear in the registered version - http://www.clicktoconvert.com