0% found this document useful (0 votes)
81 views15 pages

Adb Chapter 6

Uploaded by

Tegbaru Tamene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views15 pages

Adb Chapter 6

Uploaded by

Tegbaru Tamene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CHAPTER SIX

6. PL/SQL and Database Administrator Tasks


Learning Objectives: After completing this chapter, the learner should be familiar with the following
concepts:
 Structure of PL/SQL, PL/SQL language elements and steps to create PL/SQL program
 Basic concepts of Procedure and functions
 Basic concept of Trigger, types of trigger, DDL trigger, DML Trigger
 Database startup and shutdown
 Database backup and recovery
 Auditing database activities

6.1. Shortcomings in SQL


As we know, SQL is a powerful tool for accessing the database but it has the following limitations:
1. SQL statements can be executed only one at a time. Every time to execute a SQL statement, a call
is made to Oracle engine, thus it results in an increase in database overheads.
2. While processing an SQL statement, if an error occurs, database generates its own error message,
which is sometimes difficult to understand. If a user wants to display some other meaningful error
message, SQL does not have provision for that.
3. SQL is not able to do the conditional query on RDBMS, this means one cannot use the conditions
like if . . . then, in a SQL statement. Also, looping facility (repeating a set of instructions) is not
provided by SQL.

6.2. PL/SQL
PL/SQL stands for Procedural Language/Structured Query Language, which is provided by Oracle as a
procedural extension to SQL. SQL is a declarative language. In SQL, the statements have no control to
the program and can be executed in any order. PL/SQL, on the other hand, is a procedural
language that makes up for all the missing elements in SQL. PL/SQL allows users and designers to
develop complex database applications that require the usage of control structures and procedural
elements such as procedures, functions, and modules. Like SQL, PL/SQL is not case sensitive, so
lowercase letters are equivalent to corresponding uppercase letters except within string and character
literals. The major goals of PL/SQL are to:
 Increase the expressiveness of SQL,

1
 Process query results in a tuple-oriented way,
 Optimize combined SQL statements,
 Develop modular database application programs,
 Reuse program code, and
 Reduce the cost for maintaining and changing applications.

6.3. Structure of PL/SQL


PL/SQL is a 4GL (fourth generation) programming language. It is a block structured language. This
means a PL/SQL program is made up of blocks, where block is a smallest piece of PL/SQL code having
logically related statements and declarations. A block consists Declare, Begin, and Exception followed
by an End statement. The different sections of PL/SQL block are:
Declare Section: Declare section declares the variables, constants, processes, functions, etc., to
be used in the other parts of program. It is an optional section.
Begin Section: It is the executable section. It consists of a set of SQL and PL/SQL statements,
which is executed when PL/SQL block runs. It is a compulsory section.
Exception Section: This section handles the errors, which occurs during execution of the PL/SQL block.
This section allows the user to define his/her own error messages. This section executes only when an
error occurs. It is an optional section.
End Section: This section indicates the end of PL/SQL block. Every PL/SQL program must consist of
at least one block, which may consist of any number of nested sub-blocks.
DECLARE
Declarations of variables, constants etc. to be use in PL/SQL.
BEGIN
PL/SQL and SQL Executable statements
EXCEPTION
PL/SQL code to handle errors during execution period.
END;
6.4. Procedure
A procedure is a subprogram that performs some specific task, and stored in the data dictionary. Stored
procedures are PL/SQL programs to define a business process. When a procedure is created, the Oracle
automatically performs the following steps: Compiles the procedure and Stores the procedure in the data
dictionary. If an error occurs during creation of procedure, Oracle displays a message that procedure is
created with compilation errors, but it does not display the errors. To see the errors following statement
is used: SELECT * FROM user errors; The syntax for creating a procedure is follows:

