Tải bản đầy đủ (.pdf) (73 trang)

Sybex OCA Oracle 10g Administration I Study Guide phần 7 ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.68 MB, 73 trang )

Auditing Database Activity

345

Identifying Enabled Object Auditing Options
The object auditing options that are enabled in the database are recorded in the DBA_OBJ_
AUDIT_OPTS data dictionary view. Unlike the statement and privilege _AUDIT_OPTS views, the
DBA_OBJ_AUDIT_OPTS always has one row for each auditable object in the database. There are
columns for each object privilege that auditing can be enabled on, and in each of these columns,
a code is reported that shows the auditing options. For example, the following report on the
HR.EMPLOYEES table shows that no auditing is enabled for the INSERT object privilege and that
the SELECT object privilege has auditing enabled with one audit entry for each access when the
access is successful and one audit entry for each session when the access is not successful:
SELECT owner, object_name, object_type, ins, sel
FROM dba_obj_audit_opts
WHERE owner='HR'
AND
object_name='EMPLOYEE_SALARY';
OWNER
OBJECT_NAME
OBJECT_TY INS SEL
------------ ------------------------- --------- --- --HR
EMPLOYEE_SALARY
TABLE
-/- A/S

The coding for the object privilege columns contains one of three possible values: a dash (-) to
indicate no auditing is enabled), an A to indicate BY ACCESS, or an S to indicate BY SESSION. The
first code (preceding the slash) denotes the action for successful statements, and the second code
(after the slash) denotes the action for unsuccessful statements.


Disabling Object Auditing
To disable object auditing, use a NOAUDIT statement, which allows the same WHENEVER options
as the AUDIT statement. For example, to disable auditing of unsuccessful SELECT statements
against the HR.EMPLOYEES table, execute the following:
NOAUDIT select ON hr.employee_salary

WHENEVER NOT SUCCESSFUL;

Purging the Audit Trail
Database audit records for statement, privilege, and object auditing are stored in the table
SYS.AUD$. Depending on how extensive your auditing and retention policies are, you will need
to periodically delete old audit records from this table. The database does not provide an interface to assist in deleting rows from the audit table, so you will need to do so yourself. To purge
audit records older than 90 days, execute the following as user SYS:
DELETE FROM sys.aud$ WHERE timestamp# < SYSDATE -90;


346

Chapter 6

User Administration and Security

You might want to copy the audit records into a different table for historical retention or
export them to an operating system file before removing them. It is a good practice to audit
changes to the AUD$ table so that you can identify when changes were made.

The audit table does not have a self-managing purge job and will grow without
bounds. To keep your SYSTEM tablespace from getting too large, you should
regularly delete old entries from the sys.aud$ table.


Managing Fine-Grained Auditing
Fine-grained auditing (FGA) lets you monitor and record data access based on the content of the
data. With FGA, you define an audit policy on a table and optionally a column. When the specified
condition evaluates to TRUE, an audit record is created, and an optional event-handler program is
called. You use the PL/SQL package DBMS_FGA to configure and manage FGA.
In the following sections, you will learn how to create, drop, enable, and disable fine-grained
auditing policies.

Creating an FGA Policy
To create a new FGA policy, use the packaged procedure DBMS_FGA.ADD_POLICY. This procedure has the following parameters:
object_schema This is the owner of the object to be audited. The default is NULL, which tells
the database to use the current user.
object_name This is the name of the object to be monitored.
policy_name This is a unique name for the new policy.
audit_condition This is a SQL expression that evaluates to a Boolean. When this condition evaluates to either TRUE or NULL (the default), an audit record can be created. This condition cannot
directly use the SYSDATE, UID, USER, or USERENV functions, it cannot use subqueries or sequences,
nor can it reference the pseudocolumns LEVEL, PRIOR, or ROWNUM.
audit_column This is a comma-delimited list of columns that the database will look to access.
If a column in audit_column is referenced in the SQL statement and the audit_condition is
not FALSE, an audit record is created. Columns appearing in audit_column do not have to also
appear in the audit_condition expression. The default value is NULL, which tells the database
that any column being referenced should trigger the audit record.
handler_schema This is the owner of the event-handler procedure. The default is NULL, which
tells the database to use the current schema.
handler_module This is the name of the event-handler procedure. The default NULL tells the
database to not use an event handler. If the event handler is a packaged procedure, the handler_
module must reference both the package name and program, using dot notation, like this:
UTL_MAIL.SEND_ATTACH_RAW



Auditing Database Activity

347

enable This is a Boolean that tells the database if this policy should be in effect. The default
is TRUE.
statement_types This tells the database which types of statements to monitor. Valid values are
a comma-delimited list of SELECT, INSERT, UPDATE, and DELETE. The default is SELECT.
audit_trail This parameter tells the database whether to record the SQL statement and bind
variables for the triggering SQL in the audit trail. The default value DBMS_FGA.DB_EXTENDED
indicates that the SQL statement and bind variables should be recorded in the audit trail. Set this
parameter to DBMS_FGA.DB to save space by not recording the SQL statement or bind variables
in the audit trail.
audit_column_ops This parameter has only two valid values: DBMS_FGA.ALL_COLUMNS and
DBMS_FGA.ANY_COLUMNS. When set to DBMS_FGA.ALL_COLUMNS, this parameter tells the database that all columns appearing in the audit_column parameter must be referenced in order to
trigger an audit record. The default is DBMS_FGA.ANY_COLUMNS, which tells the database that if
any column appearing in the audit_column also appears in the SQL statement, an audit record
should be created.
To create a new disabled audit policy named COMPENSATION_AUD that looks for SELECT
statements that access the HR.EMPLOYEES table and references either SALARY or COMMISSION_
PCT, execute the following:
DBMS_FGA.ADD_POLICY(object_schema=>’HR’
,object_name=>’EMPLOYEES’
,policy_name=>’COMPENSATION_AUD’
,audit_column=>’SALARY, COMMISSION_PCT’
,enable=>FALSE
,statement_types=>’SELECT’);

Enabling an FGA Policy
Use the procedure DBMS_FGA.ENABLE_POLICY to enable an FGA policy. This procedure will

not raise an exception if the policy is already enabled. For example, you can enable the
COMPENSATION_AUD policy added in the previous section like this:
DBMS_FGA.ENABLE_POLICY(object_schema=>'HR'
,object_name=>'EMPLOYEES'
,policy_name=>'COMPENSATION_AUD');

If you use direct path inserts, be careful with FGA auditing. If an FGA policy
is enabled on a table participating in a direct path insert, the auditing overrides the hint, disabling the direct path access and causing conventional
inserts. As with all hints, the database does not directly tell you that your hint
is being ignored.


348

Chapter 6

User Administration and Security

Disabling an FGA Policy
To turn off a fine-grained access policy, use the DBMS_FGA.DISABLE_POLICY procedure. Here
is an example:
DBMS_FGA.DISABLE_POLICY(object_schema=>'HR'
,object_name=>'EMPLOYEES'
,policy_name=>'COMPENSATION_AUD');

Dropping an FGA Policy
To remove an FGA audit policy, use the DBMS_FGA.DROP_POLICY procedure. For example, to
drop the COMPENSATION_AUD policy used in this section, run this:
DBMS_FGA.DROP_POLICY(object_schema=>’HR’
,object_name=>’EMPLOYEES’

,policy_name=>’COMPENSATION_AUD’);

Identifying FGA Policies in the Database
Query the DBA_AUDIT_POLICIES data dictionary view to report on the FGA policies defined in
your database. For example, the following report shows that the policy named COMPENSATION_
AUD on the column SALARY in the table HR.EMPLOYEES is defined, but not enabled:
SELECT policy_name ,object_schema||'.'||
object_name object_name
,policy_column
,enabled ,audit_trail
FROM dba_audit_policies;
POLICY_NAME
OBJECT_NAME POLICY ENABLED AUDIT_TRAIL
---------------- ------------ ------ ------- ----------COMPENSATION_AUD HR.EMPLOYEES SALARY NO
DB_EXTENDED

Audit records from this policy, when enabled, capture the standard auditing information as
well as the text of the SQL statement that triggered the auditing (DB_EXTENDED).

Reporting on the FGA Audit Trail Entries
The DBA_FGA_AUDIT_TRAIL data dictionary view is used in reporting on the FGA audit entries
that have been recorded in the database. The following example shows audit trail entries for the
COMPENSATION_AUD policy, listing the database username and the timestamp of the audit record
and computer from which the database connection was made.
SELECT db_user, timestamp, userhost
FROM dba_fga_audit_trail


Exam Essentials


349

WHERE policy_name='COMPENSATION_AUD'
DB_USER
-----------CHIPD
JUANITA

TIMESTAMP
-------------------10-Jun-2004 09:48:14
19-Jun-2004 14:50:47

USERHOST
-------------------XYZcorp\CHIPNOTEBOOK
XYZcorp\HR_PC2

Summary
Oracle 10g gives you a well-stocked toolkit for managing your users and securing your database. You create and manage user accounts with the CREATE, ALTER, and DROP USER statements. You can assign tablespace resources to be used for sorting that are different than those
for tables or indexes. You can limit the disk, CPU, and memory resources that your users consume by employing tablespace quotas and kernel resource limits in user profiles.
To protect your data from unwanted access or manipulation, you can employee object and
system privileges. You can create and use roles to make managing these database privileges easier. You can enable object, statement, privilege and fine-grained auditing to help you monitor
and record sensitive database activity.
Your Oracle 10g database has several powerful features (user accounts and packages) that
will need to be locked down in your production systems, and in this chapter you learned which
user accounts need to be locked, as well as which standard packages should be locked down to
better protect your company’s data.

Exam Essentials
Be familiar with the authentication methods. Database accounts can be authenticated by the
database (identified by password), by the operating system (identified externally), or by an
enterprise security service (identified globally).

Know how to assign default and temporary tablespaces to users. Assign default and temporary tablespaces with either a CREATE USER or an ALTER USER statement.
Be able to identify and grant object, system, and role privileges. Know the difference
between these types of privileges and when to use each type.
Know the differences between the WITH ADMIN OPTION and the WITH GRANT OPTION
keywords. The ADMIN option applies to role or system privileges, but the GRANT option applies
to object privileges
Know how to enable roles. Know when a role needs to be enabled and how to enable it.
Be able to secure your database. Make sure you know how to lock down you database.
Know which packages should be secured and how to secure them.


350

Chapter 6

User Administration and Security

Know how to implement password security. An Oracle 10g database affords you several
standard password security settings. Know what is available in a profile and what needs to be
implemented in a password-verify function.
Know how to enable, disable and identify enabled auditing options. Be able to describe the
types of auditing, how to enable them, and how to report on the audit trail.