2
CREATE OR REPLACE PROCEDURE [schema.] package name [(argument {IN, OUT, IN OUT} data
type,. . . . . . . . .)] {IS, AS} [local variable declarations]
BEGIN
executable statements
EXCEPTION
exception handlers
END [procedure name];
Create: Creates a new procedure, if a procedure of same name already exists, it gives an error.
Replace: Creates a procedure, if a procedure of same name already exists, it replaces the older one by
the new procedure definition.
Schema: If the schema is not specified then procedure is created in user’s current schema.
Argument: It is the name of the argument to the procedure.
IN: Specifies that a value for the argument must be specified when calling the procedure.
OUT: Specifies that the procedure pass a value for this argument back to its calling environment after
execution.
IN OUT: Specifies that a value for the argument must be specified when calling the procedure and that
the procedure passes a value for this argument back to its calling environment after execution. If no
value is specified, then it takes the default value IN.
Datatype: It is the unconstrained datatype of an argument.
System and Object Privileges for Procedures: The creator of a procedure must have CREATE
PROCEDURE system privilege in his own schema. To create a procedure in other’s schema, the creator
must have CREATE ANY PROCEDURE system privilege. To EXECUTE any procedure a user must
have EXECUTE ANY PROCEDURE privilege. With this privilege he can execute a procedure which
belong to some other user.
Executing/Invoking a Procedure: The syntax used to execute a procedure depends on the environment
from which the procedure is being called. From within SQLPLUS, a procedure can be executed by using
the EXECUTE command, followed by the procedure name. Any arguments to be passed to the procedure
must be enclosed in parentheses following the procedure name.
Removing a Procedure: To remove a procedure must have DROP ANY PROCEDURE system privilege.
To remove a procedure completely from the database, following command is used:
DROP PROCEDURE <PROCEDURE NAME>;

6.5. Function
A Function is similar to procedure except that it must return one and only one value to the calling
program. Besides this, a function can be used as part of SQL expression, whereas the procedure cannot.
3
Stored functions are PL/SQL programs that can be used to create user-defined functions to return a
value. The Difference Between Function and Procedure
1. A procedure never returns a value to the calling portion of code, whereas a function returns exactly
one value to the calling program.
2. It is mandatory for a function to have at least one RETURN statement, whereas for procedures there
is no restriction. A procedure may have a RETURN statement or may not. In case of procedures
with RETURN statement, simply the control of execution is transferred back to the portion of code
that called the procedure.
The exact syntax for defining a function is given below:
CREATE OR REPLACE FUNCTION [schema.] functionname [(argument IN datatype, . . . .)]
RETURN datatype {IS,AS} [local variable declarations];
BEGIN
executable statements;
EXCEPTION
exception handlers;
END [functionname];
Where RETURN datatype is the datatype of the function’s return value. It can be any PL/SQL datatype.
Thus a function has two parts: function specification and function body. The function specification
begins with keyword FUNCTION and ends with RETURN clause which indicates the datatype of the
value returned by the function. Function body is enclosed between the keywords IS and END.
Sometimes END is followed by function name, but this is optional. Like procedure,
a function body also is composed of three parts: declarative part, executable part, and an optional
error/exception handling part.
Purity of a Function: It must satisfy the following requirements, which are known as Purity Rules.
1. When called from a SELECT statement or a parallelized INSERT, UPDATE, or DELETE statement,
the function cannot modify any database tables.
2. When called from an INSERT, UPDATE, or DELETE statement, the function cannot query or
modify any database tables modified by that statement.
3. When called from a SELECT, INSERT, UPDATE, or DELETE statement, the function cannot
execute SQL transaction control statements (such as COMMIT), session control statements (such as
SET ROLE), or system control statements (such as ALTER SYSTEM). Also, it cannot execute DDL
statements (such as CREATE) because they are followed by an automatic commit. If any of the
above rules is violated, the function is said to be not following the Purity Rules and the program
using such functions receives run time error.

4
Removing a Function: To remove a function, use following command: DROP FUNCTION
<FUNCTION NAME>;

6.6. Database Triggers