Review Questions

351

Review Questions
1.


Which of the following statements creates an Oracle account, but lets the operating system
authenticate logons?
A. create user ops$admin identified by os;
B. create user ops$admin identified externally;
C. create user ops$admin nopassword;
D. create user ops$admin authenticated by os;

2.

Which of the following types of statements can use a temporary tablespace?
A. An index creation
B. SQL statements with a GROUP BY clause
C. A hash join operation
D. All of the above

3.

Which of the following statements gives user desmond the ability to alter table gl.accounts?
A. grant alter on gl.accounts to desmond;
B. grant alter to desmond on gl.accounts;
C. grant alter table to desmond;
D. allow desmond to alter table gl.accounts;

4.

Which of the following statements gives user desmond the ability to alter table gl.accounts as
well as give this ability to other accounts?
A. grant alter any table with grant option to desmond;
B. grant alter on gl.accounts to desmond with admin option;

C. grant alter any table to desmond with grant option;
D. grant alter any table to desmond with admin option;

5.

The following SQL statement will allow user regina to perform which operations on sequence
oe.orders_seq?
GRANT ALL ON oe.orders_seq TO regina;
A. Select the next value from oe.orders_seq.
B. Alter sequence oe.orders_seq to change the next value.
C. Change the number of sequence numbers that will be cached in memory.
D. Both A and C.
E. All of the above.


352

6.

Chapter 6

User Administration and Security

User system granted SELECT on sh.products to user ian using WITH GRANT OPTION. Ian then
granted SELECT on sh.products to user stuart. Ian has left the company, and his account is
dropped. What happens to Stuart’s privileges on sh.products?
A. Stuart loses his SELECT privilege on sh.products.
B. Stuart retains his SELECT privilege on sh.products.
C. Stuart loses his SELECT privilege if Ian was dropped with the CASCADE REVOKE option.
D. Stuart retains his SELECT privilege if Ian was dropped with the NOCASCADE REVOKE option.


7.

User system granted SELECT ANY TABLE to user ian using WITH ADMIN OPTION. Ian then
granted SELECT ANY TABLE to user stuart. Ian has left the company, and his account is
dropped. What happens to Stuart’s privileges?
A. Stuart loses his privileges.
B. Stuart retains his privileges.
C. Stuart loses his privileges if Ian was dropped with the CASCADE REVOKE option.
D. Stuart retains his privileges if Ian was dropped with the NOCASCADE REVOKE option.

8.

Which of the following system privileges can allow the grantee to masquerade as another user
and therefore should be granted judiciously?
A. CREATE ANY JOB
B. ALTER USER
C. CREATE ANY PROCEDURE
D. All of the above

9.

Which of the following statements enables the role user_admin in the current session?
A. alter session enable role user_admin;
B. alter session set role user_admin;
C. alter role user_admin enable;
D. set role user_admin;

10. Which of the following SQL statements allows user augustin to use the privileges associated
with the password-protected role info_czar, which has been granted to him?

A. set role all;
B. alter user augustin default role all;
C. alter session enable role info_czar;
D. alter session enable info_czar identified by brozo
11. By default, how much tablespace can any account use for a new table?
A. None
B. Up to the current free space in the tablespace
C. Unlimited space, including autoextends
D. Up to the default quota established at tablespace creation time


Review Questions

353

12. Which of the following SQL statements results in a disconnection after a session is idle for
30 minutes?
A. alter session set idle_timeout=30;
B. alter session set idle_timeout=1800;
C. alter profile limit idle_time 30;
D. alter profile set idle_timout 30;
13. Which of the following prevents a user from reusing a password when they change their password?
A. Setting the initialization parameter NO_PASSWORD_REUSE to TRUE
B. Altering that user’s profile to UNLIMITED for PASSWORD_REUSE_TIME and 1 for PASSWORD_
REUSE_MAX
C. Altering that user’s profile to UNLIMITED for both PASSWORD_REUSE_TIME and PASSWORD_
REUSE_MAX
D. Using a password verify function to record the new password and compare the new passwords to those recorded previously
14. How can you prevent someone from using an all-numeric password?
A. Set the initialization parameter PASSWORD_COMPLEXITY to ALPHANUM.

B. Alter that user’s profile setting PASSWORD_COMPLEXITY to ALPHNANUM.
C. Alter the user’s profile to use a password verify function that performs REGEX comparisons
to validate the password.
D. There is no mechanism that lets you prevent an all-numeric password.
15. Which of the following is not an object privilege on a table?
A. SELECT
B. DEBUG
C. REFERENCES
D. READ
16. Which of the following statements about user administration and security is the most true?
Select the best answer.
A. Password-protected roles require a password before they can become enabled.
B. You can disable any role that you find in your session_roles view.
C. If you execute alter profile student limit idle_time 10; and then execute alter
user scott profile student;, then user scott will be disconnected from future sessions
after 10 minutes of idle time.
D. You can limit a table to a maximum size on disk.


354

Chapter 6

User Administration and Security

17. Which of the following SQL statements limit attempts to guess passwords by locking an account
after three failed logon attempts?
A. alter profile default limit failed_login_attempts 3;
B. alter system set max_logon_failures = 3 scope=both;
C. alter user set failed_login_attempts = 3;

D. alter system set failed_login_attempts = 3 scope=both;
18. Where can the database write audit_trail records?
A. In a database table
B. In a file outside the database
C. Both in the database and in an operating system file
D. Either in the database or in an operating system file
19. Which of the following activities can be audited?
A. Unsuccessful deletions from the audit_trail table
B. Unsuccessful selects from the employee_salary table
C. All GRANT and REVOKE statements on procedures executed by user system
D. All of the above
20. How do you manage fine-grained auditing?
A. With the AUDIT and NOAUDIT statements
B. With the DBMS_FGA package
C. With the GRANT and REVOKE statements
D. With the CREATE, ALTER, and DROP statements


Answers to Review Questions

355

Answers to Review Questions
1.

B. Authentication by the operating system is called external authentication, and the Oracle
account name must match the operating system account name prefixed with the OS_AUTHENT_
PREFIX string.

2.


D. Any operation that requires a large sort or other creation of temporary segments will create,
alter, and drop those temporary segments in the TEMPORARY tablespace.

3.

A. Altering a table in another user’s schema requires either the object privilege ALTER on that
object or the system privilege ALTER ANY TABLE. Option A has the correct syntax for granting
the object privilege on ALTER gl.accounts to user desmond. Although option C would allow
user desmond to alter his own tables, he would need the ALTER ANY TABLE privilege to alter
another user’s table.

4.

D. Either the ALTER ANY TABLE system privilege or the ALTER object privilege is required. To
confer the ability to further grant the privilege requires the keywords WITH ADMIN OPTION for
system or role privileges or the keywords WITH GRANT OPTION for object privileges. Only option
D has both the correct syntax and the correct keywords.

5.

D. The ALL option for a sequence includes the SELECT and ALTER privileges. The SELECT privilege lets Regina select the next value from the sequence. The ALTER privilege lets Regina change
the cache but not the next value.

6.

A. When object privileges are granted through an intermediary, they are implicitly dropped when
the intermediary is dropped. There are no CASCADE REVOKE or NOCASCADE REVOKE options.

7.


B. When system privileges are granted through an intermediary, they are not affected when the
intermediary is dropped. There are no CASCADE REVOKE or NOCASCADE REVOKE options.

8.

D. The CREATE ANY JOB and CREATE ANY PROCEDURE system privileges allow the grantee to create and run programs with the privileges of another user. The ALTER USER PRIVILEGE allows
the grantee to change a user’s password, connect as that user, and then change the password
back. These are all powerful system privileges and should be restricted to as few administrative
users as practical.

9.

D. The SET ROLE statement enables or disables roles in the current session.

10. B. To enable a password-protected role, you need to either execute a SET ROLE statement specifying the password or alter the user to make the role a default role. Default roles do not require
a set role statement or a password to become enabled.
11. A. By default, user accounts have no quota in any tablespace. Before a user can create a table or
an index, you need to either give the user a quota in one or more specific tablespaces, or grant
the UNLIMITED TABLESPACE system privilege to give unlimited quota (including autoextends) in
all tablespaces.
12. C. Profiles limit the amount of idle time, CPU time, logical reads, or other resource-oriented
session limits. Option C uses the correct syntax to limit idle time for a session to 30 minutes.


356

Chapter 6

User Administration and Security


13. B. Although option D could also work, it involves storing the passwords in a table in the database, which could be a security concern. It also takes a lot more effort to configure and maintain.
The better technique is to use the standard database profile features PASSWORD_RESUSE_TIME
and PASSWORD_REUSE_MAX. Setting one of these profile parameters to UNLIMITED and the other
to a specific value prevents passwords from being reused. If both of these profile parameters are
set to UNLIMITED, these parameters are essentially disabled. There is no initialization parameter
called NO_PASSWORD_REUSE.
14. C. There are no standard password complexity settings in either the initialization parameters or
profiles. A password verify function can validate new passwords against any rules that you can
code in PL/SQL, including regular expression comparisons.
15. D. The object privileges on a table include SELECT, INSERT, UPDATE, DELETE, ALTER, INDEX,
REFERENCES, and DEBUG, but not READ. READ is a valid object privilege, but only on a directory—a database object that is outside the scope of the OCA exam.
16. D. This question is tricky. All the options look correct and in fact are mostly true. But option D
is the most correct option. Password-protected roles that are included in a user’s default role list
are enabled by default and do not need a password. Your session_roles view contains both
roles granted directly to you and those you inherit through another role. You cannot disable roles
that you inherit by way of another role without disabling the role granted directly to you. For
example, you cannot disable SCHEDULER_ADMIN without disabling DBA. Limiting a profile to 10
minutes of idle time will cause future sessions to timeout after 10 idle minutes, but only if the initialization parameter RESOURCE_LIMIT is set to TRUE (the default is FALSE). Because each schema
owner can be assigned tablespace quotas, you can effectively limit all of a user’s segments to a maximum size, thus setting an upper limit on the size of any single table.
17. A. You limit the number of failed logon attempts with a profile.
18. D. The destination of audit_trail records is controlled by the initialization parameter audit_
trail. Setting this parameter to DB or DB_EXTENDED causes the audit trail to be written to a database
table. Setting the parameter to OS causes the audit trail to be written to an operating system file.
19. D. Audit unsuccessful deletions from the audit table with the following SQL:
AUDIT DELETE ON sys.aud$ WHENEVER NOT SUCCESSFUL;
Audit unsuccessful selects from all tables with the following:
AUDIT NOT EXISTS;
Audit all grant and revoke statements on procedures executed by user SYSTEM with the following:
AUDIT grant procedure BY system;