A trigger is a PL/SQL program unit that is executed when an event occurs. A database trigger is a stored
PL/SQL program unit associated with a specific database table. It can perform the role of a constraint,
which forces the integrity of data. Unlike the stored procedures or functions, which have to be explicitly
invoked, these triggers implicitly get fired whenever the table is affected by the SQL operation.
Privileges Required for Triggers are:
1. To create TRIGGER in one’s own schema, must have CREATE TRIGGER privilege. To create a
trigger in any other’s schema, one must have CREATE ANY TRIGGER system privilege.
2. To create a trigger on table, one must own the table or should have ALTER privilege for that table
or should have ALTER ANY TABLE privilege.
3. To ALTER a trigger, one must own that trigger or should have ALTER ANY TRIGGER privilege.
Also since the trigger will be operating on some table, one also requires ALTER privilege on that
table or ALTER ANY TABLE table privilege.
4. To create a TRIGGER on any database level event, one must have ADMINISTER DATABASE
TRIGGER system privilege.
Create Trigger Syntax:
CREATE [OR REPLACE] TRIGGER <trigger name>
[BEFORE/AFTER/INSTEAD OF]
[INSERT/UPDATE/DELETE [of column,..]] ON <table name>
[REFERENCING [OLD [AS] <old name> | NEW [AS] <new name>]
[FOR EACH STATEMENT/FOR EACH ROW]
[WHEN <condition>]
[BEGIN
–PL/SQL block
END];
6.6.1. Types of Triggers
The broad classification of triggers is as shown below.
1. On the basis of type of events
Triggers on System events: System events that can fire triggers are related to instance startup and
shutdown and error messages. Triggers created on startup and shutdown events have to be associated
with the database; triggers created on error events can be associated with the database or with a schema.
Trigger on User events: LOGON and LOGOFF triggers can be associated with the database or with a
schema. Their attributes include the system event and username, and they can specify simple conditions

5
on USERID and USERNAME. LOGON triggers fire after a successful logon of a user. LOGOFF
triggers fire at the start of a user logoff.
2. On the basis of the level at which triggers are executed
Row Level Triggers: A row level trigger, as its name suggests, is fired for each row that will be affected
by the SQL statement, which fires the trigger. For example, if an UPDATE statement updates “N” rows
of a table, a row level trigger defined for this UPDATE on that particular table will be fired once for
each of those “N” affected rows.
Statement Level Triggers: Unlike row level trigger, a statement level trigger is fired only once on
behalf of the triggering SQL statement, regardless of the number of rows in the table that the triggering
statement affects. Even if the triggering statement affects no rows, the statement level trigger will
execute exactly once. For example, if a DELETE statement deletes several rows from a table, a
statement-level DELETE trigger is fired only once, regardless of how many rows are deleted from the
table. Default type of any trigger is statement level trigger.
3. On the basis of type of trigger/firing or triggering transaction
BEFORE Triggers: BEFORE triggers execute the trigger action before the triggering statement is
executed. It is used to derive specific column values before completing a triggering DML, DDL
statement or to determine whether the triggering statement should be allowed to complete.
AFTER Triggers: AFTER triggers execute the trigger action after the triggering statement is executed.
AFTER triggers are used when we want the triggering statement to complete before executing the trigger
action, or to execute some additional logic to the before trigger action.
Triggers on DDL Statements
This trigger gets fired when DDL statement such as CREATE, ALTER, or DROP command is issued.
DDL triggers can be associated with the database or with a schema. Moreover, depending on the time
of firing of trigger, this trigger can be classified into BEFORE and AFTER.
Triggers on DML Statements
This trigger gets fired when DML statement such as INSERT, UPDATE, or DELETE command is
issued. DML triggers can be associated with the database or with a schema. Depending on the time of
firing of trigger, this trigger can be classified into BEFORE and AFTER.
INSTEAD-OF Triggers
INSTEAD-OF triggers are used to tell Oracle what to do instead of performing the actions that executed
the trigger. It is applicable to both object views and standard relational database. This trigger can be

6
used to redirect table inserts into a different table or to update different tables that are the part of the
view. This trigger is used to perform any action instead of the action that executes
the trigger. In simpler words if the task associated with this trigger fails, the trigger is fired. It is used
mostly for object views rather than tables.
Enabling and Disabling a Trigger
By default, a trigger is enabled when it is created. Only an enabled trigger gets fired whenever the trigger
restriction evaluates to TRUE. Triggers can be disabled and enabled. Enabled trigger executes its trigger
action if a triggering statement is issued and the trigger restriction (if any) evaluates to TRUE. Disabled
(a disabled trigger does not execute its trigger action, even if a triggering statement is issued and the
trigger restriction (if any) would evaluate to TRUE.
Syntax: ALTER TRIGGER <Trigger name> ENABLE/DISABLE;
Replacing Triggers
Triggers cannot be altered explicitly. Triggers have to be replaced with a new definition using OR
REPLACE option with CREATE TRIGGER command.
Syntax: CREATE OR REPLACE TRIGGER <trigger name> AS/IS <trigger definition>;
Dropping Triggers
Triggers can be dropped like tables using the drop trigger command. The drop trigger command removes
the trigger structure from the database. User needs to have DROP ANY TRIGGER system privilege to
drop a trigger. Syntax: DROP TRIGGER <trigger name>;

6.7. Starting Up and Shutting Down an Oracle Instance


As a DBA, you are responsible for the startup and shutdown of the Oracle instance. Oracle gives
authorized administrators the ability to perform this task using a variety of interfaces. To start up or shut
down an Oracle instance, you need to be connected to the database with the appropriate privileges. Two
special connection account authorizations are available for startup and shutdown: SYSDBA and
SYSOPER. The SYSDBA authorization is an all-empowering authorization that allows you to perform
any database task. The SYSOPER authorization is a less powerful authorization that allows startup and
shutdown abilities but restricts other administrative tasks, such as access to non-administrative schema
objects. These authorizations are managed either through a passwords file or via operating-system
control.
The startup and shutdown discussed here are for the non-container databases. For container databases,
the startup is the same but in addition the pluggable databases need to be opened separately. When you

7
issue a shutdown connected to the root container of the container database, all pluggable databases are
shut down before shutting down the container database.
6.7.1. Starting Up an Oracle Database 12c Instance
The Oracle instance is composed of a set of logical memory structures and background processes that
users interact with to communicate with the Oracle database. When Oracle is started, these memory
structures and background processes are initialized and started so that users can communicate with the
Oracle database. When Oracle database starts up, a database passes through three modes: NOMOUNT,
MOUNT, and OPEN.
STARTUP NOMOUNT: This starts the instance without mounting the database. When a database is
started in this mode, the parameter file is read, and the background processes and memory structures are
initiated, but they are not attached nor do they communicate with the disk structures of the database.
When the instance is in this state, the database is not available for use. If a database is started in NOMOUNT
mode, the background processes are started and shared memory is allocated. The instance is not
associated with any database. This state is used to create a database or to create a database control file.
STARTUP MOUNT: This performs all the work of the STARTUP NOMOUNT option and reads the
control file. At this point, Oracle obtains information from the control files that it uses to locate and
attach to the physical database structures. The control file contains the name of the database, all the data
filenames, and the redo log files associated with the database. In this mode, renaming data files, enabling
or disabling archive logging, renaming and adding redo log files, and recovering the database
administrative tasks can be performed.
STARTUP OPEN: This is the default startup mode if no mode is specified on the STARTUP command
line. STARTUP OPEN performs all the steps of the STARTUP NOMOUNT and STARTUP MOUNT
options. This option makes the database available to all users. When opening the database, you can use
a couple of options. STARTUP OPEN READ ONLY opens the database in read-only mode. STARTUP
OPEN RECOVER opens the database and performs a database recovery.
STARTUP FORCE: You can use the STARTUP FORCE startup option if you are experiencing
difficulty starting the database in a normal fashion. For example, when a database server loses power
and the database stops abruptly; the database can be left in a state in which a STARTUP FORCE startup
is necessary. This type of startup should not normally be required but can be used if a normal startup
does not work. What is also different about STARTUP FORCE is that it can be issued no matter what

8
mode the database is in. STARTUP FORCE does a shutdown abort and then restarts the database;
therefore, it can be used to cycle a database that is in open state.
STARTUP RESTRICT: The STARTUP RESTRICT option starts up the database and places it in
OPEN mode but gives access only to users who have the RESTRICTED SESSION privilege.
STARTUP UPGRADE / DOWNGRADE: The STARTUP UPGRADE option starts up the database
in UPGRADE mode and sets system initialization parameters to specific values required to enable
database upgrade scripts to be run. UPGRADE should be used only when a database is first started with
a new version of the Oracle Database Server. Similarly, the STARTUP DOWNGRADE option sets
system initialization parameters to specific values required to enable database downgrade scripts to be
run. Starting Oracle Using SQL*Plus: SQL>STARTUP [NOMOUNT|MOUNT|OPEN] [PFILE=]
[RESTRICT] [FORCE] [QUIET]
6.7.2. Shutting Down an Oracle Database 12c Instance
SHUTDOWN NORMAL: A normal shutdown is the default type of shutdown that Oracle performs if
no shutdown options are provided. In a normal shutdown: No new Oracle connections are allowed from
the time the SHUTDOWN NORMAL command is issued. The database will wait until all users are
disconnected to proceed with the shutdown process. This type of shutdown is also known as a clean
shutdown because when you start Oracle again; no recovery is necessary.
SHUTDOWN TRANSACTIONAL: A transactional shutdown of the database is a bit more aggressive
than a normal shutdown. The characteristics of the transactional shutdown are as follows:
 No new Oracle connections and No new transactions are allowed from the time the SHUTDOWN

TRANSACTIONAL command is issued.


 Once all active transactions on the database have completed, all client connections are disconnected.
SHUTDOWN IMMEDIATE: The immediate shutdown method is the next most aggressive option.
An immediate shutdown is characterized as follows:
 No new Oracle connections are allowed from the time the SHUTDOWN IMMEDIATE command is issued.
 Any uncommitted transactions are rolled back. Therefore, a user in the middle of a transaction will
lose all the uncommitted work.
 Oracle does not wait for clients to disconnect. Any unfinished transactions are rolled back, and their
database connections are terminated.
SHUTDOWN ABORT: A shutdown abort is the most aggressive type of shutdown and has the
following characteristics:

9
 No new Oracle connections are allowed from the time the SHUTDOWN ABORT command is issued.
 Any SQL statements currently in progress are terminated, regardless of their state.
 Uncommitted work is not rolled back.
 Oracle disconnects all client connections immediately upon the issuance of the SHUTDOWN ABORT
command.
Do not use SHUTDOWN ABORT regularly. Use it only if the other options for database shutdown fail or
if you are experiencing some type of database problem that is preventing Oracle from performing a clean
shutdown. Shutting Down Oracle Using SQL*Plus: You can use the command-line facility SQL*Plus
to shut down the Oracle database. You will need to connect to SQL*Plus as a user with the SYSOPER
or SYSDBA privilege. Here is the syntax of the shutdown options available to you:
SQL>SHUTDOWN [NORMAL|TRANSACTIONAL|IMMEDIATE|ABORT]
6.8. Backup and Recovery
As a database administrator, your primary goal is to keep the database open and available for users,
usually 24 hours a day, seven days a week. Backup and recovery is the most important task of DBA.
The server’s system administrator includes the following tasks:
 Proactively solving common causes of failures.
 Increasing the mean time between failure (MTBF).
 Ensuring a high level of hardware redundancy.
 Increasing availability by using Oracle options such as Real Application Clusters (RAC), Oracle
Streams (an advanced replication technology), and Oracle Data Guard (a disaster recovery solution).
 Decreasing the mean time to recover (MTTR) by setting the appropriate Oracle initialization
parameters and ensuring that backups are readily available in a recovery scenario.
 Minimizing or eliminating loss of committed transactions by using redo application, replication, and
Oracle Data Guard.
6.8.1. Backup and Recovery Concepts
Repository is a collection of information about backups. Control file keeps this information by default.
Control file: The control file is a relatively small (in the megabyte range) binary file that contains
information about the structure of the database. You can think of the control file as a metadata repository
for the physical database. It has the structure of the database, meaning the data files and redo log files
constitute a database. The control file is created when the database is created and is updated continuously

10
with information required for recovery and configuration of the database. The contents of the control
file include the following:
 The database name to which the control file belongs. A control file can belong to only one database.
 The database-creation timestamp.
 The name, location, and online/offline status information of the data files.
 The name and location of the redo log files.
 Redo log archive information.
 Tablespace names.
 The current log sequence number, which is a unique identifier that is incremented and recorded when
an online redo log file is switched.
 The most recent checkpoint information.
 The beginning and ending of undo segments.
 Recovery Manager’s backup information. The control file is updated continuously and should be
available at all times.
Redo Log Files: A redo log file records all changes to the database, before the changes are written to the data
files. The database maintains online redo log files to protect against data loss. To recover from an instance or a
media failure, redo log information is required to roll data files forward to the last committed transaction.
Archived Redo Log File: It is a copy of a redo log file before it is overwritten by new redo information. Because
the online redo log files are reused in a circular fashion, you have no way of bringing a backup of a data file up
to the latest committed transaction unless you configure the database in ARCHIVELOG mode. The process of
copying is called archiving. The ARCn background processes do this archiving. By archiving the redo log files,
you can use them later to recover a database, update a standby database, or use the LogMiner utility to audit the
database activities.
Fast Recovery Area: It is a specialized directory structure for buckups. Fast recovery area is defined
by two parameters such as: db_recovery_file_dest and db_recovery_file_dest_size. All of the files
needed to recover a database from a media failure or a logical error are contained in the Fast Recovery
Area. The Fast Recovery Area can contain control files, archived log files, Flashback Logs, control file
and Spfile autobackups, data file copies and RMAN backup sets. Issue the following query to see FRA:
SQL> SELECT file_type, percent_space_used psu, percent_space_reclaimable psr, number_of_files nf
FROM v$recovery_area_usage;
ARCHIVELOG mode vs NOARCHIVELOG mode: With NOARCHIVELOG mode, recovery
options are limited. ARCHIVELOG mode allows hot backups, recovery until the point of failure and
11
time based recovery. To know if we are in archive mode or noarchivemode: use SQLPLUS connect to
database as SYSDBA. SQL>archive log list; To enable archive log mode, use shutdown immediate to translate
the database to mount state then startup in a mount mode. SQL>shutdown immediate; SQL>startup mount;
SQL>Alter database archive log; To switch one redo log to the next: SQL>Alter system switch logfile;
6.8.2. Performing Backups
Oracle has whole backups and partial backups strategies. The backup type can be divided into two
general categories: full backups and incremental backups. Depending on whether you make your
database backups when the database is open or closed, backups can be further categorized into the
backup modes known as consistent backup and inconsistent backup.
A consistent backup, also known as an offline backup, is performed while the database is not open. An
inconsistent backup, also known as an online backup, is performed while the database is open and
available to users. An incremental backup makes a copy of all data blocks that have changed since a
previous backup. Oracle 12c supports five levels of incremental backups from 0 to 4, 0 and 1 are the
most commonly used. A full backup includes all blocks of every data file backed up in a whole or
partial database backup.
Backing Up the Control File: In addition to multiplexing the control file, you can guard against the
loss of all control files by backing up the control file. You can back up the control file using three
methods:
 An editable text file; this backup is called a backup to trace. The text backup is created using the
ALTER DATABASE BACKUP CONTROLFILE TO TRACE statement, and the file is created in
the trace directory under <ADR_HOME>/trace. SQL> alter database backup controlfile to trace;

If you want to name, the control file backup rather than using an Oracle-generated trace filename,
you can do this: SQL> alter database backup controlfile to trace as '/tmp/mydbcontrol.txt';
 A binary backup of the control file. SQL> alter database backup controlfile to '/ora_backup/11GR11/ctlfile20040911.bkp';
 An RMAN backup of the control file. Using RMAN, you can back up the control file using the
BACKUP CURRENT CONTROLFILE statement, as shown here. This backup is also a binary backup.
RMAN> BACKUP CURRENT CONTROLFILE;

6.8.3. Performing User-Managed Cold Backups


Cold backups are performed after shutting down the database. Shut down the database cleanly using the
SHUTDOWN IMMEDIATE or SHUTDOWN TRANSACTIONAL statement, and copy all control files and data
files to another location or to your tape management system using OS commands.

12
6.8.4. Performing User-Managed Hot Backups
To perform a hot backup, the database must be in ARCHIVELOG mode and opened. Before starting to
copy the data files belonging to a tablespace, you must place the tablespace in backup mode using the
BEGIN BACKUP clause. To backup users tablespace; For example, if you want to back up the USERS
tablespace, perform the following: SQL> ALTER TABLESPACE users BEGIN BACKUP; To take the tablespace
out of backup mode, use the END BACKUP clause as in the following example: SQL> ALTER
TABLESPACE users END BACKUP; You cannot perform incremental backups using user-managed backups.

You must use RMAN for incremental backups.


6.8.5. Using RMAN to Perform Backups
Recovery Manager (RMAN) is the Oracle utility you use to back up and recover databases. RMAN is
the primary component of the Oracle database used to perform backup and recovery operations. You
can use RMAN to back up all types: whole or partial databases, full or incremental, and consistent or
inconsistent. RMAN is closely integrated with EM Cloud Control. RMAN performs true block level
backup, capability of ignoring empty datafile blocks, encrypted backups and compressed backups. The
following RMAN command-line session uses the RMAN SHOW ALL command to display the RMAN
backup settings: open CMD and run: RMAN target / nocatalog RMAN> show all;
6.8.6. Creating Full and Incremental Backups
The Oracle-recommended backup strategy uses RMAN to make a one-time, whole-database, baseline
incremental level 0 online backup and then a daily level 1 incremental backup. You can easily fine-tune
this strategy for your own needs by making, for example, a level 2 incremental backup at noon during
the weekdays if heavy Data Manipulation Language (DML) activity is occurring in the database. First,
here is the code for a baseline level 0 backup at the RMAN command prompt:
RMAN> backup incremental level 0 as compressed backupset database;
Starting with a baseline level 0 incremental backup, you can make level 1 incremental backups during
the rest of the week, as in the following example: First alter RMAN>Alter system switch logfile;
RMAN> backup incremental level 1 as compressed backupset database; You can use the LIST command from
RMAN command line to see or view backup the reports. RMAN> list backup; To do a full database backup:
RMAN>Backup database;
6.9. Recovering from User Errors
We must do database recovery in a mount state and we cannot do database recovery in a Nomount and
Open state. RMAN>Shutdown immediate; SQL> Startup; RMAN>Restore datafile 6; The datafile is restored.

A user’s data was inadvertently changed or deleted or a table was dropped. Let’s see a few helpful tasks,
such as how to do the following:

13
 Use Flashback Query to retrieve selected rows from a previous state of a table. A Flashback Query
looks a lot like a standard SQL SELECT statement, with the addition of the AS OF TIMESTAMP
clause. Before users can take advantage of the Flashback Query feature, the DBA must perform two
tasks: Make sure there is an undo tablespace in the database that is large enough to retain changes
made by all users for a specified period of time. Use the initialization parameter
UNDO_RETENTION to specify how long the undo information will be retained for use by
flashback queries. Example, you want to query the EMPLOYEES table as it existed 15 minutes ago:
SQL> SELECT employee_id, last_name, email FROM hr.employees AS OF TIMESTAMP (systimestamp - interval '15' minute)
WHERE employee_id = 101;
You can just as easily specify an absolute time of day to retrieve the contents of the row at that time,
as in this example:
SQL> SELECT employee_id, last_name, email FROM hr.employees AS OF TIMESTAMP (to_timestamp ('01-Jan-14
16:18:57.845993', 'DD-Mon-RR HH24:MI:SS.FF')) WHERE employee_id = 101;
If your Flashback Query requires undo data that is no longer available in the undo tablespace, you
will receive an error message.
 Recover a table using Flashback Drop and a tablespace’s recycle bin.
 Bring an entire table and its dependent objects (such as indexes) back to a specific point in time
using the Flashback Table functionality. Flashback Table allows you to recover one or more tables
to a specific point in time without having to use more time-consuming recovery operations such as
tablespace point-in time recovery or Flashback Database that can also affect the availability of the
rest of the database.
 Perform a table-level recovery from RMAN backup.
 Roll back a specific transaction and its dependent transactions using flashback transaction
technology.
 Query previous transactions in the online and archived redo logs using the Log-Miner utility.

6.10. Auditing Database Activity


Auditing involves monitoring and recording specific database activity. Oracle Database 12c Traditional
Auditing supports four levels of auditing: Statement, Privilege, Object and Fine-grained access. Audit
records can be stored in either of these locations: Database and Operating-system files. You tell the
Oracle Database 12c where to record audit-trail records by setting the initialization parameter audit_trail.
The default is DB, as in AUDIT_TRAIL=DB (that is, if the database was created using DBCA,
otherwise the auditing is disabled), which tells the database to record audit records in the database. You
cannot change this parameter in memory, only in your pfile or spfile. For example, the following
statement will change the location of audit records in the spfile and will be in effect after a database

14
restart. SQL>ALTER SYSTEM SET audit_trail=DB SCOPE=SPFILE; After changing the audit_trail parameter, you
will need to bounce (shut down and start up) your database instance for the change to take effect.
Managing Statement Auditing: Statement auditing involves monitoring and recording the execution
of specific types of SQL statements. In the following sections, you will learn how to enable and disable
statement auditing as well as identify what statement auditing options are enabled.
Enabling Statement Auditing: You enable auditing of specific SQL statements with an AUDIT
statement. For example, to audit the SQL statements CREATE TABLE, DROP TABLE, and TRUNCATE
TABLE, use the TABLE audit option like this: QL>AUDIT table;
To record audit entries for specific users only, include a BY USER clause in the AUDIT statement. For
example, to audit CREATE, DROP, and TRUNCATE TABLE statements for user Abebe only, execute
the following: SQL>AUDIT table BY Abebe;
Frequently, you want to record only attempts that fail perhaps to look for users who are probing the
system to see what they can get away with. To further limit auditing to only these unsuccessful
executions, use a WHENEVER clause like this:
SQL>AUDIT table BY Abebe WHENEVER NOT SUCCESSFUL;

You can alternatively specify WHENEVER SUCCESSFUL to record only successful statements. If you do
not include a WHENEVER clause, both successful and unsuccessful statements will trigger audit records.
You can further configure non-DDL statements to record one audit entry for the triggering session or
one entry for each auditable action during the session. Specify BY ACCESS or BY SESSION in the AUDIT
statement, like this: SQL>AUDIT INSERT TABLE BY Abebe BY ACCESS;

Querying auditing: DBA_AUDIT_TRIAL and view that the overlays the SYS.ADU$ system table.
SQL>Show parameter Audit_trial;
SQL>Select * from db_audit_trial;
SQL>Audit select on Abebe.Staff;
SQL>Audit select on Abebe.Student whenever succussful;
SQL>Audit delete on Abebe.Course by session whenever not successful;

15

You might also like