20. B. Fine-grained auditing is managed using the DBMS_FGA package. The AUDIT and NOAUDT statements are used to manage statement, privilege, or object auditing. The GRANT and REVOKE
statements are used to manage system, object, and role privileges. The CREATE, ALTER, and
DROP statements are used to manage several types of database objects and settings.


Chapter

7

Managing Data With
SQL, PL/SQL, and
Utilities
ORACLE DATABASE 10G:
ADMINISTRATION I EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
Managing Data
Manipulate data through SQL using INSERT, UPDATE,
and DELETE.
Use Data Pump to export data.
Use Data Pump to import data.
Load Data with SQL Loader.
Create directory objects.
PL/SQL
Identify PL/SQL objects.
Describe triggers and triggering events.
Identify configuration options that affect PL/SQL
performance.

Exam objectives are subject to change at any time
without prior notice and at Oracle’s sole discretion.

Please visit Oracle’s Training and Certification website
( />for the most current exam objectives listing.


Oracle supports manipulating data via several interfaces, but the
most common are SQL and PL/SQL. Understanding how to use
and manage PL/SQL programs is an important skill for any DBA.
Some database functionality is delivered only as PL/SQL programs, such as fine-grained auditing, and some functionality is available in both a command-line version or as PL/SQL programs,
such as Data Pump export and Data Pump import. As you gain experience, you will increasingly
rely on using PL/SQL to manage your databases. So you need to have a solid grasp of SQL and
PL/SQL fundamentals to be a successful Oracle10g DBA.
In this chapter, you will learn how to create, change, and remove information from an Oracle
database using SQL and PL/SQL.

Manipulating Data through SQL
The Structured Query Language, SQL for short, includes Data Definition Language (DDL)
statements, Data Control Language (DCL) statements, and Data Manipulation Language
(DML) statements. You learned how to create, alter, and delete objects using DDL statements
in Chapter 3, “Database Storage and Schema Objects.” Chapter 6, “User Administration and
Security,” showed you how to use the DCL statements GRANT and REVOKE to give and take privileges on database objects. In this section, you will learn how to use the DML statements
INSERT, UPDATE, and DELETE to add, modify, and remove data from your tables.
After using DML statements to add rows to a table, update rows in a table, or delete rows
from a table, you must make these changes permanent by executing a COMMIT command. Alternatively, you can undo the DML changes with a ROLLBACK command. Until you commit the
changes, other database sessions will not be able to see your changes.

Using INSERT Statements
You use the INSERT statement to add rows to one or more tables. You can create these rows
with specific data values or copy them from existing tables using a subquery.

Inserting into a Single Table

When using SQL, the only way to add rows to an Oracle10g table is with an INSERT statement
and the most common variety of INSERT statement is the single table insert. Figure 7.1 shows
a diagram of the syntax for the single-table INSERT statement.


Manipulating Data through SQL

FIGURE 7.1

359

The syntax for a single-table INSERT statement
@
schema

.

DBLink
,

table
@

INSERT INTO

DBLink

(

column


)

view

(

subquery

)

,
(

VALUES

value

)
;

subquery

The column list is optional, with the default being a list of all columns in the table in COLUMN_
ID order. See the data dictionary views USER_TAB_COLUMNS, ALL_TAB_COLUMNS, or DBA_TAB_
COLUMNS for the COLUMN_ID. While inserting into a table is more common, you can also insert
into a view, as long as the view does not contain one of the following:
A DISTINCT operator
A set operator (UNION, MINUS, and so on)
An aggregate function (SUM, COUNT, AVG, and so on)

A GROUP BY, ORDER BY, or CONNECT BY clause
A subquery in the SELECT list
Here are some examples of using the INSERT statement to insert rows into a single table. The
following inserts one row, channel 3, in the channels table:
INSERT INTO channels (channel_id ,channel_desc
,channel_class ,channel_class_id
,channel_total ,channel_total_id) VALUES
(3 ,'Direct Sales' ,'Direct'
,12 ,'Channel total' ,1);

The following inserts one row, channel 5, in the channels table:
INSERT INTO channels VALUES
(5 ,'Catalog' ,'Indirect' ,13 ,'Channel total' ,1);

The following copies zero or more rows from the territories table in the home_office
database into the regions table:
INSERT INTO regions (region_id ,region_name)
SELECT region_seq.NEXTVAL , terr_name


360

Chapter 7

Managing Data With SQL, PL/SQL, and Utilities

FROM territories@home_office
WHERE class = 'R';

The number and datatypes of values in the VALUES list must match the number and datatypes

in the column list. The database will perform implicit datatype conversion if necessary to convert the values into the datatype of the target.

Inserting into Multiple Tables
Most INSERT statements are the single-table variety, but Oracle also supports a multiple-table
INSERT statement. You most frequently use multitable inserts in data warehouse Extract,
Transform, and Load (ETL) routines.
With a multitable insert, you can make a single pass through the source data and load the
data into more than one table. By reducing the number of passes through the source data, you
can reduce the overall work and thus achieve faster throughput. Figure 7.2 shows a diagram of
the multitable INSERT statement syntax.
If a WHEN condition evaluates to TRUE, the corresponding INTO clause is executed. If no WHEN condition evaluates to TRUE, the ELSE clause is executed. The keyword ALL tells the database to check
each WHEN condition. On the other hand, the keyword FIRST tells the database to stop checking
WHEN conditions after finding the first TRUE condition.
In the following example, an insurance company has policies for both property and casualty in
the policy table, but in their data mart, they break out these policy types into separate fact tables.
During the monthly load, new policies are added to both the property_premium_fact and
casualty_premium_fact tables. You can use a multitable INSERT to add these rows more efficiently than two separate INSERT statements. The multitable INSERT would look like this:
INSERT FIRST
WHEN policy_type = 'P' THEN
INTO property_premium_fact(policy_id
,policy_nbr ,premium_amt)
VALUES (property_premium_seq.nextval
,policy_number ,gross_premium)
WHEN p.policy_type = 'C' THEN
INTO property_premium_fact(policy_id
,policy_nbr ,premium_amt)
VALUES (property_premium_seq.nextval
,policy_number ,gross_premium)
SELECT policy_nbr ,gross_premium ,policy_type
FROM policies

WHERE policy_date >=
TRUNC(SYSDATE,'MM') - TO_YMINTERVAL('00-01');

By using this multitable INSERT statement instead of two separate statements, the code makes
a single pass through the policy table instead of two and thus loads the data more efficiently.


Manipulating Data through SQL

FIGURE 7.2

361

The syntax for the multitable INSERT statement

,
schema
INSERT ALL

INTO

.

(

,

column

)


table

VALUES

(

value

)

;

DEFAULT
INTO clause

THEN
ALL
INSERT

WHEN

condition THEN

FIRST

INTO

clause


INTO

clause
ELSE

INTO

clause

;

Using UPDATE Statements
You use an UPDATE statement to change existing rows in a table. Figure 7.3 shows a diagram
of the syntax for the UPDATE statement.
The column list can be either a single column or a comma-delimited list of columns. A
single list of columns lets you assign single values—either literals or from a subquery. The
following updates customer XYZ’s phone and fax numbers, and sets their quantity based on
their orders:
UPDATE order_rollup r
SET phone = '3125551212'
,fax
= '7735551212'
,qty
= (SELECT SUM(d.qty)
FROM order_details d
WHERE d.customer_id = r.customer_id)
WHERE r.customer_id = 'XYZ';

Like the CREATE TABLE and ALTER TABLE statements you saw in Chapter 6, when you use a
comma-delimited list of columns, you must enclose them in parentheses. The comma-delimited

list lets you assign multiple values from a subquery. The following updates both the quantity and
price for customer XYZ for the order they placed on October 1, 2004:
UPDATE order_rollup
SET (qty, price) = (SELECT SUM(qty), SUM(price)
FROM order_details
WHERE customer_id = 'XYZ')
WHERE customer_id = 'XYZ'
AND order_period = TO_DATE('01-Oct-2004');


362

Chapter 7

FIGURE 7.3

Managing Data With SQL, PL/SQL, and Utilities

The syntax for the UPDATE statement
,
,
schema

.

(

table

UPDATE


column

) = ( subquery )

SET

view

WHERE

expression

conditions

;

column =
(

subquery

)

Assigning multiple values from a single subquery can save you from having to perform multiple subqueries, thus improving the efficiency of your SQL.

Using DELETE Statements
You use the DELETE statement to remove rows from a table. A diagram of the syntax for the
DELETE statement is shown in Figure 7.4.
Here are some examples of a DELETE statement. The following removes orders from certain

states:
DELETE FROM orders
WHERE state IN ('TX','NY','IL')
AND order_date < TRUNC(SYSDATE) - 90

The following removes customer GOMEZ:
DELETE FROM customers
WHERE customer_id = 'GOMEZ';

The following removes duplicate line_detail_ids. Note that the keyword FROM is not
needed.
DELETE line_details
WHERE rowid NOT IN (SELECT MAX(rowid)
FROM line_detail
GROUP BY line_detail_id)
--Remove all rows from the table order_staging
DELETE FROM order_staging;

The WHERE clause is optional, and when it is not present, all rows from the table are removed.
If you need to remove all rows from a table, consider using the TRUNCATE statement. TRUNCATE
is a DDL statement and, unlike the DELETE statement, does not support a ROLLBACK. Using
TRUNCATE, unlike using DELETE, does not generate undo and executes much faster for a large
table. If you want to empty a table of all rows, use a TRUNCATE statement instead of a DELETE.
The TRUNCATE executes faster and may generate significantly less undo.


Identifying PL/SQL Objects

FIGURE 7.4


363

The syntax for the DELETE statement
@
FROM

schema

.

DBLink

@

DBLink

table

DELETE

WHERE

conditions
;

view

Identifying PL/SQL Objects
PL/SQL is Oracle’s Procedural Language extension to SQL. This Oracle proprietary language
was derived from Ada and has evolved to include a robust feature set, including sequential and

conditional controls, looping constructs, exception handing, records, and collections, as well as
object-oriented features such as methods, overloading, upcasting, and type inheritance.
Full knowledge of the PL/SQL language is well beyond the scope of the OCA/OCP exams, and
more developers than DBAs create PL/SQL programs. But a significant number of database features are delivered as PL/SQL programs, and knowledge of how to identify and work with these
programs is crucial to your effectiveness. In this section, you will learn what kinds of PL/SQL programs are available, when each is appropriate, and what configuration options are applicable to
working with PL/SQL programs.
The exam covers five types of named PL/SQL programs, which are usually stored in the database: functions, procedures, packages, package bodies, and triggers. Each of these program
types is covered in the following sections. The name and source code for each stored PL/SQL
program is available from the data dictionary views DBA_SOURCE and DBA_TRIGGERS, although
some packages are supplied “wrapped,” which means that the source code is a binary form.
You can wrap your programs as well with the wrap utility.

See the PL/SQL Users Guide and Reference for details on using wrap.

Working with Functions
Functions are PL/SQL programs that execute zero or more statements and return a value
through a RETURN statement. Functions can also receive or return zero or more values through
their parameters. Oracle provides several built-in functions such as the commonly used
SYSDATE, COUNT, and SUBSTR functions. There are over 200 SQL functions that come with your
Oracle10g database and hundreds of PL/SQL functions. See the Oracle Database SQL Reference 10g manual (part B10759-01) for a complete list of these SQL functions and the PL/SQL
Packages and Types Reference 10g manual (part B10802-01) for the functions available with


364

Chapter 7

Managing Data With SQL, PL/SQL, and Utilities

the built-in PL/SQL packages. Because functions have a return value, a datatype is associated

with them. Functions can be invoked anywhere an expression of the same datatype is allowed.
Here are some examples:
As a default value
DECLARE
today

DATE DEFAULT SYSDATE;

In an assignment
today := SYSDATE;

In a Boolean expression
IF TO_CHAR(SYSDATE,'Day') = 'Monday'

In a SQL expression
SELECT COUNT(*)
FROM employees
WHERE hire_date > SYSDATE-30;

In the parameter list of another procedure or function
SELECT TRUNC(SYSDATE)

Create a function with the CREATE FUNCTION statement, like this:
CREATE OR REPLACE FUNCTION is_weekend(
check_date IN DATE DEFAULT SYSDATE)
RETURN VARCHAR2 AS
BEGIN
CASE TO_CHAR(check_date,'DY')
WHEN 'SAT' THEN
RETURN 'YES';

WHEN 'SUN' THEN
RETURN 'YES';
ELSE
RETURN 'NO';
END CASE;
END;

Functions, like all named PL/SQL, have the OR REPLACE keywords available in the
CREATE statement. When present, OR REPLACE tells the database to not raise an exception
if the object already exists. This behavior differs from a DROP and CREATE, in that privileges
are not lost during a REPLACE operation and any objects that reference this object will not
become invalid.


Identifying PL/SQL Objects

365

Working with Procedures
Procedures are PL/SQL programs that execute one or more statements. Procedures can receive
and return values only through their parameter lists. Unlike functions, only a few built-in procedures, such as RAISE_APPLICATION_ERROR are built into the PL/SQL language.
You create a procedure with the CREATE PROCEDURE statement, like this:
CREATE OR REPLACE PROCEDURE archive_orders
(cust_id
IN NUMBER
,retention IN NUMBER) IS
BEGIN
DELETE orders
WHERE customer = cust_id
AND

order_date < SYSDATE - retention;
INSERT INTO maint_log
(action, action_date, who) VALUES
('archive orders '||retention||' for '||cust_id
,SYSDATE ,USER);
END;

The keyword IS, in the third line, is synonymous with the keyword AS, seen in the third line of
the last example function in the previous section. Both are syntactically valid for all named SQL.
You invoke a procedure as a stand-alone statement within a PL/SQL program by using the
CALL or EXEC commands. Here is an example:
EXEC DBMS_OUTPUT.PUT_LINE('Hello world!');
Hello world!
PL/SQL procedure successfully completed.
CALL DBMS_OUTPUT.PUT_LINE('Hello world!');
Hello world!
Call completed.

Working with Packages
A package is a container for functions, procedures, and data structures, such as records, cursors,
variables and constants. A package has a publicly visible portion, called the specification (or spec
for short) and a private portion called the package body. The package spec describes the programs


366

Chapter 7

Managing Data With SQL, PL/SQL, and Utilities


and data structures that can be accessed from other programs. The package body contains the
implementation of the procedures and functions. The package spec is identified in the data dictionary as the type PACKAGE, and the package body is identified as the type PACKAGE BODY.
To create a package spec, use the CREATE PACKAGE statement. In the following, the package
spec table_util contains one function and one procedure:
CREATE OR REPLACE PACKAGE table_util IS
FUNCTION version RETURN VARCHAR2;
PROCEDURE truncate (table_name IN VARCHAR2);
END table_util;

Privileges on a package are granted at the package-spec level. The EXECUTE privilege on a
package allows the grantee to execute any program or use any data structure declared in the
package specification. You cannot grant the EXECUTE privilege on only some of the programs
declared in the spec.
A package body depends on a package spec having the same name. The package body can
only be created after the spec. The package body implements the programs that were declared
in the package spec and can optionally contain private programs and data accessible only from
within the package body.
To create a package body, use the CREATE PACKAGE BODY statement:
CREATE OR REPLACE PACKAGE BODY table_util IS

Here is an example of a private variable that can be referenced only in the package body:
version_string VARCHAR2(8) := '1.0.0';

Here is the code for the version function:
FUNCTION version RETURN VARCHAR2 IS
BEGIN
RETURN version_string;
END;

Here is the code for the truncate procedure:

PROCEDURE truncate (table_name IN VARCHAR2) IS
BEGIN
IF UPPER(table_name) = 'ORDER_STAGE'
OR UPPER(table_name) = 'SALES_ROLLUP'
THEN
EXECUTE IMMEDIATE 'truncate table ' ||
UPPER(table_name);
ELSE
RAISE_APPLICATION_ERROR(-20010


Identifying PL/SQL Objects

367

,'Invalid table for truncate: '|| table_name);
END IF;
END;
END table_util;

The package name following the END statement is optional, but encouraged, as it improves
readability.

Working with Triggering Events and Managing Triggers
Triggers are PL/SQL programs that are invoked in response to an event in the database. Three
sets of events can be hooked, allowing you to integrate your business logic with the database in
an event-driven manner. Triggers can be created on DML events, DLL events, and database
events. These three trigger event classes provide developers and you, the DBA, with a robust
toolkit with which to design, build, and troubleshoot systems.
We will look at each of these events in more detail in the following sections. We will also discuss how to enable and disable triggers.


DML Event Triggers
DML triggers are invoked, or “fired,” when the specified DML events occur. If the keywords
FOR EACH ROW are included in the trigger definition, the trigger fires once for each row that is
changed. If these keywords are missing, the trigger fires once for each statement that causes the
specified change. If the DML event list includes the UPDATE event, the trigger can be further
restricted to fire only when updates of specific columns occur.
The following example creates a trigger that fires before any insert and before an update to
the hire_date column of the employee table:
CREATE OR REPLACE TRIGGER employee_trg
BEFORE INSERT OR UPDATE OF hire_date
ON employees FOR EACH ROW
BEGIN
log_update(USER,SYSTIMESTAMP);
IF INSERTING THEN -- if fired due to insert
:NEW.create_user := USER;
:NEW.create_ts
:= SYSTIMESTAMP;
ELSEIF UPDATING THEN -- if fired due to update
IF :OLD.hire_date <> :NEW.hire_date THEN
RAISE_APPLICATION_ERROR(-20013,
'update of hire_date not allowed');
END IF;
END IF;
END;


Chapter 7

368


Managing Data With SQL, PL/SQL, and Utilities

This trigger will fire once for each row affected, because the keywords FOR EACH ROW are
included. When the triggering event is an INSERT, two columns are forced to the specific values
returned by USER and SYSTIMESTAMP. DML triggers cannot be created on SYS-owned objects.
Table 7.1 shows the DML triggering events.
TABLE 7.1

DML Trigger Events

Event

When It Fires

INSERT

When a row is added to a table or a view.

UPDATE

When an UPDATE statement changes a row in a table or view. Update triggers can also specify an OF clause to limit the scope of changes that fire
this type of trigger.

DELETE

When a row is removed from a table or a view.

Multiple triggers on a table fire in the following order:
Before statement triggers

Before row triggers
After row triggers
After statement triggers

DDL Event Triggers
DDL triggers fire either for DDL changes to a specific schema or to all schemas in the database.
The keywords ON DATABASE specify that the trigger will fire for the specified event on any
schema in the database.
The following is an example of a trigger that fires for a DDL event in only one schema:
CREATE OR REPLACE TRIGGER NoGrantToPublic
BEFORE GRANT ON engineering.SCHEMA
DECLARE
grantee_list
dbms_standard.ora_name_list_t;
counter
BINARY_INTEGER;
BEGIN
-- get the list of grantees
counter := GRANTEE(grantee_list);
FOR loop_counter IN
grantee_list.FIRST..grantee_list.LAST
LOOP
-- if PUBLIC is on the grantee list, stop the action


Identifying PL/SQL Objects

369

IF REGEXP_LIKE(grantee_list(loop_counter)

,'public','i') THEN
RAISE_APPLICATION_ERROR(-20113
,'No grant to PUBLIC allowed for '
||DICTIONARY_OBJ_OWNER||'.'
||DICTIONARY_OBJ_NAME);
END IF;
END LOOP;
END;

In the preceding example, the DDL event is a GRANT statement issued by user engineering.
The code examines the grantee list, and if it finds the special user/role PUBLIC, an exception is
raised, causing the grant to fail. Table 7.2 shows the DDL triggering events.
TABLE 7.2

DDL Trigger Events

Event

When It Fires

ALTER

When an ALTER statement changes a database object.

ANALYZE

When the database gathers or deletes statistics or validates
the structure of an object.

ASSOCIATE STATISTICS


When the database associates a statistic with a database
object with an ASSOCIATE STATISTICS statement.

AUDIT

When the database records an audit action (except FGA).

COMMENT

When a comment on a table or column is modified.

CREATE

When the database object is created.

DDL

In conjunction with any of the following: ALTER, ANALYZE,
ASSOCIATE STATISTICS, AUDIT, COMMENT, CREATE, DISASSOCIATE
STATISTICS, DROP GRANT, NOAUDIT, RENAME, REVOKE, or TRUNCATE.

DISASSOCIATE STATISTICS

When a database disassociates a statistic type from a database object with a DISASSOCIATE STATISTICS statement.

DROP

When a DROP statement removes an object from the database.


GRANT

When a GRANT statement assigns a privilege.

NOAUDIT

When a NOAUDIT statement changes database auditing.


×