All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
blind folio: P
PART I
Oracle Database 10g
Administrative I Exam
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
■
ch01.indd 1
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18
Chapter 19
Chapter 20
Chapter21
Basic Oracle Concepts
Installing Oracle Database 10g
Creating an Oracle Database
Interfacing with the Oracle Database
Managing Oracle Processes
Managing Oracle Storage Structures
Administering Users
Managing Database Objects
Manipulating Database Data
Programming Oracle with PL/SQL
Securing the Database
Configuring Oracle Networking
Managing Shared Servers
Managing Database Performance
Monitoring Oracle
Managing Undo
Dealing with Locking
Configuring the Database for Backup and Recovery
Backing Up Oracle Databases
Recovering Oracle Databases
Managing Globalization in Oracle Databases
6/17/2005 4:39:32 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 / Chapter 23
blind folio: PB
ch01.indd 2
6/17/2005 4:39:57 PM
All-in-1 / Oracle
All-in-1
Database
/ Oracle10g
Database
OCP Certification
10g Certification
/ Watson
All-in-One
& Bersinic
/ Meyers
/ 5790-3
/ 5790-3
/Chapter
/ FM
1
blind folio: PB
CHAPTER 1
Basic Oracle Concepts
In this chapter you will learn
• What a database is and what makes a database relational
• What SQL is
• Which database objects are supported in Oracle 10g
• What a database administrator does
• How the Oracle database fits into the Oracle product family
3
ch01.indd 3
6/17/2005 4:39:58 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
Someone once said that the best place to start is at the beginning. With Oracle, that
means understanding where the idea of a relational database management system
(RDBMS) came from and what a database is—in computer and everyday terms. Even
though the material presented here may not be directly tested on the exam, this is
assumed knowledge, however, so a quick read is probably a good idea.
Introduction to Databases
and the Relational Model
In one form or another, databases have always been around, though their exact shape
was not always easily recognizable. As long as some form of data had to be stored,
there was always a method of storing it.
Databases, in their most simple form, are a mechanism for storing data. The data
can be logical, like the values stored in a computer program, or may be physical, like
a file or receipt. You probably have databases in existence all around you, but you
may not see them as such. For example, the shoebox in which you’ve placed your tax
receipts for the accountant is a database of your annual expenses. When you open a
file cabinet and take out a folder, you are accessing a database. The content of the file
folder is your data (e.g., your credit card statements, your bank statements, invoices,
purchase orders, etc.). The file cabinet and drawers are your data storage mechanisms.
Before the advent of computers, all data was stored in some easily recognizable
physical form. The introduction of computers simply changed the data from a physical
form that you can touch and feel to a digital form that is represented by a series of 1’s
and 0’s. Does the information that you display for an expense report on the computer
screen differ greatly from the same information in the hard-copy version of the expense
form? Perhaps the information is laid out differently than on the screen, but the key
elements—who was paid, what amount, how much was the tax, what was the purpose
of the expense, and so on—are all the same.
In looking at a database and its most basic set of characteristics, the following
points hold true:
• A database stores data. The storage of data can take a physical form, such as
a filing cabinet or a shoebox.
• Data is composed of logical units of information that have some form of
connection to each other. For example, a genealogical database stores
information on people as they are related to each other (parents, children, etc.).
• A database management system (DBMS) provides a method to easily retrieve,
add, modify, or remove data. This can be a series of filing cabinets that are
properly indexed, making it easy to find and change what you need, or a
computer program that performs the same function.
ch01.indd 4
6/17/2005 4:39:58 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
5
PART I
When data began to move from a physical form to a logical form using computers,
different theoretical versions of systems to manage data evolved. Some of the more
common database management systems in use over the last 50 years include the
hierarchical, network, and relational. Oracle is a relational database management system
(RDBMS).
The Relational Model of Databases
The relational model for database management systems was proposed in the June
1970 issue of Communications of the ACM—the Association of Computing Machinery
journal—by Dr. E.F. Codd, an IBM researcher, in a paper called “A Relational Model
of Data for Large Shared Data Banks.” For its time it was a radical departure from
established principles because it stated that tables that have related data need not
know where the related information is physically stored. Unlike previous database
models, including the hierarchical and network models, which used the physical
location of a record to relate information between two sets of data, the relational
model stated that data in one table needed to know only the name of the other table
and the value on which it is related. It was not necessary for data in one table to keep
track of the physical storage location of the related information in another.
NOTE The full text of Dr. E.F. Codd’s paper “A Relational Model of Data for
Large Shared Data Banks” can be found in the classics section of the ACM
web site at www.acm.org/classics/nov95/toc.html.
The relational model broke all data down into collections of objects or relations
that store the actual data (i.e., tables). It also introduced a set of operators to act on
the related objects to produce other objects (i.e., join conditions to produce a new
result set). Finally, the model proposed that a set of elements should exist to ensure
data integrity so that the data would be consistent and accurate (i.e., constraints). Codd
proposed a set of twelve rules that would allow designers to determine if the database
management system satisfied the requirements of the relational model. Although no
database today satisfies all twelve rules (because the database would run very slowly if
it did, since theory is not always the same as practice), it is generally accepted that any
RDBMS should comply with most of them.
The essence of the relational model is that data is made up of a set of relations.
These relations are implemented as two-dimensional tables with rows and columns
as shown in Figure 1-1. In this example, the Customers table stores information about
clients we deal with—their customer ID, their company name, their address, and so on.
The Orders table stores information about the client orders (but not the order line
items—these are in another table), including the order data, the method of payment,
the order date, and the ship date. The CustomerID column in both tables provides the
relationship between the two tables and is the source of the relation. The tables
themselves are stored in a database that resides on a computer. The physical locations
of the tables need not be known—only their names.
ch01.indd 5
6/17/2005 4:39:58 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
Figure 1-1
The Customers
and Orders tables
are related by
CustomerID.
For a database to be considered relational, and because the physical location of
rows is not something that a user querying data needs to know, the table must allow
for each row to be uniquely identified. The column (or set of columns) that uniquely
identifies a row is known as the primary key. Each table in a relational database
(according to database theory) must have a primary key. In this way, you are certain
that the specific value appears only once in the table. In Figure 1-1, the CustomerID
column of the Customers table is a primary key, ensuring that each CustomerID
appears only once in the table. For the Orders table, the OrderID is the primary key.
When relating tables together (the whole point of a relational database), the value
of a primary key column in one table can be placed in a column in another table. The
column in the second table holding the value is known as the foreign key. A foreign key
states that the value in this column for a row exists in another table and must continue
to exist, or else the relationship is broken. In Figure 1-1, the CustomerID column of
the Orders table is a foreign key to the CustomerID column in the Customers table.
In order for the relationship to be valid, any value placed in the CustomerID column
of the Orders table must already exist in the CustomerID column of the Customers
table. In other words, in order for a client to place an order, we need to know some
basic information about them. If we don’t have this information, the customer cannot
place an order. Oracle enforces the primary key–foreign key relationship through the
use of database constraints.
ch01.indd 6
6/17/2005 4:39:59 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
7
SQL: The Structured Query Language
PART I
All of the relations in a relational database are managed by a relational database
management system. As indicated earlier, an RDBMS allows you to manipulate
relational tables and their contents. It provides a language that allows you to create,
modify, and remove objects in the database, as well as add, change, and delete data.
The language that Oracle uses is the Structured Query Language, or SQL. SQL was
originally developed by IBM, for whom E.F. Codd worked, and was first called
Structured English Query Language (or SEQUEL, for short). The name has been
shortened to Structured Query Language, or SQL, but it is still pronounced sequel.
SQL is actually a collection of several different “languages,” each designed for
a particular purpose. It is made up of the following:
• Data definition language (DDL) DDL is used to create and modify
database objects. DDL statements include CREATE, ALTER, DROP, RENAME,
and TRUNCATE. If you need to add a new table to the database, you use the
CREATE TABLE statement to perform this task. To remove an index, you use
the DROP INDEX statement, and so on.
• Data manipulation language (DML) DML is used to modify data in tables
in the database. DML statements include INSERT, UPDATE, and DELETE, as
well as extensions to control transactions in the database, including COMMIT,
ROLLBACK, and SAVEPOINT. The SELECT statement used to query data in
the database is not technically considered a DML command, although it is
sometimes included with the definition of DML because it deals with the
retrieval of data.
• Data control language (DCL) DCL is used to configure security to perform
database tasks and manipulate database objects. DCL statements include GRANT
and REVOKE. Permissions can be granted to allow a user to perform a task
such as creating a table, or to manipulate or query data, as by performing an
insert into a table in the database.
Another characteristic of an RDBMS is that tables in a relational database do not
have their relationship represented by data in one table storing the physical location
of the data in a related table. As you can see in Figure 1-1, the Customers table and
the Orders table are related by the data that exists in the CustomerID column of both
tables. The physical location on disk of each table does not factor into the relationship
between them. As long as a user querying the two tables knows the column that
relates them, he/she is able to formulate a SQL statement that will extract the data
satisfying the condition of that relationship (also known as the “join condition”).
Should one of the tables be moved to a different hard disk used to store data in the
database, the relationship will still hold true.
A third characteristic of an RDBMS is that the language used to manipulate the
database has a rich and varied set of operators that can be used to manipulate the
data and explore the relationships between the various tables. The SQL language
allows you to determine, through the proper use of operators, data that is related
ch01.indd 7
6/17/2005 4:39:59 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
between tables, data where the relationship does not hold true, and much more. The
SQL language in its pure form does not, however, have any procedural elements of a
programming language such as loops, conditional logic, and the use of variables. Oracle
has extended SQL to include these elements through PL/SQL, a proprietary set of
language elements that can be used to create stored procedures, triggers, and other
subprograms.
RDBMSs have become popular in part for the preceding reasons. Nothing stays
static for long in the database world. Oracle, the first commercially available relational
database management system, has extended its database capabilities to support object
features.
Object Relational Database Management System
(ORDBMS)
Releases of Oracle prior to Oracle 8 were RDBMSs; that is, they followed the relational
model and complied with its requirements, and often improved upon them. With
the introduction of Oracle 8, Oracle was considered an object relational database
management system—something that is even more true with Oracle 10g. An ORDBMS
complies with the relational model but also extends it to support the newer object
relational database model introduced in the 1980s.
An ORDBMS is characterized by a number of additional features, including these:
• Support for user-defined datatypes This means that users can create their
own datatypes based upon the standard Oracle datatypes or other user-defined
datatypes. This feature allows for more accurate mapping of business objects
to database features and can reduce the time it takes to maintain databases
after they have been implemented.
• Support for multimedia and other large objects Oracle 8 and subsequent
releases up to 10g have full support for binary large objects, or BLOBs. This
means that it is possible to store large amounts of information such as video
clips, images, and large amounts of text in the column of a row. Even though
earlier releases of Oracle had a similar feature, it lacked functionality and was
not implemented in a way that conformed to object relational standards. The
current implementation is much improved.
• Full compatibility with relational database concepts Even though object
extensions have been added to Oracle, in order for it to remain an ORDBMS,
it needs to conform to the requirements of an RDBMS. Because of Oracle’s
strong legacy as an RDBMS, its object features can be leveraged along with the
relational features to provide robust solutions.
The one thing that defines Oracle as an ORDBMS is its capability to allow you
to create a user-defined datatype, which becomes an object in Oracle. For example,
if you wanted to use a common definition for a telephone number in several tables
(Customers, Suppliers, Employees, etc.) and wanted to be sure that any changes to
its characteristics would be inherited by all tables using it, you could create a new
ch01.indd 8
6/17/2005 4:39:59 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
9
PART I
datatype called “PhoneNumber” with the proper characteristics and then create the
tables using the PhoneNumber datatype as one of the column definitions. If the rules
for area codes, for example, changed, you could modify the attributes and methods of
the PhoneNumber datatype and all tables would inherit the change.
Database Objects
Every RDBMS needs to support a minimum number of database objects in order to
comply with the basic requirements for a relational database. Oracle supports these
and many more. This chapter presents only a listing of those objects, while subsequent
chapters will allow you to create and manipulate many of these objects.
Oracle’s collection of database objects includes all of those that are needed for
it to be called a relational database (tables, views, constraints, etc.) as well as others
that go beyond what is required and are included because they provide additional
functionality (packages, object types, synonyms, sequences, etc.). The full list of
database objects that Oracle 10g supports appears in Table 1-1.
Object
Description
Table
A collection of columns and rows representing a single entity (e.g., customers,
orders, employees, etc.).
Column
A single attribute of an entity stored in a table. A column has a name and a
datatype. A table may have, and typically does have, more than one column as
part of its definition.
Row
A single instance of an entity in a table, including all columns. For example,
a student row will store all information about a single student, such as that
student’s ID, name, and address.
Cell
The term cell is used to refer to the intersection of a single column in a single
row. For example, the CompanyName column for CustomerID 10002 in our
example would be a cell holding that data—Bradley Systems.
Constraint
A database object that is used to enforce simple business rules and database
integrity. Examples of constraints are PRIMARY KEY, FOREIGN KEY, NOT
NULL, and CHECK.
View
A view is a logical projection of data from one or more tables as represented
by a SQL statement stored in the database.Views are used to simplify
complex and repetitive SQL statements by assigning those statements a name
in the database.
Index
An index is a database object that helps speed up retrieval of data by
storing logical pointers to specific key values. By scanning the index, which is
organized in either ascending or descending order according to the key value,
you are able to retrieve a row quicker than by scanning all rows in a table.
Table 1-1 Oracle 10g Database Objects
ch01.indd 9
6/17/2005 4:39:59 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
Object
Description
Indexorganized table
A table whose physical storage is organized like an index. Unlike a regular
table, where rows are inserted in no particular order and querying all rows
will retrieve the data in random order, index-organized tables store data
organized according to the primary key defined on the table. The difference
between a table (referred to as storing data on a heap) and an indexorganized table is like the difference between storing all of your receipts in
a shoebox (i.e., in no specific order) and storing it chronologically according
to the date the expense was incurred. Taking the receipts out of the shoebox
will result in no specific logic in their retrieval, while doing the same when the
receipts are organized chronologically will allow you to predict that the June 2
receipt will appear before the August 1 receipt.
Partition
Tables in Oracle 10g can be cut into pieces for more efficient physical storage.
A partition (or subpartition) holds a subset of the table’s data, typically on
a separate physical disk, so that data retrieval is quicker either by allowing
reads from more than one physical disk simultaneously (multipartition parallel
reads) or by not reading a partition’s data at all if it
is not required to satisfy the query (partition elimination).
Cluster
A storage mechanism object that allows rows from more than one table to be
physically stored together for quicker retrieval. For example, if you store the
Order information (customer, payment info, delivery details, etc.) in one table
and the line items (item, cost, sale price, quantity, etc.) in a different table,
you will need to perform at least two reads to retrieve information about an
order: one for the order info and the second for line item info. Creating both
tables on the cluster organized by the order ID will allow Oracle to place the
order and line item data for the same order ID on the same physical block,
thereby reducing retrieval of that order’s information to a single read. The
downside of clusters is that they force you to preallocate a certain portion
or all of the disk space they require when rows are added or the cluster is
created.
Sequence
A sequence allows you to create and increment a counter that can be used
to generate numerical values to be used as primary key values for a table.
Synonym
As in the English language, a synonym is another name for an existing object.
Synonyms are used in Oracle as shorthand for objects with long names, or
to make it easier to remember a specific object.
Stored
procedure
A stored procedure is a collection of SQL and PL/SQL statements that
perform a specific task, such as to insert a row into a table or to update data.
Trigger
A trigger is a special kind of stored procedure that cannot be invoked
manually but rather is automatically invoked whenever an action is performed
on a table. Triggers can be associated with a table and a corresponding action
such as INSERT, UPDATE, or DELETE as well as system events such as user
logon and logoff, or database STARTUP and SHUTDOWN.
Function
A function is a stored program that must return a value. Unlike stored
procedures, which can have parameters passed to them and do not need
to return any value as output, a function must return a value.
Table 1-1 Oracle 10g Database Objects (continued)
ch01.indd 10
6/17/2005 4:40:00 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
11
Description
Package
A package is a collection of stored procedures and functions grouped under
a common name. This allows you to logically group all program elements for
a particular part of the database under a single name for maintenance and
performance reasons.
User-defined
datatype
A user-defined datatype is a database object that can be used in any table or
another object definition. Using user-defined datatypes allows you to ensure
consistency between tables and also lets you apply methods (i.e., actions that
can be performed by the object) as part of the definition.
BLOB
A BLOB is a binary large object used to store video, images, and large amounts
of text. BLOBs are defined as a column in a table and can be one of several
datatypes: BLOB, CLOB, NCLOB, or BFILE.
PART I
Object
Table 1-1 Oracle 10g Database Objects (continued)
Oracle also includes other objects that are beyond the scope of this book, including
dimensions, directories, materialized views, and more. These objects are created for a
specific purpose such as to facilitate data warehousing and their full coverage is beyond
the scope of this book.
Each object in an Oracle database is owned by a user. A user defined in an Oracle
database does not have to own any objects, but those that do are known as schema
users. A schema is a collection of all objects owned by a particular user, including tables,
indexes, views, and so on.
The Oracle Data Dictionary
As you may well imagine, a database may contain hundreds and even thousands of
objects. Keeping track of all this information is the job of the Oracle data dictionary. A
data dictionary in any database contains metadata information. Metadata is “data about
data,” or a set of tables and other database objects that store information about your
own tables and database objects.
The data dictionary in Oracle is a set of tables, called base tables, which contain
the most basic information about user-created database objects. These base tables are
owned by an Oracle user called SYS, which is created when the database itself is created.
The base tables are never accessed directly, as their names are cryptic by design to
discourage users from querying and modifying them. To make it easier to access the
data dictionary and get information on objects in the database, a series of views are
created during the database creation process. These views are commonly referred to
as data dictionary views.
Oracle has three sets of data dictionary views. They are as follows:
• USER_ views These views allow users to get information on objects that are
in their schema (i.e., objects that they have created and own).
ch01.indd 11
6/17/2005 4:40:00 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
• ALL_ views These views allow users to get information on objects that they
own or that they have been given access to. The ALL_ views contain a subset
of the information presented in the USER_ views for the same object and
allow users to find out what other objects they are allowed to reference or
manipulate in the database, in addition to the objects that they own.
• DBA_ views The DBA_ views, designed to be used by the database
administrator (DBA) of the database, provide a full set of information for
objects in the database, i.e., any object created by any user. Normal users
do not have access to these views, as special privileges are needed to SELECT
from them.
As you delve further in this book, you will be introduced to many DBA_ views
to help you in your duties as a database administrator. But, what does a database
administrator do in the Oracle world?
Responsibilities of a Database Administrator
One of my colleagues likes to comment that users of the databases for which he is
responsible think they control the databases. The reality, as he quite correctly puts it
(if in a control-freakish sort of way), is quite different. As a DBA, he can do whatever
he wants in any database he is responsible for, so he’s the one with control. Database
administrators do have a great deal of power, but it is important to remember that
with great power also comes great responsibility. Ultimately, the success and failure
of a database to respond to user requirements and satisfy corporate objectives rests
with the DBA. The DBA must take the blame and the praise for good or bad database
management.
The kinds of tasks DBAs in the Oracle world are responsible for include the
following:
• Sizing and evaluating server hardware As the individual responsible for the
smooth operation of databases in your organization, you will be called upon
to suggest the configuration of the server that will be used to run Oracle. Your
experience will play a key role here in determining the amount of memory,
hard disk, CPU, and other resources required to support the target database’s
operations. Understanding the architecture of Oracle and the data needs of
the business and the application will help you perform this task.
• Installing Oracle software and updates After you buy the software, the first
thing you need to do is bring it up. Installation of the Oracle software on the
target platform is the job of the DBA. It usually involves more than putting in
the CD and answering the prompts of the setup program because Oracle is a
very powerful system comprising a complex piece of software that has many
hooks and interactions with the operation system. Ensuring that the software
is installed and working properly is a key to being a successful DBA.
ch01.indd 12
6/17/2005 4:40:00 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
13
PART I
• Planning and designing the database structure Once the software is
installed, you need to make sure that the layout of the physical data structures
and logical elements of Oracle is done in an optimal way. If this is not the
case, performance will suffer and users will make their displeasure known.
If you have properly sized the hardware, this should be an easy task, since
you should have taken the database size and structure into account; if you
inherited the environment, you may need to use your expertise to determine
the optimal configuration.
• Creating databases As you will see in Chapter 3, this is a somewhat
anticlimactic task. Creation of the database is the first step to administering it.
Although relatively straightforward, the process can run into problems; with
experience, however, you should grow well equipped to fix these problems.
• Backing up databases and implementing other ways to safeguard the data
Once a database is in production and users are connecting to it, they may not
take it well if the database becomes unavailable. Even worse, if data is lost it
could mean lost productivity, sales, and customers. Ensuring that a database
is always available to users, that data loss is minimized, and that recovery is
quick and complete is perhaps one of the most important responsibilities of
the DBA.
• Creating and maintaining database users Once a new user needs to
gain access to the database or when the requirements and permissions of
another user change, the DBA must be able to make the necessary security
modifications to ensure appropriate access. In some cases, application
developers may not make use of Oracle’s built-in security fully, so being able
to recognize these situations and take appropriate action is also necessary.
• Implementing application and database designs Organizations may
purchase third-party software applications or hire database architects to
design a database to suit a specific database requirement when in-house
expertise is lacking. However, the actual implementation of these designs
will be undertaken by the DBA, since the DBA will be responsible for
ensuring that the database continues to work properly after the software
vendor or database architect leaves.
• Restoring and recovering databases Sometimes things go wrong. Hardware
fails, users improperly modify or delete data, or a natural disaster or some
other calamity befalls the data center. Being able to recover from a variety of
scenarios is critical. This is when the fault tolerance disaster recovery strategy
is tested for real—but it should also be tested in mock scenarios to ensure it
works. The DBA is the one that is answerable for their success or failure.
• Monitoring and tuning database performance In Star Trek: The Next
Generation there is an episode where the Enterprise assists a stranded vessel.
The vessel’s occupants are somewhat lacking in both engineering and
communication skills, but they do ask Captain Picard and Giordi to make
us go fast. Your users will frequently comment that the database is not fast
ch01.indd 13
6/17/2005 4:40:01 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
enough. Keeping those comments to a minimum and solving performance
problems when (or before) they occur will reduce your stress level and
increase job satisfaction.
As you can tell, the duties of a DBA are wide and varied. It is an exciting position
whose goal can sometimes be summed up in one phrase: reduce the number of times
the phone rings in a day. If you get a lot of phone calls from users or management,
this is probably not a good sign and can make your day an unhappy one. Well-tuned
databases on appropriate hardware with good disaster recovery and backup strategies
will reduce your phone calls, make happy users, and increase your job satisfaction.
Sounds simple, right?
The Oracle Product Family
As an Oracle database administrator, you may be responsible for a database that is
actually part of another Oracle product or that complements or is relied upon by that
other product. Oracle has long since become more than just a database company—
though the Oracle database is at the heart of what Oracle Corporation does best. In
addition to the database, Oracle Corporation also offers these products, among others:
• Oracle E-Business Suite Also referred to as Oracle Applications, the
E-Business Suite is the premier enterprise resource planning (ERP) suite
in the industry. Encompassing many modules, including financials, human
resources, distribution, manufacturing, and many others, the E-Business
Suite allows organizations to leverage Oracle technology to better run their
businesses and increase profitability and customer satisfaction. Oracle
E-Business Suite makes use of the Oracle database, Application Server,
and Developer Suite to run and enhance the application.
• Oracle Collaboration Suite One of Oracle’s newest products, Collaboration
Suite encompasses e-mail, fax, calendaring, web conferencing, a files repository,
voice mail, and other modules to provide a single integrated platform for an
organization’s collaboration and communication infrastructure. Like Oracle
E-Business Suite, Collaboration Suite also incorporates the Oracle database
and Application Server as its foundation.
• Oracle Application Server A Java 2 Enterprise Edition (J2EE)–certified
server platform, Oracle Application Server integrates everything you
need to deploy and develop web-based applications. Oracle Application
Server includes a portal server and tools to develop portlets, Web Services
capabilities, content management, support for forms-based applications
using Oracle Forms, reporting using Oracle Reports, development using
PL/SQL or Java, and many other features. It also includes the capability to
configure and use a single sign-on server that interfaces with other thirdparty directory services such as Microsoft’s Active Directory, Novell’s NDS,
and Sun’s iPlanet.
ch01.indd 14
6/17/2005 4:40:01 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
15
PART I
• Oracle Developer Suite If you need to develop applications for the Oracle
database or Application Server, Oracle Developer Suite provides tools for the
development of Java, PL/SQL, business intelligence, data warehousing, and
other applications.
• Oracle Consulting When you need assistance in your Oracle deployment,
Oracle Consulting can provide the expertise and individuals to help your
projects succeed.
• Oracle University The training of customers and partners on Oracle products
and technologies is the responsibility of Oracle University and its partners.
Instructor-led and online courses are available.
More information on the products available from Oracle Corporation can be
found on the Oracle web site at www.oracle.com.
Chapter Review
In this chapter you learned a bit about the history of the relational database management
system (RDBMS) concept. You also learned that SQL is actually three languages: a
data control language (DCL) for managing permissions on database objects, a data
definition language (DDL) for creating and managing those objects, and a data
manipulation language (DML) for adding, updating, or deleting data from the database,
as well as controlling those transactions. You saw what objects may appear in an
Oracle 10g database and read a brief description of each object, and you were briefed
on your responsibilities as a database administrator. Finally, you learned that Oracle
is not just a database company but one with a wealth and breadth of products and
services. At this point, you’re ready to start working with Oracle (after a few questions).
Questions
1. You need to recommend a platform for the deployment of your web-based
application written in Java. You need to make the management of web
page content easy as well as integrate security with your Active Directory
infrastructure. Which Oracle product will satisfy your requirements? (Choose
the best answer.)
A. Oracle Database
B. Oracle Application Server
C. Oracle Collaboration Suite
D. Oracle E-Business Suite
E. Oracle Developer Suite
2. For which of the following types of information stored in a database would
the use of a sequence be appropriate? (Choose two correct answers.)
ch01.indd 15
6/17/2005 4:40:01 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
A. Invoice line item
B. Invoice number
C. Employee name
D. Atomic element
E. Customer identifier
3. What is a key benefit to making use of user-defined datatypes in Oracle?
(Choose the best answer.)
A. Ability to rename Oracle built-in datatypes
B. Inheritance
C. Polymorphism
D. Consistency of similar data structures across multiple tables
E. Easier maintenance of databases
4. Your organization has outgrown its hosted e-mail system. You also need to
implement web conferencing. Development of an interface to your in-house
telephone system will take place and needs to be integrated with a new voice
mail platform. Your developers are versed in Java on a Linux platform. Which
Oracle product provides the best fit for your organization’s requirements?
(Choose the best answer.)
A. Oracle Database
B. Oracle Application Server
C. Oracle Collaboration Suite
D. Oracle E-Business Suite
E. Oracle Developer Suite
5. Which of the following is not typically a responsibility of an Oracle database
administrator? (Choose the best answer.)
A. Creating new users
B. Creating database objects
C. Installing Oracle software
D. Application development to manipulate database data
E. Backing up the database
ch01.indd 16
6/17/2005 4:40:01 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 1
PB
Chapter 1: Basic Oracle Concepts
17
Answers
PART I
1. B. Oracle Application Server provides a Java 2 Enterprise Edition (J2EE)–
certified server for deploying your web-based application. It also includes
a portal server for creating new content and a content management server
for managing changes to content. Finally, the Oracle Internet Directory
component allows for integration with third-party directory services to
provide single sign-on functionality.
2. B and E. A sequence is an automatically generated chronological number,
ideal for invoice numbers or unique identifiers for database data, such as a
customer ID. Because a sequence is numeric in nature, it is not appropriate
for text-based data such as an order line item, employee name, or atomic
element.
3. D. Using a user-defined datatype, you can ensure that the same data is always
stored the same way in all tables. In other words, a phone number will
always have a consistent structure no matter what table it is in. It can make
maintenance of the database easier as well, but this is a secondary benefit.
4. C. Oracle Collaboration Suite provides e-mail, fax, and voice mail
functionality, as well as web conferencing, calendaring, and other features.
Because it also includes Oracle Application Server, it is the perfect product for
the development and deployment of a custom application to interface with
the phone system.
5. D. The development of the application that will interface with the database
and manipulate the data within it is not something that a DBA does. This task
is performed by an application developer. The DBA is responsible for all other
tasks listed in the question, including database security, software installation,
backup and recovery, and the creation and management of database objects.
ch01.indd 17
6/17/2005 4:40:01 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 / Chapter 23
blind folio: PB
ch01.indd 18
6/17/2005 4:40:02 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
CHAPTER 2
Installing Oracle Database 10g
In this chapter you will learn how to
• Identify system requirements
• Use Optimal Flexible Architecture
• Install software with the Oracle Universal Installer
• Identify and configure commonly used environment variables
1
ch02.indd 1
6/29/2005 9:55:19 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
Understanding how a database works is a good starting point, but you actually need
to get the software installed in order to see the real thing in action. Ironically, installing
the software need not mean that you even create a database. Installing the Oracle 10g
database software means that you now have the tools to create and manage databases
at your disposal.
Oracle System Requirements
In order for Oracle 10g database software to be installed on a computer, you need to
ensure that all the prerequisites are met. Oracle, because it runs on so many platforms,
requires various forms of other software to be configured in order for it to work
properly. This includes additional packages on Linux systems, specific services
and software on Windows, kernel parameter sizing on Unix-based systems or any
combination of these, as well as other, platform-specific environment settings and
prerequisites.
Table 2-1 lists the minimum and recommended system requirements across most
Oracle platforms. Notice that the CPU type and speed are not listed. This is because the
operating system you are running will already determine which CPUs are supported.
Oracle will work on the CPUs supported by the operating system you intend to run
the software on. For a more specific list of system requirements, you should refer
to the operating system–specific installation guide found on the installation CD or
on the Oracle Technology Network (OTN) web site (www.oracle.com/technology/
documentation/database10g.html).
As a general rule, the more RAM you have in the computer, the better it is for
Oracle. RAM is the one resource that provides the best bang for the buck when it comes
to performance of an Oracle database. If you plan on running many databases on the
same server, increase the amount of RAM in the server to allow for smooth operation
of all instances.
System Requirement
Minimum
Recommended
Random Access Memory
(RAM)
512MB
1GB
Swap / Page File Space
1GB
Twice the size of RAM
Temp Space (/tmp or \TEMP)
400MB
1GB
Disk Space
1.5GB for Oracle software
1.5GB for starter database
1.5GB for Oracle software
1.5GB for starter database
Operating system and version
As specified in Oracle docs
As specified in Oracle docs
Table 2-1 Minimum and Recommended System Requirements for the Oracle 10g Database
ch02.indd 2
6/29/2005 9:55:55 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
3
In terms of disk space, if you plan on having your databases grow, you should
allocate additional disk space. The current thinking is disk is cheap, so add more space
as needed to support the size of databases you plan on running. Adding more disk
space can also allow you to more efficiently allocate that disk space for Oracle and
take advantage of striping or other techniques to further improve performance.
Oracle 10g database is supported on many different operating systems and
hardware platforms. While Linux and Windows may be the two most popular
choices these days, Oracle is also available for Solaris, IBM AIX, HP-UX, HP (formerly
Compaq) Tru64, and IBM z/OS (OS/390), as well as both 64-bit (AMD and Itanium)
and 32-bit variants of Windows and Linux. When deciding on a specific version of
an operating system, it is important to check Oracle’s MetaLink support site (http://
metalink.oracle.com) to ensure that your version of the operating system and platform
is on the certified list. Oracle supports only certified versions of the operating system.
For example, running Oracle on Red Hat’s Fedora Project Linux is not officially
supported, but Red Hat Linux Enterprise Edition AS and ES are supported. Always
verify, either through the documentation or by checking on the Certify and Availability
link on MetaLink, that you are installing Oracle on a supported platform.
PART I
EXAM TIP Oracle always recommends more RAM be available than specified
in the system requirements. This avoids performance problems like paging and
swapping due to lack of resources.
EXAM TIP The most up-to-date list of supported operating systems and
versions can be found on Oracle’s MetaLink support site.
Optimal Flexible Architecture
With the release of Oracle 8, Oracle introduced Optimal Flexible Architecture, or OFA.
OFA is a method of naming mount points and directories and of organizing datafiles
and database components to make it easy for a DBA to locate files and administer
the database. The Oracle Universal Installer, when creating a starter database, will
conform to OFA rules in the creation of that database. Furthermore, the Oracle
Universal Installer will create a file and directory structure that will make compliance
with OFA easy to achieve in the creation of additional databases using the Database
Configuration Assistant.
The Optimal Flexible Architecture was developed by Oracle’s consulting services
to make the performance and monitoring of Oracle databases easier. OFA specifies
that at least three sets of directories should be used to reduce contention and provide
good performance. One set of directories will be used to store Oracle binary files such
as the Oracle executables themselves, as well as associated support files that should
normally not be changed. A second set of directories will be used to store controlfiles,
ch02.indd 3
6/29/2005 9:55:56 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
redo log files, and other administrative files such as the parameter file for each database
on the computer. Finally, a third set of directories will be used to store all the data files.
Each set of directories should be on a separate physical hard disk, and further manual
optimization may also be required to ensure good performance.
While OFA is not perfect, it does provide the basis for good performance and
easier administration, including:
• A structured approach for locating the various files that are required and used
by Oracle. This structured approach, when followed, will allow any DBA to
easily become familiar with any database and server that they are asked to
administer.
• Easier administration of databases while performing such tasks as backing
up and restoring databases because of a familiar file and directory structure.
If you need to create additional data files, you will also be able to figure out
where to put the file by adhering to the OFA structure.
• Because the OFA configuration will make use of multiple physical disks on
the computer, this will allow for improved performance of the databases that
use it by reduced disk contention for datafiles, binary files, and redo log files.
While simply adhering to OFA principles is not enough to guarantee optimal
performance for your databases and server, it will provide a starting point for
further performance monitoring and tuning.
• If you have multiple Oracle homes on the same computer or are running
multiple versions of Oracle on the same computer, each version can adhere to
OFA principles and thereby make it less likely that files required by one version
of Oracle, or one Oracle package, will overwrite those of another version or
package. OFA helps to separate potentially conflicting files, thereby making
administration easier and contention less likely.
Directory and Mount Point Syntax
One of the things that makes OFA work well is a common naming scheme for mount
points and directories (folders). Using a common naming methodology helps make
it easier to organize and locate resources. The Oracle Database Configuration Assistant
(DBCA) will create many of the OFA components when it is used to create a database
in Oracle 10g. The Oracle Universal Installer used to install Oracle software will also
create OFA-compliant structures within the mount points and directories you indicate
as the base of the Oracle installation (ORACLE_BASE).
Recommendations for OFA-compliant naming scheme on a Linux/Unix platform
include:
• Name all mount points using a combination of a common string constant
and a variable value in the form /pm, where p is a string constant and m is a
variable value. For example, /u01, /u02, /u03, etc., or /ora01, /ora02, /ora03
would be good choices. Using this convention makes it easy to add additional
mount points that adhere to the naming convention.
ch02.indd 4
6/29/2005 9:55:57 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
5
Subdirectory
Name
Purpose
Example
adhoc
Ad hoc SQL and PL/SQL scripts for
the database
/u02/db/admin/ocp10g/adhoc
arch
Location of archived redo log files
/u02/db/admin/ocp10g/arch
adump
Location of audit files—need to set
AUDIT_FILE_DEST parameter first
/u02/db/admin/ocp10g/adump
bdump
Location of background process
trace files and the alert log file. Set
with the BACKGROUND_DUMP_
DEST parameter
/u02/db/admin/ocp10g/bdump
cdump
Core dump file location. Set with the
CORE_DUMP_DEST parameter
/u02/db/admin/ocp10g/cdump
create
Location of scripts used to create
the database. DBCA places scripts
in this location when you use it to
create a new database
/u02/db/admin/ocp10g/create
exp
Recommended location of database
export files created by the Export
utility or Oracle Data Pump
/u02/db/admin/ocp10g/exp
logbook
Location of database history and
status log files
/u02/db/admin/ocp10g/logbook
pfile
The parameter files used to start the
database is placed here
/u02/db/admin/ocp10g/pfile
udump
User process trace files are located
here. Set with the USER_DUMP_
DEST parameter
/u02/db/admin/ocp10g/udump
PART I
• Within the mount points, name directories where Oracle software is installed
in the form /pm/h/u/product/v, where /pm is the mount point as indicated in
the preceding point, h is a standard directory name indicating a purpose such as
app or db or home, u is the name of the owner of the directory (since multiple
operating system users can install and own Oracle software), product is a literal,
and v specifies the product version installed in the directory. For example, the
location of the Oracle 10g database owned by an operating system user called
“oracle” could be /u02/db/oracle/product/10.1.0. The location of an Oracle 10g
Application Server installation could be /u01/app/oracle/product/9.0.4, or an
Oracle 8i database could be /u01/db/oracle/product/8.1.7.
• Within the directory structure you would create an admin directory and
additional subdirectories within the admin directory for storing specific file
types used by Oracle. The full pathname would be /pm/h/admin/d/a, where
admin is a literal, d is the SID (system identifier or name) of the database,
and a is a subdirectory for a specific administrative file type. The common
administration directories are shown in Table 2-2.
Table 2-2 OFA-Compliant Administrative Directories and Their Contents
ch02.indd 5
6/29/2005 9:55:57 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
EXAM TIP The structure of the administrative directories of OFA is
important for the effective administration of Oracle, and Oracle strongly
recommends that it be used. DBAs are assumed to know the parameters
to set in Oracle to ensure that the appropriate files are located in the
OFA directory structure.
The naming of the mount points and directories is not enforced by Oracle. Rather,
it is strongly recommended that you follow the recommendations to make it easier
for you to identify what is installed on your computer’s hard drive. In a Windows
environment, the syntax is similar, though you could use drive letters for the mount
points or mount the partition in an empty NTFS folder that serves as the base of your
Oracle installation.
File-Naming Syntax
The final piece of a naming strategy needs to deal with the files located in the
directories. For Oracle’s data files, redo log files and controlfiles, the naming strategy
starts with a directory naming component—the root of your database file structure
(as opposed to the admin files outlined in the preceding section). The root of the
datafile structure is a directory in the form /pm/q/d, where pm is the mount point,
q is a literal indicating that the directory contains Oracle database data (e.g., “oradata”
or “oracle”), and d is the name of the database sourced either from the DB_NAME
parameter (recommended) or the ORACLE_SID environment variable. Examples
include /u03/oradata/ocp10g and /u01/ORACLE/mydb.
It is possible, and quite common, to have data for a database on multiple mount
points to spread the I/O workload across multiple physical disks and thereby provide
better performance. For this reason, you will probably see the same directory name
corresponding to a database on several mount points, such as /u02/oradata/ocp10g
and /u03/oradata/ocp10g. This method can also be used to separate different Oracle
database file types. These file types, and recommended naming convention are
outlined in Table 2-3.
File Type
Purpose
Naming Convention
Controlfiles
Used to store information about the
database, its files, and their status.
As control.ctl or controlnn.ctl, where
nn is a number (control01.ctl)
Redo log files
Store a record of changes to
database data as they occur.
As redonn.log, where nn is a number
(redo01.log)
Datafiles
Store database data.
As tablespacenamenn.dbf, where
tablespacename is the name of the
logical Oracle database storage
structure and nn is a number
(“system01.dbf” or “undo01.dbf”)
Table 2-3 Recommended Naming Conventions for Oracle Database Files
ch02.indd 6
6/29/2005 9:55:58 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
7
PART I
An important point to remember is that only Oracle database files indicated in
Table 2-3 should be stored in the OFA-compliant database file location. Storing other
files makes it harder to keep track of which file is where. The administrative directory
structure is used to store the other files used by an Oracle database and instance,
whereas the database file location is used to store all files related to the Oracle database
during normal operation—the control, redo log, and datafiles.
Installing Oracle Using
the Oracle Universal Installer
Now that you are familiar with OFA and have decided upon the directory structure
to be used for your Oracle installation, you can get the CDs out and are almost
ready to install Oracle on your computer. Because Oracle is a complex piece of software
running on many different operating systems, CPU architectures, and storage systems,
additional requirements will need to be verified and tasks completed in order to ensure
a successful installation.
Operating System Preparation
One of the first things you should do before installing the Oracle database software
is to read the appropriate installation guide for your operating system and platform.
These can be found on the Oracle Technology Network in the product documentation
section for Oracle 10g database (www.oracle.com/technology/documentation/
database10g.html). It is always a good idea to review the specific tasks that need to
be performed on your environment because kernel parameters, other systems settings,
and prerequisite software differ by platform. However, a couple of things are similar
across all platforms.
NOTE If you are installing Oracle on Linux, a special section of the OTN web
site located at www.oracle.com/technology/tech/linux/install/index html deals
with installing Oracle on Linux. Another good Linux resource is Werner
Pushitz’s Linux Page at www.puschitz.com (also linked from the OTN web
site). Oracle-Base (www.oracle-base.com) is a good resource for Linux and other
operating systems, as well as other Oracle product installation assistance.
Creating the User and Groups for Oracle
One of the first things you need to do before installing Oracle Database 10g is to
create an operating system user and group that will own the Oracle software. The
methods used depend on the operating system, but you should create at least one
user (called oracle from here on in) and two groups, one to own the Oracle installation
(oinstall will be used) and another to which users can be added for administering
Oracle (dba is a commonly used group name).
ch02.indd 7
6/29/2005 9:55:59 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
For a Linux-based computer, you could issue the following commands while
logged in as the root user to create the groups and users, as well as specifying the group
ID and user ID values, the user’s default home directory (-d /home/oracle) and
the shell for the user (-s /bin/bash):
groupadd -g 500 oinstall
groupadd -g 501 dba
useradd -u 500 -g oinstall -G dba -d /home/oracle oracle -s /bin/bash
On Linux, in order to install Oracle you must log in as the oracle user. You will
also need the root user to perform some configuration of the operating system, so
make sure you know the root password or can have someone perform those tasks
when needed. You cannot complete an install on Unix or Linux without performing
the root-level operations.
NOTE If you will be installing Oracle on Linux and need some information
on Linux commands, a couple of articles of value can be found at the Linux
Technology Center on Oracle’s web site: www.oracle.com/technology/tech/
linux/index.html.
In Windows environments the DBA group needs to be a local group on the
computer where Oracle is being installed and must be called ORA_DBA. It is important
to note that you need not create this group before you install Oracle; it can be, and
often is, created after Oracle is already installed. The only user requirement for
installing Oracle on Windows is that the person installing the software must be logged
in to the computer as a user that is a member of the local Administrators group.
Setting the Environment
In order for Oracle to operate properly after it is installed, a number of environment
variables need to be configured for the oracle user. In Windows environments these
requirements are automatically taken care of by Registry entries that Oracle creates
when the software is installed, but in Unix and Linux these environment variables
need to be configured manually. While no environment variables need to be configured
when you are installing Oracle Database 10g and Oracle indicates that none should
be set before starting the installation, setting them can ensure that Oracle performs
properly during and after the install.
These are some variables that you may wish to set beforehand:
EXAM TIP You should be very familiar with these environment variables and
their uses.
• ORACLE_BASE The root of an OFA-complaint Oracle directory structure
for installation of all products on the computer. This environment variable
specifies the directory where all Oracle products are installed on the computer,
such as /opt/oracle.
ch02.indd 8
6/29/2005 9:56:00 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
9
• ORACLE_SID The identifier of the Oracle instance that you will connect to
or create. In most environments it must be eight characters or less, beginning
with a letter and containing letters and numbers. In Real Application Cluster
environments it must be five characters or less. The default initial instance
name is ORCL, though the ORACLE_SID must always be set to connect to
an instance locally.
PART I
• ORACLE_HOME The home directory of the current Oracle installation.
Typically specifies a directory under the path indicated by ORACLE_BASE
such as $ORACLE_BASE/product/10.1.0 on a Linux or Unix system.
• NLS_LANG Specifies the globalization settings for the Oracle installation in
the form language_territory.character_set. The default value for NLS_LANG is
“American_America.US7ASCII” in all environments except Windows, where
this value is set to the regional settings specified for the operating system and
keyboard setting.
NOTE If the keyboard setting in Windows is non-US English, then this will
also cause Oracle to set the NLS_SORT value to be set to other than binary,
thereby reducing optimizer effectiveness on character-based indexes. More
information on how NLS_LANG and other NLS-related parameters work
can be found in Chapter 21.
• DISPLAY On Unix environments you need to indicate to the Oracle
Universal Installer where to send graphical screen displays. The default
behavior is to inherit the value of the DISPLAY environment variable from
the operating system and send all output there. If you want to redirect the
graphical display to an X Window terminal or some other location, you will
need to set the DISPLAY environment variable in the form hostname:display,
such as opus01.haunting.com:1.0. The user installing Oracle must have
permissions to write to the display as well, which can be set using the
xhost command in Unix-based environments.
NOTE To allow all users to write to a specific DISPLAY, the root user can
issue the command xhost + to remove any security restrictions on that
display. This is a security risk and should not be used as a permanent solution.
Check the Linux/Unix documentation for more details on the proper usage
of the xhost command.
EXAM TIP Understanding how to set the DISPLAY environment variable and
use it during installation is worthwhile knowledge for the exam.
ch02.indd 9
6/29/2005 9:56:00 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
Before starting the installation of Oracle on Unix-based systems, it is a good idea
to at least set the value of the ORACLE_HOME environment variable as the oracle
user to tell Oracle where the software is to be installed and to create the directory
path, as follows:
mkdir -p /opt/oracle/product/10.1.0
ORACLE_HOME=/opt/oracle/product/10.1.0 ; export ORACLE_HOME
Installing Oracle Software
Oracle is installed on all platforms by running the Oracle Universal Installer (OUI).
This program is automatically invoked when you insert CD-ROM 1 of the installation
media for Oracle Database 10g in the CD drive. You can also start it by issuing the
runInstaller command from the CD-ROM on Unix-based systems or setup.exe
from the root of the CD-ROM in Windows.
The Oracle Universal Installer
The Oracle Universal Installer is a Java-based application that looks and feels the same
on all platforms. It includes a number of characteristics and features that facilitate a
robust installation and configuration set:
• Java-based design The Oracle Universal Installer is written in Java and looks
and feels the same on any Oracle platform.
• Dependency checking When you use OUI to install products on your
computer, it will automatically check to see which other products might
also need to be installed in order for your choice to function properly. The
Universal Installer will then determine if the required components are
already on the computer and select any it requires for installation.
• Multiple Oracle home support OUI will keep track of all the Oracle
home directories that exist on the target computer. Multiple Oracle homes
are required if you want to install the Oracle database, Application Server,
and other Oracle products and versions on the same computer. The Oracle
Universal Installer will ensure that each product that requires a separate
Oracle home will have it created and will keep track of which products and
versions are installed where.
• National language/globalization support When installing Oracle software,
the Universal Installer will check to see what the computer’s regional/
globalization settings are and configure itself to adhere to these settings. It
will also do the same for the software that is being installed to ensure that
the interactive experience that the user is expecting is delivered.
• Web-based installation When you are prompted by the Oracle Universal
Installer for the location of the software that you are installing, you can specify
a physical or network disk location, or a URL where the files can be found.
This allows you to create web pages that would be used to invoke the OUI and
ch02.indd 10
6/29/2005 9:56:01 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
11
• Unattended installation The Oracle Universal Installer can be invoked from
the command line and passed the name of a response file that has all the
parameters required for the installation to proceed, as in this example:
PART I
then point users to a server close to them that contains the package files for
the application being installed. This can make large-scale deployments easier.
runInstaller -responsefile respfile [-silent] [-nowelcome]
The -nowelcome command-line option tells the Oracle Universal Installer
not to display the welcome screen when started. The default is to display
the Oracle Universal Installer welcome screen. The -silent option tells the
Oracle Universal Installer not to tell the user what is happening during the
installation but to simply perform all of the tasks specified in the response file.
• Intelligent uninstallation Once you install the product using the Universal
Installer, it keeps a record of the installation and allows you to uninstall a
portion of the product or the product in its entirety. While performing an
uninstall the Universal Installer will prompt you if you need to uninstall
additional components, or if the uninstall will cause other products to fail,
such that they must also be removed or the specific portion of the uninstall
affecting them cancelled.
• Support for user-defined packages The Universal Installer allows you to
add your own components to the list of packages to be installed when it is
invoked. In this way you can install the Oracle server software and your own
software at the same time. Furthermore, if specific utilities need to run during
the installation process, the Universal Installer allows you to invoke them
automatically from your installation script.
Installing Oracle Database 10g
The first thing that happens is that OUI performs a number of system checks to ensure
that your computer is properly configured for Oracle and that you are logged in as a
user with the appropriate privileges to perform the installation.
The tests that are to be performed are stored in a file called oraparam.ini located
in the install directory of the first CD-ROM. It is possible to copy that file to another
location and then make changes to the system prerequisite checks or other actions if
you are familiar with editing its contents, though this is not recommended for users
new to Oracle and OUI. You can then manually invoke the installer from the command
line indicating which parameter file to use, as in the following example:
/mnt/cdrom/runInstaller -parameterFile /home/oracle/oraparam.ini
If you do not want the Oracle Universal Installer to perform any system checks,
you can invoke it with the following command line:
/mnt/cdrom/runInstaller -ignoreSysPrereqs
In both of these examples /mnt/cdrom is the path to the CD-ROM root in a Red
Hat Linux environment, and all commands and parameters are case sensitive.
ch02.indd 11
6/29/2005 9:56:02 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
EXAM TIP You should be familiar with at least the two runInstaller
parameters indicated here and what they do.
After the system checks have been performed and passed (if things were not
properly configured, OUI will raise an error and advise you of corrective action),
the OUI welcome screen is displayed. Click Next to proceed.
NOTE The Oracle Installer on Windows has a Basic Installation option, in
which it installs everything in a default location and optionally creates a starter
database. If you choose this option, you will not be prompted for the other
items discussed in the text that follows. Choosing the Advanced Installation
option will prompt you for the items described herein.
If you are installing Oracle on a Unix-based system, you will next be asked to
provide the location of the Oracle installation inventory used by the Oracle Universal
Installer to keep track of the Oracle products installed on the computer, as well as the
operating system group to be used to install Oracle products—the oinstall group
referred to earlier. The default location for the inventory is $ORACLE_BASE/
oraInventory if the ORACLE_BASE environment variable is set; otherwise, another
ch02.indd 12
6/29/2005 9:56:02 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
13
EXAM TIP You should be familiar with the workings of OUI on Unix-based
platforms and the importance of the inventory location and files.
PART I
location will be indicated. Specify the inventory path and Oracle installation group
and then click Next to continue.
For Unix/Linux-based installations you will be prompted to run a script—
orainstRoot.sh—as root from the Oracle inventory directory you specified earlier.
This script needs to be run the first time any Oracle product is installed on a server.
It will create the inventory points file called oraInst.loc, usually at the location
specified by ORACLE_BASE—e.g., /opt/oracle/oraInst.loc—with a link to a file with
the same name in the /etc directory on a Linux system. You will need to connect to
your server as root (or open a terminal window in your X Window session and su
to root) and run this script that creates additional directories and sets appropriate
ownership and permissions on files. The contents of the script will be similar to this
code listing:
#!/bin/sh
INVPTR=/etc/oraInst.loc
INVLOC=/opt/oracle/oraInst.loc
GRP=oinstall
PTRDIR="`dirname $INVPTR1";
#Create the software inventory location pointer file
if [ ! -d "$PTRDIR" ] ; then
mkdir -p $PTRDIR
fi
echo "Creating the Oracle inventory pointer file ($INVPTR";
echo inventory_loc=$INVLOC > $INVPTR
echo inst_group=$GRP >\> $INVPTR
chmod 664 $INVPTR
# Create the Oracle inventory directory if it does not exist
if [ ! -d "$INVLOC" ] ; then
echo "Creating the Oracle inventory directory ($INVLOC)";
mkdir -p $INVLOC
chmod 775 $INVLOC
fi
echo "Changing groupname of $INVLOC to oinstall.";
chgrp oinstall $INVLOC
if [ $? != 0 ] ; then
echo "WARNING: chgrp of $INVLOC to oinstall failed!";
fi
After clicking OK to acknowledge that the script has been run successfully, you are
then asked to confirm the source of the installation media and the destination Oracle
home name and path. If you preset ORACLE_HOME, the destination path will be
filled in and a suggested name for the Oracle home will be displayed. The Oracle home
name and location will be placed by OUI into a file called /etc/oratab, which lists all
the Oracle homes for all products installed by OUI as well as any manually added
entries. This allows OUI to determine which products are found on the computer.
ch02.indd 13
6/29/2005 9:56:03 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
Clicking Next takes you to the product selection screen, allowing you to choose
which edition of Oracle Database 10g to install on the computer. The default is
Enterprise Edition, which includes such enterprise-level features as Oracle Data Guard
(for the creation, management, and monitoring of standby databases for quick failover),
several features that extend the security of Oracle databases (Oracle Advanced Security,
Oracle Label Security, Enterprise User Security, Virtual Private Database, N-tier
authentication, and Fine-Grained Auditing and Access Control), and some additional
features to support enterprise data warehousing (Oracle Partitioning, Oracle OLAP,
Transportable Tablespaces, and others). You can also select Custom, allowing you
to choose components and features to install. You should always choose only the
database edition you are licensed for and install only the features that your
organization is licensed for. Make your choice and then click Next.
ch02.indd 14
6/29/2005 9:56:04 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
15
PART I
NOTE A Personal Edition of Oracle is also available. It includes all of the
features of the Enterprise Edition and is designed for software development
on a personal workstation.
EXAM TIP A good understanding of the different editions of Oracle Database
10g is required for the exam.
You will now have the option to create a starter database to use with Oracle or
to bypass this option. You can always create a database later, but creating it during
installation speeds up the process. Three preconfigured templates for a new database,
ch02.indd 15
6/29/2005 9:56:05 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
which include database files, make the creation process quick, but you also have the
option to create a custom database, which takes longer and will create the datafiles
according to settings you specify. Make your selection and then click Next.
If you decided to create a starter database, you will be prompted for the global
database name in the format database.domain and the database SID (or system
identifier) of one to eight characters starting with a letter. Defaults will be presented
for these as well as for the character set to be used for the database (for which
guidelines for making a good choice will be provided in Chapter 3). You will also
ch02.indd 16
6/29/2005 9:56:06 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
17
PART I
be asked whether or not to include sample schemas in the database. Make your
choices and then click Next.
If you installed the agent for the Oracle Enterprise Manager Grid Control on the
computer prior to installing Oracle Database 10g, you will have the option to use it
for the management of this database; if not, you can select the Database Control to
manage this database and instance. You also can specify an SMTP e-mail server and
administrator e-mail address for notifications to be sent to. Click Next to continue.
ch02.indd 17
6/29/2005 9:56:06 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
NOTE Enterprise Manager Grid Control provides enterprise-wide
management of Oracle databases and other Oracle products—see www
.oracle.com/enterprise_manager/index.html for more information. A thorough
discussion is beyond the scope of the exam and the book.
The next screen will ask you how you want to store the database files: on the local
file system using Automated Storage Management (ASM), whereby Oracle creates and
manages the database files itself, providing striping and mirroring capabilities, or by
using raw devices or partitions dedicated to Oracle—an advanced method. The easiest
choice is always the local file system, though ASM has benefits worth considering,
so a review of the Oracle Database Administrators Guide on setting up ASM may be
worthwhile. You can find this manual on one of the CDs you were shipped or
on OTN.
EXAM TIP Oracle datafiles can be stored using three methods: file system,
ASM, and raw devices. The file system option also includes Oracle Cluster File
System and third-party disk storage arrays.
ch02.indd 18
6/29/2005 9:56:07 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
19
PART I
You next have the option to enable automatic backups. Typically it is a better idea
to configure backups after you have properly added objects to your database and have
it working as needed, so click Next on this screen to continue.
ch02.indd 19
6/29/2005 9:56:08 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
On the screen displayed you will need to specify the passwords for the Oracle
users created initially. You can specify individual passwords for each user—the default
and recommended method—or a single password for each of the accounts listed.
Enter the appropriate passwords and confirm them and then click Next.
The next screen to appear is the Summary screen, which is also the screen you
would see if you did not choose to create a database but simply decided to install
Oracle. Review the actions that are going to be performed to make sure they are correct
and then click Install. You can always click the Back button and make changes if you
find incorrect entries on the Summary screen.
ch02.indd 20
6/29/2005 9:56:09 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
21
PART I
The Oracle Universal Installer starts the installation process and presents a status
bar indicating how far along the installation is. You will also be presented with
information on the location of the installation logfile at the bottom of the window
so that you can check for any errors that may have occurred.
ch02.indd 21
6/29/2005 9:56:10 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
22
When the installation is ready to configure the database, and only if you selected
a starter database, various configuration assistants will be launched individually
including the iSQL*Plus Configuration Assistant (for configuring the Oracle Containers
for Java—OC4J—instance used to connect to the Oracle database), the Oracle Net
Configuration Assistant (NETCA) to set up basic networking for the Oracle database,
and the Oracle Database Configuration Assistant (DBCA) to actually perform the
configuration of the database you selected for installation. You will be provided with
a screen to notify you which assistants are being launched and their status. At their
completion Oracle will specify if they succeeded or not, in which case you can retry
the ones that failed, and then the install is complete.
EXAM TIP Be familiar with what each configuration assistant does.
Once the Oracle Database Configuration Assistant has completed, you will be
provided with information on the URL for the Oracle Enterprise Manager web site and
have the option to unlock other user accounts in the database. Click OK to complete
the database configuration.
ch02.indd 22
6/29/2005 9:56:11 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
23
PART I
On Unix/Linux
platforms you will also
be asked to run a script
called root.sh as the
user root. This script
is located in ORACLE_
HOME directory and
populates the /etc/
oratab file with
information on the
Oracle homes and
database instances
on the computer. This
information is used
by Oracle Enterprise
Manager and other administrative components to determine where databases are
located, and whether or not they should be automatically started when the operating
system starts. In Windows this information is located in the Registry, and no script
needs to be run.
EXAM TIP Understand the importance, location, and contents of the
oratab file.
The final screen will provide a summary of all URLs for the various products
installed, including iSQL*Plus, Oracle Enterprise Manager, and Ultra Search. Make
a note of these and then click Exit to complete the installation.
ch02.indd 23
6/29/2005 9:56:11 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
24
Exercise 2-1: Installing Oracle Database 10g
In this exercise you will install Oracle Database 10g on your computer and create
the starter database. You can perform this task on either a Windows or Linux-based
computer. Remember to create the user and group accounts and verify the system
requirements prior to starting the installation. If you do not have the software, you
can download Oracle Database 10g for your platform from the Oracle Technology
Network (http://otn.oracle.com).
NOTE Unix and Linux will be used interchangeably in this book. You should
assume that when one is mentioned, both are included.
1. Log on to your computer as the oracle user (on Linux) or a user that is a
member of the Administrators group on Windows.
2. Insert the Oracle Database 10g CD-ROM in the CD-ROM drive. The install
program should start automatically. If not, execute setup.exe (Windows)
or runInstaller from the root of the CD drive to invoke it.
3. If you are on Windows, choose the Advanced Installation option and click
Next; for Linux click Next on the Welcome screen.
4. If you are installing on Linux, you will be asked to confirm the location of
the inventory directory and the install group. Verify the information presented
and click Next.
5. If you are installing on Linux and are asked to run a script as root, launch
a new terminal window and run the script and then click Continue.
6. Verify the source and destination file locations in the Specify File Locations
screen. Enter a name for the Oracle home (16 characters or less) and then
click Next.
7. When prompted for the edition of Oracle to install, choose Enterprise Edition
and then click Next.
8. The Oracle Universal Installer will perform prerequisite checks. If there are
any errors, correct them and then click Next.
9. On the Select Database Configuration screen select a General Purpose starter
database and then click Next.
10. Enter a database name and SID. Choose a database name in the format
database.domain such as orcl.haunting.com and a SID name of ORCL. Leave
the character set and other choices as is and click Next to continue.
11. When prompted whether to use the Database Control or Grid Control
to manage the database, select Database Control and click Next.
12. On the File Storage Option screen, choose File System as the storage type
and a path for the datafiles, or leave the default and click Next.
ch02.indd 24
6/29/2005 9:56:12 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
25
14. Select “Use the same password for all accounts” on the following screen and
enter and confirm a password you will easily remember, such as “oracle.”
Then click Next.
PART I
13. On the Backup and Recovery screen leave the default of no backups and
click Next.
15. Verify the installation parameters on the Summary screen and then click
Install to begin the installation of Oracle Database 10g.
16. Monitor the installation on the following screen and then review activity
as the configuration assistants are launched. This may take some time to
complete. Acknowledge the completion of the Database Configuration
Assistant by clicking OK on the dialog box presented and then review the
information on ports configured. Click Exit to end the Oracle Universal
Installer.
17. Start your web browser and navigate to http://localhost:5500/em to connect
to the Enterprise Manager web site. Enter a username of SYSTEM with the
password you specified in Step 14 and then click Login, acknowledge the
licensing screen by clicking “I Agree” to display the EM web site for your
database.
18. Close your browser. Congratulations—you have successfully installed Oracle
Database 10g on your computer.
ch02.indd 25
6/29/2005 9:56:13 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
26
Post-Installation Tasks
If you installed Oracle on Windows, the Registry will have information on the path,
environment variables, and other settings that need to be configured in order to run
and manage the Oracle database on the computer. For Unix-based systems it is
necessary to configure the oracle user’s environment to administer and manage Oracle.
One of the easiest ways to do this is to create a shell script or modify the user’s login
script with the appropriate settings.
The required settings include configuring ORACLE_HOME, ORACLE_BASE,
ORACLE_SID, PATH, and other environment variables with the appropriate values.
The following is a sample of a Linux .bash_profile login script used for the BASH shell
with the appropriate settings to be used to manage the ORCL database created in the
previous exercise. You can use it is as template to modify your own file.
# Oracle Settings
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR
ORACLE_BASE=/opt/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/10.1.0/orcl; export ORACLE_HOME
ORACLE_SID=ORCL; export ORACLE_SID
PATH=$ORACLE_HOME/bin:/usr/sbin:$PATH; export PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export
CLASSPATH
LD_ASSUME_KERNEL=2.4.1; export LD_ASSUME_KERNEL
ulimit -u 16384 -n 65536
Chapter Review
Oracle Database 10g can be installed on many platforms, including Windows, Linux,
and several varieties of Unix, as well as others. The Oracle Universal Installer is used
to perform the installation and provides a similar interface on all Oracle platforms.
Before installing Oracle, you will need to ensure your target computer and operating
system satisfy the prerequisites, as well as perform some preconfiguration tasks.
Optimal Flexible Architecture is a set of standard directory and file naming
conventions, as well as directory structures to make management of Oracle databases
easier. Though using an OFA-compliant directory and file naming method is not
enforced, it is strongly recommended to make your life easier.
Oracle Database 10g software is available in several editions, with Enterprise Edition
providing all of the features and functions, while Standard Edition lacks some of the
more advanced features such as Oracle OLAP and high-availability architecture.
Even though you have purchased the Enterprise Edition, you may not be licensed to
use the additional-cost features, such as Oracle Advanced Security, Oracle Partitioning,
or Oracle Data Mining.
Questions
1. You are asked to describe the benefits of the Oracle Universal Installer to your
manager. Which of the following are key features of OUI? (Choose all correct
answers.)
ch02.indd 26
6/29/2005 9:56:14 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
27
A. OUI performs identically on all platforms on which Oracle runs.
C. OUI is written using a .NET-based language ideal for Windows platforms.
D. OUI is a text-based application not requiring a graphical display.
PART I
B. Web-based deployments can be performed using OUI.
E. Unattended installations can be performed using OUI.
2. The oratab file contains the following information. (Choose two correct
answers.)
A. A list of all Oracle products installed on the computer
B. A list of all database instances and Oracle homes installed on the
computer
C. Version-specific information about each Oracle product and database
on the computer
D. Startup information for database instances on the computer
E. Information to help Enterprise Manager manage Oracle databases on the
computer
3. When installing Oracle on Unix-based systems, which of the following must
you create before starting the installation? (Choose three correct answers.)
A. The root user account
B. The oracle user account
C. The oracle group account
D. The oinstall user account
E. The oinstall group account
F. The dba group account
4. Installing Oracle on a Windows computer requires that you be logged in as
whom? (Choose the best answer.)
A. The oracle user
B. A user that is a member of the Domain Admins group
C. A user that is a member of the oinstall group
D. A user that is a member of the local Administrators group
E. Any user with login privileges on the computer
5. Which of the following environment variables must be set on Unix-based
computers before starting to install Oracle software? (Choose all correct
answers.)
A. ORACLE_HOME
B. ORACLE_BASE
C. ORACLE_SID
D. LD_LIBRARY_PATH
ch02.indd 27
6/29/2005 9:56:15 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
28
E. All of the above
F. None of the above
6. When deciding between Enterprise Edition and Standard Edition of Oracle
software, which of the following needed features would require that you
purchase and install Enterprise Edition? (Choose two correct answers.)
A. Real Application Clusters
B. N-tier authentication
C. Support of multiple CPUs on the server platform
D. Oracle Enterprise Manager Database Control
E. The ability to partition data in the database
7. Which of the following paths are consistent with Optimal Flexible
Architecture? (Choose all correct answers.)
A. /opt/oracle/ocsdb
B. /opt/oracle/product/10.1.0/ocsdb
C. /opt/oracle/admin/ocsdb/bdump
D. /oracle/mydb
E. /opt/oracle/admin/bdump
8. You are deciding on whether or not to implement Optimal Flexible
Architecture for your Oracle installation. What are some of the considerations
in favor of using OFA? (Choose all correct answers.)
A. It provides a standardized directory structure, making files easier to find.
B. It provides a standardized naming convention for Oracle executable files.
C. It automatically spreads Oracle files across multiple disks when creating a
new database using a standard directory structure.
D. It makes all Oracle installations appear similar, reducing learning curves
for database administration of many servers.
E. It is required by Oracle.
9. You are installing Oracle Database 10g on a computer with the Red Hat
Enterprise Linux ES 4 operating system. You are certain that the Oracle
Universal Installer system check will fail on this operating system, but you
want to install Oracle anyway. How would you invoke the OUI and force it
not to perform system checks? (Choose the best answer.)
A. setup -ignorePreReqs
B. setup -ignorePrereqs
C. runInstaller -ignoreSysPrereqs
D. runInstaller -ignoreSysprereqs
E. runInstaller -bypassPrereqs
F. setup -bypassPrereqs
ch02.indd 28
6/29/2005 9:56:15 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 2: Installing Oracle Database 10g
29
A. oraparam.ini
PART I
10. If you wanted to modify the file used by the Oracle Universal Installer with
system prerequisite information, which file would you modify? (Choose the
best answer.)
B. oraparam.ora
C. oraparam.ins
D. sysprereqs.ini
E. sysprereqs.ora
F. sysprereqs.ins
Answers
1. A, B, and E. Oracle Universal Installer is a graphical Java-based (not .NETbased) application that runs identically on all Oracle platforms. It allows the
source location to be a URL, thereby allowing for web-based deployments,
and it can be run unattended for silent installations.
2. B and D. The oratab file on a Unix-based system includes a list of database
instances installed on the computer and an indicator whether or not the
instance should be automatically started when the computer is booted. It does
not contain a list of installed Oracle products (that’s in the installer inventory
location), any version-specific Oracle information, or Enterprise Manager
configuration details.
3. B, E, and F. Installing Oracle on a Linux-based computer requires that you
create the oracle user, and the oinstall (to own the Oracle installation
information) and dba (for database administration) groups prior to starting
the installation. The root user is created when you install the operating
system, though that user is required to complete parts of the installation.
4. D. Installing Oracle on a Windows computer requires that you be logged in as
a member of the local Administrators group. If you are logged in as a member
of the Domain Admins group, you will also be able to install Oracle but will
also have more privileges than needed, which may compromise security. The
oinstall group and the oracle user are needed in Unix-based environments.
5. F. None of the environment variables must be set for Oracle to be installed
on a Unix-based computer. However, in order to manage and administer
the database, the ORACLE_HOME, ORACLE_SID and LD_LIBRARY_PATH
variables may need to be set.
6. B and E. If you want to use N-tier authentication and partition table data
in your database, you must install and purchase Enterprise Edition. All of
the other features (RAC, multiple CPU support, and the Enterprise Manager
Database Control) are available in Standard Edition.
7. B and C. While Oracle does not require you to use OFA, when you decide to
use OFA the path and file naming conventions do set rules for usage. Only
ch02.indd 29
6/29/2005 9:56:16 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
30
“/opt/oracle/product/10.1.0/ocsdb” for an ORACLE_HOME path and “/opt/
oracle/admin/ocsdb/bdump” for a background dump and log destination
adhere to the naming conventions specified by OFA.
8. A and D. OFA is targeted at making administration of Oracle databases easier
by making Oracle files easier to find on any platform and file system. In order
to do this, it provides a standardized directory structure for Oracle installations
that makes all Oracle installations similar, reducing learning curves for
administrators. It is not required by Oracle, but highly recommended. OFA
does not automatically spread files across multiple drives, nor does it provide
a naming convention for Oracle executable files, but only Oracle data, redo,
control, and other files attached to a database instance.
9. C. The runInstaller -ignoreSysPrereqs command will invoke OUI
on a Linux computer, telling it not to check system prerequisites before
performing the installation. OUI parameters are case-sensitive, making answer
D incorrect, while “setup” is the command to invoke OUI on a Windows
platform.
10. A. The oraparam.ini file contains the system prerequisite information used by
OUI to verify the operating system and other requirements for installation.
ch02.indd 30
6/29/2005 9:56:16 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
CHAPTER 3
Creating an Oracle Database
In this chapter you will learn how to
• Create an Oracle database
• Explain the Oracle database architecture
• Explain the instance architecture
• Use the management framework
• Use DBCA to create a database
• Use DBCA to configure a database
• Use DBCA to drop a database
• Use DBCA to manage templates
1
ch03.indd 1
5/18/2005 11:10:41 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
2
This chapter goes through the theory and practice of creating a database: a review of
the Oracle server architecture, followed by the mechanics of database creation with a
look at the relevant tools, both GUI and command line, and the management options.
But one immediate objective is to demystify the process. Creating a database is not a
big deal. You can create twenty databases during a tea break (and you may well have
to do this if you are, for example, supporting an IT teaching institution) once you
understand what is required and have prepared appropriate scripts. Furthermore, do
not worry about getting it right. Hardly anything is fixed at database creation time. It
certainly makes sense to think about how your database will be structured, its purpose
and environment, at creation time, but (with one exception) everything can be changed
afterward. As a general rule, keep things as simple as possible at this stage. Get the
thing created and working first, worry about configuring it for use later.
Architecture of the Oracle Server
An Oracle server consists of two entities: the instance and the database (as shown in
Figure 3-1). They are separate, but connected. During the creation process, the instance
is created first, and then the database. In a typical single instance environment the
relationship of instance to database is one-to-one, a single instance connected to a
single database, but always bear in mind that the relationship may be many-to-one:
multiple instances on different computers opening a common database on a shared
disk system. This is known as Real Application Clusters, or RAC. RAC gives amazing
capabilities for performance, fault tolerance, and scalability (and possibly cost savings)
and is integral to the Oracle’s concept of the grid. With previous releases RAC (or its
precursor, Oracle Parallel Server) was an expensive add-on, but with Database release 10g
Standard Edition, RAC is bundled. This is an indication of how much Oracle Corporation
Figure 3-1
The instance and
the database:
memory structures,
processes, and files
ch03.indd 2
5/18/2005 11:10:54 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
3
PART I
wants to push users toward the RAC environment. Standard Edition RAC is limited to
computers with no more than two CPUs, and a maximum of four computers in the
cluster, but even that gives access to a phenomenally powerful environment. RAC is
an extra cost option for the Enterprise Edition, where the scalability becomes effectively
limitless: bounded only by the capacities of the underlying operating system and
hardware. It is also possible for one instance, through database links, to connect to
multiple databases. For the most part, you will be dealing with the most common
environment in this book: one instance on one computer, opening a database stored
on local disks.
The instance consists of memory structures and processes. Its existence is transient,
in your RAM and on your CPU(s). The database consists of physical files, on disk.
Thus the lifetime of the instance is only as long as it exists in memory—it can be
started and stopped. By contrast, the database, once created, persists indefinitely—
until you deliberately delete the files that compose it. Within the physical structures
of the database, which our system administrators see, are the logical structures that
our end users (developers, business analysts, data warehouse architects, etc.) see. The
Oracle architecture guarantees abstraction of the logical from the physical: there is
no way that a programmer can determine where, physically, a bit of data is located.
He/she addresses only logical structures, such as tables. Similarly, it is impossible for
a system administrator to know what bits of data are in any physical structure: all he
can see is the operating system files, not what is within them. Only you, the database
administrator, is permitted (and required) to see both sides of the story. The data
dictionary, which contains metadata describing the whole server, manages the
relationship between physical and logical structures. Creating the data dictionary is
an integral part of database creation. The final stages of the creation process make the
newly created database usable, by generating various views and PL/SQL packages, and
manageable, by generating the Enterprise Manager Database Control facility.
The Instance: Memory Structures and Processes
An Oracle instance consists of a block of shared memory known as the System Global
Area, or SGA, and a number of processes. At a minimum, the SGA will contain three
data structures: the shared pool, the database buffer cache, and the log buffer. It may,
optionally, also contain a large pool, a Java pool, and a streams pool. Some of these
SGA structures are fixed in size when you start the instance; others can be changed
dynamically. But none are fixed at database creation time: you can stop the instance
and restart it whenever you please, with a totally different memory configuration. You
should remember, though, that if you are continually making memory configuration
changes on a live system and those changes are of a type that requires the instance to
be shut down, incurring downtime, your end users will not be happy with you.
EXAM TIP Remember the three required elements of the SGA: the shared
pool, the database buffer cache, and the log buffer.
ch03.indd 3
5/18/2005 11:10:55 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
4
The shared pool is further subdivided into a number of other structures. This
book will only briefly mention two of the shared pool components: the library
cache and the data dictionary cache. The library cache is a memory area for storing
recently executed code, in its parsed form. Parsing is the conversion of code written
by programmers into something executable, and it is a slow process that Oracle does
on demand. By caching parsed code in the shared pool so that it can be reused without
reparsing, performance can be greatly improved. The data dictionary cache stores
recently used object definitions: descriptions of tables, indexes, users, and other
metadata definitions. Keeping such definitions in memory, rather than having to
read them repeatedly from the data dictionary on disk, enhances performance.
The database buffer cache is Oracle’s work area for executing SQL. Users don’t ever
update data on disk. They copy data into the database buffer cache and update it there,
in memory. Ideally, all the data that is frequently accessed will be in the database buffer
cache, therefore minimizing the need for disk I/O.
The log buffer is a very small memory structure used as a short-term staging area
for all changes that are applied to data in the database buffer cache. Chapter 9 will
describe in detail how the log buffer and the database buffer cache are used when SQL
statements retrieve and manipulate data.
The large pool is an optional area that, if created, will be used automatically by
various processes that would otherwise take memory from the shared pool. You will
be introduced to one of its main uses in Chapter 13 in the discussion on shared (or
multithreaded) servers. The Recovery Manager, RMAN, covered in later chapters, will
also use the large pool for its disk and tape I/O slave processes.
The Java pool is required only if your application is going to run Java stored
procedures within the database: it is used for the heap space needed to instantiate
the Java objects. However, a number of Oracle options are written in Java, so the
Java pool is considered standard nowadays.
The streams pool is used by Oracle streams, an advanced tool that is beyond the
scope of the exam or this book.
TIP The sizing of SGA memory structures is critical for performance. In
general, they should be large enough, but not too large. In addition to wasted
memory, performance can degrade if too much memory is assigned to the
SGA components.
Along with its SGA, the instance will also have, at a minimum, five processes: the
system monitor, SMON; the process monitor, PMON; the database writer, DBWn (you
may have up to ten of these); the log writer, LGWR; and the checkpoint process, CKPT.
These are known as “background” processes, because they always exist while the instance
is running, whether or not any sessions are actually logged onto the instance, or indeed
even if a database has not yet been created or opened.
SMON’s major function is opening the database: enabling the connection between
the instance and a database. Chapter 5 will detail how it does this. During normal
running, it carries out a number of monitoring and tidying-up operations.
ch03.indd 4
5/18/2005 11:10:55 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
5
PART I
PMON looks after user sessions, taking appropriate action if a session gets into
trouble. For instance, if a user’s PC reboots while the user is logged on to the database,
PMON will detect this and tidy up whatever work the user had in progress.
The DBWn process or processes (by default, an instance will have one database
writer per eight CPUs) is responsible for all writing to datafiles. Remember, no sessions
ever update data on disk; they update only data in the database buffer cache: all updates
are then funneled through the DBWn to disk. In general, DBWn writes as little and as
rarely as possible. The assumption is that disk I/O is bad for performance, so Oracle
keeps it to a minimum.
The LGWR propagates all changes applied to data in the database buffer cache to
the online redo log files on disk. In contrast with DBWn, this disk write activity is
done as near as possible in real time—and when you issue the COMMIT statement,
it really is done in real time: it immediately flushes the changes from their small and
temporary staging area, the log buffer in the SGA, to the online redo log files on disk.
This is to ensure that all users’ work is saved so that, in the event of damage to the
database’s datafiles, the changes can be applied to a restored backup. In this manner
(as is covered in later chapters), Oracle can guarantee that data will never be lost.
The CKPT process is responsible for ensuring that, from time to time, the instance
is synchronized with the database. In principle, the database is always out of date: there
will be changes that have been applied in memory that have not yet been written to
the datafiles by DBWn (though the changes themselves will have been streamed out
to the online redo log files by LGWR as they happen). There are occasions when it
is necessary to force a write of all changed data from the database buffer cache to
the datafiles, to bring the database right up-to-date. The CKPT process controls the
frequency of this.
EXAM TIP Remember the five required background processes: system monitor,
process monitor, database writer, log writer, and checkpoint process.
There are also a number of optional background processes (far more with 10g than
with previous releases), some of which you will see in later chapters. Some of the
background processes can be tuned. For example, you can decide how many database
writer processes to launch, and you can (to a certain extent) control how frequently
they will write changed data bocks from the database buffer cache to the datafiles. You
do not need to consider this at database creation time: you can sort such things out
later, always bearing in mind that some changes will require downtime.
The Database: Physical Structures
Three file types make up an Oracle database, along with a few others that exist
externally to the database and, strictly speaking, are optional. The required files are
the controlfiles, the online redo log files, and the datafiles. The external files are the
initialization parameter file, the password file, and archived redo log files.
ch03.indd 5
5/18/2005 11:10:55 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
6
Every database has one controlfile, but a good DBA will always create multiple copies
of the controlfile so that if one copy is damaged, the database itself will survive. If all
copies of the controlfile are lost, it is possible (though perhaps awkward) to recover,
but you should never find yourself in that situation. You don’t have to worry about
keeping multiplexed copies of the controlfile synchronized—Oracle will take care of
that. The controlfile is small, but vital. It contains pointers to the rest of the database:
the locations of the online redo log files and of the datafiles. It also stores information
required to maintain database integrity: various critical sequence numbers and
timestamps, for example. If you use the Recovery Manager, RMAN, then some backup
information will also be stored in the controlfile. The controlfile will usually be no
more than a few megabytes big, but you can’t survive without it. Its maintenance is
automatic; your only control is how many copies to have, and where to put them. If
you get the number of copies, or their location, wrong at creation time, you can add
or remove copies later, or move them around—but you should bear in mind that any
such operations will require downtime.
Every database has at least two online redo log files, but as with the controlfile, a
good DBA creates multiple copies of each online redo log file. The online redo logs
store a continuous chain in chronological order of every change applied to the database.
This will be the bare minimum of information required to reconstruct, or redo, changes.
The redo log consists of groups of redo log files, each file being known as a member.
Oracle requires at least two groups of at least one member each to function. You may
create more than two groups for performance reasons, and more than one member
per group for safety. The requirement for a minimum of two groups is in order that
one group can accept the current changes while the other group is being backed up
(or “archived,” to use the correct term). One of the groups is the “current” group:
changes are written to the current logfile group by LGWR. As user sessions update
data in the database buffer cache, they also write out the minimal changes to the redo
log buffer. LGWR continually flushes this buffer to the current online log group. Redo
log files are fixed size; therefore, eventually the file members making up the current
group will fill. LGWR will then perform what is called a log switch. It makes the second
group current, and starts writing to that. If your database is configured appropriately,
you will then archive (back up) the logfile members making up the first group. When
the second group fills, LGWR will switch back to the first group, making it current,
and overwriting it. Thus, the online redo log groups (and therefore the members
making them up) are used in a circular fashion.
As with the controlfile, if you have multiple members per group (and you should!)
you don’t have to worry about keeping them synchronized. LGWR will ensure that it
writes to all of them, in parallel, thus keeping them identical. If you lose one member
of a group, as long as you have a surviving member, the database will continue to
function.
The size and number of your online redo log file groups is a matter of tuning.
In general, you will choose a size appropriate to the amount of activity you anticipate.
A very busy database will require larger members than a largely static database. The
number of members per group will depend on what level of fault tolerance is deemed
appropriate. However, you don’t have to worry about this at database creation time.
ch03.indd 6
5/18/2005 11:10:55 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
7
PART I
You can move your online redo log files around, add or drop them, and create ones
of different sizes as you please at any time later on. Such operations are performed
“online” and don’t require downtime; therefore, they are transparent to the end users.
The third file type making up a database is the datafile. At a minimum, you must
have two datafiles, to be created at database creation time. With previous releases of
Oracle, you could create a database with only one datafile—10g requires two. You will,
however, have many more than that when your database goes live, and you will usually
create a few more to begin with.
Datafiles are the repository for data. Their sizes and number are effectively unlimited.
A small database, of only a few gigabytes, might have just half a dozen datafiles of only
a few hundred megabytes each. A larger database could have thousands of datafiles,
whose size is limited only by the capabilities of the host operating system and hardware.
The datafiles are the physical structures visible to the system administrators.
Logically, they are the repository for the segments containing user data that the
programmers see, and also for the segments that make up the data dictionary. Datafiles
can be renamed, resized, moved, added, or dropped at any time in the lifetime of the
database, but remember that some operations on some datafiles may require downtime.
Logical Structures: Tablespaces and Segments
The physical structures that make up a database are visible as operating system files
to your system administrators. Your users see logical structures such as tables. Oracle
uses the term “segment” to describe any structure that contains data. Your typical
segment is a table, containing rows of data, but there are more than a dozen possible
segment types in an Oracle database. Of particular interest (for exam purposes) are
table segments, index segments, and undo segments, all of which are investigated
in detail in later chapters. For now, you don’t need to know more than that tables
contain rows of information; that indexes are a mechanism for giving fast access
to any particular row; and that undo segments are data structures used for storing
information that might be needed to reverse, or roll back, any transactions that you
do not wish to make permanent.
System administrators see physical datafiles; programmers see logical segments.
Oracle abstracts the logical storage from the physical storage by means of the tablespace.
A tablespace is logically a collection of one or more segments, and physically a collection
of one or more datafiles. Put in terms of relational analysis, there is a many-to-many
relationship between segments and datafiles: one table may be cut across many
datafiles; one datafile may contain bits of many tables. By inserting the tablespace
entity between the segments and the files, Oracle resolves this many-to-many
relationship.
A number of segments must be created at database creation time: these are the
segments that make up the data dictionary. These segments are stored in two tablespaces,
called SYSTEM and SYSAUX. The SYSAUX tablespace is new with 10g: in previous
releases, the whole of the data dictionary went into SYSTEM. The database creation
process must create at least these two tablespaces, with at least one datafile each, to
store the data dictionary.
ch03.indd 7
5/18/2005 11:10:56 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
8
EXAM TIP The SYSAUX tablespace must be created at database creation
time in Oracle 10g. If you do not specify it, one will be created by default.
The Data Dictionary
The data dictionary is metadata: data about data. It describes the database, both
physically and logically, and its contents. User definitions, security information,
integrity constraints, and (with release 10g) performance monitoring information
are all part of the data dictionary. It is stored as a set of segments in the SYSTEM
and SYSAUX tablespaces.
In many ways, the segments that make up the data dictionary are segments like
any other: just tables and indexes. The critical difference is that the data dictionary
tables are generated at database creation time, and you are not allowed to access
them directly. There is nothing to stop an inquisitive DBA from investigating the data
dictionary directly, but if you do any updates to it, you may cause irreparable damage
to your database, and certainly Oracle Corporation will not support you. Creating a
data dictionary is part of the database creation process. It is maintained subsequently
by data definition language commands. When you issue the CREATE TABLE command,
you are in fact inserting rows into data dictionary tables, as you are with commands
such as CREATE USER or GRANT.
To query the dictionary, Oracle provides a set of views. The views come in three
forms, prefixed DBA_, ALL_, or USER_. Most of the views come in all three forms.
Any view prefixed USER_ will be populated with rows describing objects owned by the
user querying the view, so no two people will see the same contents. If user SCOTT
queries USER_TABLES, he will see information about his tables; if you query USER_
TABLES, you will see information about your tables. Any view prefixed ALL_ will be
populated with rows describing objects to which you have access. Thus ALL_TABLES
will contain rows describing your own tables, plus rows describing tables belonging
to anyone else that you have been given permission to see. Any view prefixed DBA_
will have rows for every object in the database, so DBA_TABLES will have one row for
every table in the database, no matter who created it. These views are created as part
of the database creation process, along with a large number of PL/SQL packages that
are provided by Oracle to assist database administrators in managing the database
and programmers in developing applications. PL/SQL code is also stored in the data
dictionary.
EXAM TIP Which view will show you all the tables in the database? Remember
that the answer is DBA_TABLES, not ALL_TABLES.
ch03.indd 8
5/18/2005 11:10:56 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
9
Management Tools
PART I
Oracle database 10g provides two management environments: Enterprise Manager
Database Control and Enterprise Manager Grid Control. Both are optional, but Oracle
strongly advises you to use one or the other. Grid control is more complicated, and
more capable. To use Grid Control, you must have already installed it somewhere on
your network and installed the Grid Control Management agent on the computer
where you are creating the database. You are going to create Database Control in this
exercise, which is implemented as a set of tables and procedures within the database,
generated at database creation time. Throughout this book, and for the purposes of
the exam, Database Control is the tool to be used. Grid Control is undoubtedly more
powerful, but it is not necessary in a straightforward environment; it also has licensing
implications.
There are also numerous third-party products you can buy (and a few that you can
download free of charge) to assist you in managing the Oracle environment. By all
means investigate these, but Enterprise Manager in one of its two forms is Oracle’s
approved tool.
External Files
The remaining topic to cover before creating a database is the three file types that exist
externally to the database: the parameter file, the password file, and the archive log files.
The parameter file defines the instance. You already know that an instance consists
of memory structures and processes. The instance parameters specified in the parameter
file control, among other things, how big the various memory structures should be,
and how the background processes will behave. They also set certain limits, such as
how many user sessions are permitted to log on to the instance concurrently. There
are defaults for all parameters except one: DB_NAME, the name of the database to
which the instance will connect. With this exception it is possible to start an instance
relying totally on defaults, but such an instance will be useless for any practical
purpose. Many parameters are dynamic, meaning that their values can be changed
while the instance is running and the database is open, but some are fixed at instance
startup. With one exception, all parameters can be changed subsequent to database
creation by closing the database, shutting down the instance, editing the parameter
file, and starting up again. The one exception is DB_BLOCK_SIZE, more on which
later. You must create a parameter file and use it to build an instance in memory
before creating a database.
TIP Parameters are divided into “basic” and “advanced.” You will usually need
to set the two dozen or so basic parameters, but the advanced ones (of which
there are over two hundred) can often be left at default.
ch03.indd 9
5/18/2005 11:10:57 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
10
There are two types of parameter files: the old-fashioned static parameter file
(usually called init/SID/.ora, where /SID/ is the name of the instance) and the dynamic
parameter file introduced with release 9i (called spfileSID.ora). A static parameter file
is a simple text file that you create and edit with any ASCII editor you please, typically
Notepad on Windows, or vi on Unix. It is read only once by the instance, at startup
time. The dynamic parameter file is a binary file that is maintained and edited by
Oracle itself, in response to commands you issue.
The password file causes much confusion in the Oracle world, particularly among
computer auditors who do not understand its purpose. The problem it addresses is
how to authenticate a user when the database is not open, or indeed before the database
has even been created or an instance started. Users are nothing more than rows in a
table in the data dictionary. You can see them and their encrypted passwords by querying
the data dictionary view DBA_USERS. When you create a user, as you will in Chapter 7,
you are simply inserting rows into the data dictionary. Now, it is a simple fact in the
Oracle environment that if you have the privileges that let you start an instance and
subsequently open or create a database, you can do absolutely anything within that
database. It is therefore vitally important that Oracle should authenticate you, before
letting you connect as such a user. But if the database is not already created and open,
how can Oracle query the data dictionary to validate your username and password,
and thus work out who you are and what you are allowed to do? To resolve this
paradox, Oracle has provided two means of authentication that are not data dictionary
based and therefore do not require the database to be open, or even to exist. These are
operating system authentication and password file authentication.
For operating system authentication, Oracle delegates responsibility for identifying
a user to the host operating system. At installation time (not database creation time!)
you specified an operating system group name that would own the Oracle software,
defaulting to dba on Unix, ORA_DBA on Windows. If you are logged on to the
computer hosting the Oracle installation as a member of that group, then you will be
allowed to connect (using appropriate syntax) to an instance, start it up, and open or
create a database without any username/password prompt. Clearly, this relies totally
on your operating system being secure, which it should be: that is out of Oracle’s control
and relies on decent system administration. But this mechanism can’t work if you are
connecting to the instance remotely, across a network: you will never actually log on
to the operating system of the machine hosting the Oracle server, only to the machine
where you are working. This is where the password file comes in: it is an operating
system file, with usernames and passwords encrypted within it, that exists independently
of the database. Using appropriate syntax, you can connect to an instance, respond to
a prompt with a username/password combination that exists in the password file, start
the instance, and open an existing database or create a new one. If you do not need to
start the instance and open the database across a network but you can always log on
to the computer hosting the Oracle installation, then a password file is not strictly
necessary because you can use operating system authentication instead. However, for
practical purposes, you will always have one.
ch03.indd 10
5/18/2005 11:10:57 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
11
PART I
Archive log files will be dealt with in detail in later chapters. They are copies of
filled online redo log files: as the online logs are filled with changes, they should be
copied to one or more destinations as archived logs, thus giving you a complete history
of all changes applied to the database. While it is not an Oracle requirement to archive
your online redo logs, in virtually all live installations it will certainly be a business
requirement, as it is the archive logs that guarantee the impossibility of losing data.
Creating a Database
To create a database, there are a number of steps that must be followed in the correct
order:
1. Create a parameter file and a password file.
2. Use the parameter file to build an instance in memory.
3. Issue the CREATE DATABASE command. This will generate, at a minimum,
a controlfile; two online redo log files; two datafiles for the SYSTEM and
SYSAUX tablespaces, and a data dictionary.
4. Run SQL scripts to generate the data dictionary views and the supplied PL/SQL
packages.
5. Run SQL scripts to generate Enterprise Manager Database Control, along with
any options (such as Java) that the database will require.
On Windows systems, there is an additional step because Oracle runs as a Windows
service. Oracle provides a utility, ORADIM.EXE, to assist you in creating this service.
EXAM TIP You can create a database with two words, CREATE DATABASE.
There are defaults for everything.
These steps can be executed interactively from the SQL*Plus prompt or through
a GUI tool, the Database Configuration Assistant (DBCA). Alternatively, you can
automate the process by using scripts or a DBCA response file. Whatever platform you
are running on, the easiest way to create a database is through the DBCA. You may
well have run this as part of the installation. It will give you prompts that walk you
through the whole process. It first creates a parameter file and a password file, and
then it generates scripts that will start the instance, create the database, and generate
the data dictionary, the data dictionary views, and Enterprise Manager Database Control.
Alternatively, you can create the parameter file and the password file by hand and
then do the rest from a SQL*Plus session. Many DBAs combine the two techniques:
they use DBCA to generate the files and scripts and then look at them and perhaps
edit them before running them from SQL*Plus.
ch03.indd 11
5/18/2005 11:10:57 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
12
DBCA is written in Java; it is therefore the same on all platforms. The only variation
is that on Microsoft Windows you must be sitting in front of the machine where you
are running it, because that is where the DBCA windows will open. On Unix, you run
DBCA on the machine where you wish to create the database, but you can launch and
control it from any machine that has an X server to display the DBCA windows. This
is standard for the X Window System: you set an environment variable DISPLAY to
tell the program where to send the windows it opens. For example,
export DISPLAY=10.10.10.65:0.0
will redirect all X windows to the machine identified by IP address 10.10.10.65, no
matter which machine you are actually running DBCA on.
Exercise 3-1: Creating a Database with Database
Configuration Assistant
In this exercise, you will first use DBCA to create a database and then inspect and
interpret the scripts that it generates.
1. Log on to your computer as a member of the group that owns the Oracle
software. By default, this will be the group dba on Unix, ORA_DBA on Windows.
2. Confirm that your ORACLE_HOME is set to point to the directory where your
software is installed. On Unix, run
echo $ORACLE_HOME
On Windows, it will be the registry variable that was set at installation time.
3. Confirm that your search path includes the directory bin within your Oracle
home. On Unix, display your search path with
echo $PATH
On Windows,
echo %PATH%
One additional required variable for Unix is DISPLAY. This must point to the
terminal on which you are working. Show it with
echo $DISPLAY.
If you are working on the machine where you want to create the database,
a suitable setting might be
export DISPLAY=127.0.0.1:0.0
4. Launch DBCA. On Unix it is called dbca; on Windows it is dbca.bat. It is located
in your ORACLE_HOME/bin directory, which must be in your search path.
ch03.indd 12
5/18/2005 11:10:57 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
13
PART I
5. Respond to the prompts as follows:
a. At the prompt “Select the operation you wish to perform,” type Create
a database and click Next.
b. At the prompt “Select a template,” type Custom database and click Next.
c. Type ocp10g for both the Global database name and the SID, and then
click Next.
d. Select the checkboxes for “Configure the database with enterprise manager”
and “Use database control for database management,” but not the
checkbox for “Use grid control for database management,” and click Next.
e. Do not select the checkboxes for “Enable email notification” or “Enable
daily backup.” Click Next.
f. Select the checkbox for “Use the same password for all accounts” and enter
the password as ORACLE. Enter it again to confirm, and click Next.
g. Select “file system” as the storage mechanism, and click Next.
h. Select “Use file locations from template” as the location for the database
files, and click Next.
i. Select the checkbox for “Specify flash recovery area” but not the checkbox
for “Enable archiving,” and click Next.
j. De-select the checkboxes for “Oracle text,” “Oracle OLAP,” and “Oracle
spatial.” Select the check box for “Enterprise Manager Repository.” In
“Standard Database Components,” de-select everything. Click Next.
ch03.indd 13
5/18/2005 11:10:58 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
14
k. Leave the Memory, Sizing, Character Sets, and Connection Mode on defaults,
and click Next.
l. Leave the Database Storage on defaults, and click Next.
m. Select the check boxes for “Create database” and “Generate database
creation scripts,” de-select the checkbox for “Save as a database template.”
Click Next.
The final screen shows the details of the instance and the database that will be
created. Depending on the speed of your computer, creation as suggested in this
exercise (excluding all options) may take from fifteen to forty minutes.
The Database Creation Scripts
While the database is creating, take a look at database creation scripts that DBCA
generated. DBCA will tell you where they are—typically, in the admin//
scripts directory (where is the name of the database you are creating)
beneath the directory where you installed Oracle. The init.ora file should look
something like this:
############################################################################
# Copyright (c) 1991, 2001, 2002 by Oracle Corporation
############################################################################
###########################################
# Cache and I/O
###########################################
ch03.indd 14
5/18/2005 11:10:58 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
15
ch03.indd 15
PART I
db_block_size=8192
db_cache_size=25165824
db_file_multiblock_read_count=16
###########################################
# Cursors and Library Cache
###########################################
open_cursors=300
###########################################
# Database Identification
###########################################
db_domain=""
db_name=ocp10g
###########################################
# Diagnostics and Statistics
###########################################
background_dump_dest=C:\oracle\admin\ocp10g\bdump
core_dump_dest=C:\oracle\admin\ocp10g\cdump
user_dump_dest=C:\oracle\admin\ocp10g\udump
###########################################
# File Configuration
###########################################
control_files=("C:\oracle\oradata\ocp10g\control01.ctl",
"C:\oracle\oradata\ocp10g\control02.ctl",
"C:\oracle\oradata\ocp10g\control03.ctl")
db_recovery_file_dest=C:\oracle\flash_recovery_area
db_recovery_file_dest_size=2147483648
###########################################
# Job Queues
###########################################
job_queue_processes=10
###########################################
# Miscellaneous
###########################################
compatible=10.1.0.2.0
###########################################
# Pools
###########################################
java_pool_size=0
large_pool_size=8388608
shared_pool_size=83886080
###########################################
# Processes and Sessions
###########################################
processes=150
###########################################
# Security and Auditing
###########################################
remote_login_passwordfile=EXCLUSIVE
###########################################
# Sort, Hash Joins, Bitmap Indexes
###########################################
pga_aggregate_target=25165824
sort_area_size=65536
###########################################
# System Managed Undo and Rollback Segments
###########################################
undo_management=AUTO
undo_tablespace=UNDOTBS1
5/18/2005 11:10:58 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
16
Note that this is a static parameter file. Later in the process, it can be converted
to a dynamic parameter file. These are the parameters that will be used to build the
instance in memory. Two to emphasize at this point are DB_BLOCK_SIZE and
CONTROL_FILES. DB_BLOCK_SIZE determines the size of the buffers in the database
buffer cache. When the instance is instructed to create a database, this size will also be
used to format the datafiles that make up the SYSTEM and SYSAUX tablespaces. It can
never be changed after database creation. CONTROL_FILES is the pointer that allows
the instance to find the database controlfile, including all the multiplexed copies. At
this stage in our exercise, the controlfile does not exist: this parameter will tell the
instance where to create it. Some of the other parameters are self-explanatory, but
eventually you must refer to the Oracle Documentation Library (the volume you need
is titled “Reference”) and read up on all of them. All!
EXAM TIP You can never change your database block size parameter after
creation. All other parameters can be adjusted later.
The next file to inspect is ocp10g.bat (it will be a shell script on Unix):
mkdir C:\oracle\admin\ocp10g\bdump
mkdir C:\oracle\admin\ocp10g\cdump
mkdir C:\oracle\admin\ocp10g\create
mkdir C:\oracle\admin\ocp10g\pfile
mkdir C:\oracle\admin\ocp10g\udump
mkdir C:\oracle\flash_recovery_area
mkdir C:\oracle\oradata\ocp10g
mkdir C:\oracle\product\10.1.0\Db_1\database
set ORACLE_SID=ocp10g
C:\oracle\product\10.1.0\Db_1\bin\oradim.exe -new -sid OCP10G
-startmode manual -spfile
C:\oracle\product\10.1.0\Db_1\bin\oradim.exe -edit -sid OCP10G
-startmode auto -srvcstart system
C:\oracle\product\10.1.0\Db_1\bin\sqlplus /nolog
@C:\oracle\admin\ocp10g\scripts\ocp10g.sql
The script creates some directories, sets the ORACLE_SID environment variable,
and then (because this example is Windows) uses the ORADIM.EXE utility to create
the Windows service for the instance and put it on automatic start. Then it launches
SQL*Plus and runs a SQL script called ocp10g.sql:
set verify off
PROMPT specify a password for sys as parameter 1;
DEFINE sysPassword = &1
PROMPT specify a password for system as parameter 2;
DEFINE systemPassword = &2
PROMPT specify a password for sysman as parameter 3;
DEFINE sysmanPassword = &3
PROMPT specify a password for dbsnmp as parameter 4;
DEFINE dbsnmpPassword = &4
host C:\oracle\product\10.1.0\Db_1\bin\orapwd.exe
file=C:\oracle\product\10.1.0\Db_1\database\PWDocp10g.ora
password=&&sysPassword force=y
ch03.indd 16
5/18/2005 11:10:59 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
17
PART I
@C:\oracle\admin\ocp10g\scripts\CreateDB.sql
@C:\oracle\admin\ocp10g\scripts\CreateDBFiles.sql
@C:\oracle\admin\ocp10g\scripts\CreateDBCatalog.sql
@C:\oracle\admin\ocp10g\scripts\emRepository.sql
@C:\oracle\admin\ocp10g\scripts\postDBCreation.sql
This script prompts for some passwords, already provided when you ran the DBCA.
Then it calls the ORAPWD.EXE utility to create an external password file (the utility is
orapwd on Unix). Then it calls another five SQL scripts. First, CreateDB.sql:
connect SYS/&&sysPassword as SYSDBA
set echo on
spool C:\oracle\product\10.1.0\Db_1\assistants\dbca\logs\CreateDB.log
startup nomount pfile="C:\oracle\admin\ocp10g\scripts\init.ora";
CREATE DATABASE "ocp10g"
MAXINSTANCES 8
MAXLOGHISTORY 1
MAXLOGFILES 16
MAXLOGMEMBERS 3
MAXDATAFILES 100
DATAFILE 'C:\oracle\oradata\ocp10g\system01.dbf' SIZE 300M
REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
EXTENT MANAGEMENT LOCAL
SYSAUX DATAFILE 'C:\oracle\oradata\ocp10g\sysaux01.dbf' SIZE 120M REUSE
AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
DEFAULT TEMPORARY TABLESPACE TEMP TEMPFILE
'C:\oracle\oradata\ocp10g\temp01.dbf' SIZE 20M REUSE AUTOEXTEND ON
NEXT 640K MAXSIZE UNLIMITED
UNDO TABLESPACE "UNDOTBS1" DATAFILE 'C:\oracle\oradata\ocp10g\undotbs01.dbf'
SIZE 200M REUSE AUTOEXTEND ON NEXT 5120K MAXSIZE UNLIMITED
CHARACTER SET WE8MSWIN1252
NATIONAL CHARACTER SET AL16UTF16
LOGFILE GROUP 1 ('C:\oracle\oradata\ocp10g\redo01.log') SIZE 10240K,
GROUP 2 ('C:\oracle\oradata\ocp10g\redo02.log') SIZE 10240K,
GROUP 3 ('C:\oracle\oradata\ocp10g\redo03.log') SIZE 10240K
USER SYS IDENTIFIED BY "&&sysPassword" USER SYSTEM IDENTIFIED BY
"&&systemPassword";
spool off
The script connects to the instance, using the syntax for password file authentication.
Then the STARTUP NOMOUNT command builds the instance in memory, using the
static parameter file you saw earlier. The significance of “NOMOUNT” will be dealt
with in Chapter 5; for now, let it suffice that it is necessary, as there is no database to
mount and open. And then at last we get the CREATE DATABASE command, which
continues to the end of the file. The first section sets some overall limits for the
database. They can all be changed subsequently, but if they are clearly inappropriate,
it is a good idea to change them now, before creation. Two datafile specifications
follow: these are the files that will be used for the SYSTEM and SYSAUX tablespaces.
Next come specifications for a TEMPORARY tablespace and an UNDO tablespace
(more on this in Chapter 16). Then a character set is specified. Until version 9i of the
database, there was no method for changing the database character set after creation:
it was therefore vital to get this right. With 9i and 10g, it is possible to change it later,
but this is not an operation to embark on lightly—and in fact may not be feasible.
ch03.indd 17
5/18/2005 11:10:59 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
18
Get it right now! This area will be covered in detail in Chapter 21. Finally comes the
specification for three online logfile groups, each consisting of one member, and the
passwords for database users SYS and SYSTEM are initialized.
TIP Be sure to change the passwords for all the standard users before the
database goes live.You would be amazed at the number of live systems where
this is not done.
This one file will create a database. After its successful execution, you will have an
instance running in memory, and a database consisting of a controlfile and copies as
specified by the CONTROL_FILES initialization parameter, and the datafiles and redo
logs specified in the CREATE DATABASE command. A data dictionary will have been
generated. But although the database has been created, it is unusable. The remaining
scripts called by ocp10g.sql make the database usable:
• CreateDBfiles.sql creates another tablespace, to be used as a default storage
location for user data.
• CreateDBcatalog.sql generates the data dictionary views and the PL/SQL
supplied packages.
• emRepository.sql generates the Enterprise Manager Database Control tool.
• postDBcreation.sql tidies everything up.
And that’s all there is to it: run DBCA, follow the prompts, and wait for it to finish.
As a test, from an operating system prompt, set your ORACLE_SID environment
variable and log on to your new database. For Windows,
C:\>
C:\>set ORACLE_SID=ocp10g
C:\>sqlplus sys/oracle as sysdba
SQL*Plus: Release 10.1.0.2.0 - Production on Sun Jul 25 12:34:14 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> select name,open_mode from v$database;
NAME
OPEN_MODE
--------- ---------OCP10G
READ WRITE
SQL>
DBCA Additional Functions
The opening screen of DBCA gives you four options:
• Create A Database
• Configure Database Options
ch03.indd 18
5/18/2005 11:10:59 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
19
• Delete A Database
Configure Database Options helps you change the configuration of a database
you have already created. In Exercise 3-1, you de-selected all the options; this was to
make the creation as quick and simple as possible.
PART I
• Manage Templates
TIP By de-selecting all the options, particularly those for “standard database
components,” creation time is reduced dramatically.
If you decide subsequently to install some optional features, such as Java or OLAP,
running DBCA again is the simplest way to do it. An alternative method is to run the
scripts to install the options by hand, but these are not always fully documented and
it is possible to make mistakes; DBCA is better.
The Delete A Database radio button will prompt you for which database you wish
to delete, and then give you one more chance to back out before it deletes all the files
that make up the database and (for a Windows system) invokes ORADIM.EXE to delete
the service as well.
Finally, you manage templates to store database definitions for use later. Remember
that in the exercise, you chose to create a “custom” database. A custom database is not
preconfigured; you chose it in order to see all the possibilities as you worked your way
through DBCA. But apart from “custom,” there were options for “data warehouse,”
“general purpose,” and “transaction processing.” If you take any of these, you’ll be
presented with an abbreviated version of the DBCA prompts that will create a database
with different defaults, at least partly optimized for decision support systems (DSS, the
data warehouse option), online transaction processing systems (OLTP, the transaction
processing option), or mixed workload (the general purpose option). The final question
when you created your database gave you the possibility of saving it as a template, that
is, not to create it at all, but to save the definition for future use. DBCA will let you
manage templates, either the presupplied ones or ones you create yourself, by copying,
modifying, or deleting them. Templates can be extremely useful if you are in a position
where you are frequently creating and re-creating databases that are very similar.
Chapter Review
This chapter began with a detailed description of the Oracle server architecture. A
thorough understanding of this is essential for further progress. You must be familiar
with the elements that make up an instance and a database: the memory structures,
the processes, and the file types. Then there was a brief look at the purpose and contents
of the data dictionary, and a brief discussion of the logical storage of segments within
tablespaces. Finally you used the DBCA to create a database, and you walked through
the various scripts and commands it generated for this purpose.
ch03.indd 19
5/18/2005 11:10:59 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
20
Questions
1. Which of the following memory structures are required, rather than optional,
parts of the SGA? (Choose three answers.)
A. Database buffer cache
B. Java pool
C. Large pool
D. Redo log buffer
E. Shared pool
F. Streams pool
2. You are creating a database. Put these steps in the correct sequence:
A. Build the data dictionary.
B. Create a parameter file.
C. Create the data dictionary views.
D. Issue the CREATE DATABASE command.
E. Issue the STARTUP NOMOUNT command.
3. If you do not specify a SYSAUX datafile on your CREATE DATABASE command,
what will happen? (Choose the best answer.)
A. The command will fail because SYSAUX is a required tablespace.
B. The command will succeed, but you must add a SYSAUX tablespace after
database creation.
C. The command will succeed, and a default SYSAUX tablespace will be
created for you.
D. The command will succeed, but the whole data dictionary will be in the
SYSTEM tablespace.
4. Which of the following can never be changed after database creation? (Choose
the best answer.)
A. Database block size
B. Database character set
C. Database name
D. None of the above: nothing is fixed at database creation time
5. Which of the following is required to create a database? (Choose the best
answer.)
A. The operating system’s root (for Unix/Linux) or Administrator (for Windows)
password
B. Execute permission on the DBCA
ch03.indd 20
5/18/2005 11:11:00 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
21
C. At least as much RAM as the size of the SGA
6. On Unix/Linux, you launch the DBCA, and nothing happens. What could be
the cause of this? (Choose the best answer.)
PART I
D. None of the above
A. You are not a member of the dba group.
B. Your DISPLAY variable is not set to your terminal’s address.
C. You have not set your DISPLAY variable.
D. You have not set your ORACLE_SID variable.
7. Which of the following files are optional? (Choose three answers.)
A. Online redo log files
B. Parameter file
C. Password file
D. SYSAUX tablespace datafile
E. SYSTEM tablespace datafile
F. UNDO tablespace datafile
8. If you do not specify an UNDO tablespace on your CREATE DATABASE
command, what will happen? (Choose the best answer.)
A. The command will fail because an UNDO tablespace is required.
B. The command will succeed, and a default UNDO tablespace will be
created for you.
C. The command will succeed, but you must create an UNDO tablespace later.
D. The command will succeed, and you may create an UNDO tablespace later.
9. You have created a database but cannot connect to it with Database Control.
What could be the cause of this? (Choose the best answer.)
A. You are not being authenticated by the operating system, or by password
file authentication.
B. You have not run the scripts to create Database Control.
C. Grid control is a prerequisite for Database Control.
D. You are not licensed to use Database Control.
10. When does the data dictionary get created? (Choose the best answer.)
A. When you create a database
B. When you run the post-creation scripts catalog.sql and catproc.sql, called
by CreateDBcatalog.sql
C. When the SYSTEM and SYSAUX tablespaces are created
D. It does not need to be created; it is always available as part of the instance
ch03.indd 21
5/18/2005 11:11:00 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Oracle Database OCP 10g Certification All-in-One Exam Guide
22
11. Which of the following processes are optional? (Choose three answers.)
A. Archive process
B. Checkpoint process
C. Database listener
D. Grid Control Management Agent
E. Log writer
F. Process monitor
12. You created a database with two online redo log file groups, one member each.
What must you do to provide fault tolerance? (Choose the best answer.)
A. Add two more groups, to mirror the first two.
B. Add one more member to each group.
C. You can do nothing; these characteristics are fixed at creation time.
D. You need do nothing; the second group already mirrors the first.
13. Which data dictionary view will show you all the tables in the database?
(Choose the correct answer.)
A. ALL_TABLES
B. DBA_TABLES
C. USER_TABLES
D. None. To see all the tables, you must query the data dictionary directly.
14. Which of the following is not stored in the data dictionary? (Choose the best
answer.)
A. User definitions
B. Supplied PL/SQL packages
C. Data dictionary views
D. None; they are all stored in the data dictionary
15. You de-selected the Oracle Java Virtual Machine when running DBCA, but you
later wish to install it. What must you do? (Choose the best answer.)
A. Create the Java pool in the database.
B. Run scripts to create the JVM.
C. Drop the database and re-create it with the JVM.
D. Start the JVM background process.
ch03.indd 22
5/18/2005 11:11:00 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 3
Chapter 3: Creating an Oracle Database
23
Answers
ch03.indd 23
PART I
1. A, D, and E. The remaining components are optional: a Java pool is required
only if you are going to run Java; the large pool is a performance option; the
streams pool is needed only if you using streams, an advanced option.
2. B, E, D, A, and C. You can’t start up an instance until you have created a
parameter file to define it. Then the CREATE DATABASE command will
create your data dictionary. Only then can you run scripts to make the
database usable.
3. C. The SYSAUX tablespace is needed at creation time; if you don’t specify it,
Oracle will create one for you.
4. A. This is the only setting that can never be changed without re-creation. Of
course, there are plenty of other things that are very awkward to change.
5. D. The operating system root password may be required at installation time,
but it isn’t needed for creation. DBCA may be nice, but you don’t have to
use it. RAM is largely irrelevant; Oracle doesn’t care if it is running in main
memory or virtual memory.
6. B. With DISPLAY pointing to the wrong place, your X windows will appear
there—where you can’t see them. A and C will cause errors, and D is irrelevant;
it gets set while running DBCA.
7. B, C, and F. You can add an UNDO tablespace later. The password file may
be a practical necessity but is certainly not required. The parameter file is
optional if you are using a static parameter file; you can delete it after starting
the instance (though you wouldn’t want to).
8. D. Unlike the SYSAUX tablespace, an UNDO tablespace really is optional,
though as you’ll see, it is a great performance and manageability feature.
9. B. The scripts to create the Enterprise Manager repository must be run before
you can use Database Control.
10. A. Creation of a data dictionary is, more than anything else, what happens
when you issue the CREATE DATABASE command.
11. A, C, and D. A listener may be needed for practical purposes (or users won’t
be able to connect), but it is optional. Archiving is also optional, though a
very good idea. The Grid Control Agent is, of course, needed only if you want
to use Grid Control.
12. B. Online redo log fault tolerance is provided by having multiple members
per group.
13. B. This is a classic OCP trick question, pointing out that the names of the
views are possibly ambiguous.
14. D. The catch here is that PL/SQL packages are stored in the data dictionary,
even though they are owned by database users.
15. B. Though you could, of course, do it through DBCA—much simpler. A is
the trick answer: you need a Java pool to run Java, not to create the JVM.
5/18/2005 11:11:00 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 / Chapter 23
blind folio: 24
ch03.indd 24
5/18/2005 11:11:01 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
CHAPTER 4
Interfacing with the
Oracle Database
In this chapter you will learn how to
• Use SQL*Plus and iSQL*Plus to access Oracle Database 10g
• Use SQL*Plus and iSQL*Plus to describe the logical structure of tables
• Use SQL to query, manipulate, and define data using SELECT, UPDATE/INSERT/
DELETE, and CREATE/ALTER/DROP
• Identify common database interfaces
• Describe a database transaction
1
ch04.indd 1
6/30/2005 4:05:03 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
After you have installed the Oracle Database 10g software and created a database,
the next logical step is to be able to query the database for data. While querying the
metadata (data about the data) in the database may seem a good starting point, the
real value is in populating the database with data useful to your organization using
data structures such as tables and views that logically make sense to your enterprise.
The key language that you will use in doing all these tasks is SQL, the Structured Query
Language. In order to interface with the database, you will make use of one or more
Oracle tools built for that task: SQL*Plus, iSQL*Plus (a web-based version of SQL*Plus),
or a third-party tool. This chapter will provide you with information on SQL as well
as the tools to make effective use of it.
Using SQL
SQL was developed by IBM in the 1970s as a way to query relational data that can be
used by individuals other than programmers. It was originally called Structured English
Query Language (or SEQUEL for short), but eventually the English was dropped and
we have SQL. SQL can be broken down into three basic sections or “languages”: Data
Definition Language (DDL), data control language (DCL), and the Data Manipulation
Language (DML).
DDL statements do not deal with data directly; rather, they deal with the objects
that hold and provide access to data. When you want to add, modify, or remove any
object in the database (such as a table, a view, or an index), you must do so using a
DDL statement. DDL includes all CREATE, ALTER, and DROP statements. Database
creation begins with DDL statements; they build the entire framework of tables and
constraints that will become the structure of the database. Before data can be added,
you must have some place to add it to. Your users, normally, will not issue DDL
statements, but you as a database administrator (DBA) and your database developers
will perform them.
EXAM TIP The three key DDL statements are CREATE, ALTER, and DROP.
They are used to add, change, and remove objects from the database.
Database access is controlled by the data control language. Once an account is
created for a user, that user can be given permission on the database using the GRANT
statement or it can be taken away using the REVOKE statement. These two statements
form the core of the DCL.
Two types of permissions can be granted and revoked: system and object permissions.
System permissions enable a user to perform action on the database. Performing such
activities as creating a table or index, or backing up the database, requires system
permissions. Object permissions are applied to particular objects in the database, and
these permissions may change depending on the type of object. For example, you
ch04.indd 2
6/30/2005 4:05:36 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
3
PART I
could grant a particular user the permission to issue SELECT, INSERT, or UPDATE
commands against a table, but an EXECUTE permission on a stored procedure. DCL
statements are, for the most part, the job of the DBA. It is his or her job to create user
accounts for every user and to assign those accounts the appropriate permissions.
EXAM TIP DCL statements are GRANT and REVOKE, which can be used to
add or remove permissions for a user or role. System and object permissions
are available. Object permissions can differ, depending on the type of object.
DML statements deal directly with data. Any manipulation or retrieval of data
requires a DML statement. The key elements of the DML are SELECT, INSERT, UPDATE,
and DELETE. These commands enable you to retrieve data from a table, add new data
to a table, modify existing data, and delete rows from a table. DML also includes
transactional control language elements consisting of COMMIT, ROLLBACK, and
SAVEPOINT. These language elements help control the execution of DML statements
by grouping them together into transactions. DML statements are the most common
type of interaction with the database. It is the level of SQL that your users will be
working in almost exclusively.
EXAM TIP This chapter will provide an overview of SQL and some of the key
elements of the SQL language used by Oracle. The exam will test your ability
to write correct SQL syntax, so you should review the Oracle Database 10g
documentation for additional information on programming in SQL. SQL is a
vast topic that cannot be adequately covered in a single chapter and has had
thick books written about how to best make use of it.
The SELECT Statement
All SQL queries begin with the SELECT statement. This statement enables you to retrieve
all data or only certain columns and rows in a table. It can also return data from more
than one table. It enables you not only to retrieve data, but also to perform calculations
on existing data and return the results of these calculations. The basic SELECT statement
requires two elements: the select list and a FROM clause. This specifies what columns
to retrieve and from where. Here is the basic format:
SELECT [DISTINCT] {* | column,[expression], . . . }
FROM table;
The select list can contain either the asterisk or a list of column names or expressions.
The select list dictates what is returned by the query. The asterisk is simply shorthand,
meaning all columns. For example, to retrieve information on all users in the database,
you can issue the following SQL statement—the semicolon (;) is a line terminator:
SELECT * FROM DBA_USERS;
ch04.indd 3
6/30/2005 4:05:37 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
To list all users and their account lockout statuses, you can use an expression in the
SELECT list and concatenate two columns in the table to provide the result, as well as
alias the resulting column name, as in this example:
SELECT USERNAME || ' is ' || ACCOUNT_STATUS AS "User and Status" FROM DBA_USERS;
Limiting Rows Returned with the WHERE Clause
In all of the examples so far, the queries have limited which columns have been
returned but have returned all rows in the table, but most of the time database queries
return a specific set of data required by the user. For example, an order entry person
taking an order on the phone will want to know the price of the specific product the
customer is asking about instead of the price of all products. In SQL, you limit the
number of rows returned with the use of a WHERE clause. In a SELECT statement,
the WHERE clause is always placed after the FROM clause:
SELECT [DISTINCT] {* | column,[expression], . . . }
FROM table;
[WHERE condition1 [{AND | OR [NOT]} condition2 . . .] ]
The conditions of a WHERE clause consist of two expressions compared by an
operator such as equal (=), not equal (<>), less than (<), or greater than (>), along
with other operators such as BETWEEN, LIKE, and IN. When SQL processes the
WHERE clause, it tests the value of each row in a column (or the result of each row in
an expression) against a particular value. The query includes only rows that meet the
condition in the result set. For example, to return the number of tables in the database
owned by the user SYSMAN, a DBA could issue the following query:
SELECT COUNT(*) FROM DBA_TABLES WHERE OWNER = 'SYSMAN';
When you refer to character and date values in a WHERE clause, you must enclose
them in single quotes. Numeric data does not require single quotes. If you omit the
single quotes, Oracle attempts to interpret the value as a database object, and you
will most likely receive an error. Furthermore, when using comparison operators
with character data, you should always remember that Oracle is case-sensitive when
performing character comparisons. These two queries will result in different sets of
data returned—one with the rows and the other with no rows—just because of the
difference in case for the value being retrieved:
SELECT COUNT(*) FROM DBA_OBJECTS WHERE OWNER='SYSMAN';
COUNT(*)
---------1263
SELECT COUNT(*) FROM DBA_OBJECTS WHERE OWNER='sysman';
COUNT(*)
---------0
ch04.indd 4
6/30/2005 4:05:37 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
5
SELECT COUNT(*) FROM DBA_OBJECTS WHERE OWNER='SYSMAN';
COUNT(*)
---------1263
PART I
An important point to remember is that Oracle is not case sensitive when it comes
to the SQL syntax itself, just when comparing character values. Issuing the following
commands will always result in the same data being retrieved:
select count(*) from dba_objects where owner='SYSMAN';
COUNT(*)
---------1263
Eliminating Duplicates in the Result Set
When you issue a SELECT statement, Oracle returns all rows that match the query.
What if, however, you wanted a list only of all the users who own database objects?
To create such a list, you have to use the DISTINCT keyword. When you include this
keyword, Oracle sorts the result set and then returns only the first occurrence of each
value returned by the query. To use the DISTINCT keyword, you place it in the SELECT
list after the SELECT keyword. For example, to display the list of users who own objects
in the database, you would issue the following command with the displayed result:
SQL> SELECT DISTINCT owner FROM DBA_OBJECTS;
OWNER
-----------------------------DBSNMP
OUTLN
PUBLIC
SYS
SYSMAN
SYSTEM
WMSYS
7 rows selected.
If, on the other hand, you omitted the DISTINCT keyword, you would get a much
larger number of rows (several thousand, in fact). It is important to remember that
the DISTINCT keyword applies to the entire SELECT list. If you specify more than one
column or expression in the SELECT list, the DISTINCT keyword will return the unique
occurrences of the combination of all columns in the SELECT list. For example, issuing
the following command will return the unique combination of owner and object_type
from DBA_OBJECTS and return many more rows than the seven in the previous query:
SELECT DISTINCT owner, object_type FROM DBA_OBJECTS;
EXAM TIP DISTINCT will apply to the whole set of columns or expressions
on the SELECT list.
ch04.indd 5
6/30/2005 4:05:38 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
Retrieving Data from More Than One Table
All SQL queries require two elements: a SELECT list specifying what to retrieve and
a FROM clause specifying where to retrieve those items from. In all of the previous
examples only one table is referenced in the FROM clause, but it is possible to include
more than one table in the FROM clause of a query and then specify how the tables
are related to form a join.
It is important to understand how to work with joins, not just because it is required
for the exam, but because the majority of queries used in the real world will include
joins. Even for DBAs it is necessary to write joins to extract data from Oracle’s data
dictionary. For example, if you wanted to retrieve a list of tablespaces and the names of
their associated datafiles, you would need to write a query joining DBA_TABLESPACES
and DBA_DATA_FILES.
Writing a join requires more than just a SELECT list and a FROM clause; it also
requires a join condition. A join condition is a way to equate specific rows in one
table with specific rows in another table. This condition is most often a primary key/
foreign key pair and is expressed in the WHERE clause (in all versions of Oracle) or
in the ANSI JOIN syntax available in Oracle 9i and Oracle 10g. Therefore the join that
would retrieve a list of tablespaces and their associated datafiles can be written two
ways, as follows:
SELECT DBA_DATA_FILES.tablespace_name, file_name
FROM DBA_TABLESPACES, DBA_DATA_FILES
WHERE DBA_TABLESPACES.TABLESPACE_NAME=DBA_DATA_FILES.TABLESPACE_NAME;
SELECT DBA_TABLESPACES.tablespace_name, file_name
FROM DBA_TABLESPACES JOIN DBA_DATA_FILES
ON DBA_TABLESPACES.TABLESPACE_NAME = DBA_DATA_FILES.TABLESPACE_NAME;
The advantage of using the ANSI JOIN syntax is that it is easier to read and clearly
specifies the join condition. You can also add a WHERE clause to further narrow down
the query, while in the first syntax the WHERE clause and join condition are in the
same place: the WHERE clause.
EXAM TIP Oracle supports both the classic join syntax and the preferred
ANSI join syntax.
Notice that the column tablespace_name in the SELECT list had to be qualified
in both SQL statements, but the parent table could be either of the joined tables. This
is because Oracle needs to be told which specific instance of the tablespace_name
column you want to display because there are two, one in each table being joined. If
you do not qualify the column name with the parent table name Oracle encounters
ch04.indd 6
6/30/2005 4:05:39 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
7
PART I
an ambiguous reference and returns an error. However, if a column appears in only
one table in the join, it does not need to be qualified, as is the case with the file_
name column, since it exists only in the DBA_DATA_FILES table.
Another important thing to remember about joins is that the columns in the join
condition do not need to be in the SELECT list; they can serve only to link the tables
together. In fact, the join condition need not be specified at all, in which case you get
what is known as a CROSS JOIN or Cartesian product where all rows in the first table
are joined to all rows in the second table. While you may not think that this is useful,
and in most cases it serves to simply cause excessive work for Oracle, cross-joins are
very handy in data warehousing, where many tables are being related.
Not all joins are simple equijoins (joins whose join condition is based on the =
operator) like the examples just shown. There are different join types that can return
all matching data (inner joins, which can be equijoins or use other operators), more
than the matching data (outer joins), and even data in two tables that is not related—
i.e. the unrelated items—an extension of the outer join called the outer theta join. In
the ANSI JOIN syntax you also have a NATURAL JOIN, which matches column names
in the tables being related and then attempts to perform an equijoin based upon all
matching column names in both tables. Finally, a SELECT statement can include more
than one join so that it is possible to relate several tables in a single SQL statement.
NOTE For more information on joins and join syntax, refer to the Oracle 10g
SQL Reference documentation in the Oracle 10g documentation library that can
be found at www.oracle.com/technology/documentation/database10g.html.
Sorting and Grouping Data
When you issue a SELECT statement in SQL, you receive a result set that contains all
data in the table or tables that match the query. However, the order in which that data
is returned is completely random. It is conceivably possible to issue the same query
ten times and receive the same data back in ten different orders. When you want the
data returned in a specific order, you must use the ORDER BY statement. With this
statement, you specify the columns or expression that you want as the basis of your
ordering. You can also specify whether you want the data sorted in ascending order
(lowest to highest) or descending order (highest to lowest). You can order by a column
of any datatype except for the large object datatypes (that is, CLOB, NCLOB, BLOB,
BFILE, RAW, LONGRAW, and LONG). The default for character columns is to sort
alphabetically in ascending order. To retrieve a list of tablespaces in alphabetical order
and the associated datafiles, you can issue a query like this:
SELECT DBA_TABLESPACES.tablespace_name, file_name
FROM DBA_TABLESPACES JOIN DBA_DATA_FILES
ON DBA_TABLESPACES.TABLESPACE_NAME = DBA_DATA_FILES.TABLESPACE_NAME
ORDER BY DBA_TABLESPACES.TABLESPACE_NAME;
ch04.indd 7
6/30/2005 4:05:40 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
EXAM TIP The ORDER BY clause must always appear last in the SQL
statement.You can order by any valid expression, such as a formula or
calculation applied against the data.
To make things more interesting, the expression in the ORDER BY clause need not
be in the SELECT list, JOIN condition, or WHERE clause. The data can be sorted using
any valid expression and even columns not referenced in the query, such as this example,
which sorts the output according to the size of the datafiles from largest to smallest:
SELECT DBA_TABLESPACES.tablespace_name, file_name
FROM DBA_TABLESPACES JOIN DBA_DATA_FILES
ON DBA_TABLESPACES.TABLESPACE_NAME = DBA_DATA_FILES.TABLESPACE_NAME
ORDER BY DBA_DATA_FILES.BYTES DESC;
Manipulating Data Using INSERT, UPDATE, and DELETE
The Oracle engine controls all access to the database and its data. This means that
when you want to place or modify data in a table, you must instruct Oracle to make
those changes for you. This is achieved through the INSERT, UPDATE, and DELETE
statements. Because storing and manipulating data is the key function of an Oracle
database, it is important to have a full understanding of how to issue these statements
to work with and manage an Oracle database.
The INSERT Statement
In order to get data into tables, you must issue the correct DML statement. To add data
to a table, you use the INSERT statement. The basic syntax for an INSERT statement is
as follows:
INSERT INTO table [(column, [column . . . ])]
VALUES (value [, value . . . ]);
You can insert data into only one table at a time using the INSERT statement. Thus,
you can include only one table name in the INSERT statement. The VALUES keyword
is followed by a list of values that are entered into the table in the same order as the
columns for that table. When you are inserting character data or date data into a table,
you must enclose this information in single quotes. Numeric data does not require
single quotes. If you do not want to specify a value for a column in the table, you can
assign it null by using the keyword NULL in place of data. NULL is the absence of a
value and can be specified for any column that a NOT NULL constraint is not defined on.
NOTE NULL is a state of a column. A column can be NULL, in which case it
does not have a value, or NOT NULL, if a value exists. When defining a table, it
is possible to indicate whether a column must have a value or not by using the
keywords NOT NULL or NULL, respectively, after the name and datatype of
the column have been specified. Chapter 8 will provide more information on
creating and managing tables.
ch04.indd 8
6/30/2005 4:05:40 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
9
PART I
If you plan to enter data into fewer columns than are defined for the table, you must
include a column list after the table name. This list specifies the column or columns
that you want to insert data into, and the order in which those columns appear in the
VALUES list.
NOTE Oracle provides syntax allowing the insertion of data into more than one
table using conditional logic. The INSERT ALL and INSERT FIRST statements
can be used to add data to more than one table or the first table matching the
criteria, something very useful in data warehousing environments where data
loads are frequently performed.
The UPDATE Statement
In a transaction-oriented database such as an order entry system or an airline reservation
system, data is constantly changing—shipping dates are added to orders, passengers
change seat assignments, flights are rescheduled, and so on. To modify data after a
row has been inserted into a table, you must use the UPDATE statement. The basic
syntax for the UPDATE statement follows:
UPDATE table
SET column = value [, column = value, . . . ]
[WHERE condition];
It is possible to modify more than one column with a single UPDATE statement;
however, you can update only one table at time. The WHERE condition in an UPDATE
statement controls which rows are updated. An UPDATE statement updates all rows
that match the WHERE condition. If the WHERE clause is omitted, all rows in the
table are modified.
NOTE Oracle 10g also includes a MERGE INTO statement that allows you
to update data in one table when matching data is found and INSERT data
into another table when no match is found. This is also known as an UPSERT
(UPDATE and INSERT). In fact, Oracle 10g enhanced the MERGE statement
to allow conditional and optional extension clauses. The enhancements allow
conditional updates and inserts and an optional delete clause when updating
data (e.g., refresh existing row or delete obsolete row).
The DELETE Statement
Many databases will need to allow data to be removed as part of transactional
processing, or to reduce the size of tables by taking data no longer needed out of the
table. To remove a row from a table, you use the DELETE command. The basic syntax
for the DELETE statement is as follows:
DELETE [FROM] table
[WHERE condition];
ch04.indd 9
6/30/2005 4:05:41 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
As with the UPDATE statement, the WHERE clause is used to control which rows
are affected by the DELETE statement. If you omit the WHERE clause, the DELETE
statement removes all rows from the table. If this is not your intention, you may remove
data that others need and cause some work for yourself to recover the missing data.
Luckily, there are commands in Oracle that determine whether or not to save your
changes.
EXAM TIP INSERT, UPDATE, and DELETE are always applied against data
in one and only one table.
Transaction Control
Each DML statement in Oracle is a single operation that affects one or more rows.
However, Oracle does not automatically save the changes you made, because it may
be necessary for more than one INSERT, UPDATE, or DELETE statement to be executed
for the data to be in a consistent and logical state. For example, consider the steps
involved in a bank transfer, which requires that you reduce the balance of the source
account and increase the balance of the target account in order for the transfer to be
valid. If the statement reducing the balance of the source account succeeds and the
second statement increasing the balance of the target account fails, there is a problem—
someone is out some money. With a transaction, you can group these two operations
into a single action. Transactions do more than just group statements together; they
also ensure the logical consistency of the database and your data.
Transactional control in Oracle has been designed to meet the ACID test first
suggested by Jim Gray and Andreas Reuter. ACID stands for “Atomicity,” “Consistency,”
“Isolation,” and “Durability,” as defined here:
• Atomicity The entire transaction must commit as a unit, or not at all.
• Consistency The transaction must follow some logical rules. In the account
transfer example, you are moving money from one location to another.
Consistency, in this case, requires that money not be created or destroyed.
It must be moved, and the amount credited must be the amount debited.
• Isolation The process carrying out the transaction must have absolute
control over all of the elements it is affecting. Oracle provides a concurrent
environment through a locking mechanism. While a process has a row locked,
it cannot be modified by another process. However, via the read consistency
mechanism, other processes can see the data in the column before it was
modified until the changes are committed to the database. This is achieved
in Oracle through the use of the undo or rollback segment, which will be
discussed in Chapter 16.
• Durability Durability means that after a transaction completes (or commits),
the data must remain that way and will be visible to all users. If changes need
to be made, another transaction will need to be initiated.
ch04.indd 10
6/30/2005 4:05:42 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
11
PART I
Oracle does not commit a transaction and make changes permanent unless
instructed to do so. For this reason, several commands exist to control transactions.
A transaction implicitly starts when the DML statement is executed. It is not terminated
until it is either committed or rolled back.
In Oracle SQL, you can explicitly control the end of a transaction using the COMMIT
and ROLLBACK commands. When you issue a COMMIT statement, the changes made
by the DML statement become permanent. When you issue a ROLLBACK, the changes
are reversed. The advantage of this system is that it is possible to verify an operation
before committing it. When you query the table that you have modified, Oracle
displays the results of all DML statements within the transaction. These changes are
not visible to other users until you either commit or roll back the transaction. This
provides isolation. You can issue several DML statements, realize that you have made
a mistake, and undo your actions without other users being aware of the change. To
undo the changes, you simply issue a ROLLBACK statement.
EXAM TIP The first DML statement issued starts a transaction. A transaction
ends when a COMMIT or ROLLBACK is encountered, or an implicit COMMIT
or ROLLBACK takes place. Implicit commits take place when the connection
to the server is terminated normally, such as exiting a program. An implicit
rollback takes place if the connection to the database is aborted for any reason.
At times, however, you may not want to roll back the entire transaction. For instance,
you may want to verify each step of a multistep transaction and roll back individual
steps. This level of transactional control can be achieved with the use of savepoints.
Savepoints are named markers within the transaction that can be used as the target
for a rollback. You set savepoints with the following syntax:
SAVEPOINT name;
After the savepoint is set, you can roll back to that point by including the TO
operator and the name of the savepoint. After you issue a ROLLBACK TO statement,
all DML statements before the savepoint are committed and all changes after the
savepoint are rolled back. Also, all savepoints are erased and the current transaction
is ended. If you want to make further changes, you must start a new transaction by
issuing a DML statement.
Locking
Part of the ACID test was isolation, which implies that while a transaction is being
processed, no other user can make changes to the data that is the subject of the
transaction. Oracle controls this isolation with the use of locks. There are two types
of locks in Oracle: shared locks and exclusive locks.
Shared locks are acquired when you issue a SELECT statement. Oracle locks the
table to ensure that no one modifies its structure while you are using its data, but it
does not place any locks on the rows being queried. Shared locks do not prevent other
users from reading or modifying the data in the table, only from making changes to the
ch04.indd 11
6/30/2005 4:05:43 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
table’s structure using the ALTER TABLE command or from dropping the table using
the DROP TABLE command. Multiple users can acquire share locks on the same data.
EXAM TIP SELECT statements apply no locks to the rows being queried.
Exclusive locks are acquired when you issue a DML statement, and they are acquired
for each row being modified. The exclusive lock prevents other users from acquiring
exclusive locks on the data you are working with as part of your transaction until you
issue a COMMIT or ROLLBACK statement. This prevents two users from attempting to
update the same data at the same time. When a user attempts to update data that is
locked by another user, the user must wait until the lock is removed.
NOTE Oracle allows you to manually perform locking of a table using the
LOCK TABLE command. As a general rule, applying your own manual locks is
a bad idea because it will probably apply more locks on the data than Oracle
would itself and therefore slow down processing. As a general rule, never apply
locks manually.
Data Definition Language
Before you can add data to a table, you need to create the table in the database. data
definition language (DDL) commands are used to create, modify, and remove objects
from a database. The three key DDL commands are:
• CREATE The CREATE statement adds a new object to the database. You use
it to create new tables, views, stored procedures, and other objects. In order for
the CREATE command to succeed, no other object with the same name can
exist in the schema.
• ALTER The ALTER statement is used to change the characteristics of tables,
indexes, and other objects in the database. The ALTER statement does not
apply to all objects in the database.
• DROP The DROP statement is used to remove objects from the database.
When used on tables, it also gets rid of any data that existed in the table. Once
dropped, the referenced object is no longer available and any commands that
attempt to make use of it will return an error.
NOTE Creating, modifying, and dropping database objects will be covered in
more detail in Chapter 8.
ch04.indd 12
6/30/2005 4:05:44 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
13
PART I
Names of objects in Oracle must follow certain rules; for instance, all object names
must begin with a letter; may be from 1 to 30 characters in length; and may contain
letters, numbers, the underscore character (_), the dollar sign symbol ($), or the pound
sign symbol (#). Object names cannot be the same as any Oracle reserved word. Oracle
reserved words include most commands (for example, SELECT, INSERT, DROP, GRANT),
as well as the names of functions, and other language constructs. The complete list of
Oracle reserved words can be found in the SQL Reference Manual. If you do not follow
the rules and attempt to create an object, Oracle will generate an error.
An object name must not be the same as the name of another object owned by the
same user. When you attempt to create an object with the same name as another in
the same schema, Oracle generates an error. The names of objects in Oracle are case
insensitive, so if you use uppercase only, lowercase only, or mixed case when you create
an object, Oracle always returns the object name in uppercase.
Database, System, and Session Management Commands
Oracle also includes a number of special commands that are used to manage the
instance, database, or user session. These include the ALTER DATABASE, ALTER
SYSTEM, ALTER SESSION, and other commands.
The ALTER DATABASE command is used to make changes to the database as a
whole or a part of it. For example, you can use the ALTER DATABASE command to
indicate that one or more datafiles are the target of a backup, or to change the state
of the database from one mode to another.
The ALTER SYSTEM command is used to change the state of the running instance.
It can be used to change the values of Oracle initialization parameters either dynamically
or in the SPFILE. The ALTER SYSTEM command can also be used to allow only database
administrators to connect to the instance, as well as many other options.
The ALTER SESSION command allows a user to change the properties of his or her
session. For example, provided the user has permissions to issue the command, it can
be used to increase the amount of memory that is available for sorting or whether or not
parallel executions can be used on queries, or how date and other data will be output.
Understanding PL/SQL
While SQL is a great language for retrieving data from a database and for adding, making
changes to, or deleting the data, it does lack some important programming constructs.
For example, SQL does not have any provisions to control execution flow or to store
data in variables for later reuse or to perform specific actions if an error takes place.
Oracle’s solution to this problem was PL/SQL, which stands for Procedural Language
Extensions to SQL.
Before the integration of the PL/SQL language in Oracle, applications were limited
in how they could retrieve and manipulate database information. The two methods
were to send a number of SQL statements to the server in a script file from an interactive
tool like SQL*Plus or to embed those statements into a language precompiler called
ch04.indd 13
6/30/2005 4:05:44 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
Pro*C. The latter provided the desired processing power but was not trivial to implement.
It took several lines of code to explain how to connect to the database, what statement
to run, and how to use the results from that statement. There were also differences in
the datatypes available in SQL and the precompiled language. PL/SQL addresses the
limitations of both of these methods.
PL/SQL code must be written in specific pieces called blocks. Because PL/SQL is
a compiled language, these blocks must be processed by a compiler before they can
execute. Compilation is the process of checking to ensure that the objects referred to
in the code exist and that the statements have a valid syntax. After this process is
completed, the code can then run, but it must run within a PL/SQL engine. The PL/SQL
engine is not a separate product from the Oracle server, but an integral part of the
Oracle database that takes a PL/SQL block and executes it.
PL/SQL blocks come in two varieties: anonymous blocks and named blocks.
Anonymous PL/SQL blocks are pieces of PL/SQL code that have no header with a name.
As such, you send them to the PL/SQL engine through an interactive tool like SQL*Plus,
and they run once. Remember that PL/SQL is a compiled language, so the block is
compiled, is run, and then disappears. If you want to run it again, you have to send
the entire block to the engine again, where it once again is compiled, is run, and then
disappears. These anonymous blocks can be saved to script files in the operating system
to make re-running them easier.
A named block can be “called” one or more times by its name. For this reason, the
named blocks are often used to implement modularity within a program. The program
can be broken down into several modules or subprograms, which can be called one
or more times. There are four types of named subprograms in Oracle: procedures,
functions, packages, and triggers. Procedures and functions are subprograms that can
be created as objects in the database, in the schema of their owner. When this happens,
they are called stored subprograms. The advantage of using stored subprograms is that they
are compiled at creation time and then can be run many times without the processing
overhead of recompiling. A package is a collection of procedures and functions and
cannot be invoked by its name, but the individual subprograms within the package
(the procedures or functions) can be called individually as long as they are preceded
by the package name. Triggers are blocks of code that are automatically invoked when
the triggering action takes place, such as inserting a row into a table or the user logging
on to the database or a system error occurring.
All PL/SQL blocks have the same structure, including a declaration section for
declaring variables and other identifiers (the DECLARE keyword starts this section),
an executable section for the code to be run (BEGIN keyword), an exception section
for trapping errors (EXCEPTION), and a block terminator indicated by the END
keyword. Only the BEGIN and END (and the code between them) are required elements
of an anonymous PL/SQL block.
EXAM TIP A valid PL/SQL block requires only BEGIN and END statements
and at least one line of valid code between them.
ch04.indd 14
6/30/2005 4:05:45 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
15
PART I
Each line of a PL/SQL block is terminated by a semicolon, and the entire block
is treated by Oracle as a unit of execution, meaning it is run and completed and the
results are then sent to the calling program or client tool. A sample of an anonymous
PL/SQL block is as follows:
DECLARE
Val1 NUMBER := 5;
Val2 NUMBER := 2;
TheAnswer NUMBER;
BEGIN
TheAnswer := Val1 + Val2;
DBMS_OUTPUT.PUT_LINE('The answer is ' || TheAnswer);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero!');
END;
Named PL/SQL blocks have a similar structure but allow the passing of parameters
into the block and, optionally, can return values back to the calling program. Functions
must always return a value and specify a return type, whereas procedures and triggers
do not need to. An example of the preceding anonymous PL/SQL block as a procedure
is as shown next. Note that the DECLARE keyword is not required as the declaration
section is assumed to follow the procedure name and parameter definition.
CREATE OR REPLACE PROCEDURE Add_Nums (Val1 IN NUMBER, Val2 IN NUMBER)
AS
TheAnswer NUMBER;
BEGIN
TheAnswer := Val1 + Val2;
DBMS_OUTPUT.PUT_LINE('The answer is ' || TheAnswer);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero!');
END;
To invoke the procedure and pass it the numbers to add, you would issue the
following commands in SQL*Plus, iSQL*Plus, or another client query tool that
supports Oracle:
execute Add_Nums(10,2);
Chapter 10 will provide greater insight into how to program PL/SQL to access and
manipulate Oracle databases.
Query Tools in Oracle 10g
Oracle provides two key tools to send commands to the database to query its contents,
create objects, administer the database and instance, and perform other manipulation:
SQL*Plus and iSQL*Plus. SQL*Plus is a command-line tool executed on a client
computer and is installed when the Oracle client software is installed; iSQL*Plus runs
on the same computer as the database instance and is started as a service or background
ch04.indd 15
6/30/2005 4:05:46 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
process on the host. Users access iSQL*Plus using Internet Explorer or any other
supported web browser.
SQL*Plus
SQL*Plus is a tool with a number of features that can enhance development. The
capability to save commands and use variables enables you to save and reuse common
SQL statements. The capability to customize your environment and format your output
enables you to write reports without purchasing a separate reporting tool. It is the main
tool used to start up and shut down a database instance, and it includes a set of
commands for managing the SQL*Plus environment as well as some useful shortcuts,
such as the DESCRIBE SQL*Plus command to display the structure of a database object.
In SQL*Plus your last executable SQL statement or PL/SQL block is saved in a
buffer that can be accessed and modified using the EDIT SQL*Plus command or other
statements. You can use substitution variables in SQL statements and PL/SQL blocks
to dynamically specify values for those variables when you execute the SQL statement.
SQL*Plus also includes a set of commands that enables you to save commands to script
files on disk, which can later be executed. You can also use the SPOOL SQL*Plus
command to store the results of executions for logging or other purposes.
SQL*Plus includes a number of options for the SET command that allows you to
configure your SQL*Plus environment so that it is best suited for you or affect how
output is displayed. Those commands can be saved in a file called login.sql and will
be executed whenever you start SQL*Plus to configure your SQL*Plus environment
properly. The SHOW SQL*Plus command can be used to display the current settings.
SQL*Plus also includes a set of commands that enable you to format your output and
create formatted reports. Furthermore, the DBA can restrict the commands that users
can execute in SQL*Plus by adding entries to the PRODUCT_USER_PROFILE table,
which is owned by the SYSTEM schema.
In Windows environments there are two versions of SQL*Plus: the graphical one
invoked from the Oracle program group when you install the Oracle software (called
SQLPLUSW.EXE) and the command-line version also available on all Oracle platforms
and invoked using the command sqlplus.
Exercise 4-1: Working with SQL*Plus
In this exercise you will invoke SQL*Plus from your Oracle host and execute and
format a few queries.
1. Log on to your computer as the oracle user, i.e., the user who owns the Oracle
software.
2. Invoke SQL*Plus from the command line by issuing the following command:
$ sqlplus /nolog
3. Within SQL*Plus, connect to the default database instance as the user system
with the appropriate password.
SQL> connect system/oracle
ch04.indd 16
6/30/2005 4:05:47 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
17
4. Describe the structures of the DBA_TABLESPACES and DBA_DATA_FILES tables.
5. Display the list of all tablespaces and their associated datafiles.
PART I
SQL> desc DBA_TABLESPACES;
SQL> desc dba_data_files;
SQL> SELECT DBA_TABLESPACES.tablespace_name, file_name
2 FROM DBA_TABLESPACES JOIN DBA_DATA_FILES
3 ON DBA_TABLESPACES.TABLESPACE_NAME = DBA_DATA_FILES.TABLESPACE_NAME;
6. Format the output of the filename to be 55 characters wide and the tablespace
name to be 20 characters long, and then reissue the query.
SQL>
SQL>
SQL>
2
3
col file_name format a55
col tablespace_name format a20
SELECT DBA_TABLESPACES.tablespace_name, file_name
FROM DBA_TABLESPACES JOIN DBA_DATA_FILES
ON DBA_TABLESPACES.TABLESPACE_NAME = DBA_DATA_FILES.TABLESPACE_NAME
7. Return a list of all users who own objects in the database, with each user
name appearing only once.
SQL> SELECT DISTINCT owner FROM DBA_OBJECTS;
8. Exit SQL*Plus.
SQL> exit;
iSQL*Plus
If you do not want to install the Oracle 10g client software on your computer (because
it does take up a lot of disk space), there is a way to send queries to the database as well
as execute scripts and do most things that you can do with SQL*Plus. This is by starting
and using iSQL*Plus running on the Oracle server computer and then connecting to it
using a web browser. Each installation of the Oracle 10g database will have iSQL*Plus
available, though it needs to be started on the server first.
To start iSQL*Plus on a Linux system, log in to the computer where Oracle is
installed as the oracle user, i.e., the owner of the Oracle installation, and while ensuring
that the PATH includes $ORACLE_HOME/bin, issue the command
isqlplusctl start
If you want to stop iSQL*Plus on Linux, issue the command
isqlplusctl stop
On Windows systems iSQL*Plus runs as a service and can be started and stopped
using the Services Microsoft Management Console (MMC) snap-in as shown in
Figure 4-1. You can still use the isqlplusctl command to stop and start the service
and check its status.
The best way to determine if iSQL*Plus is running, as well as to make use of it, is
to connect to it using a web browser and then specify the URL in the form http://
:/isqlplus, where server is the name or IP address of the
computer on which Oracle is running and port is the TCP port number on which
ch04.indd 17
6/30/2005 4:05:47 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
Figure 4-1 Startup and shutdown of iSQL*Plus is managed using the Services MMC snap-in in
Windows.
iSQL*Plus is listening—usually 5560, as shown in Figure 4-2. If the Oracle Universal
Installer detects that port 5560 is already in use, it will go to the next higher available
port until it finds one that is free (5561, 5562, etc.). To determine what port is being
used, you can always check the contents of the portlist.ini file in $ORACLE_HOME/
install.
EXAM TIP The default port number where iSQL*Plus is installed is 5560.
ch04.indd 18
6/30/2005 4:05:48 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
19
PART I
Figure 4-2
Use a web browser to connect to iSQL*Plus at the appropriate server port.
Once you have connected to iSQL*Plus, you need to specify an Oracle database
username, password, and connect string. The connect string is the database you want
to query and must be resolvable by the Oracle networking components of the computer
where iSQL*Plus is running. If you leave the connect string blank, an attempt to connect
to the default instance will be made, if one is defined. Once connected, you can issue
and execute queries, load and run scripts, and save the commands to history for later
recall or in a script from the main iSQL*Plus workspace shown in Figure 4-3.
ch04.indd 19
6/30/2005 4:05:49 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
Figure 4-3 The iSQL*Plus main screen allows you to execute queries against the database.
Exercise 4-2: Working with iSQL*Plus
In this exercise you will connect to iSQL*Plus on your Oracle host using a browser
and execute and format a few queries.
1. Start a web browser and connect to the iSQL*Plus URL on your Oracle
database server, specifying the appropriate port number and machine name.
ch04.indd 20
6/30/2005 4:05:50 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
21
3. In iSQL*Plus, enter the command to describe the DBA_TABLESPACES table,
and then click Execute. Do the same for the DBA_DATA_FILES table. (Hint:
You can enter both commands and then click Execute to see both results at
the same time.)
ch04.indd 21
PART I
2. At the iSQL*Plus logon, enter SYSTEM as the username and the password you
assigned as the password. Leave the Connect Identifier blank. Click the Login
button to log on.
6/30/2005 4:05:50 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
22
4. Click Clear to remove the previous commands and results, and then enter the
SQL command to display a list of all tablespaces and their associated data
files. Then click Execute.
ch04.indd 22
6/30/2005 4:05:51 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
23
ch04.indd 23
PART I
5. Modify the command to format the output of the filename to be 55 characters
wide and the tablespace name to be 20 characters long. Then reissue the
query.
6/30/2005 4:05:52 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
24
6. Clear out the previous results and then enter a command to return a list of
all users who own objects in the database, with each username appearing
only once.
ch04.indd 24
6/30/2005 4:05:53 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
25
7. Click the History tab to view your session history.
PART I
8. Click Logout on the top right to end your iSQL*Plus session.
ch04.indd 25
6/30/2005 4:05:53 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
26
Other Methods to Interface
with the Oracle Database
SQL*Plus and iSQL*Plus are not the only methods to interface with the Oracle database
and manipulate the objects within it. Oracle databases can be accessed using Java and
JDBC, programmatically using the Oracle Call Interface (OCI) application programming
interface (API) and several other object interfaces and APIs, as well as by writing SQL
statements in your 3GL code and then using precompilers like Pro*C++ to produce
valid run-time calls.
Java in Oracle
Java is an industry-standard object-oriented programming language developed by
Sun Microsystems. One of its major strengths is the ability to write programs on
one supported Java platform, such as Windows, and have that code execute on other
supported Java platforms. This is possible because Java includes a concept of a Java
Virtual Machine, or JVM, which executes the code. The JVM runs on the target operating
system but presents the same objects to the Java application, meaning that the
programmer does not have to worry about programming for Windows or Unix—
only about programming for the JVM.
Oracle has provided Java support since Oracle 8 and continues to enhance the Java
capabilities of the database. Oracle 10g includes a JVM in the database (as did Oracle 8,
8i, and 9i) and allows you to program stored procedures and functions in Java that can
be called from PL/SQL, and vice versa, by using Java Database Connectivity (JDBC).
This provides the ability to make use of Java code and PL/SQL code interchangeably
within the same database, and it is something that Oracle itself does. The JVM is
installed and configured in the database when you create the database using the
Database Configuration Assistant or run the appropriate scripts.
EXAM TIP Oracle Database 10g includes a Java VM used to execute Java
stored procedures and functions stored in the database. JDBC is used by
the built-in JVM to manipulate database data.
Oracle Call Interface (OCI)
If you want to write C code in the same API that many of the Oracle tools and other
programs are written in, you can make use of the Oracle Call Interface (OCI). OCI is
a relatively low-level and complex API for advanced C and C++ programmers. Its main
advantage is that it provides precise control over what is sent to Oracle and how the
results are interpreted, and provides the best performance. In fact, all other Oracle APIs
are built on top of OCI and make extensive use of it. Programming using OCI is the
most efficient way to make use of third-generation languages (3GLs) like C and C++
for interfacing with Oracle.
ch04.indd 26
6/30/2005 4:05:54 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
27
PART I
EXAM TIP OCI is the fastest but the most difficult API to write Oracle
applications in.
Other APIs
Oracle does not exist in a vacuum and needs to provide programmers with methods to
interface with Oracle that make the most sense in their environments. For this reason,
a number of other APIs are released and supported by Oracle, including these:
• Java Database Connectivity (JDBC) Oracle exposes the database for access
by Java-based programs using JDBC. This means that developers can write
programs in Java and query and manipulate Oracle databases by making a
thin-client JDBC connection to Oracle. In fact, running Java stored procedures
and functions in the Oracle JVM also makes use of JDBC to connect to the
SQL engine within the Oracle database.
• Pro*C/C++ and Pro*/COBOL Before the advent of PL/SQL and from
the earliest days of the Oracle database, programmers had embedded SQL
statements within their C or COBOL code and then run that code through
a precompiler to produce code that would include run-time library calls for
database access and compile properly with the C, C++, or COBOL compiler
they were using. Pro*C/C++ and Pro*COBOL continue to be valid ways to
embed SQL statements in 3GLs.
• Oracle C++ Call Interface (OCCI) C++ provides an object-oriented approach
to programming, and OCCI provides object-oriented access to the Oracle
database for C++ programmers. OCCI exposes many of the low-level functions
of OCI while being easier for C++ programmers to work with than Pro*C++.
• Open Database Connectivity (ODBC) ODBC is a standard developed by
Microsoft in the late 1980s to provide generic database access. It is still widely
used by many programmers in Microsoft-centric organizations, though faster
methods like .NET managed providers exist. In order to make use of ODBC
to access an Oracle database, the Oracle 10g networking components must be
installed on the computer running the ODBC-based application.
• Oracle Data Provider for .NET (ODP.NET) With the introduction of Visual
Studio .NET, Microsoft also changed the way database access was handled in
.NET-based applications. ODP.NET is a managed provider for Oracle database
access that can be used in applications developed to the Microsoft .NET
Framework.
• Oracle Objects for OLE (OO4O) Before .NET Microsoft Windows
applications were written to take advantage of Object Linking and Embedding
(OLE). OO4O allows for access to data stored in an Oracle database from pre-
ch04.indd 27
6/30/2005 4:05:55 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
28
.NET languages such as Visual Basic 6 or from any Microsoft-based scripting
language such as Active Server Pages (ASP) or Visual Basic for Applications (VBA).
EXAM TIP Developers using the Windows platform can program applications
to access Oracle data using ODP.NET, OO4O, and ODBC, as well as any of
the other APIs mentioned.
Oracle continues to enhance the methods that can be used to interface to the
database and also has added support for access to Oracle data using FTP, HTTP, and
Web Distributed Authoring and Versioning (WebDAV) when the XML DB feature of
Oracle is installed and configured.
Chapter Review
Oracle provides a number of mechanisms to interact with the database and its data,
including the SQL language, PL/SQL, Java, and other lower-level APIs such as OCI,
OO4O, and ODP.NET, to name a few.
SQL is composed of three languages: DDL for creating and managing objects; DCL
for granting and revoking permissions; and DML for adding, changing, and deleting
data. Transaction control statements, including COMMIT and ROLLBACK, are used to
control how data is saved to the database. SAVEPOINTs can be used to logically break a
transaction into subparts that can be committed should later parts of the transaction fail.
PL/SQL contains language elements allowing a programmer to define variables
and other identifiers, perform looping, conditionally execute statements according to
the results of previous executions or the values of variables, and take advantage of other
features familiar to programmers of any language. It is the foundation for programming
powerful applications for Oracle. PL/SQL requires a PL/SQL engine for execution,
which exists in the Oracle 10g database.
When executing queries against the database or PL/SQL blocks, you can make use
of SQL*Plus on the client computer or iSQL*Plus using a web browser and connecting
to the database server. Both provide similar functionality, but iSQL*Plus does not
require that Oracle client software be installed on your computer.
Java can also be used to program database applications for Oracle. Oracle includes
a Java Virtual Machine, allowing developers to create and execute Java procedures and
functions in the database. JDBC is used to access and manipulate database data
from Java.
Lower-level APIs can also be used to program applications that access an Oracle
database. The Oracle Call Interface (OCI) is the fastest and most complicated of these;
others include OO4O, ODP.NET, and ODBC, as well as precompilers such as Pro*C/
C++ and Pro*COBOL.
ch04.indd 28
6/30/2005 4:05:56 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
29
Questions
PART I
1. You want to create an anonymous PL/SQL block to access data in your database
based upon the value of a variable. In which section of the PL/SQL block would
you need to define the variable? (Choose the best answer.)
A. Declaration section
B. Definition section
C. Includable section
D. Executable section
E. Exception section
2. Which of the following APIs can you use to program an application on the
Windows platform to access an Oracle database? (Choose all correct answers.)
A. PL/SQL
B. Oracle Objects for OLE
C. Oracle Call Interface
D. Java
E. Oracle Data Provider for .NET
3. Given the following SQL statement, which line of code will cause the statement
to fail? (Choose the best answer.)
1
2
3
4
SELECT LastName, FirstName, Email
FROM Customers, EmailUsers
ON Customers.UserName = EmailUsers.UserName
ORDER BY LastName ASC
A. 1
B. 2
C. 3
D. 4
E. The statement will succeed
4. You need a mechanism to import data into Oracle from a legacy application
and, using a value in one of the columns in the source data, add the row to
one of several tables in your database. Which of the following can you use
to satisfy your requirements? (Choose two correct answers.)
A. PL/SQL
B. MERGE INTO
C. UPSERT
D. INSERT
E. INSERT ALL
F. INSERT FIRST
ch04.indd 29
6/30/2005 4:05:56 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
30
5. Which of the following is not a valid SQL command? (Choose all correct
answers.)
A. SELECT
B. COLUMN
C. ROLLBACK
D. DESCRIBE
E. SAVEPOINT
6. Which of the following SQL statements will cause a transaction to be started?
(Choose two correct answers.)
A. INSERT
B. SELECT
C. COMMIT
D. SAVEPOINT
E. DELETE
F. ROLLBACK
7. You issue the following SQL statement against your database to change the
price of SKU 347711 from $90.75 to $99.75 without committing the change.
At the same time another user queries the value of the same SKU. What will
the result of that user’s query be?
UPDATE Products SET MSRP = 99.75 WHERE SKU=347711
A. $90.75
B. $99.75
C. The user will wait until you commit your transaction before being
displayed a value
D. Oracle will return the error “ORA-20001: Current row locked by another
process”
8. You attempt to connect to iSQL*Plus on your Oracle database server running
on Linux and receive an error in your browser that the page cannot be opened.
You suspect that iSQL*Plus is not started on the database server. Which of the
following commands can you use to start the process? (Choose the best answer.)
A. emctl start isqlplus
B. emctl startup isqlplus
C. isqlplusctl startup
D. isqlplusctl start
E. isqlplus start
ch04.indd 30
6/30/2005 4:05:57 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 4: Interfacing with the Oracle Database
31
A. Java Virtual Machine
PART I
9. Which of the following make it possible for Java procedures created and
compiled in the Oracle 10g database to access data in the same database?
(Choose the best answer.)
B. JDBC
C. PL/SQL engine
D. SQL engine
E. Java procedures cannot access database data in Oracle
10. On which line will the following PL/SQL block fail? (Choose the best answer.)
1
2
3
4
5
DECLARE
vNum NUMBER := 100;
BEGIN
vNum = vNum / 10;
END;
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed
Answers
1. A. You need to define all variables in your anonymous PL/SQL block following
the DECLARE keyword in the declaration section of the PL/SQL block. The
definition and includable sections do not exist. The executable section starts
with the BEGIN keyword and includes the code being executed. The exception
section is used to trap for expected errors in the code and starts with the
EXCEPTION keyword.
2. B, C, and E. Any of the APIs available for Oracle can be used to program a
Windows application to access Oracle data, including OO4O, OCI, ODP.NET,
ODBC, and JDBC. You can also use precompilers to embed SQL code in your
3GL code. PL/SQL and Java are not APIs but programming languages and are
therefore incorrect, since the question asked you to identify the APIs.
3. C. This SQL statement mixes classic join syntax with ANSI join syntax, making
it invalid. The ON keyword can be used only in ANSI join syntax and must be
preceded by the JOIN keyword between the table names. In classic join syntax
the WHERE clause is used to specify the join condition and the ON keyword
is invalid.
ch04.indd 31
6/30/2005 4:05:57 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
32
4. A and F. Because you need to add data to one of several tables, you need to
perform conditional logic on each of the rows in the source table as they
are read and then insert that row into the appropriate table. PL/SQL is a
programming language with conditional logic capabilities and can be used to
perform this task. You can also use the INSERT FIRST statement, which will
add the data to the first table matching the conditions specified. INSERT ALL
may insert data into more than one table, since all conditions are evaluated,
whereas INSERT cannot perform any conditional logic. MERGE INTO performs
an UPDATE and INSERT based upon data in an existing table, and there is no
UPSERT statement in Oracle SQL.
5. B and D. COLUMN and DESCRIBE are not valid SQL statements but are valid
SQL*Plus and iSQL*Plus commands to format the display of a column or
provide information on the structure of a database object. SELECT, ROLLBACK,
and SAVEPOINT are valid SQL commands in Oracle.
6. A and E. A transaction is started by any valid DML statement, including INSERT,
UPDATE, and DELETE. A SELECT statement will execute a query against the
database but not start a transaction. ROLLBACK and COMMIT will end a
transaction but start another one. SAVEPOINT defines a named marker in
your transaction that allows data before it to be committed and following it
to be rolled back when the ROLLBACK TO savepoint statement is issued.
7. A. Oracle allows users to query the database even if changes to the data being
queried are in process. The values returned will be those committed to the
database at the time the query was issued, which in this case is $90.75, since
the UPDATE was not yet committed.
8. D. The command to start iSQL*Plus on a Unix environment is isqlplusctl
start. The emctl command is used to start Oracle Enterprise Manager and
its controls and cannot be used to start iSQL*Plus. C and E are not correct
syntax for starting iSQL*Plus.
9. B. Java Database Connectivity is used by Java procedures and functions created
in the Oracle database to access the database data. The Java code will run in
the JVM and then make JDBC calls for database data. The PL/SQL engine is
not involved with Java in Oracle. The SQL engine is what JDBC uses to parse
and execute the queries and send the results back to the Java code in the JVM.
10. D. The assignment operator in PL/SQL is := and not just the equal sign. The
equal sign (=) is a comparison operator. The rest of the PL/SQL block is valid.
ch04.indd 32
6/30/2005 4:05:58 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
CHAPTER 5
Managing Oracle Processes
In this chapter you will learn how to
• Control the database
• Start and stop iSQL*Plus
• Start and stop Enterprise Manager Database Control
• Start and stop the Oracle Listener
• Start up and shut down Oracle Database 10g
• Describe startup and shutdown options for the Oracle database
• Handle parameter files
• Locate and view the database alert log
1
ch05.indd 1
5/18/2005 11:19:07 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
A number of processes are required for an Oracle server to be working, and usable. To
begin with, you need a user process. This is the process that the end user runs: in the
last chapter, you saw SQL*Plus and iSQL*Plus, but of course for a production system
with a full user interface, the user process will be much more complicated than either
of those. Then there is the management process, in our case Database Control; the
Database Listener, a process that responds to connection requests from remote user
processes; and finally, the background processes that make up the instance itself. In
this chapter, you will go through starting these processes and then look at how the
database itself is opened for use.
Starting SQL*Plus
This couldn’t be simpler. SQL*Plus is just an elementary process for issuing ad hoc
SQL commands to a database. It is a client/server tool. On Windows systems, you
have a choice between the character-based version, SQLPLUS.EXE, and the graphical
version, SQLPLUSW.EXE. Both can be launched from a command prompt, or the
standard installation of Oracle will have created a shortcut to SQLPLUSW.EXE in your
Start menu. On Unix, there is just the one version, called sqlplus. On either operating
system you will find the executable program in your ORACLE_HOME/bin directory.
A variation you need to be aware of is the NOLOG switch. By default, the
SQL*Plus program immediately prompts you for an Oracle username, password,
and database connect string. This is fine for regular end users, but it is useless for
database administrators because it requires that the database be already open. To
launch SQL*Plus without a login prompt, use the /NOLOG switch:
sqlplus /nolog
or for the Windows GUI version:
sqlplus w /nolog
This will give you a SQL prompt, from which you can connect with a variety of syntaxes,
to be detailed in the sections that follow.
Starting iSQL*Plus
The iSQL*Plus program is a graphical version of SQL*Plus that runs as an Application
Server service. End users connect to it from a browser, such as Internet Explorer.
Conceptually, it is identical to SQL*Plus: it is a user process for issuing ad hoc SQL. The
difference is that whereas the SQL*Plus user process is a single process on the client
machine, iSQL*Plus divides the user process into two layers: a user interface layer
running in the user’s browser, which handles the bare bones of the graphical user
interface (local window management, tracking mouse movements, keyboard control,
and so on), and the application layer, which runs (typically) on a central server. It is
ch05.indd 2
5/18/2005 11:19:15 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
3
isqlplusctl start
and stop it with
PART I
this application layer product that we need to launch. Once running, it can be used by
any browser anywhere. On Unix or Windows, launch the iSQL*Plus server with
isqlplusctl st op
Alternatively, on Windows, you can start the iSQL*Plus server as a service, either
through the Windows or from the command line with net start.
To contact iSQL*Plus, issue the URL
http://:/isqlplus
GUI as shown in Figure 5-1, where is the address of the
machine hosting your Oracle installation, and is the IP port on which
the iSQL*Plus server is listening. By default, this will be port 5560, but if your
installation is nonstandard, it may be something different. Check the file
portlist.ini in your ORACLE_HOME/install directory to see which port was
Figure 5-1 The iSQL*Plus logon screen—note the URL.
ch05.indd 3
5/18/2005 11:19:16 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
selected by the installer at install time. The iSQL*Plus tool is in fact implemented as
a stand-alone OC4J application. (OC4J, Oracle Components for Java 2 Enterprise
Edition, is Oracle’s run-time environment for Java, normally shipped as part of the
Application Server.)
TIP Note that iSQL*Plus is a little more effort to start than SQL*Plus, but it
can be vastly more convenient to use. For example, column formatting is much
better. Furthermore, you do not need a single line of Oracle code installed on
your client machine; all you need is a browser.
Starting the Database Listener
You will look at the Database Listener in much greater detail in Chapter 12, but for
now, be content with just stopping and starting it, and checking its status. From the
command line, use the Listener Control utility:
lsnrctl start
lsnrctl stop
lsnrctl status
The will default to LISTENER, and unless you have created additional
listeners with different names, this will be fine, so you can leave it out.
Alternatively, if you have Database Control running, you can use it to control the
listener instead of using the command-line utility. From the Database home page, click
the listener name to go to the listener’s home page and stop or start it from there. Finally,
if you are using Windows, you can control the listener as a Windows service.
If your Database Listener is not running, no clients will be able to connect unless
they are logged on to the server machine and are running their user process there,
locally to the database. In particular, Database Control will not be able to connect to
the database if the listener is not running. However, note that if you stop the listener,
this will not affect already established sessions; it will mean only that no new sessions
can be established.
Starting the Database Control Daemon
Enterprise Manager Database Control is an alternative to Enterprise Manager Grid
Control. Unlike Grid Control, Database Control is limited to administering one
database at a time, whereas Grid Control can be used to manage numerous databases
at once, as well as application servers. Database Control is a web tool, consisting of
tables and procedures within the database (you created these as part of the database
creation process) and an OC4J application running on your database server. If there
are multiple databases on the same server, you will need one running instance of the
OC4J program for each one. You will contact them on a different port for each
ch05.indd 4
5/18/2005 11:19:16 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
5
emctl start dbconsole
PART I
database. As with iSQL*Plus, your browser provides the user interface: the local window
management and so on.
To start the Database Control process, whatever your platform, use the emctl utility:
and to stop the daemon or see if it is running,
emctl sto p dbconsole
emctl stat us dbconsole
Alternatively, on Windows where emctl runs as a service, if you wish you can control
it from the Services MMC snap-in, or the Computer Management MMC console.
However, there are some possible complications, as shown in Figure 5-2.
First, if there are multiple databases on your server, you must set the ORACLE_
SID environment variable before starting Database Control. Second, Database Control
does not like DHCP, or any other reason for changing the address of the server. Of
course, this is not a problem for production systems, but it can be very annoying if
you are using a laptop that is sometimes connected to a network and sometimes
not. For this example in the figure, the database called ocp10g (there was already a
database called orcl10g on the computer) was created while not attached to a network.
Database Control therefore used a directory named after the localhost for its
configuration data. Then the computer connected to a network, picked up a DHCPissued address, and the user tried to start the dbconsole. As you can see, the first
attempt to start dbconsole failed because the user had not set his ORACLE_SID
environment variable. He fixed that and tried again; it then failed because Database
Control next looked for its configuration information in a nonexistent directory
whose name was derived from the newly acquired IP address. Then the user unplugged
Figure 5-2 Some dbconsole startup problems
ch05.indd 5
5/18/2005 11:19:16 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
the network lead, and dbconsole started successfully. Your server should be configured
with a static IP address to avoid this problem.
TIP An undocumented environment variable, EMHOSTNAME, may help
with changing an IP address. Set it to point to your local machine name before
creating any databases, and then dbconsole should always look for
that directory name for its config data.
Once the process is running, you contact it with the URL
http://:/em
where is the address of your database server, as shown in Figure 5-3.
The port will default to 5500 for your first database on the computer, 5501 for your
second, and so on. If in any doubt, check the portlist.ini file as you did for iSQL*Plus.
TIP There is a link in Database Control to navigate to iSQL*Plus.
Figure 5-3 Database Control logon, showing the SYSDBA privilege selected. Note the URL.
ch05.indd 6
5/18/2005 11:19:17 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
7
To be precise, one does not start or stop a database: an instance may be started and
stopped; a database is mounted and opened, and then dismounted and closed. This
can be done from either SQL*Plus, using the STARTUP and SHUTDOWN commands,
or through Database Control. The alert log will give details of all such operations.
PART I
Database Startup and Shutdown
Connecting with an Appropriate Privilege
Ordinary users cannot start up or shut down a database. This is because an ordinary
user is authenticated against the data dictionary, and it is logically impossible for an
ordinary user to start up (or create) a database, since the data dictionary cannot be
read until the database is open. You must therefore connect with some form of external
authentication, as discussed in Chapter 3: you must be authenticated either by the
operating system, as being a member of the group that owns the Oracle software,
or by giving a username/password combination that exists in the external password
file. You tell Oracle that you wish to use external authentication by using appropriate
syntax in the CONNECT command that you give in your user process. If you are
using Database Control, it is easy: in the Connect As combo box you select either
SYSOPER or SYSDBA (the difference will be defined shortly).
Database Control does not give you the option of using operating system
authentication. This is because it always connects via a listener, as though it were
a remote process. If your listener is not running or does not recognize the database
you wish to connect to, you will not be able to use Database Control. If you are
using SQL*Plus, the syntax of the CONNECT command tells Oracle what type
of authentication you wish to use: the default of data dictionary authentication
(“Normal” in Database Control parlance), password file, or operating system.
These are the possibilities:
connect
connect
connect
connect
connect
user/pass[@db]
user/pass[@db] as sysdba
user/pass[@db] as sysoper
/ as sysdba
/ as sysoper
The first example is normal, data dictionary, authentication. Oracle will validate
the username/password combination against values stored in the data dictionary. The
database must be open. Anyone connecting with this syntax cannot—no matter who
he is—issue startup or shutdown commands. The second two examples instruct Oracle
to go to the external password file to validate the username/password combination.
The last two examples use operating system authentication: Oracle will go to the host
operating system and check whether the operating system user running SQL*Plus is a
member of the operating system group that owns the Oracle software, and if the user
passes this test, he will be logged on as SYSDBA or SYSOPER without any need to give
a username and password. A user connecting with any of the bottom four syntaxes will
be able to issue startup and shutdown commands and will be able to connect no matter
what state the database is in—it may not even have been created yet. Note that the first
ch05.indd 7
5/18/2005 11:19:17 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
three examples can include a database connect string: this is necessary if the connection
is to be made across a network. Naturally, this is not an option for operating system
authentication, because operating system authentication relies on the user’s being
logged on to the machine hosting the Oracle server: he must either be working on
it directly or have logged in to it with telnet or some similar utility.
SYSOPER and SYSDBA
These are special privileges with special capabilities. They can be enabled only when
users are connecting with an external authentication method. SYSOPER has the ability
to issue these commands:
STARTUP
SHUTDOWN
ALTER DATABASE [MOUNT | OPEN | CLOSE | DISMOUNT]
ALTER [DATABASE | TABLESPACE] [BEGIN | END] BACKUP
RECOVER
The SYSDBA privilege encompasses all of these commands but in addition has
the ability to create a database, to do an incomplete recovery, and to create other
SYSOPER and SYSDBA users.
EXAM TIP SYSDBA and SYSOPER are not users; they are privileges that can
be granted to users. By default, only user SYS has these privileges.
You may be wondering what Oracle user you are actually logging on as when you
use operating system authentication. To find out, from a SQL*Plus prompt connect
using the operating system authentication syntax just shown and then issue the show
user command, as in Figure 5-4.
Figure 5-4 Use of external authentication
ch05.indd 8
5/18/2005 11:19:17 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
9
PART I
As you see, use of the SYSDBA privilege logs you on to the instance as user SYS, the
most powerful user in the database and the owner of the data dictionary. Use of the
SYSOPER privilege connects you as a user PUBLIC. PUBLIC is not a user in any normal
sense but a notional user with administration privileges but (by default) no privileges
that let him see or manipulate data. You should connect with either of these privileges
only when you need to carry out procedures that no normal user can do.
Startup
Remember that the instance and the database are separate entities: they can exist
independently of each other. The startup process is therefore staged: first you build
the instance in memory, second you enable a connection to the database by mounting
it, and third you open the database for use. At any moment, a database will be in one
of four states:
• SHUTDOWN
• NOMOUNT
• MOUNT
• OPEN
When the database is in SHUTDOWN mode, all files are closed and the instance
does not exist. In the NOMOUNT mode, the instance has been built in memory (the
SGA has been created and the background processes started, according to whatever
is specified in its parameter file) but no connection has been made to a database.
It is indeed possible that the database does not yet exist. In MOUNT mode, the
instance locates and reads the database control file. In OPEN mode, all database
files are located and opened and the database is made available for use by end users.
The startup process is staged: whenever you issue a startup command, it will go
through these stages. It is possible to stop the startup part way. For example, if your
control file is damaged, or a multiplexed copy is missing, you will not be able to
mount the database, but by stopping in NOMOUNT mode, you may be able to
repair the damage. Similarly, if there are problems with any datafiles or redo log
files, you may be able to repair them in MOUNT mode before transitioning the
database to OPEN mode.
At any stage, how does the instance find the files it needs, and exactly what happens?
Start with NOMOUNT. When you issue a startup command, Oracle will attempt to
locate a parameter file. There are three default filenames. On Unix they are
$ORACLE_HOME/dbs/spfile.ora
$ORACLE_HOME/dbs/spfile.ora
$ORACLE_HOME/dbs/init.ora
and on Windows,
%ORACLE_HOME %\database \SPFILE.ORA
%ORACLE_HOME %\database \SPFILE.ORA
%ORACLE_HOME %\database \INIT.ORA
ch05.indd 9
5/18/2005 11:19:18 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
TIP The spfile.ora file is undoubtedly the most convenient file to
use as your parameter file. Normally, you will use spfile.ora only in a RAC
environment, where one file may be used to start several instances.You will
use an init.ora file only if for some reason you need to make manual
edits: spfiles are binary files and cannot be edited by hand.
In all cases, refers to the name of the instance which the parameter file will
start. This search order is important! Oracle will work its way down the list, using the
first file it finds and ignoring the rest. If none of them exist, the instance will not start.
The only files used in NOMOUNT mode are the parameter file and the alert log. The
parameters in the parameter file are used to build the SGA in memory and to start the
background processes. Entries will be written out to the alert log describing this process.
Where is the alert log? In the location given by the BACKGROUND_DUMP_DEST
parameter. If the log already exists, it will be appended to. Otherwise, it will be created.
If any problems occur during this stage, trace files may also be generated in the same
location.
EXAM TIP An “init” file is known as a “static” parameter file, because it
is read only once, at instance startup. An “spfile” is known as a “dynamic”
parameter file, because Oracle continuously reads and updates it while the
instance is running.
Once the instance is successfully started in NOMOUNT mode, it may be transitioned
to MOUNT mode by reading the controlfile. It locates the controlfile by using the
CONTROL_FILES parameter, which it knows from having read the parameter file used
when starting in NOMOUNT mode. If the controlfile (or any multiplexed copy of it) is
damaged or missing, the database will not mount and you will have to take appropriate
action before proceeding further. All copies of the controlfile must be available and
identical if the mount is to be successful.
As part of the mount, the names and locations of all the datafiles and online
redo logs are read from the controlfile, but Oracle does not yet attempt to find them.
This happens during the transition to OPEN mode. If any files are missing or damaged,
the database will remain in MOUNT mode and cannot be opened until you take
appropriate action. Furthermore, even if all the files are present, they must be
synchronized before the database opens. If the last shutdown was orderly, with all
database buffers in the database buffer cache being flushed to disk by DBWn, then
everything will be synchronized: Oracle will know that all committed transactions
are safely stored in the datafiles, and that no uncommitted transactions are hanging
about waiting to be rolled back. However, if the last shutdown was disorderly (such
as a power cut, or the server being rebooted), then Oracle must repair the damage.
(You will go into the mechanism for this in Chapter 20.) The process that mounts
and opens the database (and carries out repairs, if the previous shutdown was
disorderly) is the SMON. Only after the database has been successfully opened
will Oracle permit user sessions to be established.
ch05.indd 10
5/18/2005 11:19:18 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
11
PART I
Shutdown should be the reverse of startup. During an orderly shutdown, the
database is first closed and then dismounted, and finally the instance is stopped.
During the close phase, all sessions are terminated: active transactions are rolled back
by PMON, completed transactions are flushed to disk by DBWn, and the datafiles and
redo log files are closed. During the dismount, the controlfile is closed. Then the
instance is stopped by deallocating the SGA and terminating the background processes.
Now look at the syntax for startup and shutdown, beginning with how to connect.
Exercise 5-1: Starting Up and Shutting Down
Your Database with SQL*Plus
Use SQL*Plus to start and stop the database. Alternatively, if your database is already
running, stop it and then restart it with SQL*Plus. If you are working on Windows,
make sure that the Windows service is running. It will be called
OracleServiceOCP10g
if your instance is called OCP10g. Start it through the Windows GUI, or from a
command prompt with
net start OracleServiceOCP10g
The sequence of SQL*Plus commands is shown in Figure 5-5.
TIP The Windows service may be configured to start the instance and open
the database whenever you start the service.You can control this with the
Registry variable ORA_OCP10G_AUTOSTART, setting it to TRUE or FALSE.
1. Launch SQL*Plus, using the /nolog switch.
sqlplusw /nolog
2. Connect with operating system authentication.
connect / as sysdba
3. Start the instance only.
startup nomount;
4. Mount the database.
alter database mount;
5. Open the database.
alter database open;
6. Shut down, using the immediate option.
shutdown immediate;
7. Connect with password file authentication.
connect sys/oracle as sysdba;
ch05.indd 11
5/18/2005 11:19:18 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
8. Perform a complete startup, with one command.
startup;
9. Show the BACKGROUND_DUMP_DEST parameter.
show parameter background_dump_dest;
10. Navigate to the directory identified by the BACKGROUND_DUMP_DEST
parameter. In it you will find your alert log, called alert_.log.
11. Open the alert log with any editor you wish and look at the last few dozen
lines. You will see a history of the startup and shutdown commands, as well
as information about the starting and stopping of the various background
processes and a listing of the nondefault parameters read from the parameter
file and used to build the instance in memory.
Figure 5-5 Startup/shutdown exercise
ch05.indd 12
5/18/2005 11:19:19 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
13
Shutdown
shutdown [normal | transactional | immediate | abort]
PART I
There are options that may be used on the shutdown command:
• Normal This is the default. No new user connections will be permitted,
but all current connections are allowed to continue. Only once all users
have (voluntarily!) logged off will the database actually shut down.
TIP Typically, a normal shutdown is useless: there is always someone logged
on, even if it is only Database Control itself.
• Transactional No new user connections are permitted; existing sessions that
are not in a transaction will be terminated; sessions currently in a transaction
are allowed to complete the transaction and will then be terminated. Once all
sessions are terminated, the database will shut down.
• Immediate No new sessions are permitted, and all currently connected
sessions are terminated. Any active transactions are rolled back, and the
database will then shut down.
• Abort As far as Oracle is concerned, this is the equivalent of a power cut.
The instance terminates immediately. Nothing is written to disk; no file
handles are closed; there is no attempt to terminate transactions that may
be in progress in any orderly fashion.
TIP Using shutdown abort will not damage the database but will leave it in
an inconsistent state; therefore, some operations (such as backups) are not
advisable after an abort.
The “normal,” “immediate,” and “transactional” shutdown modes are usually
referred to as “clean,” “consistent,” or “orderly” shutdowns. After all sessions are
terminated, PMON will roll back any incomplete transactions. Then a checkpoint is
issued (remember the CKPT process from Chapter 3?), forcing the DBWn process to
write all updated data from the database buffer cache down to the datafiles. LGWR
also flushes any change vectors still in memory to the logfiles. Then the file headers
are updated, and the file handles closed. This means that the database is in a
“consistent” state: all committed transactions are in the datafiles, there are no
uncommitted transactions hanging about that need to be rolled back, and all
datafiles and logfiles are synchronized.
The “abort” mode, often referred to as a “disorderly” shutdown, leaves the database
in an “inconsistent” state: it is quite possible that committed transactions have been
lost, because they existed only in memory and DBWn had not yet written them to the
datafiles. Equally, there may be uncommitted transactions in the datafiles that have
ch05.indd 13
5/18/2005 11:19:19 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
not yet been rolled back. This is the definition of a corrupted database: it may be
missing committed transactions, or storing uncommitted transactions. These corruptions
must be repaired by instance recovery. It is exactly as though the database server had
been switched off, or perhaps rebooted, while the database was running.
Instance Recovery
You will find a full treatment of instance recovery in Chapter 20. For now, accept
that the mechanisms of rollback and redo make it impossible to corrupt an Oracle
database. DBAs do not say this just because they happen to work with Oracle; they
say it because it is a fact. You can do horrible things to Oracle databases, but you
will never manage to corrupt one. The mechanism of instance recovery absolutely
guarantees that the database cannot be corrupted: committed transactions will
always be reinstated; uncommitted transactions will always be backed out. If for
some reason (always involving damage to disk files, which is out of Oracle’s control)
the instance recovery fails, then the database will not open until you have repaired
the damaged files through the restore and recover routines that we deal with in later
chapters. This impossibility of corruption is why people buy the Oracle database,
and likewise why it isn’t cheap.
EXAM TIP If Oracle detects that instance recovery is necessary, it will happen
automatically. There is no way to initiate it (or to cancel it) manually.
When an instance attempts to open a database, the SMON process checks the state
of the datafiles and of the online redo log files. If the shutdown was disorderly, the
fact will be immediately apparent at this time, and SMON will initiate the instance
recovery process. Only once this has completed will the database open. Conversely, if
the shutdown was orderly, SMON will detect this and open the database immediately.
Thus you can always guarantee that an opened database has no corruptions, but the
shutdown method chosen determines when corruptions are repaired.
With an orderly shutdown (normal, transactional, or immediate), any possible
problems are fixed during the shutdown: incomplete transactions are rolled back,
committed transactions are saved. The shutdown may take some considerable time
as this is done, but the startup will be fast. With a disorderly shutdown (an abort, or
perhaps a hardware failure or operating system crash) the shutdown is instantaneous,
but the startup will be delayed while any problems are fixed by the instance recovery.
It is possible to tune the speed of the shutdown/startup cycle, which will impact on
the mean-time-to-recover, or MTTR, after a failure. The MTTR will often be specified
in service level agreements.
ch05.indd 14
5/18/2005 11:19:19 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
15
As in Exercise 5-1, become familiar with starting and stopping the instance and
opening and closing the database.
PART I
Exercise 5-2: Starting Up and Shutting Down
Your Database with Database Control
1. Ensure that your Database Listener and Database Control processes are
running, by entering
lsnrctl status
emctl status dbconsole
from an operating system prompt.
2. Launch your browser, and contact Database Control with the appropriate
URL, such as
http://127.0.0.1:5501/ em
3. Log on as in Figure 5-3. Click the SHUTDOWN button. Type in both operating
system credentials and database credentials, as shown in Figure 5-6, and click OK.
TIP On Windows, the operating system account you use must have been
granted the “Logon as a Batch Job” privilege. Note that by default, not even
the Windows Administrator account has this privilege! Refer to your Windows
documentation on how to grant this privilege; there are changes with different
releases. On both Windows and Unix, the account should be a member of the
group that owns the Oracle software.
4. Click Yes for an immediate shutdown. Note that the Advanced Options tab
gives a choice of all four shutdown modes.
5. Refresh your browser (it may take a few moments) and you will see the screen
shown in Figure 5-7.
6. Click Startup, and enter credentials as in Figure 5-6.
7. Click Yes to accept the default startup mode, which is “open.”
TIP When you start and stop the database, Database Control does
sometimes get confused about whether the database is actually up or down.
This is perhaps hardly surprising, when you consider that a large part of
Database Control actually resides within the database itself. If you realize
(and it will be obvious) that this has happened, simply stop and start the
dbconsole process with emctl, and reconnect with your browser.
ch05.indd 15
5/18/2005 11:19:20 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
8. When the database has opened, dbconsole will present you with a login
screen. Log in as user SYSTEM.
9. From the database home page, take the Alert Log Content link in the
Related Links section at the bottom of the page and examine the contents
of the alert log.
Figure 5-6 Oracle and OS credentials in dbconsole
ch05.indd 16
5/18/2005 11:19:20 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
17
PART I
Figure 5-7 The dbconsole startup screen
The Initialization File
In Chapter 3, you saw a static initialization parameter file, init.ora. This was the
only type of initialization file supported until release 9i of the Oracle database, but
from 9i onward if you wish you can use a dynamic initialization file, spfile.ora.
Most database administrators prefer to work with the dynamic file, and if you created
your database with DBCA, your static file will have been converted to a dynamic file
at the end of the creation process by the script postDBCreation.sql. If you examine
this script, the conversion process is self-explanatory.
To view parameters, a static file can be inspected with any text editor you please,
but a dynamic spfile can be inspected only from within the Oracle environment: it
contains nonprintable characters and should never be edited by hand.
ch05.indd 17
5/18/2005 11:19:20 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
Exercise 5-3: Viewing Parameters
with Database Control
In this exercise, you will look at your parameter settings and distinguish between the
basic and advanced parameters.
1. Launch your browser, and log on to your instance through Database Control.
2. From the database home page, take the Administration tab.
3. In the Instance section, take the All Initialization Parameters link.
4. Inspect the values of the parameters used to control your instance. Note that
of the more than two hundred and fifty parameters, less than thirty are classed
as “basic.”
Chapter Review
In this chapter you’ve gone through the details of launching the various processes
involved in an Oracle database and its management. Remember that we have not
covered the Grid Control—that is beyond the scope of this book, and of the examination.
The database itself doesn’t have any processes: it is simply a set of files. The processes
are part of the instance, and you start them with a STARTUP command, issued from
SQL*Plus, or through Database Control. The instance is defined by parameters in an
initialization parameter file. The instance then attaches to a database: first it mounts
the database, by reading the controlfile, and then it opens the database, by reading the
datafiles and redo log files. In addition to starting the instance (and preferably before
you start it), you must also start the Database Listener. Without a listener, you will not
be able to connect with Database Control. The control processes are either Database
Control, which requires you to start the OC4J engine within which it runs, or SQL*Plus,
which runs as a self-contained program. An alternative to SQL*Plus is iSQL*Plus, an
application server process that lets you connect to a database from a browser.
Questions
1. Which of the following commands will start the iSQL*Plus server process?
(Choose the best answer.)
A. emctl start isqlplus
B. isqlplusctl start
C. isqlplus /nolog
D. lsnrctl start isqlplus
2. You issued the URL http://127.0.0.1:5500/em and received an error. What
could be the problem? (Choose three answers.)
A. You have not started the Database Listener.
ch05.indd 18
5/18/2005 11:19:21 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
19
B. You have not started the dbconsole.
D. You are not logged onto the database server node.
E. You have not started the Grid Control agent.
PART I
C. The dbconsole is running on a different port.
F. You have not started the database.
3. Which files must be synchronized for a database to open? (Choose the best
answer.)
A. Datafiles, online redo log files, and the controlfile
B. The parameter file and the password file
C. All the multiplexed controlfile copies
D. None. SMON will synchronize all files by instance recovery after opening
the database.
4. During the transition from NOMOUNT to MOUNT mode, which file or files
are required? (Choose the best answer.)
A. Parameter file
B. Controlfiles
C. Online redo logs
D. Datafiles
E. All of the above
5. You shut down your instance with SHUTDOWN IMMEDIATE. What will
happen on the next startup? (Choose the best answer.)
A. SMON will perform automatic instance recovery.
B. You must perform manual instance recovery.
C. PMON will roll back uncommitted transactions.
D. The database will open without recovery.
6. You have created two databases on your computer and want to use Database
Control to manage them. Which of the following statements are correct?
(Choose two answers.)
A. You cannot use Database Control, because it can manage only one
database per computer.
B. You must use Grid Control, as you have multiple databases on the
computer.
C. You must start one OC4J process and contact it on different ports for each
database.
D. You must start one OC4J instance per database.
E. You must set the ORACLE_SID variable appropriately before starting an
OC4J instance.
ch05.indd 19
5/18/2005 11:19:21 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
7. You issue the command SHUTDOWN, and it seems to hang. What could be
the reason? (Choose the best answer.)
A. You are not connected as SYSDBA or SYSOPER.
B. There are other sessions logged on.
C. You have not connected with operating system or password file
authentication.
D. There are active transactions in the database; when they complete, the
SHUTDOWN will proceed.
8. What action should you take after terminating the instance with SHUTDOWN
ABORT? (Choose the best answer.)
A. Back up the database immediately.
B. Open the database and perform database recovery.
C. Open the database and perform instance recovery.
D. None, but some transactions may be lost.
E. None. Recovery will be automatic.
9. Using Database Control, you stop the Database Listener. Which of the
following statements is true? (Choose the best answer.)
A. Database Control will no longer be able to manage the database.
B. Existing sessions will be terminated.
C. No new sessions can be established.
D. You must restart the listener with the lsnrctl utility.
10. Database Control is a multitier web application. Which tier is responsible for
window management? (Choose the best answer.)
A. The dbconsole middle tier
B. The procedures within the database tier
C. The client browser
D. The OC4J application runtime environment
Answers
1. B. The emctl command is used to start the dbconsole, lsnrctl is used to start
database listeners, and isqlplus from a command line won’t do anything.
2. B, C, and D. Any of these could be a reason. A, E, and F are related to other
processes.
3. A. These are the three file types that make up a database: datafiles, online
redo log files, and the controlfile.
ch05.indd 20
5/18/2005 11:19:22 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic/ 5790-3 /Chapter 5
Chapter 5: Managing Oracle Processes
21
5. D. This holds true because IMMEDIATE is a clean shutdown.
6. D and E. D is correct because one OC4J can only support one Database Control
process to manage one database, and E is correct because without this the emctl
utility will not know which OC4J to start.
PART I
4. B. Remember which files are read at each stage: the parameter file at NOMOUNT,
the online redo log files and the datafiles at OPEN.
7. B. This answer is correct because the default shutdown mode is NORMAL,
which will wait for all sessions to log off.
8. E. It is vital to remember this! After a crash, or an abort, recovery is automatic
and unstoppable. No data is ever lost, and you need take no action at all.
9. C. Without a listener there is no way to launch the server process needed for
a session.
10. C. Your local window management is done by your local browser. The other
answers refer to processes that reside on the application server tier (A and D),
or within the database (B).
ch05.indd 21
5/18/2005 11:19:22 AM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 / Chapter 23
blind folio: 22
ch05.indd 22
5/18/2005 11:19:22 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
CHAPTER 6
Managing Oracle Storage
Structures
In this chapter you will learn how to
• Define the purpose of tablespaces and datafiles
• Create tablespaces
• Manage tablespaces (alter, drop, generate DDL, take offline, put online, add datafiles,
make read-only or read/write)
• Obtain tablespace information from Enterprise Manager and the data dictionary
• Drop tablespaces
• Describe the default tablespace
1
ch06.indd 1
6/30/2005 9:58:36 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
You have now created a database and know how to manage the instance to get access
to the database data. The next logical step is to create storage structures in the database
to hold your data and to ensure that those storage structures are managed efficiently.
You don’t want to overallocate disk space, and you don’t want to underallocate.
Furthermore, you want to ensure that the use of disk space is as efficient as possible
for the type of database you will be managing and the disk resources available to
you. Understanding how Oracle manages storage, both logically and physically, and
understanding the different components involved in storing Oracle database data are
some of the key concepts any DBA must master.
Oracle Storage Basics: Tablespaces and Datafiles
Storage in an Oracle database has two distinct “sides”: physical and logical. Physical
storage is how the storage components that make up an Oracle database at the
operating system level are seen, normally, as a series of datafiles. Logical storage is how
Oracle internally manages the objects that are stored in the database. The logical and
physical storage structures in Oracle and their relationships can be expressed as
a model shown in Figure 6-1.
Looking at the model of Oracle storage, a few key elements can be discerned, such
as these:
• Every database must consist of one or more tablespaces. Every tablespace must
belong to one and only one database.
• Every tablespace must consist of one or more datafiles. Each datafile must
belong to one and only one tablespace.
Figure 6-1
Entity-relationship
model of Oracle
database storage
structures
ch06.indd 2
6/30/2005 9:59:09 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
3
• Every tablespace may contain one or more segments. Every segment must exist
in one and only one tablespace.
PART I
• Every datafile must consist of one or more operating system blocks. Each operating
system block may belong to one and only one datafile.
• Every segment must consist of one or more extents. Each extent must belong
to one and only one segment.
• Every extent must consist of one or more Oracle blocks. Each Oracle block may
belong to one and only one extent.
• Every extent must be located in one and only one datafile. The space in the
datafile may be allocated as one or more extents.
• Every Oracle block must consist of one or more operating system blocks. Every
operating system block may be part of one and only one Oracle block.
EXAM TIP It is important to be clear on the physical and logical makeup of an
Oracle database. Be familiar with the terms used in both.
Physical Storage Structures
The physical structure is what the operating system sees when “looking” at an Oracle
database. Oracle physical storage is quite simple to understand and see: it is a collection
of one or more datafiles. It is also possible for Oracle to make use of raw devices
(partitions of a hard disk not managed by the operating system), but doing so
introduces complexity when it comes to backup and recoverability. It is also possible
for Oracle to manage physical storage itself through something called Automated
Storage Management, or ASM, in which case the operating system is also not involved.
However, by and large, most Oracle physical storage is made up of operating system
datafiles.
Each datafile is composed of operating system blocks and is created on a disk
partition or volume, all managed by the host operating system. This is the most
common scenario and one that you will encounter most frequently.
Oracle Datafiles
Datafiles are operating system files that hold Oracle data. When you create a database,
a number of datafiles are created to hold the data dictionary and the SYSAUX
tablespace data, along with any other tablespaces you decided to create at that time.
The datafiles consist of the header and the space that can be used to allocate extents
to segments. In effect, most datafiles have three parts: the header, the extents (allocated
space), and free (unallocated space).
The header of a datafile identifies it as part of a database and stores specifics of
that datafile: which tablespace it belongs to and the last checkpoint performed. This
way, Oracle can check that all files are synchronized when it starts up. If it detects that
one of the files is older than the rest (or all files are older than the controlfile), it will
ch06.indd 3
6/30/2005 9:59:10 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
assume that the file was restored from a backup and initiate recovery. The rest of the
datafile consists of extents and free space, the management of which is performed by
creating, dropping, and altering the logical storage components of Oracle: segments.
Each Oracle datafile belongs to one and only one tablespace and is made up of
operating system blocks. As you will see later in this chapter, it is possible to specify
growth characteristics for datafiles and resize them either manually or automatically.
You can also take a datafile offline, making its contents unavailable, provided it does
not belong to the SYSTEM tablespace.
Operating System Blocks
Operating system blocks are the minimum allocation unit for the file system. Each file
system has its own minimum and default sizes, which often vary with the hard disk
geometry and size, as well as the file system used to format the drive. Most systems
will allow you to configure the block size when formatting the drive. It is a good idea
to keep the operating system block size the same as the Oracle block size. So, if you
are planning to add a drive in order to keep Oracle datafiles on it, and your database
block size is 8KB, you may want to format the drive using 8KB blocks. However,
because Oracle Database 10g allows you to create tablespaces with differing block
sizes, you may want to ensure that the operating system block size is the same size as
the largest database block. This way, for every Oracle I/O request the operating system
needs to retrieve only one block.
Logical Storage Structures
As a DBA, you will be spending a great deal of your time looking at database storage
from the logical point of view. You will be creating and managing tablespaces, segments,
and extents and ensuring that the Oracle block size is efficiently configured for your
database. The logical structure of the database is the left side of the model in Figure 6-1.
The database is the highest and final unit of organization for Oracle. It is selfcontained and consists of at least three tablespaces (preferably more) in Oracle 10g
(up from one in previous releases). In order to access database data, an instance must
be started.
Tablespaces
Within a database the tablespace is the largest storage structure. A database in Oracle
10g must have at least three tablespaces: SYSTEM, SYSAUX, and one undo tablespace.
These are created when you create the database; you create others for a specific purpose
in order to manage your database objects and ensure the instance and database perform
well. You should also create at least one additional tablespace for specific data: a
temporary tablespace to hold temporary objects created when a sort takes place and
cannot be completely performed in memory.
Tablespace Types Tablespaces can be classified using many different criteria,
the first of which is based upon the type of objects the tablespace stores: SYSTEM or
non-SYSTEM. In Oracle 10g two tablespaces make up the SYSTEM type: SYSTEM and
SYSAUX. All other tablespaces are classified as non-SYSTEM.
ch06.indd 4
6/30/2005 9:59:11 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
5
The SYSTEM tablespace contains the data dictionary—internal tables that describe
the structure of the database itself, all of the objects in it, users, roles, and privileges.
When a user issues a query or a DML statement, the data dictionary is used in order
to verify the user’s permissions and find the data that belongs to the segment being
queried or changed. When a DDL statement is processed, the internal tables are
modified in order to reflect the change: CREATE, ALTER, or DROP. The SYSTEM
tablespace also contains the SYSTEM undo or rollback segment (also called SYSTEM),
which can be used only for operations on objects stored in the SYSTEM tablespace.
User objects should be kept out of the SYSTEM tablespace in order to keep it
operating efficiently.
PART I
EXAM TIP Oracle Database 10g has two tablespaces that are considered part
of the system: SYSTEM and SYSAUX. Previous releases of Oracle required only
a SYSTEM tablespace.
EXAM TIP The SYSTEM tablespace is the location of the data dictionary in an
Oracle database. The database cannot operate without a SYSTEM tablespace.
The SYSAUX tablespace is also considered a SYSTEM tablespace and is used to
store statistical and other information that used to be kept in the SYSTEM tablespace
in previous versions.
After you create the database, you will need to create additional tablespaces to
store your data. The number of tablespaces you create and what is stored within them
depend on what your database will be used for and the amount of data. Here are
some of the guidelines to follow when creating additional tablespaces and to help
with performance:
• Separate data that will participate in resource contention For example, a
table and its indexes will normally be accessed simultaneously during inserts
and updates, so to prevent a bottleneck, it is best to place them on different
hard drives. One way to do this is to create different tablespaces—DATA
and INDEX—to hold the data and then place each tablespace’s datafiles on
a different hard disk. This way, you can update both the table and its index
simultaneously and not risk resource contention.
• Separate objects that have different storage requirements Keeping small
tables and large tables on different tablespaces will provide better space
management and performance. While extent management can be largely
automated in Oracle 10g, there is no reason to make Oracle’s job more
difficult by placing dissimilar objects on the same tablespace.
• Store different partitions in different tablespaces One of the benefits of
partitioning your data is to gain performance improvements for queries. Place
each partition on a separate tablespace and, preferably, each tablespace’s
datafiles on a separate hard disk. In this way Oracle can read data from more
than one hard disk at the same time when satisfying the query.
ch06.indd 5
6/30/2005 9:59:11 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
Tablespace Contents A tablespace can store one of three types of segments:
permanent, temporary, and undo. Permanent segments are what you expect to find
in a database, such as a table or index. Temporary segments are those that exist for a
short time and are then overwritten, such as a sort operation. Undo segments hold
the before image of the data being modified so that other users can still have their
queries answered even if the data is in the process of being changed.
EXAM TIP Tablespaces can store one of three types of objects: permanent
objects such as tables and indexes; temporary segments such as sort segments
and temporary table data; and undo data used for transaction rollback or
flashback queries.
When you create a user in Oracle, you specify the default tablespace that will be
used to store extents for any segment the user creates, as well as a temporary tablespace
to store temporary segments, although a global temporary tablespace defined for the
database can be used as well.
All users share the undo tablespace, which is set by the DBA. To determine what
the users’ default and temporary tablespaces are, you can issue this query:
SQL> SELECT username, default_tablespace, temporary_tablespace
2 FROM DBA_USERS;
USERNAME
DEFAULT_TABLESPACE
TEMPORARY_TABLESPACE
-------------------- ------------------------- ------------------------SYS
SYSTEM
TEMP
SYSTEM
SYSTEM
TEMP
OUTLN
SYSTEM
TEMP
DBSNMP
SYSAUX
TEMP
SYSMAN
SYSAUX
TEMP
MGMT_VIEW
SYSAUX
TEMP
WK_TEST
SYSAUX
TEMP
MDSYS
SYSAUX
TEMP
ORDSYS
SYSAUX
TEMP
CTXSYS
SYSAUX
TEMP
ANONYMOUS
SYSAUX
TEMP
EXFSYS
SYSAUX
TEMP
DMSYS
SYSAUX
TEMP
WMSYS
SYSAUX
TEMP
XDB
SYSAUX
TEMP
WKPROXY
SYSAUX
TEMP
ORDPLUGINS
SYSAUX
TEMP
SI_INFORMTN_SCHEMA
SYSAUX
TEMP
OLAPSYS
SYSAUX
TEMP
WKSYS
SYSAUX
TEMP
MDDATA
USERS
TEMP
DIP
USERS
TEMP
SCOTT
USERS
TEMP
Tablespaces in Databases Created with the Database Configuration
Assistant A typical example of tablespaces that exist in most databases can
be ascertained by looking at the tablespaces created when you use the Database
Configuration Assistant. The DBCA will create a database with the following
tablespaces, as shown in Figure 6-2.
ch06.indd 6
6/30/2005 9:59:12 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
7
PART I
Figure 6-2 Tablespaces in a database created by the Database Configuration Assistant
• SYSTEM Used to store the Oracle data dictionary and all objects in the SYS
schema. Access to these objects is restricted to the user SYS and others that
have been granted the DBA role, by default. Every database must have a
SYSTEM tablespace.
• SYSAUX The SYSAUX tablespace was introduced in Oracle Database 10g
to store objects not owned by SYS but required in order for the database to
function. In previous releases of Oracle these were stored in the SYSTEM
tablespace; they include Oracle Enterprise Manager components, among
others. Every Oracle 10g database must have a SYSAUX tablespace.
• TEMP Used to store temporary objects and their data. Examples of these
include the data portion of a global temporary table and sort segments created
when a sort cannot be completely performed in memory. Every database should
have a temporary tablespace, though it is not required, and one should be
designated as the default temporary tablespace to be assigned to users if one
is not specified when the user is created. Temporary tablespaces consist of
tempfiles instead of datafiles. If no temporary tablespace is created, then
temporary segments are created in the SYSTEM tablespace by default—a bad
idea from a performance perspective.
ch06.indd 7
6/30/2005 9:59:12 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
• UNDOTBS1 Used to store undo information for the database. Undo is data
kept in the database to allow users to read rows that are in the process of
being changed but whose transactions have not yet committed. This allows
any user needing to get a read-consistent image of the data to avoid being
held up by people changing the data. An undo tablespace is required in each
database.
• USERS When a database user creates a segment, its data needs to be stored
in a tablespace. The USERS tablespace serves this purpose. You can create
additional tablespaces and allow users to store their segments in them, but
one tablespace needs to be made the default users’ tablespace, which the
USERS tablespace is for nonsystem (i.e., not SYS or SYSTEM) users.
If you decided to load the example schemas when you created the database with
DBCA, you will also have an EXAMPLE tablespace that stores those segments in the
example schemas.
Segments
Within a tablespace, space is allocated to segments. A segment is an object in the
database that requires storage, such as a table or an index. A view, on the other hand,
is not a segment, since it does not store data; it is just a prewritten query that allows
easy access to data stored in tables. Oracle allows you to create many different segment
types. A query against the DBA_SEGMENTS view will display a list of segments created
in the database, as follows:
SQL> SELECT DISTINCT segment_type FROM DBA_SEGMENTS;
SEGMENT_TYPE
-----------------CLUSTER
INDEX
INDEX PARTITION
LOB PARTITION
LOBINDEX
LOBSEGMENT
NESTED TABLE
ROLLBACK
TABLE
TABLE PARTITION
TYPE2 UNDO
This query shows only the segment types that exist in your database, not all
possible types. How to manage many (but not all) of the segment types listed will
be the discussion of several future chapters.
EXAM TIP Any object requiring storage in a database is classified as
a segment.
ch06.indd 8
6/30/2005 9:59:13 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
9
Extents
PART I
When space is allocated for segments in a tablespace, it is allocated an extent at a time.
A segment consists of one or more extents, and when a segment (e.g., a table or an
index) is created, at least one extent is allocated at creation time. Extents are made
of contiguous data blocks and can be managed either manually by the DBA or
automatically by Oracle, depending upon the conditions specified by the DBA, or
Oracle defaults. Extents are created in the datafiles belonging to the tablespace on
which the segment is defined. A segment can exist in only one tablespace, and an
extent exists in a datafile belonging to the tablespace.
Extent Management in Tablespaces When you create a tablespace, you can
specify whether extents should be locally managed or dictionary-managed. Locally
managed extents are more efficient and are recommended for all database data. In a
tablespace where extents are locally managed, free extents are stored in a bitmap in
the tablespace. Each bit in the bitmap represents a single database block or a multiple
of database blocks if extent management has been configured to be of a uniform size
or automatic. As an extent is allocated to a segment or freed up because a segment was
dropped, truncated, or resized, the bitmap is updated to reflect the change.
EXAM TIP Extents are a collection of contiguous blocks allocated to a
segment. Extents can be managed locally in the tablespace (preferred) or
in the dictionary (for backward compatibility).
Dictionary-managed tablespaces are the historical way of managing extents and
require any allocation or deallocation of an extent to update a table in the data
dictionary. This means that any time an extent is allocated to a table, the data dictionary
must be touched to record the change. When a table is dropped or truncated, the
data dictionary must be changed. Because of the amount of work required on the data
dictionary when using dictionary-managed extents, they are no longer recommended
and exist primarily for backward compatibility. All tablespaces should be created with
local extent management.
NOTE You can use Enterprise Manager or the DBMS_SPACE_ADMIN
.TABLESPACE_MIGRATE_TO_LOCAL procedure to migrate a dictionarymanaged tablespace to local extent management.
Database Blocks
A database block is the minimum unit of I/O in the database. When the database
needs to read data, it cannot read just one row; it must read the entire block. The
same happens with writing: even if only one row in a block is changed, the DBWn
process has to write the entire block during the checkpoint. When a database is
created, the default block size for tablespaces is specified. It is possible to have more
than one block size specified for a database, but a tablespace and its datafiles will
ch06.indd 9
6/30/2005 9:59:14 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
always only have one database block size. In other words, you specify the block size
for the tablespace when you create it, or assume the database default. For a different
tablespace you can specify a different block size. You cannot change the block size for
a tablespace once it is created, except by dropping and re-creating it (and possibly
losing all the tablespace contents).
Creating and Managing Tablespaces
There are two ways to create a tablespace in Oracle: using Oracle Enterprise Manager
(OEM) or by issuing the CREATE TABLESPACE command in SQL*Plus or iSQL*Plus.
The end result is the same, since OEM will send the appropriate command to the
database to perform the operation.
The CREATE TABLESPACE Command
The CREATE TABLESPACE and CREATE TEMPORARY TABLESPACE commands allow
you to create a tablespace using SQL*Plus or iSQL*Plus. Alternatively, you can create
a tablespace from Enterprise Manager, which provides a nice point-and-click interface,
and then optionally view the command sent to the Oracle server before it is executed.
The overall syntax of the command is somewhat complex because of the number
of options available, but we will break it down into manageable chunks.
CREATE [BIGFILE | SMALLFILE] [TEMPORARY] TABLESPACE tablespace name
DATAFILE datafile spec | TEMPFILE tempfile spec
[MINIMUM EXTENT minimum extent size]
[BLOCKSIZE blocksize]
[[COMPRESS|NOCOMPRESS] DEFAULT STORAGE (default storage clause)]
[LOGGING|NOLOGGING]
[FORCE LOGGING]
[ONLINE|OFFLINE]
[EXTENT MANAGEMENT DICTIONARY |
LOCAL [AUTOALLOCATE|UNIFORM SIZE size]]
[SEGMENT SPACE MANAGEMENT MANUAL|AUTO]
[FLASHBACK ON|OFF]
To create a tablespace, all you need is the name of the tablespace and the datafile
specification; all other settings are left at Oracle defaults, as in this example:
CREATE TABLESPACE default_demo
DATAFILE '$ORACLE_BASE/oradata/default_demo01.dbf' SIZE 10M;
This one command did everything: physically created the datafile, created the
tablespace, updated the controlfile and the data dictionary, and set all the defaults
for the new tablespace.
NOTE If the datafile already exists on disk, the creation of the tablespace
will fail.You can specify the REUSE parameter to the datafile specification to
instruct Oracle to overwrite any file with the same name as the datafile you
want to create. This is useful when re-creating tablespaces that you dropped.
ch06.indd 10
6/30/2005 9:59:14 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
11
PART I
Perhaps the best way to create a tablespace in Oracle 10g is to use Enterprise
Manager. With EM you can create a tablespace with an easy interface and also learn
about the syntax to do so by displaying the SQL code to perform the action.
Exercise 6-1: Using Enterprise Manager
to Create a Tablespace
In this exercise you will connect to Enterprise Manager and create a tablespace in your
database.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server, specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
4. Click the Tablespaces hyperlink under Storage to display the current
tablespaces in the database and their space utilization.
5. To create a new tablespace, click Create on the right side to bring up the
Create Tablespace screen.
ch06.indd 11
6/30/2005 9:59:15 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
6. In the Name text box, enter the name of the tablespace you want to create,
OCP10gData, for example. You will notice that you also have a number of
selections to make regarding the tablespace characteristics, including extent
management (local or dictionary), tablespace type (permanent, temporary,
or undo), and status (read/write, read-only, or offline).
Permanent tablespaces are the default and can be used to hold segment data
such as tables, indexes, and clusters. The majority of the tablespaces you
create will be of the Permanent variety. If you select the Set As Default check
box for the tablespace, any user created in the database that does not have a
default tablespace specified at creation time will be assigned this tablespace
as his default tablespace. Any segments the user creates will occupy space on
this tablespace by default, unless a different tablespace is specified when the
object is created.
Status determines the initial state of the tablespace after creation. Read/write
means that objects can be created and otherwise modified on the tablespace
and its contents can change. Read-only means that it cannot be written to,
and offline means that the contents of the tablespace are not available. When
creating a tablespace, it is best to choose Read Write; you can always change
the status later.
Leave your tablespace at the default values of Locally Managed, Permanent,
and Read Write.
ch06.indd 12
6/30/2005 9:59:16 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
13
PART I
7. Under the Datafiles heading you have the option to add one or more datafiles
to the tablespace. If you select the Use Bigfile Tablespace check box, your
tablespace can have only one datafile whose size limit is as large as the
file system will allow. Bigfile tablespaces cannot be dictionary-managed.
Leave the Use Bigfile Tablespace option unchecked and then click Add to
bring up the Add Datafile page.
8. On the Add Datafile page, enter the name of the datafile for the tablespace
and verify that the location provided is appropriate. Enterprise Manager will
display the default location for datafiles according to OFA guidelines, typically
the directory pointed to by the location $ORACLE_BASE/oradata/.
You also need to specify a file size or accept the default value. Under Storage
you can specify whether or not to automatically grow the file (AUTOEXEND)
when it becomes full as well as how much to grow it by and whether or not
to specify a maximum size the file can grow to. Autoextend allows you to
automate file growth while at the same time optionally providing a limit
on the growth so that a file does not occupy all available disk space.
Leave the datafile size at the default of 100MB and specify autogrowth
in increments of 50MB up to a maximum size of 500MB. Click Continue
when done.
ch06.indd 13
6/30/2005 9:59:17 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
9. On the Create Tablespace page, click Show SQL to display the SQL commands
that will be sent to the database to create the tablespace. Click Return when
done reviewing the code.
10. Click the Storage hyperlink to display the Storage Options page. Because you
specified that the tablespace will be locally managed, here you can specify
whether extent allocation will be automatically handled by Oracle based
upon the data stored on the tablespace, in which case you cannot control
extent sizing. If you want to make all extents the same size, you can specify
Uniform sizing, which defaults to extent sizes of 1MB. Uniform sizing makes
sense for temporary tablespaces and for those tablespaces where the data
being stored is of the same row size (i.e., all large rows or all small rows,
etc.). You cannot use automatic extent allocation for temporary tablespaces.
ch06.indd 14
6/30/2005 9:59:18 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
15
PART I
The second option on this screen deals with the way that space will be
managed within the segment. With automatic segment space management
Oracle will use bitmaps to determine which blocks are free and which contain
large amounts of data. The amount of space that exists for inserting rows will
be automatically tracked by the bitmap containing all blocks allocated to the
segment. This is an efficient method that frees the DBA from setting segment
space management parameters manually. Using manual space management
requires the DBA or the creator of the segment to specify values for the
PCTFREE, PCTUSED, FREELISTS, and FREELIST GROUPS parameters when
creating the object and maintaining them as the volume of segment data
increases.
EXAM TIP PCTFREE, PCTUSED, FREELISTS, and FREELIST GROUPS can be
set only for dictionary-managed tablespaces.
ch06.indd 15
6/30/2005 9:59:18 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
The last section requires you to specify whether changes made to segments
in the tablespace should be logged to the redo log files (LOGGING) or not
(NOLOGGING). While you can specify this parameter when you create the
segment, if you do not, the segment will inherit it from the tablespace. If you
specify NOLOGGING, then it may not be possible to recover segments in the
tablespace in the event of failure.
If you created a dictionary-managed tablespace, you would also need to
specify default storage parameters using the DEFAULT STORAGE clause of
the CREATE TABLESPACE command. Table 6-1 lists the parameters of the
DEFAULT STORAGE clause and their values.
Specify automatic extent management, automatic segment management, and
logging for the tablespace.
Table 6-1
DEFAULT
STORAGE
Parameters
for DictionaryManaged
Tablespaces
ch06.indd 16
Setting
Description
MINEXTENTS
The number of extents each segment will be created
with, which defaults to the minimum of 1.
MAXEXTENTS
The maximum number of extents a segment will be
allocated if necessary. The default value depends on
the DB_BLOCK_SIZE setting, while the maximum
is UNLIMITED. Avoid setting MAXEXTENTS to
UNLIMITED, as this will allow a segment to take all
the available space in the tablespace and can disrupt
normal operation of the database.
INITIAL
Allows you to specify the size of the first extent for
the segment in bytes (use K or M as suffixes to the
numeric value to specify KB or MB). The default is 5
database blocks, with a minimum of 2 database blocks.
NEXT
Specifies the size of the second or subsequent extents
in bytes, KB or MB.
PCTINCREASE
Specifies how much bigger to make the third extent
compared to the second extent, the fourth compared
to the third, etc., as a percentage. For example, if
PCTINCREASE is set to 20, the INITIAL and NEXT
are set to 100K, the third extent will be 120K, the
fourth, 144K, etc., rounded up to the next multiple
of DB_BLOCK_SIZE. If PCTINCREASE is set to 0,
SMON will not automatically coalesce the free space
in the tablespace.
6/30/2005 9:59:19 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
17
PART I
11. Click the Thresholds hyperlink to bring up the Thresholds page. Thresholds
allow you to have Enterprise Manager warn you when space in the tablespace
is getting used up. You can specify thresholds for the database, specify them
for the individual tablespace, or disable them for the tablespace. Thresholds
will be covered in more detail in Chapter 15. Leave the current settings at the
default values and then click OK to create the tablespace.
12. After a short delay, you will be presented with the Tablespaces page of Enterprise
Manager, shown next, where the tablespace you just created is listed. You can
also create more tablespaces or manage the ones that are there.
ch06.indd 17
6/30/2005 9:59:20 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
Modifying Tablespaces
Since databases generally are not static, you will from time to time need to make
changes to the tablespaces you created. These can be common tasks such as adding
datafiles to a tablespace or increasing the size of existing datafiles, taking a tablespace
offline for maintenance or recovery purposes, or changing the mode from read/write
to read-only or vice versa. All of these tasks can be accomplished from the command
line using the ALTER TABLESPACE command or using Enterprise Manager. You can
also rename a tablespace if needed, but this is generally not recommended after
segments have been created on it.
Exercise 6-2: Using Enterprise Manager
to Alter a Tablespace
In this exercise you will connect to Enterprise Manager and change the characteristics
of the tablespace you created in the previous exercise.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
ch06.indd 18
6/30/2005 9:59:21 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
19
4. Click the Tablespaces hyperlink under Storage to display the current
tablespaces in the database and their space utilization.
PART I
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
5. Select the tablespace created in the preceding exercise (OCP10GDATA, for
example) and then click Edit to display the Edit Tablespace page. Note that
the majority of options are grayed out except for the check box to make this
the default tablespace for the database, and the various status options. This is
because the extent management and type of tablespace cannot be modified after
creation time; you must drop and then re-create the tablespace to change these.
The normal mode of operation of a tablespace is read/write, meaning that
objects can be created on the tablespace and their contents modified—data
inserted, updated, or deleted. Making a tablespace read-only does not allow any
changes to segment data on the tablespace but does allow SELECT statements
to be executed against it. The read-only status of a tablespace does not prevent
dropping objects created on the tablespace, since the object definition is not
stored on the tablespace but rather in the data dictionary. Think of this as
similar to the phone company changing your phone number—they have to
come to the house to install the phones, but to change your phone number
all they have to do is modify an entry at the central office to specify which
number will cause your phone at home to ring.
ch06.indd 19
6/30/2005 9:59:22 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
6. Click the drop-down list box next to Offline Mode to display the four
available modes. Taking a tablespace offline makes its contents unavailable
until the tablespace is brought back online, but taking a tablespace offline
should be done gracefully to prevent having to perform recovery when the
tablespace is brought online. The NORMAL and IMMEDIATE options will
issue a checkpoint before taking all datafiles belonging to the tablespace
offline, although the IMMEDIATE option cannot be used if the database is
in noarchivelog mode. Using the TEMPORARY option will gracefully take
the datafiles offline and not require recovery unless one of the datafiles was
already offline due to media failure, in which case recovery will be needed.
FOR RECOVER is deprecated and should not be used; it is included for
backward compatibility.
7. If you want to add a datafile to the tablespace, you can click Add. For now
click Edit to display the Edit Datafile page. Notice that you can change the
size of the datafile by entering a new value. You can specify a value smaller
or larger than the existing file size, but no smaller than the amount of data
physically in the file; otherwise, you receive the “ORA-03297: file contains
used data beyond requested RESIZE value” error. You can also change
autogrowth characteristics, rename the datafile, or change its location.
Decrease the size of the datafile to 50MB and click Continue.
ch06.indd 20
6/30/2005 9:59:23 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
21
ALTER DATABASE DATAFILE '/oracle/oradata/ocp10g/ocp10gdata01.dbf' RESIZE 50M
9. Click Apply to save your changes.
PART I
8. Click Show SQL to display the SQL code required to make your changes, as in
this code listing example, and then click Return:
10. Click the Tablespaces hyperlink at the top
of the Enterprise Manager page to display
the list of tablespaces in the database.
11. Click the drop-down list box next to Actions
to display the list of available actions.
Actions are activities that can be performed
on the selected tablespace. They are
described in more detail in Table 6-2.
12. Close Enterprise Manager.
Table 6-2
Available
Tablespace
Actions
ch06.indd 21
Action
Description
Add Datafile
Allows you to add another datafile to the tablespace.
Create Like
Uses the selected tablespace as a template for another
tablespace. Characteristics such as extent and segment
management, datafile location, and size are copied to the
new tablespace.
Generate DDL
Displays a page with the generated SQL statement used
to re-create the tablespace.
Make Locally
Managed
Converts a dictionary-managed tablespace to a locally
managed tablespace.
Make Read Only
Makes a read/write tablespace read-only. Current
transactions are allowed to complete, but no new
transactions can be started on segment data in the
tablespace. Also forces a checkpoint to update the
controlfile and datafile headers. This action cannot
be performed on UNDO, SYSTEM, and SYSAUX
tablespaces.
Make Writable
Allows writes on tablespace segment data.
Place Online
Brings a currently offline tablespace online.
Reorganize
Starts the Reorganization Wizard of Enterprise Manager
to allow you to move objects around to make space
utilization more efficient. This process can severely
impact performance of tablespace data and should be
performed during off-hours.
Show
Dependencies
Lists objects dependent on this tablespace (i.e., segments
created on it) or objects the tablespace is dependent upon.
Run Segment
Advisor
Segment Advisor allows you to determine if segments on
the tablespace have space available to be reclaimed for
use by other objects.
Take Offline
Takes a tablespace offline. Cannot be performed on the
SYSTEM or SYSAUX tablespace.
6/30/2005 9:59:23 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
22
Dropping Tablespaces
The DROP TABLESPACE command allows you to drop an existing tablespace in
the database. To perform this action, you must have the DROP TABLESPACE system
privilege. You can then issue the following command:
DROP TABLESPACE OCP10GDATA;
If there are objects in the tablespace, you will get the following error:
DROP TABLESPACE OCP10GDATA
*
ORA-01549: tablespace not empty, use INCLUDING CONTENTS option
If there are foreign key constraints that depend on tables on the tablespace, you
can modify the syntax to drop those links too by using the following syntax:
DROP TABLESPACE OCP10GDATA INCLUDING CONTENTS CASCADE CONSTRAINTS;
EXAM TIP Tablespaces can be dropped only if they contain no permanent
objects, unless the INCLUDING CONTENTS and CASCADE CONSTRAINTS
parameters are specified.
The result of dropping a tablespace is that any reference to it is erased from the
data dictionary and the controlfile of the database. The datafile is not actually deleted,
so you will need to do that manually (though Enterprise Manager can be used to do
that step as well).
EXAM TIP Dropping a tablespace from the command line does not remove
the datafile from disk. Deleting a tablespace using Enterprise Manager provides
the option to also delete the datafile.
Exercise 6-3: Using Enterprise Manager
to Drop a Tablespace
In this exercise you will connect to Enterprise Manager and drop the tablespace you
created earlier.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server, specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
4. Click the Tablespaces hyperlink under Storage to display the current
tablespaces in the database and their space utilization.
ch06.indd 22
6/30/2005 9:59:24 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
23
PART I
5. Select the tablespace created in Exercise 6-1 (OCP10GDATA, for example)
and then click Delete to display the Delete Tablespace warning page. Read the
warning and note that a backup should always be performed before deleting
a tablespace in case you want to get the data back.
6. Ensure that the Delete Associated Datafiles From The OS check box is checked,
and then click Yes to delete the tablespace.
7. Notice that the tablespace is no longer listed on the Tablespaces page. Verify
at the operating system to ensure that the datafile is also removed.
8. Close Enterprise Manager.
Viewing Tablespace Information
The easiest way to view tablespace information is by using Enterprise Manager—
selecting a tablespace and then clicking the View button is the best way to get full
information on a tablespace. Oracle also includes a number of data dictionary and
dynamic performance views that can be used to gather information on tablespaces.
To get a list of tablespaces in the database and their characteristics, you can use the
DBA_TABLESPACES or V$TABLESPACE views. The DBA_TABLESPACES view provides
information on tablespace storage characteristics not found in V$TABLESPACE.
ch06.indd 23
6/30/2005 9:59:25 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
24
For a list of datafiles, you can query the DBA_DATA_FILES view or the V$DATAFILE
view. The DBA_DATA_FILES view will list the name of the tablespace to which the
datafile belongs, whereas V$DATAFILE lists only the tablespace number, which must
be joined to V$TABLESPACE to get the tablespace name, but V$DATAFILE provides
more details on the file status.
EXAM TIP The V$TABLESPACE,V$DATAFILE, and V$TEMPFILE views can be
queried when the database is in a MOUNT state.
For temporary tablespaces, you can query the V$TEMPFILE and DBA_TEMP_FILES
views to get a list of tempfiles and their storage characteristics.
Chapter Review
A database has a physical structure and a logical structure. From the physical point
of view, the database consists of datafiles built out of operating system blocks. The
logical representation of a database consists of tablespaces, which contain segments
built out of extents. The smallest logical unit in the database is the database block.
A tablespace is the link between the physical and logical structures of a database.
By using tablespaces, we can control the location of data and administer parts of the
database separately.
A segment is an object that is allocated space in the datafiles. There are different
types of segments: tables, indexes, rollback, temporary, and many others. A segment
can be located in only one tablespace.
An extent is the unit of space allocation in a tablespace. An extent is a group of
contiguous blocks and must exist in one datafile. Different extents belonging to the
same segment can be located in different datafiles belonging to the same tablespace.
Multiple segments cannot share an extent in Oracle.
A database block is the minimum unit of I/O within the database. The size of all
blocks in the database is set at its creation and cannot be changed.
Tablespaces can be of different types: SYSTEM or non-SYSTEM, permanent or
temporary, locally managed or dictionary-managed.
Tablespaces can contain permanent objects or temporary objects. Temporary
objects are segments created for sort operations and temporary tables.
Tablespaces are created using the CREATE TABLESPACE command, either from the
command line or using Enterprise Manager. When creating a tablespace, you need to
specify the datafiles it will use, extent management characteristics, storage settings for
the segments created in it, and whether it can be written to.
Datafiles can extend automatically if necessary by using the AUTOEXTEND clause
in the datafile definition. When using AUTOEXTEND, make sure that you specify
NEXT (how much the file will grow by) and MAXSIZE (the maximum size it will grow
to) values so that a file does not occupy all available disk space.
You can increase the size of an existing tablespace by increasing the size of an
existing datafile or adding new ones. You can make a tablespace unavailable by taking
it offline using the ALTER TABLESPACE command. A tablespace that contains static or
ch06.indd 24
6/30/2005 9:59:26 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
25
PART I
historical data should be made Read Only by using the ALTER TABLESPACE command.
Read-only tablespaces do not need to be backed up regularly, and most changes to
data are prevented. You can, however, drop an object located in a read-only tablespace.
If you no longer need a tablespace, it can be dropped. Dropping the tablespace
does not delete the operating system files, but it does remove the tablespace from the
controlfile and from the data dictionary. If the tablespace contains objects, you need
to use the DROP TABLESPACE ... INCLUDING CONTENTS command.
In order to view information on your tablespaces and datafiles, you can use the
DBA_TABLESPACES, DBA_DATA_FILES, and DBA_TEMP_FILES views. When the
database is not open, you can query the V$TABLESPACE, V$DATAFILE and
V$TEMPFILE views.
Questions
1. Which line of code will cause the following SQL statement to fail? (Choose
the best answer.)
1
2
3
4
5
CREATE BIGFILE TABLESPACE OCP10gDATA
DATAFILE '/oracle/ocp10gdata/ocp10gdata02.dbf'
EXTENT MANAGEMENT LOCAL
FREELISTS 5
NOLOGGING;
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed
2. You have mounted the database but did not open it. Which views do you
need to query if you need the locations of all datafiles and the names of
the tablespaces they belong to? (Choose all correct answers.)
A. V$DATAFILE
B. DBA_DATA_FILES
C. V$TABLESPACE
D. DBA_TABLESPACES
E. V$TEMPFILE
F. DBA_TEMP_FILES
G. V$UNDOFILE
3. You attempt to create a tablespace but receive an error that the datafile for the
tablespace cannot be created. The size of the datafile you wanted to create is
3GB, and you specified the SMALLFILE option for the tablespace. You verify
that the operating system directory where the file will reside is owned by the
same user as Oracle and the user has full read/write permissions. You are logged
ch06.indd 25
6/30/2005 9:59:26 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
26
in to the database as the user SYSTEM, and there is plenty of disk space on the
hard drive. What is the likely cause of the error? (Choose the best answer.)
A. You cannot create a file larger than 2GB in an Oracle database when
specifying SMALLFILE.
B. The operating system cannot create a file larger than 2GB.
C. You must specify the WITH OVERWRITE option for the datafile
specification.
D. You must specify the REUSE option for the datafile specification.
E. You must specify the AUTOEXEND option for the datafile specification.
4. You want to be able to re-create a tablespace quickly in case of failure but do
not have the SQL code to perform the operation. What is the best way to
determine which SQL statement will properly re-create the tablespace with
all options correctly set? (Choose the best answer.)
A. Use the Generate DDL option of iSQL*Plus.
B. Use the Generate DDL option of Enterprise Manager.
C. Use the Create Like option of iSQL*Plus.
D. Use the Create Like option of Enterprise Manager.
E. Query the CODE column of the V$TABLESPACE view.
F. Query the TEXT column of the DBA_TABLESPACES view.
5. Which line of code will cause the following SQL statement to fail? (Choose
the best answer.)
1
2
3
4
5
CREATE BIGFILE TABLESPACE OCP10gDATA
DATAFILE '/oracle/ocp10gdata/ocp10gdata02.dbf'
EXTENT MANAGEMENT DICTIONARY
FREELISTS 5
NOLOGGING;
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed
6. You determine that a datafile belonging to your ARCHIVE2002 tablespace
is too large. You want to reduce the size of the datafile so that disk space is
not wasted. This tablespace will not have any data added to it. When you
use Enterprise Manager to reduce the size of the datafile belonging to the
tablespace, you receive an error. What is the most likely cause? (Choose
the best answer.)
A. You cannot reduce the size of datafiles in Oracle.
B. You cannot reduce the size of datafiles using Enterprise Manager.
ch06.indd 26
6/30/2005 9:59:27 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
27
C. You do not have sufficient permissions to reduce the size of the file.
E. The file contains data beyond the size you want to reduce the file to.
7. You issue the following command to drop a tablespace and receive an error
indicating that the tablespace cannot be dropped. What is the likely cause?
(Choose the best answer.)
PART I
D. The file does not exist.
DROP TABLESPACE SYSAUX INCLUDING CONTENTS CASCADE CONSTRAINTS;
A. System tablespaces cannot be dropped.
B. You do not have permissions to drop the SYSAUX tablespace.
C. Objects in other tablespaces depend on objects in the tablespace being
dropped.
D. You cannot drop objects in the tablespace that you did not create.
E. The command should succeed.
8. You want to change extent management on your DATA09 tablespace from local
to dictionary to match the other tablespaces in the DATA01–DATA08 range.
Which method can be used to make this change? (Choose the best answer.)
A. DBMS_SPACE_ADMIN.TABLESPACE_DICTIONARY_MANAGED
B. DBMS_SPACE_ADMIN.TABLESPACE_MIGRATE_TO_DICITONARY
C. Enterprise Manager
D. ALTER TABLESPACE DATA09 EXTENT MANAGEMENT DICTIONARY
E. You cannot convert a locally managed tablespace to dictionary
management
9. What permissions are required to create a tablespace? (Choose all correct
answers.)
A. CREATE TABLESPACE
B. MANAGE DATABASE
C. DBA
D. SYSDBA
E. SYSOPER
10. What types of segments can tablespaces in Oracle Database 10g store?
(Choose all correct answers.)
A. Tables
B. Sort segments
C. Redo segments
D. Undo segments
E. DBA segments
F. Clusters
ch06.indd 27
6/30/2005 9:59:27 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
28
Answers
1. D. When specifying local extent management in the creation of a tablespace,
you cannot specify a dictionary-managed segment storage parameter as well.
FREELISTS can be specified only when extent management is dictionary,
so that part of the CREATE TABLESPACE statement would cause the entire
statement to fail.
2. A, C, and E. Because the database is not yet in an OPEN state, any of the
DBA_ data dictionary views are not yet accessible; they can be queries only
when the database is in an open state. The V$TABLESPACE view will provide
you a list of tablespaces. The V$DATAFILE and V$TEMPFILE views can be
joined to the V$TABLESPACE view using the TS# column to retrieve a list
of all tablespaces and their datafiles. There is no V$UNDOFILE view.
3. D. The most likely reason that you are receiving an error on the creation of
the datafile for the tablespace is that a file with that name already exists. To
correct this, you must specify the REUSE option on the datafile specification
to have Oracle overwrite the existing file (or delete the file manually from the
hard disk). Neither Oracle nor the operating system will prevent a file of 3GB
being created for a SMALLFILE tablespace.
4. B. The Generate DDL option of Enterprise Manager will generate the SQL
code to re-create the selected tablespace. You can then cut and paste this into
a SQL script for later execution. There is no Generate or Create Like option
in iSQL*Plus, and the Create Like option of Enterprise Manager will display
a new page to enter the name of a tablespace with the same parameters as
the one selected. There is no CODE column in the V$TABLESPACE or TEXT
column in DBA_TABLESPACES.
5. C. In order to create a BIGFILE tablespace, you must specify local extent
management and automatic segment space management. You cannot create
a dictionary-managed BIGFILE tablespace.
6. E. Oracle allows you to reduce the size of datafiles, and this can be
accomplished from the command line or using Enterprise Manager. If
you are able to change the size of the file in Enterprise Manager, you have
the necessary permissions to perform the action. The most likely reason
you are unable to perform the action is that more data exists in the datafile
than the size you want to reduce it to. Specify a larger value and try again.
7. A. SYSAUX is a system tablespace and cannot be dropped. The same holds
true for the SYSTEM tablespace.
8. E. Once a tablespace is made locally managed, it is not possible to convert
it to a dictionary-managed tablespace. There is no command or Enterprise
Manager option to perform the change.
ch06.indd 28
6/30/2005 9:59:28 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 6: Managing Oracle Storage Structures
29
PART I
9. A and C. You must be granted either the CREATE TABLESPACE system
permission or the DBA role to create a tablespace. There is no MANAGE
DATABASE permission. The SYSOPER and SYSDBA roles provide permissions
for managing the instance and database but do not specifically grant the
holder the permission to create a tablespace.
10. A, B, D, and F. Tablespaces in Oracle can store tables, clusters (both are types
of permanent segments, which also include indexes, partitions, and others),
undo segments, and sort segments (a type of temporary segment). Redo
segments and DBA segments do not exist. Redo is stored in the redo log files.
ch06.indd 29
6/30/2005 9:59:28 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
ch06.indd 30
6/30/2005 9:59:29 AM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
CHAPTER 7
Administering Database Users
In this chapter you will learn how to
• Create and manage database user accounts
• Create and manage roles
• Grant and revoke privileges
• Control resource usage by users
1
ch07.indd 1
6/30/2005 5:00:42 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
As a database administrator, you must ensure that individuals that need access to
the database have the appropriate level of permission. This means creating users in
the database to allow individuals to connect to the instance, as well as granting the
appropriate system permissions to let users create and manage objects. Once a user
creates an object, he can then grant others permissions to manipulate those objects;
the DBA need not be involved in managing permissions to an individual user’s objects.
Finally, you want to ensure that no user can consume all database resources when
issuing an errant SQL statement or by other means.
Creating and Managing Database Users
In order for anyone to be able to access the database, that person needs to be
authenticated by Oracle as a valid database user. Applications can be configured to
require each individual needing access to have a separate database account, or the
application itself can connect to the database as a common user and handle applicationlevel permissions internally. No matter which method is chosen, at least one database
user will need to be created in the database to allow data manipulation.
Users and Schemas
When you create a database, depending on what options you have selected, a number
of database users will be created but will be locked by default. Two database users are
always created and are always unlocked: SYS and SYSTEM. The SYS user owns the data
dictionary and all of its associated objects. The user SYSTEM has access to all objects
in the database. The distinction between a user owning objects and a user only having
access to objects that are owned by another user is an important one in Oracle.
Any user that has been given the permission to create objects and does so is said
to own a schema. The schema is a collection of all objects that are owned by a user.
The schema has the same name as the user. For example, if a database user called John
created a table called Customers, John has now also created his schema and will be
schema owner of the “John” schema. Anyone wanting to query the new table in John’s
schema can prefix the table name with the schema name and query the data as JOHN
.CUSTOMERS (assuming John has granted them permissions to do so). If Damir wants
to query the JOHN.CUSTOMERS table, he may do so if he has permissions. Damir does
not have to be a schema owner like John, just a database user. In fact, the majority of
users in a database are not schema owners (i.e., they do not own database objects)
but are simply users accessing other schemas.
EXAM TIP Any user that has created a database object (view, table, etc.)
owns a schema and is considered a schema user.
ch07.indd 2
6/30/2005 5:01:15 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
3
PART I
To relate the concept of schema users and non-schema users to a real-world example,
think of it as being similar to your still living with your parents. Your parents own the
house that you live in, just as an Oracle user owns a schema. They allow you to live in
the house (with or without cost), which makes you the non-schema user, since you
do not own the house. In fact, they have given you permission to access objects in the
house (your room, the bathroom, the kitchen, and—most important—the fridge),
much as a schema owner grants privileges to other Oracle users to access a table or
other object. The schema owner always has the option to revoke any privileges granted
to objects in the database, just as a parent may have the option to kick you out of the
house if you overstay your welcome.
Creating Users
Gaining access to an Oracle database requires that you have a user account in the
database, which is created for you by the DBA. The DBA is an Oracle user who has
been granted all permissions in the database because he owns the database. The user
SYS in Oracle has that power and has also granted it to the SYSTEM user by granting
SYSTEM the DBA role (roles will be explained in the next section of this chapter). SYS
can also grant this authority to other Oracle users, so that not everyone needs to know
the SYS or SYSTEM password. The password for the SYS user is always “change_on_
install” by default, and for user SYSTEM, it is “manager” if you create the database from
the command line using the CREATE DATABASE statement. If you use the Database
Configuration Assistant to create a database, you will be prompted to specify passwords
other than the default for these users. In any case, ensure that the default passwords
are not the ones used for SYS or SYSTEM; otherwise, you are making a hacker’s job
rather easy.
EXAM TIP Oracle Database 10g databases will typically have many more
users besides SYS and SYSTEM defined when the database is created. The
majority of these users will have their accounts locked and will need to be
manually unlocked by the DBA or when running DBCA.
The command that creates a user in Oracle is the CREATE USER command. The
syntax for this command is listed here, while Table 7-1 provides additional information
on the various parameters for the CREATE USER command listed in the syntax.
CREATE USER username
IDENTIFIED [BY password | EXTERNALLY | GLOBALLY AS extname]
[DEFAULT TABLESPACE tablespacename]
[TEMPORARY TABLESPACE tablespacename]
[ACCOUNT LOCK | UNLOCK]
[PROFILE profilename | DEFAULT]
[PASSWORD EXPIRE]
[QUOTA num [K|M] | UNLIMITED ON tablespace
[QUOTA num [K|M] | UNLIMITED ON tablespace] ... ]
ch07.indd 3
6/30/2005 5:01:16 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
Parameter
Description
username
The name of the user to be created. The name must be specified and must be unique
within the database. A username can be up to 30 characters long and must adhere to
Oracle naming conventions (starts with a letter and may contain numbers; letters; or
the symbols #, _, or $).
IDENTIFIED
Specifies how the user will have their authenticity validated. The three methods include:
—BY password, where password represents a DBA-specified password of up to 30
characters. The database will check the credentials provided by the user against the
username and passwords in the data dictionary and deny or grant access, depending
upon whether or not a match is found.
—EXTERNALLY, where the username will be authenticated by the operating system
of the computer on which the database is running and Oracle will allow access if the
operating system authenticates the user. In order to configure this type of authentication,
some additional processes are involved.
—GLOBALLY AS extname, where the username and password will be passed to
the extname service for logon validation. This type of authentication requires external
authentication mechanisms, such as a RADIUS server.
DEFAULT
TABLESPACE
The name of a tablespace that will be used to store segments created by the user if no
tablespace is specified at object creation time. If the DEFAULT TABLESPACE parameter
is not specified at user creation time, the tablespace configured at the database level
to be the database default tablespace will be used. If no database default tablespace is
configured, this parameter defaults to SYSTEM. It is strongly recommended that you
always specify a DEFAULT TABLESPACE for the user and assign the user a quota on
this tablespace if you expect her to create segments.
TEMPORARY
TABLESPACE
The name of a tablespace that will be used to store temporary segments, such as sort
segments. If the TEMPORARY TABLESPACE parameter is not specified at user creation
time, the tablespace configured at the database level to be the database temporary
tablespace will be used. If no database temporary tablespace is configured, this parameter
defaults to SYSTEM. It is strongly recommended that you specify a TEMPORARY
TABLESPACE for the user.
ACCOUNT
LOCK |
UNLOCK
Allows you to explicitly lock or unlock a user account at creation time. The default for
this parameter is UNLOCK, which means that a user can connect to the instance as soon
as the account is created and the appropriate privileges granted.
PROFILE
Specifies the profile that will be assigned to the user. The profile will determine password
management and, optionally, resource limits that will apply to the user. If this parameter is
not specified, or if the keyword DEFAULT is used, the user will be assigned the DEFAULT
profile.
PASSWORD
EXPIRE
This parameter allows you to automatically expire the user’s password at creation time,
forcing them to change the password the first time a successful connection to the instance
is established. The default behavior is not to expire the user’s password, though use of
this parameter is recommended.
QUOTA
Lets you configure a quota for the user on tablespaces in the database. The quota is
specified in bytes, kilobytes (K), or megabytes (M).You should specify a quota on the user’s
DEFAULT TABLESPACE if you expect the user to create segments.You should not specify
an UNLIMITED quota on a tablespace for a regular user.
Table 7-1 CREATE USER Command Parameters
You can also use Oracle Enterprise Manager to create a user, as well as see the
syntax to perform the action. Enterprise Manager also allows the creation of users
with similar settings as an already-existing database user.
ch07.indd 4
6/30/2005 5:01:17 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
5
In this exercise you will connect to Enterprise Manager and create a database user.
PART I
Exercise 7-1: Using Enterprise Manager
to Create a Database User
1. Start a web browser and connect to the Enterprise Manager URL on your
Oracle database server, specifying the appropriate port number and machine
name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
4. Click the Users hyperlink under Security to display the users currently defined
in the database and their statuses and parameters.
ch07.indd 5
6/30/2005 5:01:17 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
5. Click Create to display the Create User page.
6. Enter values for the parameters required, including a username and a password,
confirming the password of your choice. Choose a default tablespace (use
USERS if it exists; otherwise, use the flashlight to select a tablespace in the
database) and a temporary tablespace (use TEMP if it exists), and ensure
that the status is Unlocked and Expire Password Now is unchecked.
7. Click Show SQL to display the code for creating the user. Notice the
“GRANT CONNECT TO ” portion of the code. This grants
the user the CONNECT role, which allows him to connect to the instance.
Without the CONNECT role granted, the user would get an error when
attempting to connect to the instance. Creating a user account by itself
does not grant the user permission to connect to the instance and access
the database.
ch07.indd 6
6/30/2005 5:01:18 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
7
PART I
8. Click Return to return to the Create User page.
9. Click OK to create the User. You should be returned to the list of users with
your user now visible in the list. Verify this and then close Enterprise Manager.
Modifying User Properties
While it is possible to have users never change anything for the duration of their
existence in the database, this is probably not a good security practice, nor is it likely.
Users may forget their password, or you may need to specify a different tablespace as
the user’s default tablespace, or grant new quotas or increased quotas for the user’s
objects, or lock out a user temporarily. The ALTER USER command can be used to
accomplish these tasks. Its syntax is as follows:
ALTER USER username
IDENTIFIED [BY password | EXTERNALLY | GLOBALLY AS extname]
[DEFAULT TABLESPACE tablespacename]
[TEMPORARY TABLESPACE tablespacename]
[ACCOUNT LOCK | UNLOCK]
[PROFILE profilename]
[PASSWORD EXPIRE]
[QUOTA num [K|M] | UNLIMITED ON tablespace
[QUOTA num [K|M] | UNLIMITED ON tablespace] ... ]
ch07.indd 7
6/30/2005 5:01:19 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
As you can see, the syntax hardly varies from that of the CREATE USER command.
The options available are the same. Perhaps one of the most useful features of the
ALTER USER command is that a database user can also issue this command to change
their password, as follows:
ALTER USER Damir IDENTIFIED BY newpassword;
EXAM TIP All user properties except the username can be modified using
the ALTER USER command.
Note that the password itself is not masked when the command is issued. If you
want the password masked, you can use the Edit User page in Enterprise Manager
to change a user’s password, though this is not a method the user himself could use.
Enterprise Manager can also be used to perform any other action in modifying a
user, such as assigning a quota.
Dropping Users
If you guessed that the DROP USER command is the one that removes a user from a
database, you would be correct. However, the syntax is not as simple as “DROP USER
username” because of the possibility that the user may have a schema. If a user owns
objects in the database, his account cannot be dropped, because other users may depend
on the objects in that schema. The syntax of the DROP USER command is as follows:
DROP USER username [CASCADE]
Oracle prevents you from dropping a user from a database whose schema contains
objects. This is to ensure that objects created by one user and depended upon by
another user’s objects are not inadvertently removed from the database. Since the user
and the schema are linked, dropping the user will also drop the schema. Oracle does
not allow you to drop both the user and the schema, unless you specify the CASCADE
option on the DROP USER command.
Using the CASCADE option will drop all objects, as well as any data contained in
tables, that the user owns (i.e., that are in the user’s schema). This can have drastic side
effects in the database if not planned properly. It is always recommended that before
dropping a user, you determine if the user owns any objects in the database, and if so,
drop the objects after verifying that they are not depended upon by other users.
EXAM TIP To drop a schema user, you must specify the CASCADE option
of the DROP USER command or, preferably, drop the user’s objects first and
then drop the user.
ch07.indd 8
6/30/2005 5:01:20 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
9
SQL> SELECT OBJECT_NAME, OBJECT_TYPE FROM DBA_OBJECTS
2 WHERE OWNER='DAMIR';
PART I
To find out which objects are owned by a user you wish to drop, you can query
the DBA_OBJECTS view. If you get zero rows returned, as in the following example,
you can safely drop the user:
no rows selected
On the other hand, if you do get a list of objects back, you should also query
the DBA_DEPENDENCIES view to determine which objects are dependent on those
owned by the user you wish to drop.
Granting and Revoking Privileges
Once you have created user accounts in Oracle, you will need to allow those users to
perform certain actions in the database or to access and manipulate objects in the
database. This is accomplished through the granting and revoking of different privileges
(or permissions). Oracle has two different types of privileges that can be granted:
system privileges and object privileges. System privileges allow a user to perform
certain database actions, such as create a table, or create an index, or even connect to
the instance. Object privileges allow a user to manipulate objects, as by reading data
through a view, executing a stored procedure, or changing data in a table. System
privileges are granted to and revoked from users by the DBA, while object privileges
are granted to and revoked from users by the owner of the object.
System Privileges
Oracle 10g has well over one hundred system privileges that can be granted to users,
of which some of the most common are listed in Table 7-2. These privileges include
the capability to create various database objects, modify the configuration of the
database, and many more. The right to grant these privileges is restricted to the DBA
by default, though these permissions can be granted to other users as well.
Granting System Privileges
You can grant system privileges either using the command line or through Oracle
Enterprise Manager. The syntax for assigning system privileges is as follows:
GRANT privilege [, privilege, ...]
TO username [, username, ...]
[WITH ADMIN OPTION];
As you can see by this syntax, it is possible to grant multiple privileges to multiple
users at the same time. The privileges granted to a user are immediately available to
the user. This means that the user does not need to disconnect from the instance and
log in again in order for the privilege change to take effect. Simply granting the
privilege lets the user make use of it right away.
ch07.indd 9
6/30/2005 5:01:21 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
Privilege
Description
CREATE SESSION
Allows the grantee to connect to the database instance. After creating
a new user, you need to grant the CREATE SESSION privilege;
otherwise, the user will not be able to connect.
CREATE TABLE
Allows the grantee to create a table in her schema.
CREATE VIEW
Allows the grantee to create a view in her schema.
CREATE SYNONYM
Allows the grantee to create a private synonym in her schema.
CREATE PUBLIC
SYNONYM
Allows the grantee to create a synonym in the SYS schema that can
be used by any user in the database.
CREATE
PROCEDURE
Allows the grantee to create a stored procedure or function in her
schema.
CREATE SEQUENCE
Allows the grantee to create a sequence in her schema.
CREATE TRIGGER
Allows the grantee to create a trigger in her schema on a table in her
schema.
CREATE USER
Allows the grantee to create another user in the database and specify
the password and other settings at creation time.
ALTER USER
Allows the grantee who has been granted the privilege to modify the
user information of another user in the database, including changing the
user’s password.
DROP ANY TABLE
Allows the grantee to drop any table in any schema in the database.
ALTER ANY TABLE
Allows the grantee to alter any table in any schema in the database.
BACKUP ANY TABLE
Allows the grantee to make a copy of any table in the database using
the Export utility (exp).
SELECT ANY TABLE
Allows the grantee to issue a SELECT statement against any table
in the database, whether or not permissions to the table have been
explicitly granted to the grantee performing the action.
INSERT ANY TABLE
Allows the grantee to issue an INSERT statement against any table
in the database, whether or not permissions to the table have been
explicitly granted to the grantee performing the action.
UPDATE ANY TABLE
Allows the grantee to issue an UPDATE statement against any table
in the database, whether or not permissions to the table have been
explicitly granted to the grantee performing the action.
DELETE ANY TABLE
Allows the grantee to issue a DELETE statement against any table
in the database, whether or not permissions to the table have been
explicitly granted to the grantee performing the action.
Table 7-2 Commonly Granted System Privileges in Oracle 10g
For example, if you want to allow Damir to create tables, views, triggers, indexes,
synonyms, and sequences in his schema, you can issue the following command:
GRANT CREATE TABLE, CREATE VIEW, CREATE SYNONYM,
CREATE SEQUENCE, CREATE TRIGGER, CREATE INDEX
TO Damir;
ch07.indd 10
6/30/2005 5:01:21 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
11
PART I
Just because a user has been granted a system privilege does not always mean that
the user can exercise that privilege, as evident by this error indicating an insufficient
quota for Damir on the USERS tablespace when Damir tries to connect to the instance
and create a table:
SQL> connect Damir/newpass1@ocp10g.haunting.com
Connected.
SQL> CREATE TABLE DamirTable
2 (DamirID number,
3 Name varchar2(40));
CREATE TABLE DamirTable
*
ERROR at line 1:
ORA-01950: no privileges on tablespace 'USERS'
WITH ADMIN OPTION When a user is granted a system privilege, the grantor
(i.e., the person granting the privilege, typically the DBA) also has the option to allow
the grantee (the person receiving the privilege, typically the user) to grant the same
privilege to other users. If this is the result desired, the grantor can grant the privilege
using the WITH ADMIN OPTION. When privileges are granted WITH ADMIN OPTION,
this means that the grantor has decided that the grantee can be fully trusted by him as
well as by the user that granted him the system privilege in the first place. In essence
all users holding a system privilege WITH ADMIN OPTION are considered equal and
can grant and revoke that privilege from anyone, including the person who granted it
to them in the first place.
EXAM TIP The WITH ADMIN OPTION allows you to grant your grantee the
ability to grant system privileges to other users.
Exercise 7-2: Using Enterprise Manager
to Grant System Privileges
In this exercise you will connect to Enterprise Manager and create additional database
users and grant them system privileges.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server, specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
4. Click the Users hyperlink under Security to display the users currently defined
in the database and their statuses and parameters.
ch07.indd 11
6/30/2005 5:01:22 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
5. Click Create to display the Create User page.
6. Fill in the values to create a new user called John with a password of “oracle,”
a default tablespace of USERS, and a temporary tablespace of TEMP. Ensure
that the account is not locked and that the password is not set to expire; then
click OK to create the user.
7. Create two additional users—Tim and Jessica—with the same settings as John.
8. Open another browser window and connect to iSQL*Plus for your database
instance and log in as the user SYSTEM with the appropriate password.
9. Enter the following SQL statements in the Workspace window and then click
Execute to run them:
GRANT CREATE TABLE TO JOHN WITH ADMIN OPTION
/
GRANT CREATE VIEW TO TIM
/
GRANT SELECT ANY TABLE TO JESSICA
/
ch07.indd 12
6/30/2005 5:01:22 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
13
10. Log out from iSQL*Plus and then log in as John with the appropriate password.
CREATE TABLE JOHN1 (JohnID NUMBER);
PART I
11. Issue the following command to create a table and notice the error you receive
due to an absence of quota on the tablespace:
12. Go back to Enterprise Manager and select the user John in the user list; then
click Edit.
13. Click the Quotas hyperlink for the user, and then for the Users tablespace
select Value from the Quota drop-down. Enter 50 in the Value column to
grant the user John a 50MB quota on the Users tablespace, as shown next,
and then click Apply.
ch07.indd 13
6/30/2005 5:01:23 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
14. Modify the quota for the Users tablespace for users Tim and Jessica to also
be 50MB.
15. In iSQL*Plus connected as John, attempt to re-create the John1 table again.
Notice that the command succeeded, since John now has a quota on the
Users tablespace.
16. Insert some data into the John1 table by issuing the following commands
in iSQL*Plus and then clicking Execute:
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
COMMIT;
ch07.indd 14
JOHN1
JOHN1
JOHN1
JOHN1
JOHN1
VALUES
VALUES
VALUES
VALUES
VALUES
(100);
(101);
(102);
(103);
(104);
6/30/2005 5:01:24 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
15
18. Log out from iSQL*Plus as John and log in as Tim.
19. Attempt to query data in the John1 table. Notice the error indicating that the
object cannot be found, which really means you don’t have permissions.
PART I
17. Issue the command GRANT CREATE TABLE TO TIM to allow Tim to create
tables, and then click Execute.
20. Issue the same CREATE TABLE JOHN1 command as previously while
connected as Tim. Notice that it is possible to create two tables called
John1 as long as they are in different schemas.
21. Log out of iSQL*Plus and log in again as Jessica.
ch07.indd 15
6/30/2005 5:01:25 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
22. Attempt to query the John1 tables in both the John and Tim schemas. Notice
that you can perform these actions, since Jessica has been granted the SELECT
ANY TABLE privilege.
23. In Enterprise Manager, select Jessica and click View to display information on
Jessica’s user account and the privileges granted to her.
ch07.indd 16
6/30/2005 5:01:26 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
17
PART I
24. Log out of iSQL*Plus and Enterprise Manager.
Revoking System Privileges
If you do not want anyone to continue to have a system privilege granted to them,
you can use the REVOKE command or Enterprise Manager to remove the privileges
granted. The syntax of the REVOKE command to revoke system privileges is very
ch07.indd 17
6/30/2005 5:01:27 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
similar to that of granting it and can be used to revoke one or more privileges from
one or more users/grantees, as follows:
REVOKE privilege [, privilege, ...]
FROM username [, username, ...];
It is important to note one side effect when the WITH ADMIN OPTION is specified
at the time a system privilege is granted. While the DBA may revoke the privilege granted
to the user WITH ADMIN OPTION, if the user has granted that same privilege to others,
it is not removed from those users that were granted the privilege. For example, if you
give the key to your car to a friend and tell him that it is alright to make copies of the
key, when you ask for the key back from your friend, you cannot, at the same time, get
back all copies that were made by him and given to others. In order to get the other
copies of the key back, you need to find out who has them. Similarly, in Oracle you
need to query the data dictionary to determine which other users were granted the
permission being revoked by the user from which it is being revoked.
EXAM TIP Revoking system privileges from a user will not cascade to anyone
the revokee granted the same system privilege if he had been granted the
privilege WITH ADMIN OPTION.
Determining System Privileges Granted
If you want to find out which system privileges you have been granted, you can query
the DBA_SYS_PRIVS (for all system privileges granted to all users) and USER_SYS_
PRIVS (for system privileges granted to the currently logged-on user) data dictionary
views. These views will let you see which privileges you have been granted and whether
or not they have been granted WITH ADMIN OPTION. Only those system privileges
that have been granted will appear on the list. Any privileges that have been revoked
will not be listed, as Oracle does not keep track of permissions denied a user. The
default for Oracle is to deny all actions except those explicitly granted; therefore, only
those explicitly granted are listed.
To determine which privileges have been granted to individual users, you can use
Enterprise Manager to display the user information, including privileges and quotas.
Object Privileges
Users in Oracle can also be granted object privileges. Object privileges allow a user to
manipulate data in the database or perform an action on an object, such as executing
a stored procedure. Unlike system privileges, which are granted by the DBA, object
privileges need to be granted by the owner of the object.
Granting Object Privileges
The syntax to assign object privileges is as follows:
ch07.indd 18
6/30/2005 5:01:28 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
19
The major difference in the syntax between system and object privileges is that the
keyword ON needs to be specified to determine which object the privileges apply to.
Furthermore, object privileges for views and tables can also specify which column of
the view or table they should be applied to. The keyword ALL specifies that all privileges
that apply to the object should be granted. The privilege can be granted to a user, a role
(to be discussed later), or the keyword PUBLIC, which means all users in the database.
PART I
GRANT privilege [,privilege, ...] | ALL [(column[, column, ...])]
ON objectname
TO user | role | PUBLIC
[WITH GRANT OPTION];
EXAM TIP Object privileges are granted by the owner of the object.
The types of privileges that can be granted depend on the object that they are being
granted on. For example, it makes no sense to grant the SELECT privilege to a stored
procedure, while the SELECT privilege makes perfect sense on a table. The object
privileges that can be granted and the object they can be granted to are outlined in
Table 7-3. For example, you cannot issue an ALTER VIEW command, so therefore the
ALTER privilege cannot apply to a view, and so on.
One privilege that requires a bit of an explanation is the REFERENCES privilege.
The REFERENCES privilege is one that can be granted to a user to create a FOREIGN
KEY on a column of a table. By granting the user the REFERENCES privilege, you do
not need to allow the user to be able to see that data, as they would with the SELECT
privilege, but are only allowing them to reference the data in the FOREIGN KEY. The
SELECT permission alone is not sufficient to create a FOREIGN KEY or view that
references a column in the table; the REFERENCES permission is also required. Even
if the user has the SELECT permission on the table, the creation of a FOREIGN KEY or
view will fail without the REFERENCES permission.
Table 7-3
Privileges and
the Objects
They Can Be
Granted On
ch07.indd 19
Privilege
Granted On
SELECT
Table, view, sequence
INSERT
Table, view
UPDATE
Table, view
DELETE
Table, view
ALTER
Table, sequence
INDEX
Table
REFERENCES
Table
EXECUTE
Procedure, function, package
6/30/2005 5:01:28 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
NOTE It is generally not recommended, and often frowned upon, to grant
object privileges at the column level. The management of many column-level
privileges can become quite time consuming, as well as confusing. Generally,
it is recommended that when you need to assign privileges to only certain
columns of a table, you should create a view including only those columns and
grant the appropriate permission on the view itself. This way, if you drop the
view or remove permission from the view for a user, the management is easier
and cleaner.
WITH GRANT OPTION Similar to the WITH ADMIN OPTION of system
privileges, the WITH GRANT OPTION on object privileges allows a user granted
the privilege to grant it to someone else. The reason for doing this is to minimize the
administrative burden of granting object privileges.
Revoking Object Privileges
Revoking object privileges has similar syntax to granting them, as follows:
REVOKE privilege [,privilege, ...] | ALL [(column[, column, ...])]
ON objectname
FROM user | role | PUBLIC
[CASCADE CONSTRAINTS];
Unlike the WITH ADMIN OPTION for system privileges, if an object privilege is
revoked from a user to whom it was granted WITH GRANT OPTION, that privilege
would also be removed from anyone that user granted the privilege to. For example,
if Damir granted John the SELECT privilege on the DAMIR.JOHN1 table WITH GRANT
OPTION, and John then granted the SELECT privilege to Tim, then if Damir issued
the command REVOKE SELECT ON DAMIR.JOHN1 FROM JOHN, Tim would also
no longer have the privilege. This is because when object privileges are revoked, the
revoke also cascades to anyone that the privilege was granted to by the user from
whom it is being revoked.
EXAM TIP Object privileges revoked from a user to whom they were granted
WITH GRANT OPTION will also be revoked from anyone the revokee
granted them to; i.e., the revoke will cascade.
The CASCADE CONSTRAINTS option of the REVOKE command for object
privileges is needed in those situations where a user has been granted REFERENCES
permission on a table in your schema, and they have used this privilege to create a
table with a FOREIGN KEY constraint depending upon the table you own. Attempting
to revoke the REFERENCES privilege will generate an error:
ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke
To correct the problem, simply reissue the command using the CASCADE
CONSTRAINTS option. When using the CASCADE CONSTRAINTS option of the
ch07.indd 20
6/30/2005 5:01:29 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
21
PART I
REVOKE command for object privileges, verify that any FOREIGN KEY created in
another schema referencing the table is no longer required. One of the things you do
not want to do is break the database and invite inconsistent data by simply revoking
an object privilege. If you do get the ORA-01981 error, query the data dictionary to
determine which objects are referencing the table and notify those table’s owners of
your intentions prior to performing the action.
Determining the Object Privileges Granted
As for system privileges, Oracle also allows a user to determine which object privileges
have been granted to him/her by querying the data dictionary, or by using Enterprise
Manager. These are some of the data dictionary views that can be used to determine
which privileges have been granted to a user or granted by the user:
• USER_TAB_PRIVS_MADE Object privileges the user has granted to others
on his schema objects
• USER_TAB_PRIVS_RECD Privileges granted to the user to objects in other
schemas
• ALL_TAB_PRIVS_MADE Object privileges the user has granted to others on
his and other schema objects
• ALL_TAB_PRIVS_RECD Privileges granted to the user to objects in his and
other schemas
• USER_COL_PRIVS_MADE Column privileges granted by the user to tables
in his schema
• USER_COL_PRIVS_RECD Column privileges granted to the user to columns
in tables in other schemas
• ALL_COL_PRIVS_MADE Column privileges granted by the user to tables in
his and other schemas
• ALL_COL_PRIVS_RECD Column privileges granted to the user to columns
in tables in his and other schemas
Exercise 7-3: Using Enterprise Manager
to Grant Object Privileges
In this exercise you will connect to Enterprise Manager and grant and revoke privileges
to users on schema objects and then test the results.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server, specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
ch07.indd 21
6/30/2005 5:01:29 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
22
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
4. Click the Users hyperlink under Security to display the users currently defined
in the database and their statuses and parameters.
5. Click the user Damir created in a pervious exercise to bring up the Edit
User page.
6. Click the Object Privileges hyperlink to display the existing list of object
privileges granted to the user. The list should be empty.
ch07.indd 22
6/30/2005 5:01:30 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
23
8. Enter JOHN.JOHN1 as the table name (or use the flashlight to find the table
in the data dictionary) and choose the SELECT, INSERT, UPDATE, and DELETE
privileges from the list; then click Move.
ch07.indd 23
PART I
7. On the Select Object Type drop-down list box, select Table and then click Add
to display the Add Table Object privilege page.
6/30/2005 5:01:31 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
24
9. Click OK to save your changes and display the updated list of object
privileges.
10. For the SELECT privilege check the check box under the Grant Option heading
and then click Show SQL to display the SQL code to grant the privileges.
ch07.indd 24
6/30/2005 5:01:32 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
25
PART I
11. Click Return and then Apply to save your changes.
12. Invoke a browser and connect to iSQL*Plus and the database as DAMIR with
the appropriate password.
13. Issue the command SELECT * FROM JOHN.JOHN1 to make sure you can
query the table you have just been granted privileges on. Also insert a row
into the table, and delete and update a row to test all privileges.
ch07.indd 25
6/30/2005 5:01:32 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
26
14. Issue the command GRANT SELECT ON JOHN.JOHN1 TO TIM and verify
that it succeeds.
15. Attempt to grant the INSERT privilege on the JOHN.JOHN1 table and review
the error you receive.
16. From a different browser window and in another iSQL*Plus session, connect
as Tim and attempt to query the JOHN.JOHN1 table.
17. As Tim, issue the command CREATE VIEW JOHN1VIEW AS SELECT * FROM
JOHN.JOHN1. Remember that Tim has previously been granted the CREATE
VIEW system privilege.
18. Issue the command SELECT * FROM JOHN1VIEW and see that all the data
from the JOHN.JOHN1 table appears.
19. Attempt to insert a row in the JOHN.JOHN1 table. Notice the “ORA-01031:
insufficient privilege” error message.
20. Log out of iSQL* Plus as Tim and log in as John with the appropriate password.
21. Issue the command REVOKE ALL ON JOHN.JOHN1 FROM DAMIR.
22. In the iSQL*Plus session where you are logged in as Damir, attempt to select
from the JOHN.JOHN1 table. Notice the “ORA-00942: table or view does not
exist” error.
23. Log out as Damir, log in to iSQL*Plus as Tim, and then attempt to query
the JOHN1VIEW view. Notice the message indicating the view has an error.
Attempt to SELECT from the JOHN.JOHN1 table and notice the error.
24. Issue the command DROP VIEW JOHN1VIEW.
25. Close all iSQL*Plus and Enterprise Manager sessions.
Creating and Managing Roles
Up to this point you have seen how to assign permissions to other users. In small
environments assigning permissions directly to users may be sufficient, especially if
new users need to be created in the database only occasionally. However, in more
complex or larger environments, or those where users are added and deleted frequently,
Oracle provides a mechanism to group permissions together and then assign the
whole group of permissions to a user: the ROLE.
A role is a container that holds privileges. The main benefit of a role is that it
simplifies the process of granting privileges to users. To make the process efficient, a
DBA creates a role and then grants all of the privileges required by a user to perform
a task to the role. If another user comes along that needs to perform the same task,
instead of granting that user the permission explicitly, the DBA grants the user the
role. Any privileges that have been granted to a role that has been granted to a user
automatically apply to the user. Similarly, if you need to grant new privileges to users
or revoke existing privileges from users, and if these were granted to a role rather than
users, you need to grant or revoke the privileges only once—at the role level—instead
ch07.indd 26
6/30/2005 5:01:33 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
27
PART I
of numerous times. Furthermore, those privileges granted will be automatically active
once the grant or revoke takes place. Changes to role privileges are dynamically modified
for all users holding the role.
When you grant privileges to users, those privileges will be available no matter
how the user accesses the database. This means that someone using a front-end client
application that presents preconfigured forms may need the same level of privileges as
someone connecting to the instance using iSQL*Plus and performing interactive queries.
The problem with this is that a user of the front-end application could also connect
to the instance and perform deletes, or other data manipulation, that may be more
controlled through the front-end application. Roles, which can be selectively enabled
and disabled, allow you to provide the user with additional privileges by enabling
them when the user is using the front-end application, but not allow the user to have
the same set of privileges if they connect to the instance using iSQL*Plus.
EXAM TIP Roles are containers for privileges or other roles and can be
authenticated externally.
Roles, in a similar fashion to database users, can be authenticated by the operating
system instead of the Oracle server. Creating roles that are authenticated by the operating
system allows you to create groups at the OS level and map their membership to roles
in the database, and grant those individuals that are members of an OS group additional
privileges. This can also allow you to have individuals who just joined your company,
or have been moved into new positions within the organization, that have been granted
certain group membership by the system administrator automatically inherit database
privileges that can allow them to do their job (and you did not have to do anything).
Of course, the other edge of this sword means that you, as a DBA, have now lost some
control over who can perform certain actions in the database. In other words, having
roles authenticated by the OS can be both good and bad, depending on how it is
implemented.
When you revoke an object privilege from a user in Oracle, if that user was granted
the privilege WITH GRANT OPTION, anyone that the user granted the privilege to
will also have it revoked. With roles, there are no cascading revokes for object privileges
granted to roles, because you cannot grant object privileges to a role WITH GRANT
OPTION; the syntax is not allowed. However, you can grant a system privilege, or
another role, to a role WITH ADMIN OPTION. Doing so allows anyone granted the
role to grant those system privileges or roles to others.
Finally, the evaluation of roles by the database takes less work than evaluating
privileges assigned to users directly. This means—in a nutshell—that roles provide
better performance than granting privileges directly to users. This is because the
privileges granted to a role can be cached in the data dictionary cache when they are
first used and do not need to be reloaded, unless flushed out, the next time a user
who has been assigned the role makes use of the privileges. Individual user privileges
must be checked against the data dictionary each time a command is sent to the
server, and will be cached only if they are frequently used.
ch07.indd 27
6/30/2005 5:01:34 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
28
Predefined Roles
Every Oracle 10g database, once created and once the CATPROC.SQL and CATALOG
.SQL scripts are run, will include a number of predefined roles. Some of these still exist
for backward compatibility with previous versions, whereas some are there to ease
administration and to provide the DBA with the necessary privileges to do his/her job.
In fact, the DBA gets all of the privileges required to manage the database through a
predefined role called, ironically enough, “DBA.” Table 7-4 lists the predefined roles in
an Oracle 10g database. Other roles will be created as you install additional database
options or functionality.
In your database you may also find that other roles are created. They are most
likely there because you have enabled certain database functionality. For example, if
your database will host a Recovery Catalog to be used by Recovery Manager for storing
information about backup and restore operations, you may find that your database
Role
Privileges Granted
DBA
Almost all system privileges and some roles
SELECT_CATALOG_ROLE
Object privileges on the data dictionary. No system privileges
EXECUTE_CATALOG_ROLE
Object privileges on data dictionary packages, procedures and
functions
DELETE_CATALOG_ROLE
DELETE ON SYS.AUD$
DELETE ON SYS.FGA_LOG$
EXP_FULL_DATABASE
Privileges to query any table or sequence, execute any
procedure or type, and modify data dictionary objects when
exporting data from the database
IMP_FULL_DATABASE
Privileges to create any object in any schema in the database,
except the SYS schema when performing an import
CONNECT
ALTER SESSION
CREATE CLUSTER
CREATE DATABASE LINK
CREATE SEQUENCE
CREATE SESSION
CREATE SYNONYM
CREATE TABLE
CREATE VIEW
RESOURCE
CREATE CLUSTER
CREATE INDEXTYPE
CREATE OPERATOR
CREATE PROCEDURE
CREATE SEQUENCE
CREATE TABLE
CREATE TRIGGER
CREATE TYPE
UNLIMITED TABLESPACE (when granted)
Table 7-4 Sample List of Predefined Roles in Oracle 10g and the Permissions Granted to Them
ch07.indd 28
6/30/2005 5:17:47 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
29
Privileges Granted
AQ_ADMINISTRATOR_ROLE
Object privileges on Advanced Queuing objects
CREATE EVALUATION CONTEXT
CREATE RULE
CREATE RULE SET
DEQUEUE ANY QUEUE
ENQUEUE ANY QUEUE
MANAGE ANY QUEUE
AQ_USER_ROLE
EXECUTE ON SYS.DBMS_AQ
EXECUTE ON SYS.DBMS_AQIN
EXECUTE ON SYS.DBMS_AQJMS_INTERNAL
EXECUTE ON SYS.DBMS_TRANSFORM
SCHEDULER_ADMIN
CREATE ANY JOB
CREATE JOB
EXECUTE ANY CLASS
EXECUTE ANY PROGRAM
MANAGE SCHEDULE
(All are granted WITH ADMIN OPTION)
PUBLIC
No special permissions, but when permissions are granted
to PUBLIC, all users inherit those permissions
PART I
Role
Table 7-4 Sample List of Predefined Roles in Oracle 10g and the Permissions Granted to Them
(continued)
includes the RECOVERY_CATALOG_OWNER role. If you use Oracle Enterprise Manager,
you may also have an OEM_MONITOR role created, and so on. The number of
predefined roles depends on the features selected and enabled.
If you find that these roles meet your needs, then you should make use of them.
However, if you find that they do not provide all the functionality required, or they
give away too many privileges, like CONNECT and RESOURCE, then do not use them
but create your own roles and assign them the privileges you want users to have.
EXAM TIP The CONNECT role is automatically granted to a user when
the user is created with Enterprise Manager. Be aware of the privileges this
provides the user.
Creating Roles
Like most other security-related items in Oracle, you can create roles from the command
line using iSQL*Plus or with Enterprise Manager. In order to create a role, you must
have been assigned the CREATE ROLE system privilege, or the DBA role. The syntax
for the CREATE ROLE command is
CREATE ROLE rolename
[NOT IDENTIFIED | IDENTIFIED
BY password | EXTERNALLY | GLOBALLY];
ch07.indd 29
6/30/2005 5:18:20 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
30
The name of each role must be unique in the database and cannot be the same as
that of an existing user, since users and roles are both stored in the same place in the
data dictionary. When you issue the CREATE ROLE command, the default is to create
a role with the name specified and not require any authentication to have the role
enabled for the user. However, if you want to enable the role through an application,
you can specify a password for the role by using the IDENTIFIED BY clause followed
by the password.
You can also have the role IDENTIFIED EXTERNALLY, which means that the user
must be a member of an operating system group with a name that corresponds to the
role in order for it to be enabled. In order for roles to be authenticated by the operating
system, you need to set the Oracle initialization parameter OS_ROLES to TRUE (the
default is FALSE). Once you have decided that you want to support roles that are
IDENTIFIED EXTERNALLY, you will need to create groups on the server where the
database resides with a naming convention as follows:
ora__[_[d][a]]
The naming convention is used to ensure that the proper group membership can
be assigned at the OS level to users that need the roles. The parts that make up the
group name have these meanings:
• The value of the ORACLE_SID parameter for the instance to which
the user will be connecting. It should ideally be the same as the name of the
database. On Windows this value is not case sensitive; it is case sensitive on
most other platforms.
• The name of the role you created in the database to be IDENTIFIED
EXTERNALLY. In order for operating system authentication to work, the role
must still be created in the database, as well as the group being created at the
operating system.
• d Indicates that the role specified by the portion will be a default
role for the user. If either a or d, or both, are specified, they must be preceded
by an underscore.
• a Indicates that the role specified by the portion will be granted to
the user WITH ADMIN OPTION. If either a or d, or both, are specified, they
must be preceded by an underscore.
For example, if you create a role in the OCP10G database called JuniorAdmin that
will be identified externally, and if you want that role to be the default role for some
users and the default role but granted WITH ADMIN OPTION to others, you would
create two groups at the OS level called “ora_OCP10G_JuniorAdmin_d” and “ora_
OCP10G_JuniorAdmin_da.”
Modifying Roles
Once a role is created, its authentication method can be changed after the fact using
Enterprise Manager or by issuing the ALTER ROLE command:
ch07.indd 30
6/30/2005 5:01:36 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
31
Changes to role permissions or who it is granted to are done using the standard
GRANT and REVOKE commands.
PART I
ALTER ROLE rolename
[NOT IDENTIFIED | IDENTIFIED
BY password | EXTERNALLY | GLOBALLY];
Granting and Revoking Permissions for Roles
You grant permissions to roles just as you grant them to users: using Enterprise Manager
or the GRANT command. Permissions are revoked the same way as well: using the
REVOKE command. The syntax for granting system permissions to roles is as follows:
GRANT system_priv [, system_priv, ...]
TO role | PUBLIC [, role | PUBLIC, ...]
[WITH ADMIN OPTION];
For granting object privileges to roles the syntax is as follows:
GRANT ALL [PRIVILEGES] | object_priv [(column, column, ...)]
[, object_priv [(column, column, ...(] , ...]
ON [schema_name.]object_name
TO role | PUBLIC [, role | PUBLIC, ...];
Notice that you cannot grant object privileges WITH GRANT OPTION to roles, but
you can grant system privileges WITH ADMIN OPTION.
To revoke system and object privileges from roles, the syntax is similar to revoking
those same privileges from a user. For system privileges:
REVOKE system_priv | role_name [, system_priv | role_name, ...]
FROM role | PUBLIC [,role | PUBLIC, ...];
And for object privileges:
REVOKE ALL [PRIVILEGES] | object_priv [, object_priv, ...]
ON [schema_name.]object_name
FROM role | PUBLIC [,role | PUBLIC, ...]
[CASCADE CONSTRAINTS]
Granting and Revoking Roles for Users
Once you have created a role and granted the role its further roles, along with the object
and system privileges desired, you next need to assign the role to users that you want
to inherit all the privileges that the role has. To do so, you use the GRANT command
or Oracle Enterprise Manager. The syntax of the GRANT command to grant roles to
users (as well as other roles) is
GRANT role_name [, role_name, ...]
TO user_name | role | PUBLIC [, user_name | role | PUBLIC, ...]
[WITH ADMIN OPTION];
ch07.indd 31
6/30/2005 5:01:36 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
32
If you grant a role WITH ADMIN OPTION, you are allowing the user to whom
you are granting the role to also grant the role (and all its associated privileges) to
others. In order to grant a role to a user or another role, you need to be the owner of
the role (i.e., you are the user that issued the CREATE ROLE command) or have been
granted the GRANT ANY ROLE privilege by the DBA.
Just as you can grant a role to a user, you can also revoke the role to remove all of
the role’s privileges from the user using the REVOKE command or Oracle Enterprise
Manager. The syntax of the REVOKE command is again similar to what you have seen
previously, as follows:
REVOKE role_name [, role_name, ...]
FROM user_name | role | PUBLIC [, user_name | role | PUBLIC, ...];
If you revoke the role from a user, the role’s permissions will not be immediately
taken away from the user, unless the user disconnects from the instance or disables
the role. However, the user will not be able to reenable the role on the next connection
attempt or by using the SET ROLE command once it has been revoked.
Setting a User’s Default Roles
Once you grant a role to a user, it is automatically configured to be a default role. This
means that when the user connects to the instance, the role will automatically be
enabled for the user and any privileges that the role has been granted will be available
to the user. However, if you want some of the roles granted to the user to be active
only when the user connects to the instance, you need to modify the set of default
roles that are automatically enabled.
EXAM TIP All roles granted to a user are considered the user’s default
roles unless otherwise specified by the ALTER USER command or Enterprise
Manager.
The ALTER USER command, or Oracle Enterprise Manager, can be used to manage
a user’s default roles. The syntax of the ALTER USER command to manage a user’s
default role list is as follows:
ALTER USER username DEFAULT ROLE
role [, role, ...] | ALL [EXCEPT role [, role, ...]] | NONE;
If you do not want Oracle to enable all roles that a user has been granted, you must
use the ALTER USER command to disable any roles that you do not want the user to
have when they connect to the instance. You can then programmatically enable the
roles or have the user issue the SET ROLE command to enable those roles that you
disabled by default.
If you grant the user a role that requires a password, and if you make that role a
default role, the user will not be required to enter a password in order to make use of
ch07.indd 32
6/30/2005 5:01:37 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
33
PART I
the privileges granted to the role. In essence, making a role that has a password a
default role for the user bypasses the password requirement. In this way some users
may have the role and its privileges when they connect, by default, while other users
will be required to enable the role manually and specify a password in order to access
the privileges granted the role.
You can also disable all roles that have been assigned to the user by using the NONE
option when specifying which roles are default roles. After doing so, all roles granted
to the user will be disabled and will need to be enabled using the SET ROLE command.
The user will have only the capability to perform actions according to those system and
object privileges that have been assigned directly to him/her, or to PUBLIC.
Enabling and Disabling Roles
One of the major benefits of roles is the ability to selectively grant and revoke a set of
privileges by enabling and disabling roles that contain them. While a user is connected
to the instance, your application (typically) can issue the SET ROLE command, or
execute the DBMS_SESSION.SET_ROLE package procedure, to enable or disable roles
dynamically. A role that was created with a password will need to have the password
specified when it is enabled. This allows you to further control the enabling of roles
by users by ensuring that roles are enabled only while a particular application is being
used to connect to the database. The syntax for the SET ROLE command is as follows:
SET ROLE ALL [EXCEPT role_name [,role_name]] | NONE |
role_name [IDENTIFIED BY password] [, role_name [IDENTIFIED BY password, ...];
If you want to disable a role for a user, you need to issue the SET ROLE command,
or execute the DBMS_SESSION.SET_ROLE procedure a second time, omitting the role
that you do not want the user to have enabled. In other words, there is no “UNSET
ROLE” command or its equivalent.
Dropping Roles
If you no longer need a role that you have been using, you can drop it from the database
by issuing the DROP ROLE command, or by using Oracle Enterprise Manager. In order
to drop a role, you must be the user who created the role, have been granted the DROP
ANY ROLE system privilege, or have been granted the role WITH ADMIN OPTION. If
any of these is not true, the command will fail and the role will not be dropped. The
syntax of the DROP ROLE command is as follows:
DROP ROLE role_name;
When you drop a role, any user or role to which the role being dropped has been
granted will have it revoked at the time the role is dropped. Any privileges that the
role granted its holders will also be revoked at the time the role is dropped.
ch07.indd 33
6/30/2005 5:01:37 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
34
Exercise 7-4: Using Enterprise Manager
to Create and Manage Roles
In this exercise you will connect to Enterprise Manager and create a role, assign it
permissions, grant the role to a user, and then test the results.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server, specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
4. Click the Roles hyperlink under Security to display the roles currently defined
in the database and their statuses and parameters.
ch07.indd 34
6/30/2005 5:01:38 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
35
5. Click Create to display the Create Role page.
PART I
6. Enter OCP10GROLE as the role name and then expand the Authentication
drop-down list box and select None.
7. Click the Object Privileges hyperlink and grant the role OCP10GROLE all
permissions on the JOHN.JOHN1 table.
8. Click System Privileges and grant the role OCP10GROLE the CREATE VIEW
privilege.
ch07.indd 35
6/30/2005 5:01:39 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
36
9. Click Show SQL to display the SQL code to create the role and grant it
privileges.
10. Click Return and then OK to create the role OCP10GROLE.
11. Click the database hyperlink at the top left of the page, then Administration,
then Users, and then the user Tim.
12. Verify that Tim does not have permissions on the JOHN.JOHN1 table by
invoking iSQL*Plus in another browser session and issue a SELECT statement
to query the table.
13. In Enterprise Manager, grant Tim the role OCP10GROLE.
14. In iSQL*Plus, log out and then log in as Tim and verify that you can SELECT
from the JOHN.JOHN1 table.
15. Exit Enterprise Manager and iSQL*Plus.
ch07.indd 36
6/30/2005 5:01:40 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
37
One aspect of the Oracle security domain deals with ensuring that password management
and account lockout policies for the database are adhered to. These may be set at the
enterprise level and need to be enforced at the database level. Furthermore, as a DBA,
you may need to ensure that a database is available to all users and that no one user
is able to invoke a SELECT statement that performs a large query and consumes all
system resources, as an example. The creation and management of account lockout
and password policies, as well as limiting resource usage for a user’s session or an
individual SQL statement, is handled in Oracle by the use of profiles.
A profile is an Oracle object that allows you to set both password management and
resource limits. In every Oracle database a single profile is created when you create the
database. This profile, called DEFAULT, places no limits on password and account
lockout, or on resource utilization. You can change the settings of the DEFAULT profile
to conform to your requirements, and they will then be applied to all users in the
database assigned the DEFAULT profile.
A database administrator may create additional profiles dealing with password or
account lockout issues, resource management settings, or both. Once created, a profile
can be assigned to a user account as it is created, or it can be assigned to the user with
the ALTER USER command. Any settings in the profile will then apply to the user the
next time he/she connects to the database. A user may have only one profile active at one
time, so you need to ensure that the settings within the profile match the requirements
of each user.
When deciding to make use of profiles, it is important to understand what settings
are always applied and which require that you change your database and instance
configuration. Because of the very nature of security requirements, Oracle ensures that
password management and account lockout settings in profiles are always enforced.
Any settings dealing with security policy are considered important enough that simply
configuring them enables them. The utilization of system resources, such as CPU and
disk I/O, is not automatically enforced by Oracle. In order to have these aspects of a
profile limit a user’s actions, you need to enable them by setting them in the parameter
file (SPFILE or INIT.ORA file) or by changing the value of the RESOURCE_LIMIT
initialization parameter to TRUE with the ALTER SYSTEM command.
PART I
Using Profiles to Control Resource Usage
EXAM TIP Resource limits are enforced only when the RESOURCE_LIMIT
system initialization parameter is set to TRUE. It is FALSE by default.
Resource Limits Enforceable Using Profiles
Oracle profiles also allow you to limit the use of system resources by a user. The limit
can be specified for the session (known as a per session limit) or for a single SQL
statement (known as a per call limit). Table 7-5 lists the resource limits that can be
enforced in Oracle 10g.
ch07.indd 37
6/30/2005 5:01:41 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
38
Setting
Description
CPU_PER_SESSION
The total CPU time, measured in hundredths of a second, that a user
is allowed to consume during a session. Once the limit is reached,
the user’s session is terminated with an Oracle server error message.
To reset this limit, the user needs to disconnect from the instance
and connect again.
CPU_PER_CALL
The total CPU time, measured in hundredths of a second, that a user
is allowed to consume for a single SQL statement. Once the limit is
reached, the SQL statement is aborted and the transaction it is
a part of is rolled back. The user’s session remains connected.
The limit is reset on every call to the database.
SESSIONS_PER_USER
The maximum number of concurrent sessions that a user may have
at one time.
CONNECT_TIME
The maximum amount of time, specified in minutes, that a user may
remain connected to the instance.
IDLE_TIME
The maximum amount of time, specified in minutes, that a user’s
session may remain connected to the instance while not performing
any database activity.
LOGICAL_READS_PER_
SESSION
The number of blocks (both physical—from disk—and logical—
from the database buffer cache) that the user is allowed to read
during their session. Once the number of blocks specified by this
parameter are read, the user will need to start another session in
order to access data in the database.
LOGICAL_READS_PER_
CALL
The number of blocks (both physical—from disk—and logical—from
the database buffer cache) that the user is allowed to read when
executing a SQL statement. Once the number of blocks specified by
this parameter are read, the SQL statement will be terminated and
any transaction that it is a part of will be rolled back.
PRIVATE_SGA
In a Multi-Threaded Server (MTS) environment, this parameter
specifies the maximum number of bytes that a user’s session can
occupy in the SGA.
If you are not connected to the database instance with an MTS
connection, this parameter is ignored.
COMPOSITE_LIMIT
Specifies a numerical value that is the weighed average of four
resource limits:
CPU_PER_SESSION
CONNECT_TIME
LOGICAL_READS_PER_SESSION
PRIVATE_SGA
Setting COMPOSITE_LIMIT will allow Oracle to monitor all four
of these parameter values; when the combination of all exceeds the
value specified by COMPOSITE_LIMIT, the user’s session will be
terminated.
Table 7-5 Profile Resource Limits
ch07.indd 38
6/30/2005 5:01:41 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
39
Creating, Altering, and Dropping Profiles
CREATE PROFILE profile_name LIMIT
[SESSIONS_PER_USER
[CPU_PER_SESSION
[CPU_PER_CALL
[CONNECT_TIME
[IDLE_TIME
[LOGICAL_READS_PER_SESSION
[LOGICAL_READS_PER_CALL
[COMPOSITE_LIMIT
[PRIVATE_SGA
bytes
PART I
You can create, alter, and drop profiles using the CREATE PROFILE, ALTER PROFILE,
and DROP PROFILE commands or by using Oracle Enterprise Manager. Profiles, once
created, are not used until they are assigned to users. Once a profile is created, its limits
can be modified and then those changes will apply to all users assigned the profile the
next time the users connect to the server (i.e., the changes are not applied to any loggedon users). Dropping a profile requires that no users be assigned the profile, unless the
CASCADE option is specified. If you use the CASCADE option of the DROP PROFILE
command, users to whom the profile was assigned will automatically have the default
profile assigned.
To create a profile, issue the CREATE PROFILE command, whose syntax is as follows
when dealing with resource limits. Password limits will be discussed in Chapter 11 and
are not shown here.
value]
value]
value]
value]
value]
value]
value]
value]
[K|M]]
You can specify the keyword UNLIMITED for any profile limit to not have any
limitation imposed for that resource. Specifying the keyword DEFAULT for any limit
when creating or altering a profile will assign the value of the DEFAULT profile for the
resources. This way, you can have some limits specific to a profile and others at the
same value for all users. If the DEFAULT profile imposes a limit, specifying DEFAULT
for the profile you are creating will impose the same limit.
To modify a profile, you issue the ALTER PROFILE command, whose options are
the same as the CREATE PROFILE command. As indicated earlier, any changes to the
profile limits do not take effect until the next time the user to whom the profile applies
logs on. Any existing user session will not be affected by the profile change.
The DROP PROFILE command deletes a profile and optionally, if the CASCADE
option is specified, assigns the DEFAULT profile to any users for whom the profile was
active when it was dropped. The syntax of the DROP PROFILE command is
DROP PROFILE profile_name [CASCADE]
You cannot drop the DEFAULT profile, since it must exist in the database. You also
should not drop the MONITORING_PROFILE, because it is needed by Oracle to perform
system monitoring functions in the database.
If you want to determine the currently configured profile values, you can query the
DBA_PROFILES data dictionary view or use Enterprise Manager to display the
information.
ch07.indd 39
6/30/2005 5:01:42 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
40
Assigning Profiles to Users
Users are assigned profiles when they are either created or altered via the command
interface or Enterprise Manager. You can use the ALTER USER command at any time to
assign a profile to an existing user. Only one profile is active for a user at any time, so
it is not possible for a user to be assigned more than one profile. The profile limits
apply each time the user connects to the instance and creates a session, and they are
enforced for the duration of the session.
EXAM TIP A user has only one profile active at any time.
To assign a profile called DBA_PROFILE to the user John, who already exists in the
database, you can issue the following command:
ALTER USER JOHN PROFILE DBA_PROFILE
If you create a new user called Stephen and want to assign him the DBA_PROFILE,
you can issue the following command:
CREATE USER STEPHEN IDENTIFIED BY ORACLE PROFILE DBA_PROFILE
Exercise 7-5: Using Enterprise Manager
to Create and Manage Profiles
In this exercise you will connect to Enterprise Manager and create a profile, assign
resource limits to it, assign the profile to a user, view profile information, and test the
results.
1. Start a web browser and connect to the Enterprise Manager URL on your Oracle
database server, specifying the appropriate port number and machine name.
2. Log in to your database as the user SYSTEM with the appropriate password.
If you receive the licensing information page, click I Agree to continue.
3. On the Enterprise Manager main page, click the Administration hyperlink
to display the Administration page.
ch07.indd 40
6/30/2005 5:01:42 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
41
5. Click Create to create a new profile called DBA_PROFILE and assign it a connect
time value of UNLIMITED, an idle time of 15 minutes, and a concurrent
sessions value of UNLIMITED. Leave all other settings at the value of DEFAULT.
ch07.indd 41
PART I
4. Click the Profiles hyperlink under Security to display the profiles currently
defined in the database. There should be two: DEFAULT and MONITORING_
PROFILE.
6/30/2005 5:01:43 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
42
6. Click Show SQL to view the SQL code to perform the action and then click
Return and then OK to create the profile.
7. On the profile list page, select DEFAULT and then click Edit. Modify the value
of the default profile to specify a connect time of 600 minutes, an idle time of 30
minutes, and a concurrent sessions value of 1. Then click Apply to save your
changes. Click the Profiles hyperlink to return to the list of profiles.
ch07.indd 42
6/30/2005 5:01:44 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
43
PART I
8. Open another browser window and connect to the instance using iSQL*Plus
as the user John with the appropriate password.
9. Open another browser window and once again attempt to connect to the
instance using iSQL*Plus as John. Notice that you do not receive an error
message and John is able to connect. That is because resource limits have not
been configured to be enforced on this instance. Log out of iSQL*Plus as John
but keep the browser window open.
ch07.indd 43
6/30/2005 5:01:44 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
44
10. In another browser window, connect to the instance using iSQL*Plus as SYSTEM
with the appropriate password and issue the command ALTER SYSTEM SET
RESOURCE_LIMIT=TRUE. Attempt to log in as John for the second time.
Notice the error you receive now.
11. As user SYSTEM turn off resource limits by issuing the command ALTER
SYSTEM SET RESOURCE_LIMIT=FALSE and close that iSQL*Plus session.
Also log out of all other iSQL*Plus sessions and return to the Enterprise
Manager console.
12. Navigate to the Administration page in Enterprise Manager and click Users
under Security.
ch07.indd 44
6/30/2005 5:01:45 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
45
14. Return to the Administration page and then select Profiles under Security.
Select the DBA_PROFILE and in the Actions drop-down list box select Show
Dependencies. Then click Go.
PART I
13. Click the user Damir and on the Edit User page select the drop-down list box
next to Profile and assign Damir the DBA_PROFILE. Then click Apply. Return
to the Users page and edit the user John, assigning him the DBA_PROFILE.
15. On the Show Dependents page, click the Dependents hyperlink to see which
users have been assigned the DBA_PROFILE (the objects that these users own
will also be displayed as part of the dependency tree). Click OK to return to
the Profiles page.
ch07.indd 45
6/30/2005 5:01:46 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
46
16. Select DBA_PROFILE and then click Delete. Notice the error you receive,
indicating that the profile cannot be dropped, since it is assigned to users.
17. In another browser window, invoke iSQL*Plus, connect to the instance as
SYSTEM, and issue the command DROP PROFILE DBA_PROFILE CASCADE.
Then exit iSQL*Plus.
18. In Enterprise Manager, navigate to the Users page for Damir and John and
notice that the DEFAULT profile is now assigned to the users. Exit Enterprise
Manager when done.
Chapter Review
In order for an individual to access database data a user account must be created for
him and appropriate privileges assigned. Database administrators can use the CREATE
USER command or Enterprise Manager to create and manage user accounts and assign
ch07.indd 46
6/30/2005 5:01:47 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
47
PART I
them privileges, a default tablespace, a temporary tablespace, quotas, and profiles.
Users who have been granted permission to create objects are called “schema users,”
since the collection of objects they create is considered their “schema.”
Two kinds of privileges exist in Oracle: system privileges, which allow you to
perform an action such as create a table or drop an index, and object privileges, which
allow you to manipulate objects, for instance, to SELECT from a table or EXECUTE a
procedure. System privileges are granted by the DBA role and anyone who has had
them granted WITH ADMIN OPTION. Object privileges are granted by the owner of
the object and anyone granted those permissions WITH GRANT OPTION. Privileges
can be revoked using the REVOKE command and, for object privileges only, will also
be revoked from anyone the revokee granted them to.
In many environments it is preferable to create roles to hold both system and object
privileges that need to be assigned to users. Permission assignment is simplified because
only the role needs to be granted to a user. Any permission changes on the role
automatically are changed for all users holding the role. A user may have several roles
active at one time and may have other roles made active during a session using the
SET ROLE command or the DBMS_SESSION.SET_ROLE package procedure.
Profiles allow a DBA to control resource usage by users when activated with the
RESOURCE_LIMIT initialization parameter. A user may have only one profile active
at a time, and any profile changes do not take effect until a user assigned the profile
creates a new session on the instance. If a profile is dropped using the CASCADE option,
the DEFAULT profile, which must exist, is assigned to all users.
Questions
1. You have created a new user called George. You have assigned George the
RESTRICTED_ACCESS user profile. The profile settings have all limits
configured as DEFAULT except for a concurrent sessions limit whose value is
set to 1. George asks you to help with a problem, and when you arrive at his
desk, you notice that he has several SQL*Plus sessions open, all of which are
connected to the instance with his user account. You suspect that your profile
limits are not being enforced. Which of the following should you investigate
to determine the cause of the problem? (Choose two correct answers.)
A. DBA_USER_LIMITS table
B. RESOURCE_LIMIT initialization parameter
C. DBA_PROFILE_LIMITS data dictionary view
D. DBA_PROFILES data dictionary view
E. V$LIMITS dynamic performance view
ch07.indd 47
6/30/2005 5:01:48 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
48
2. Which line of code will cause the following SQL statement to fail? (Choose
the best answer.)
1
2
3
4
5
CREATE USER Sam
IDENTIFIED EXTERNALLY BY $amP@ssw0rd
DEFAULT TABLESPACE Users
TEMPORARY TABLESPACE User_Temp
QUOTA 2048MB ON APPS_DATA
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed
3. You have been asked to provide additional information to your manager on
how system privileges can be assigned and behave. Which of the following
statements about system privileges are true? (Choose all correct answers.)
A. System privileges can be granted to others if you use the WITH ADMIN
OPTION.
B. System privileges can be granted to others if you use the WITH GRANT
OPTION.
C. Only the DBA can grant system privileges, since the DBA owns the database.
D. System privileges can be granted only by the owner of the database.
E. When revoked for a user, system privileges will also be revoked for any
user to whom that revokee granted them.
F. When revoked for a user, system privileges will not be revoked for any user
to whom that revokee granted them.
4. How would a user change his active profile? (Choose the best answer.)
A. ALTER USER SET PROFILE=NewProfile
B. ALTER SYSTEM SET PROFILE=NewProfile
C. ALTER SESSION SET PROFILE=NewProfile
D. ALTER DATABASE SET PROFILE=NewProfile
E. A user cannot change his active profile
5. If you create a profile and specify limits for only some of the profile settings,
what value will be automatically assigned to any resource limit you do not
include in your CREATE PROFILE statement? (Choose the best answer.)
A. DEFAULT
B. 0
C. UNLIMITED
ch07.indd 48
6/30/2005 5:01:48 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
49
7.
8.
9.
ch07.indd 49
PART I
6.
D. UNKNOWN
E. You must specify a value for all profile limits
If you do not specify a TEMPORARY TABLESPACE when creating a new user
account, what will be the value of this parameter when the user is created?
(Choose the best answer.)
A. SYSTEM
B. TEMP
C. NULL
D. Database default temporary tablespace
E. You must specify a value for TEMPORARY TABLESPACE
Which of the following commands can a new user called Anthony issue after
successfully connecting to the instance and establishing a user session? (Choose
all correct answers.)
A. ALTER USER Anthony PASSWORD EXPIRE;
B. ALTER USER Anthony QUOTA 2M ON SYSTEM;
C. ALTER USER Anthony ACCOUNT LOCK;
D. ALTER USER Anthony TEMPORARY TABLESPACE TEMP;
E. ALTER USER Anthony IDENTIFIED BY NEWPASS;
While passing by Benjamin’s desk, you notice that he is using SQL*Plus to
query data in your TempOrders table. You did not grant Benjamin privileges
to issue SELECT statements against your TempOrders table. Why is Benjamin
able to query your table? (Choose all correct answers.)
A. A user to whom you granted the SELECT privilege on the table also granted
it to Benjamin.
B. Benjamin is a DBA and can query any table in the database.
C. You granted Benjamin the UPDATE privilege on the TempOrders table,
which automatically grants the SELECT privilege.
D. Benjamin has been granted the SELECT ANY TABLE privilege by the DBA.
E. Benjamin has been granted the SELECT privilege on your TempOrders
table by a user to whom you granted the SELECT privilege WITH ADMIN
OPTION.
Which of the following statements will fail when granting privileges to the
role QueryRole? (Choose the best answer.)
A. GRANT CONNECT TO QueryRole;
B. GRANT CONNECT TO QueryRole WITH ADMIN OPTION;
C. GRANT SELECT ON Orders TO QueryRole;
D. GRANT SELECT ON Orders TO QueryRole WITH GRANT OPTION;
E. GRANT DBA TO QueryRole WITH ADMIN OPTION;
6/30/2005 5:01:49 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
50
10. When creating a user using Enterprise Manager instead of the CREATE USER
statement, which additional privileges are granted to the user? (Choose the
best answer.)
A. SELECT_CATALOG_ROLE
B. SYSDBA
C. CONNECT
D. RESOURCE
E. DBA
Answers
1. B and D. You can query the DBA_PROFILES data dictionary view to determine
the settings of all profiles in the database, including the one George is supposed
to have assigned to him. The RESOURCE_LIMIT initialization parameter must
be set to TRUE for the concurrent sessions limit to be enforced, so you need
to verify this setting in the running instance and in the SPFILE. DBA_USER_
LIMITS, DBA_PROFILE_LIMITS, and V$LIMITS views do not exist.
2. B. When you create a user, you can specify at most one authentication
method. This SQL statement specified both EXTERNALLY and password
(BY $amP@ssw0rd) authentication at the same time, which would generate
an error when the command was executed.
3. A and F. If you have been granted a system privilege WITH ADMIN OPTION,
you can also grant the same privilege to others and specify the WITH ADMIN
OPTION. The WITH GRANT OPTION applies to object privileges and not
system privileges. If system privileges are revoked for a user to whom they
were granted WITH ADMIN OPTION, they will not be revoked for other
users to whom the revoke granted them; there are no cascading revokes for
system privileges. The DBA is a role and is not the only one that can grant
system privileges, and neither is the user SYS (the database owner), in that
anyone holding the DBA role can grant them, since the DBA role has system
privileges granted to it WITH ADMIN OPTION.
4. E. A user cannot himself change his active profile. Only the DBA can modify
a user’s profile or the profile limits.
5. A. If you do not specify a value for a limit in your profile, it will automatically
be assigned the value of DEFAULT. This means that Oracle will enforce whatever
value exists for the limit in the DEFAULT profile.
6. D. The currently defined database default temporary tablespace will be assigned
to the user if you do not specify a TEMPORARY TABLESPACE for the user. If
no database default temporary tablespace is defined, the user will be assigned
SYSTEM as the temporary tablespace.
ch07.indd 50
6/30/2005 5:01:50 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 7: Administering Database Users
51
8. B and D. Benjamin can query your TempOrders table only if he is a DBA, who
automatically has the SELECT ANY TABLE privilege, or if Benjamin has been
granted the SELECT ANY TABLE privilege by the DBA. Another user to whom
you only granted the SELECT privilege could not grant it to Benjamin unless
you specified the WITH GRANT OPTION. Granting the UPDATE privilege on
the table does not automatically grant the SELECT privilege.
PART I
7. E. Anthony, like any new user who has been configured with password
authentication, has the ability to change his password at any time. No other
changes to the user account are allowed to be performed by the user himself.
9. D. It is not possible to grant object privileges to roles WITH GRANT OPTION,
so this statement will fail. All other statements will succeed, assuming you
have the privileges required to perform the operation.
10. C. Using Enterprise Manager to create a user will automatically grant the user
the CONNECT role, which includes the CREATE SESSION privilege, so the
user is able to connect to the instance right away. This role also includes the
privileges to create tables, views, synonyms, sequences, and other database
objects, which may or may not be desired for all users.
ch07.indd 51
6/30/2005 5:01:50 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
ch07.indd 52
6/30/2005 5:01:51 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3/Ch8
CHAPTER 8
Managing Database Objects
In this chapter you will learn how to
• Create and modify tables
• Define constraints
• View the attributes of a table
• View the contents of a table
• Create indexes and views
• Name database objects
• Select appropriate datatypes
• Create and use sequences
1
ch08.indd 1
7/11/2005 3:05:53 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
In a typical database, the greater part of the data is stored in tables. This chapter covers
the syntax for creating tables with columns of various datatypes, and also creating some
associated objects: the constraints that guarantee that the rows inserted into tables
conform to certain business rules; the indexes that enhance the performance of
retrieving rows from tables; and the views that can conceal the underlying table
structures from end users. Finally, you will see how to create sequences: data structures
that can deliver numbers that are guaranteed to be unique.
All these objects are stored in schemas: a schema is associated with a user—create
a user, and a schema is automatically created.
Bear in mind that the topics covered in this chapter are very large, and that this is
only a superficial introduction.
Users, Schemas, and Schema Objects
A user is a person, uniquely identified by username, who exists within the database.
Chapter 7 covered the techniques for creating users and giving them the privileges that
allow them to connect to the database, and then create and use objects. When a user
is created, a schema is created too. A schema consists of the objects owned by a user;
initially, it will be empty. As far as SQL is concerned, a schema is nothing more than
a container for tables, views, code, and other database elements.
Users and Schemas
Some schemas will always be empty: the user will never create any objects, because he
does not need to and (if he is set up correctly) will not have the necessary privileges
anyway. Users such as this will have been granted permissions, either through direct
privileges or through roles, to use code and access data in other schemas, owned by
other users. Other users may be the reverse of this: they will own many objects but
will never actually log on to the database. They need not even have been granted the
CREATE SESSION privilege, so the account is effectively disabled (or indeed it can be
locked); these schemas are used as repositories for code and data, accessed by others.
Schema objects are objects with an owner. The unique identifier for an object of a
particular type is not its name; it is its name, prefixed with the name of the schema to
which it belongs. Thus the table HR.REGIONS is a table called REGIONS that is owned
by user HR. There could be another table SYSTEM.REGIONS that would be a completely
different table (perhaps different in both structure and contents) owned by user
SYSTEM and residing in his schema.
A number of users (and their associated schemas) are created automatically at
database creation time. Principal among these are SYS and SYSTEM. User SYS owns
the data dictionary: a set of tables (in the SYS schema) that define the database and its
contents. SYS also owns several hundred PL/SQL packages: code that is provided for
the use of the Oracle kernel, database administrators, and developers. Objects in the
SYS schema should never be modified with DML commands. If you were to execute
DML against the data dictionary tables, you would run the risk of corrupting the data
dictionary, with disastrous results. You update the data dictionary by running DDL
ch08.indd 2
7/11/2005 3:06:28 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
3
PART I
commands (such as CREATE TABLE), which provide a layer of abstraction between
you and the data dictionary itself. The SYSTEM schema stores various additional objects
used for administration and monitoring.
Depending on the options selected during database creation, there may be more
users created, perhaps up to thirty in total. These users are used for storing the code
and data required by various options. For example, the user MDSYS stores the objects
used by Oracle Spatial, an option that extends the capabilities of the Oracle database
to manage geographical information.
Naming Schema Objects
A schema object is an object that is owned by a user. The database will also contain
non-schema objects: these may be objects that have nothing to do with users, such as
tablespaces, or in some cases they are objects owned by SYS and directly accessible by
all users; examples of the latter include public synonyms and public database links
that can be used by all users regardless of privileges.
To view schema objects through database control, take the appropriate link for the
type of object of interest from the Schema section in the Administration window, as
in Figure 8-1, and you will be prompted for various search criteria.
All schema object names must conform to certain rules:
• The name may be from one to thirty characters long, with the exception
of database link names, which may be up to 128 characters long.
• Reserved words (such as SELECT) cannot be used as object names.
• All names must begin with a letter from A through Z.
• Names can only use letters, numbers, the underscore (_), the dollar sign ($),
or the hash symbol (#).
• Lowercase letters will be converted to uppercase.
By enclosing the name within double quotes, all these rules (with the exception of
the length) can be broken, but to get to the object subsequently, it must always be
specified with double quotes, as in the examples in Figure 8-2. Note that the same
restrictions apply to column names.
Although tools such as SQL*Plus will automatically convert lowercase letters to
uppercase, unless the name is enclosed within double quotes, remember that object
names are always case sensitive. In this example, the two tables are completely different:
ocp10g> create table lower(c1 date);
Table created.
ocp10g> create table "lower"(col1 varchar(2));
Table created.
ocp10g> select table_name from dba_tables where
2 lower(table_name) = 'lower';
TABLE_NAME
-----------------------------lower
LOWER
ch08.indd 3
7/11/2005 3:06:28 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
Figure 8-1 Schema objects manageable with Database Control
TIP While it is possible to use lowercase names and nonstandard characters
(even spaces), it is considered bad practice, because of the confusion it can
cause.
Object Namespaces
It is often said that the unique identifier for an object is the object name, prefixed
with the schema name. While this is generally true, for a full understanding of naming
it is necessary to introduce the concept of a namespace. A namespace defines a group
of object types, within which all names must be uniquely identified—by schema and
name. Objects in different namespaces can share the same name.
ch08.indd 4
7/11/2005 3:06:29 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
5
PART I
Figure 8-2 Using double quotes to use nonstandard names
These object types all share the same namespace:
• Tables
• Views
• Sequences
• Private synonyms
• Stand-alone procedures
• Stand-alone stored functions
• Packages
• Materialized views
• User-defined types
Thus it is impossible to create a view with the same name as a table; at least, it
is impossible if they are in the same schema. And once created, SQL statements can
address a view as though it were a table. The fact that tables, views, and private synonyms
share the same namespace means that you can set up several layers of abstraction
between what the users see and the actual tables, which can be invaluable for both
security and for simplifying application development.
ch08.indd 5
7/11/2005 3:06:30 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
These object types each have their own namespace:
• Indexes
• Constraints
• Clusters
• Database triggers
• Private database links
• Dimensions
Thus it is possible for an index to have the same name as a table, even within the
same schema.
Datatypes
When creating tables, each column must be assigned a datatype, which determines
the nature of the values that can be inserted into the column. These datatypes are also
used to specify the nature of the arguments for PL/SQL procedures and functions.
When selecting a datatype, you must consider the data that you need to store and the
operations you will want to perform upon it. It may be possible to change a column
to a different datatype after creation, but this is not always easy. Space is also a
consideration: some datatypes are fixed length, taking up the same number of bytes no
matter what data is actually in them; others are variable. If a column is not populated,
then Oracle will not give it any space at all; if you later update the row to populate the
column, then the row will get bigger, no matter whether the datatype is fixed length
or variable. Tables 8-1 through 8-4 describe the various internal datatypes, grouped by
character data, numeric data, date-time data, and large objects.
Datatype
Description
VARCHAR2
Variable-length character data from 1 byte to 4KB. The data is stored in the
database character set.
NVARCHAR2
As VARCHAR2, but the data is stored in the alternative national language
character set: one of the permitted Unicode character sets.
CHAR
Fixed-length data in the database character set. If the data is not the length
of the column, then it will be padded with spaces.
RAW
Variable-length binary data from 1 byte to 2KB. Unlike the CHAR and
VARCHAR datatypes, RAW data is not converted by Oracle Net from the
database’s character set to the user process’s character set on select or the
other way on insert.
Table 8-1 Datatypes for Alphanumeric Data
ch08.indd 6
7/11/2005 3:06:31 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
7
Description
NUMBER
Numeric data for which you can specify precision and scale. The precision can
range from to 1 to 38, and the scale can range from –84 to 127.
FLOAT
This is an ANSI datatype, for floating-point numbers with precision of 126
binary (or 38 decimal). Oracle also provides BINARY_FLOAT and BINARY_
DOUBLE as alternatives.
INTEGER
Equivalent to NUMBER, with scale zero.
PART I
Datatype
Table 8-2 Datatypes for Numeric Data, All Variable Length
TIP For ISO/ANSI compliance, you can specify a VARCHAR datatype, but any
columns of this type will be automatically converted to VARCHAR2.
Oracle provides a range of type-casting functions for converting between datatypes,
and in some circumstances it will do automatic type casting. Figure 8-3 illustrates both
techniques.
Datatype
Description
DATE
This is either length zero, if the column is empty, or 7 bytes.
All DATE data includes century, year, month, day, hour, minute,
and second. The valid range is from January 1, 4712 B.C. to
December 31, 9999 A.D.
TIMESTAMP
This is length zero if the column is empty, or up to 11 bytes
depending on the precision specified. Similar to DATE, but
with precision of up to nine decimal places for the seconds,
six places by default.
TIMESTAMP WITH TIMEZONE
As TIMESTAMP, but the data is stored with a record kept of
the time zone to which it refers. The length may be up to
13 bytes depending on precision. This datatype lets Oracle
determine the difference between two times by normalizing
them to UTC, even if the times are for different time zones.
TIMESTAMP WITH LOCAL
TIMEZONE
As TIMESTAMP, but the data is normalized to the database
time zone on saving. When retrieved, it is normalized to the
time zone of the user process selecting it.
INTERVAL YEAR TO MONTH
Used for recording a period in years and months between
two DATEs or TIMESTAMPs.
INTERVAL DAY TO SECOND
Used for recording a period in days and seconds between
two DATEs or TIMESTAMPs.
Table 8-3 Datatypes for Date and Time Data, All Fixed Length
ch08.indd 7
7/11/2005 3:06:31 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
Datatype
Description
CLOB
Character data stored in the database character set, size effectively unlimited:
4GB multiplied by the database block size.
NCLOB
As CLOB, but the data is stored in the alternative national language character
set: one of the permitted Unicode character sets.
BLOB
As CLOB, but binary data that will not undergo character set conversion by
Oracle Net.
BFILE
A locator pointing to a file stored on the operating system of the database
server. The size of the files is limited to 4GB.
LONG
Character data in the database character set, up to 2GB. All the functionality
of LONG (and more) is provided by CLOB; LONGs should not be used in
a modern database, and if your database has any columns of this type, they
should be converted to CLOB.
LONG RAW
As LONG, but binary data that will not be converted by Oracle Net. Any
LONG RAW columns should be converted to BLOBs.
Table 8-4 Large Object Datatypes
In the example shown in the figure, the first insert uses type-casting functions to
convert the character data entered to the datatypes specified for the table columns.
The second insert attempts to insert character strings into all three columns, but the
Figure 8-3 Use of type-casting functions and automatic type casting
ch08.indd 8
7/11/2005 3:06:32 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
9
TIP Do not rely on automatic type casting. It can impact on performance and
may not always work. The Oracle environment is strongly typed, and your
programmers should respect this.
PART I
insert still succeeds because Oracle can convert datatypes automatically if necessary,
and if the format of the data is suitable.
Creating Tables
The syntax for creating a table requires giving the table a name (which must be unique
within the schema to which the table belongs) and specifying one or more columns, each
with a datatype. It is also possible to specify constraints when creating a table;
alternatively, constraints can be added later. There are many examples in this book of
creating tables from the SQL*Plus command line (there have already been two examples
in this chapter!) but it can also be done through Database Control. Database Control
provides a fully functional menu-driven interface for creating and editing table structures,
and also for managing the constraints, indexes, and views that will be based on the tables.
The CREATE TABLE command can be quite complex (when you look it up in the
“SQL Reference” volume of the Documentation Library, you will see that it takes up 72
pages) and includes a vast range of options for specifying physical and logical attributes.
Most of the examples given in this book are very simple; this is a little more complicated:
ocp10g> create table emp
2 (empno number(6)
3 constraint emp_empno_pk primary key
4 using index
5 create index emp_empno_pk on emp(empno) tablespace idx_ts),
6 firstname varchar2(20),
7 lastname varchar2(25)
8 constraint emp_last_name_nn not null,
9 hire_date date default sysdate,
10 salary number(8,2),
11 managerid number(6)
12 constraint emp_managerid_fk references emp(empno),
13 deptno number(4)
14 constraint emp_deptno_fk references dept(deptno),
15 photo blob,
16 resume clob,
17 email varchar2(25),
18 constraint emp_salary_min check (salary >= 0),
19 constraint emp_email_uk unique (email))
20 lob (photo, resume) store as
21 (tablespace example chunk 4096);
Table created.
Lines 2, 3, 4, and 5 define a numeric column EMPNO, which is to be used as a
primary key. Rather than letting Oracle create the primary key index using its defaults,
the USING INDEX clause can specify a full index creation command.
ch08.indd 9
7/11/2005 3:06:33 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
Lines 7 and 8 demonstrate creating a NOT NULL constraint.
Line 9 creates a column with a default value to be applied at insert time, if the
column is not populated by the INSERT statement.
Line 10 creates a numeric column with a precision of two decimal places.
Lines 11 and 12 create a column with a self-referencing foreign key constraint:
each employee must have a valid manager, who is also an employee. Constraints of
this nature can impact on the order in which rows can be inserted. Lines 13 and 14
create a foreign key constraint to a different table.
Lines 15 and 16 create two large object columns.
Lines 18 and 19 demonstrate creating constraints on columns defined earlier. The
UNIQUE constraint will force the creation of an index, using defaults.
Finally, lines 20 and 21 specify some storage options for the large objects.
To reach the table management window of Database Control, from the database
home page take the Administration tab, then the Tables link in the Schema section.
Enter whatever search criteria are needed to locate the table of interest, and then open
the Actions drop-down box to see what possibilities are available, as in Figure 8-4.
Figure 8-4 The Database Control Tables window
ch08.indd 10
7/11/2005 3:06:34 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
11
These are the actions:
• CREATE INDEX Define and generate an index on the table.
PART I
• CREATE LIKE Create a new table based on the same structure as the selected
table.
• CREATE SYNONYM Create a logical name, or alias, that can be used as
a pseudonym for the table.
• CREATE TRIGGER Create a block of PL/SQL code that will run
automatically whenever DML is executed against the table.
• GATHER STATISTICS Analyze the contents of the table, to gather statistics
to be used by the optimizer to work out how best to access the table.
• GENERATE DDL Reverse-engineer the table’s structure, to generate a CREATE
TABLE statement that could be used to re-create the table.
• GRANT PRIVILEGES Give users permission to read or alter the data in
the table.
• REORGANIZE Run a wizard to go through the process of reorganizing the
data in a table to move the table, or to change its structure.
• RUN SEGMENT ADVISOR Use the advisor to generate a recommendation
for whether the table should be shrunk.
• SHRINK SEGMENT Use the online reorganization tool to reclaim wasted
space from a segment.
• SHOW DEPENDENCIES Display all the objects that are in some way related
to the table and could therefore be affected by any action on the table.
• VIEW DATA Run a wizard to assist with querying and displaying the contents
of the table.
• FLASHBACK TABLE Reverse all DML operations against the table, in reverse
chronological order, to take the table back to a previous state.
• FLASHBACK BY ROW VERSIONS Query historical data, to display previous
versions of rows.
Creating Constraints
Table constraints are a means by which the database can enforce business rules and
guarantee that the data conforms to the entity-relationship model determined by the
system’s analysis that defines the application data structures. For example, the business
analysts of your organization may have decided that every customer and every invoice
must be uniquely identifiable by number; that no invoices can be issued to a customer
before he has been inserted; and that every invoice must have a valid date and a value
ch08.indd 11
7/11/2005 3:06:34 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
greater than zero. These would be implemented by creating primary key constraints
on the CUSTOMER_NUMBER column of the CUSTOMERS table and the INVOICE_
NUMBER column of the INVOICES table, a foreign key constraint on the INVOICES
table referencing the CUSTOMERS table, a not-null constraint on the INVOICE_DATE
column of the INVOICES table (the DATE datatype will itself ensure that any dates are
valid automatically—it will not accept invalid dates), and a check constraint on the
AMOUNT column on the INVOICES table.
If any DML is executed against a table with constraints defined, if the DML violates
a constraint then the whole statement will be rolled back automatically. If the statement
is part of a multistatement transaction, then the statements that have already succeeded
will remain intact, but uncommitted.
These constraints are supported by Oracle:
• UNIQUE No two rows can have the same value for a UNIQUE column.
However, NULL values are permitted; indeed, multiple rows can have NULL
values.
• NOT NULL The column must have a value.
• PRIMARY KEY The primary key is the means of locating a row: the value
must be both UNIQUE and NOT NULL.
• CHECK A CHECK constraint can be used to enforce simple rules, such
as ranges of values. The internal implementation of NOT NULL is in fact
a preconfigured CHECK constraint.
Exercise 8-1: Creating Tables and Constraints
Use Database Control to create two tables with constraints, and validate the structures
with SQL*Plus.
1. Connect to your database as user SYSTEM using Database Control.
2. From the database home page, take the Administration tab, and then the Tables
link in the Schema section. Click Create.
3. On the Create Table: Table Organization window, select the Standard, Heap
Organized radio button, and click Continue.
4. On the Create Table window, enter the name CUSTOMERS, and define two
columns, as in Figure 8-5.
ch08.indd 12
7/11/2005 3:06:35 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
13
PART I
Figure 8-5 Creating the CUSTOMERS table
5. Create a second table, INVOICES, as in Figure 8-6. Note that the Not Null check
box has been selected for the INVOICE_DATE column.
6. To add a primary key constraint to the CUSTOMERS table, navigate to the Tables
window as in Step 2, and search for the table called CUSTOMERS. Select it,
and click Edit. Select the Constraints tab.
7. Select PRIMARY from the drop-down box, and click Add.
8. Choose CUSTOMER_NUMBER as the column on which to base the constraint,
leave all other options on default, and click OK, as in Figure 8-7. Click Apply
to create the constraint.
ch08.indd 13
7/11/2005 3:06:35 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
Figure 8-6 The INVOICES table
9. Repeat the process to add a primary key constraint to the INVOICES table, using
the INVOICE_NUMBER column.
10. To add the foreign key constraint connecting INVOICES to CUSTOMERS, fill
in the Add FOREIGN Constraint window as in Figure 8-8. Click Apply to create
the constraint.
11. To add the check constraint ensuring that the AMOUNT is greater than zero,
fill in the Add CHECK Constraint window as in Figure 8-9. Click OK and Apply.
12. Connect to your database as user SYSTEM with SQL*Plus.
ch08.indd 14
7/11/2005 3:06:36 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
15
PART I
Figure 8-7 Adding a primary key constraint
13. Insert some valid data as follows:
insert into
insert into
insert into
insert into
commit;
customers values(1,'John');
customers values(2,'Damir');
invoices values(10,1,sysdate,100);
invoices values(11,2,sysdate,200);
14. Demonstrate the effectiveness of the constraints by attempting to insert some
data that violates them, such as
ocp10g> insert into customers values(1,'McGraw');
ocp10g> insert into invoices values (30,3,sysdate,50);
ocp10g> insert into invoices values(10,1,sysdate,0);
ch08.indd 15
7/11/2005 3:06:37 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
Figure 8-8 Adding a foreign key constraint
Figure 8-9 Adding a check constraint
ch08.indd 16
7/11/2005 3:06:38 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
17
Indexes have a dual purpose: to enhance the performance of retrieving rows, and to
enforce constraints. When you define a unique or primary key constraint on a column
(or on a number of columns), Oracle will check whether an index already exists on the
column(s), and if it does not, an index will be created for you.
Indexes can be based on one column, on several columns, or on functions applied
to columns: there are no restrictions regarding datatype or column order. A table can
have any number of indexes, and they are maintained automatically to keep them
synchronized with the table.
When deciding on your indexing strategy, you must consider the nature of access
to the data. As a general rule, indexes will improve performance of retrieving individual
rows but will tend to reduce the performance of executing DML against them. So indexes
will help SELECT statements but hinder INSERT statements. They will assist with finding
rows to be updated or deleted but will work against the efficiency of actually doing
the UPDATE or DELETE. It is not necessary for programmers to know the name of an
index, or even that it exists. For all retrieval operations, the Oracle optimizer will make
an intelligent decision about whether or not to use any available indexes, but for DML
it has no choice: indexes must always be maintained.
To create an index from the command line, use the CREATE INDEX command.
For example, to index the CUSTOMER_NAME column of the CUSTOMERS table
used in the previous exercise, you could use this command:
PART I
Creating Indexes
ocp10g> create index name_idx on customers(customer_name);
Alternatively, it can be done through Database Control as in Figure 8-10.
To see what indexes exist on a table, query the DBA_INDEXES data dictionary view:
ocp10g> select index_name from dba_indexes where owner='SYSTEM'
2 and table_name='CUSTOMERS';
INDEX_NAME
-----------------------------NAME_IDX
SYS_C0010004
The first index listed is that created on the CUSTOMER_NAME column. The second,
SYS_C0010004, is the index created automatically by Oracle when the primary key
constraint on the CUSTOMER_NUMBER column was defined. Primary key constraints
require an index, and if one does not exist, one is created for you, with a systemgenerated name.
TIP System-generated names are cryptic; therefore, DBAs typically provide
descriptive names, which help during the investigation of constraint violations
and other error conditions.
ch08.indd 17
7/11/2005 3:06:39 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
Figure 8-10 Creating an index on the CUSTOMER_NAME column
Creating Views
A view is a means of presenting data to your users. Rather than having your programmers
address actual tables, they can address views instead. This can shield them from the
complexities of the underlying data structures and can also be used for security: the
views can conceal certain rows or columns. The tables on which a view is based are
referred to as either the “detail” tables or the “base” tables.
A view is in fact a query—a SELECT statement stored within the data dictionary.
Whenever a user addresses a view, using the same syntax as to address a table, the query
runs to generate a result set, and the user’s statement executes against this set. Note
that there are no performance benefits. In order to simplify data access, a view might
join many tables and perform aggregations or sorts to produce a simple result set; this
will take some time, and it must be done every time the view is queried.
Whether or not DML statements can be executed against a view depends on how
complicated is the query on which the view is based.
ch08.indd 18
7/11/2005 3:06:39 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
19
ocp10g> create view emp_30 as
2 select * from employees where department_id=30;
View created.
ocp10g> select first_name,last_name from emp_30;
FIRST_NAME
LAST_NAME
-------------------- ------------------------Den
Raphaely
Alexander
Khoo
Shelli
Baida
3 rows selected.
ocp10g> delete from emp_30 where last_name='Raphaely';
1 row deleted.
PART I
For example, a simple view defined by a query against just one detail table can be
used for DML:
A more complex view cannot support DML, as is the case with this example, which
joins two tables and performs an aggregation:
ocp10g> create view dept_sal as
2 select department_name,sum(salary) tot_sal from departments
3 join employees using(department_id) group by department_name;
View created.
ocp10g> select * from dept_sal;
DEPARTMENT_NAME
TOT_SAL
------------------------------ ---------Accounting
20300
Administration
4400
Purchasing
13900
Sales
304500
Shipping
156400
5 rows selected.
ocp10g> update dept_sal set tot_sal=tot_sal*1.1;
update dept_sal set tot_sal=tot_sal*1.1
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view
TIP By creating INSTEAD OF triggers on views, your programmers can convert
unexecutable DML commands against complex views into executable DML
against the detail tables.
Views can also be created and edited through Database Control, as in Figure 8-11.
Views can be created from detail tables in any schemas, providing that the owner
of the view has been granted privileges to see the tables. Then the owner of the view
can grant other users permission to see the view. This establishes a layer of abstraction
between users and the tables that is useful for security: users can only ever get to data
through views, and need not be given permissions against the tables themselves.
ch08.indd 19
7/11/2005 3:06:40 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
Figure 8-11 Editing the DEPT_SAL view with Database Control
Creating and Using Sequences
There are many cases in a typical database system where unique numbers are required.
Typically, this is for primary key values. For instance, the business analysts of a sales
organization may have decided that every invoice issued must have a unique invoice
number. Relying on the data entry staff to supply unique numbers is impractical, so
the database must generate them instead. A sequence is defined with a starting point
and an increment, both defaulting to one.
To read a value from the sequence (which will cause it to increment, ready for the
next usage—either by the same session or any other session), use the NEXTVAL pseudocolumn:
ocp10g> create sequence inv_nos start with 1 increment by 1;
Sequence created.
ocp10g> select inv_nos.nextval from dual;
NEXTVAL
---------1
ocp10g> select inv_nos.nextval from dual;
NEXTVAL
---------2
ch08.indd 20
7/11/2005 3:06:40 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
21
PART I
Selecting the NEXTVAL from a sequence will increment it automatically; there is
no way to roll back this increment, and it is immediately visible to all other sessions
that may be selecting from the same sequence. This means that there will be gaps in
the sequence of numbers used.
TIP You can increase the performance of sequences by using the CACHE
clause when you create them, but this can result in more gaps. This is of
no significance to the database, but some auditors get upset about gaps in
sequences.
Exercise 8-2: Using Constraints, Views,
and Sequences
Create a sequence to generate unique invoice numbers, and create a view to join your
INVOICES and CUSTOMERS tables.
1. Connect to your database as user SYSTEM using SQL*Plus.
2. Create a sequence. Since the previous exercise issued invoice numbers 10 and
11, start the sequence at 12.
ocp10g> create sequence inv_nos start with 12;
3. Use the sequence to enter new invoices, with unique numbers.
ocp10g> insert into invoices values (inv_nos.nextval,1,sysdate,150);
ocp10g> insert into invoices values (inv_nos.nextval,2,sysdate,250);
4. Create a view to display invoices with the customers’ names, and select
from it.
ocp10g> create view cust_inv as
2 select invoice_number,customer_name,amount from
3 invoices join customers using (customer_number);
View created.
ocp10g> select * from cust_inv;
INVOICE_NUMBER CUSTOMER_NAME
AMOUNT
-------------- -------------------- ---------10 John
100
11 Damir
200
12 John
150
13 Damir
250
5. Tidy up.
ocp10g>
ocp10g>
ocp10g>
ocp10g>
drop
drop
drop
drop
table invoices;
table customers;
view cust_inv;
sequence inv_nos;
Note that there is no need to drop any constraints or indexes: they are dropped
automatically along with the tables.
ch08.indd 21
7/11/2005 3:06:41 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
22
Chapter Review
This chapter has introduced tables, along with the commonly used associated objects:
constraints, indexes, and views. Also shown were sequences, typically used for generating
unique values for inserts into primary key–constrained columns. All these objects
are “schema” objects, meaning that they must belong to a user; they cannot exist
independently. A schema object must have a unique name within its namespace and
schema; some objects, such as indexes, have their own namespace; others, such as
tables and views, share a namespace.
Tables are defined with one or more columns, which can be any of Oracle’s
supported internal datatypes. Oracle is a strongly typed environment, and datatypes
must match; however, in some circumstances Oracle can do automatic type casting to
avoid errors when users attempt, for example, to insert a numeric value into a character
column.
Constraints are defined on tables to enforce business rules. Unique and primary
key constraints are enforced through the use of indexes: if an index does not exist on
the constrained column(s), one will be created for you. You can also create additional
indexes to enhance performance.
In many cases, the table structure within a database may be overly complex. Views
can conceal these complexities by presenting the data in a simplified form. Some views
can be treated exactly as though they were tables; others can only be selected from, DML
being impossible. Views are also invaluable for security: users can be granted permissions
against views, without being granted permissions against their detail (or “base”) tables.
Questions
1. Which of these statements will fail because the table name is not legal?
(Choose two answers.)
A. create table "SELECT" (col1 date);
B. create table "lower case" (col1 date);
C. create table number1 (col1 date);
D. create table 1number(col1 date);
E. create table update(col1 date);
2. Several object types share the same namespace and therefore cannot have the
same name in the same schema. Which of the following object types is not in
the same namespace as the others? (Choose the best answer.)
A. Index
B. PL/SQL stored procedure
C. Synonym
D. Table
E. View
ch08.indd 22
7/11/2005 3:06:42 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 8: Managing Database Objects
23
ch08.indd 23
PART I
3. Which of the following is not supported by Oracle as an internal datatype?
(Choose the best answer.)
A. CHAR
B. FLOAT
C. INTEGER
D. STRING
4. You need to record date/time values, with a precision of one second. What
would be a suitable datatype for a single column to store this information?
A. DATE
B. TIMESTAMP
C. Either DATE or TIMESTAMP
D. You must develop your own user defined datatype, because the internal
types store either the date or the time.
5. Which types of constraint require an index? (Choose all that apply.)
A. CHECK
B. NOT NULL
C. PRIMARY KEY
D. UNIQUE
6. A transaction consists of two statements. The first succeeds, but the second
(which updates several rows) fails part way through because of a constraint
violation. What will happen? (Choose the best answer.)
A. The whole transaction will be rolled back.
B. The second statement will be rolled back completely, and the first will
be committed.
C. The second statement will be rolled back completely, and the first will
remain uncommitted.
D. Only the one update that caused the violation will be rolled back;
everything else will be committed.
E. Only the one update that caused the violation will be rolled back;
everything else will remain uncommitted.
7. Which of the following statements is correct about indexes? (Choose the best
answer.)
A. An index can be based on multiple columns of a table, but the columns
must be of the same datatype.
B. An index can be based on multiple columns of a table, but the columns must
be adjacent and specified in the order that they are defined in the table.
C. An index cannot have the same name as a table, unless the index and the
table are in separate schemas.
D. None of the above statements is correct.
7/11/2005 3:06:42 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
24
8. For what purposes might you choose to create views? (Choose two answers.)
A. To enhance security
B. To present data in a simple form
C. To improve performance
D. To save result sets of commonly executed queries
9. You insert a row using a sequence INV_NOS and then roll back the insert,
as follows:
ocp10g> insert into invoices values (inv_nos.nextval,1,sysdate,150);
1 row created.
ocp10g> rollback;
Rollback complete.
Before this transaction, the sequence was at value 10. What will be the next
value it will issue? (Choose the best answer.)
A. 10
B. 11
C. 12
D. It depends on how the sequence was created
Answers
1. D and E. D violates the rule that a table name must begin with a letter, and E
violates the rule that a table name cannot be a reserved word. Both rules can
be bypassed by using double quotes.
2. A. Indexes have their own namespace.
3. D. There is no STRING datatype.
4. C. Both DATE and TIMESTAMP columns always record the date and the time
to a precision of at least one second.
5. C and D. These are enforced with indexes, which will be created automatically
if they do not exist.
6. C. SQL is a set-oriented language: it is impossible for a statement to be partially
completed. Transactions can be incomplete, but COMMIT is all or nothing.
7. D. None of these are restrictions on index creation.
8. A and B. Views are about usability, not performance. D applies to materialized
views, not to views per se.
9. D. The sequence will have been incremented, and the increment does not
get rolled back, but you do not know what the next value will be, unless you
know what STEP was defined when the sequence was created.
ch08.indd 24
7/11/2005 3:06:43 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Meyers / 5790-3 /Chapter 23
CHAPTER 9
Manipulating Database Data
In this chapter you will learn how to
• 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
1
ch09.indd 1
6/29/2005 12:16:57 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
Chapter 4 offers a brief look at the SQL syntax for the SELECT, INSERT, UPDATE, and
DELETE commands but doesn’t go into what actually happens in memory and on disk
when these commands are executed. Similarly, Chapter 8 shows the syntax for creating
tables but doesn’t look at how data is actually entered into and retrieved from them.
This chapter will make good these gaps by walking through the whole process, including
the generation of undo (which enables the rollback command) and of redo (which
enables commit and recovery operations). As a precursor for this, you will review some
of the principles of a relational database to which all databases (not just Oracle’s) must
conform. Then the chapter finishes with a look at the tools provided by Oracle for bulk
data loading and unloading operations: Data Pump and SQL*Loader.
Database Transactions
This is not the place to go into detail on the relational database transactional paradigm—
there are any number of academic texts on this, and there is not enough space to cover
this topic in a practical guide—but a quick review of transaction theory is necessary
before looking at how Oracle has implemented transaction management and the data
manipulation language (DML). Oracle’s mechanism for transactional integrity combines
undo segments and redo log files: this mechanism is undoubtedly the best of any
database yet developed, and it conforms perfectly to the international standards for
data processing. Other database vendors comply with the same standards with their
own mechanisms, but with varying levels of effectiveness. In brief, any relational
database must be able to pass the ACID test.
A Is for Atomicity
The principle of atomicity states that all parts of a transaction must complete, or none of
them. For example, if your business analysts have said that every time you change an
employee’s salary you must also change his grade, then the “atomic” transaction will
consist of two updates. The database must guarantee that both go through, or neither. If
only one of the updates were to succeed, you would have an employee on a salary that
was incompatible with his grade: a data corruption, in business terms. If anything
(anything at all!) goes wrong before the transaction is complete, the database itself must
guarantee that any parts that did go through are reversed: this must happen automatically.
But although an atomic transaction sounds small (like an atom), it could be
enormous. To take another example, it is logically impossible for the nominal ledger
of an accounting package to be half in August and half in September: the end-of-month
rollover is therefore (in business terms) one atomic transaction, which may affect
millions of rows in thousands of tables and take hours to complete (or to roll back,
if anything goes wrong).
The rollback of an incomplete transaction may be manual (as when you issue the
ROLLBACK command), but it must be automatic and unstoppable in the case of an
error. Oracle guarantees atomicity absolutely through the use of undo segments, dealt
with in detail in Chapter 16.
ch09.indd 2
6/29/2005 12:17:32 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
3
C Is for Consistency
PART I
The principle of consistency states that the results of a query must be consistent with
the state of the database at the time the query started. Imagine a simple query that
averages the value of a column of a table. If the table is large, it will take many minutes
to pass through the table. If other users are updating the column while the query is in
progress, should the query include the new or the old values? Should it include rows
that were inserted or deleted after the query started? The principle of consistency
requires that the database ensure that changed values are not seen by the query: it will
give you an average of the column as it was when the query started, no matter how
long the query takes or what other activity is occurring on the tables concerned.
Through the use of undo segments Oracle guarantees that if a query succeeds, the
result will be consistent. However, if your undo segments are incorrectly configured,
the query may not succeed: a famous Oracle error, “ORA-1555 snapshot too old,” is
raised. This used to be an extremely difficult problem to fix with earlier releases of the
database, but from release 9i onward you should always be able to avoid it.
I Is for Isolation
The principle of isolation states that an incomplete (that is, uncommitted) transaction
must be invisible to the rest of the world. While the transaction is in progress, only the
one session that is executing the transaction is allowed to see the changes: all other
sessions must see the unchanged data, not the new values. The logic behind this is, first,
that the full transaction might not go through (remember the principle of atomicity?)
and that therefore no other users should be allowed to see changes that might be
reversed. And second, during the progress of a transaction the data is (in business terms)
incoherent: there is a short time when the employee has had his salary changed, but not
his grade. Transaction isolation requires that the database must conceal transactions
in progress from other users: they will see the preupdate version of the data until the
transaction completes, when they will see all the changes as a consistent set. Again,
Oracle guarantees transaction isolation through use of undo segments.
D Is for Durability
The principle of durability states that once a transaction completes with a COMMIT, it
must be impossible for the database to lose it. During the time that the transaction is
in progress, the principle of isolation requires that no one (other than the session
concerned) can see the changes it has made so far. But the instant the transaction
completes, it must be broadcast to the world, and the database must guarantee that the
change is never lost: a relational database is not allowed to lose data. Oracle fulfils this
requirement through the use of logfiles. Logfiles come in two forms: online redo log
files, and archive redo log files. These are dealt with in detail in Chapter 18. For now,
remember that it is impossible for a properly configured Oracle database to lose data.
Of course, data can be lost through user error: inappropriate DML, or dropping objects.
But as far as Oracle and the DBA are concerned, such events are transactions like any
other: according to the principle of durability, they are absolutely nonreversible.
ch09.indd 3
6/29/2005 12:17:32 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
TIP If a database ever loses data, Management’s first, and fully justified,
reaction is to fire the DBA. Everyone knows that a properly configured
Oracle database won’t lose data; therefore, it must be the administrator’s
fault. Careers have been broken for this reason.
Executing SQL statements
The whole of the SQL language is only a dozen or so commands. The ones we are
concerned with here are
• SELECT
• INSERT
• UPDATE
• DELETE
• COMMIT
• ROLLBACK
Remember that from release 9i Oracle has included a very efficient and powerful
MERGE command, but since the end result of a merge is identical to a combination
of INSERT, UPDATE, and DELETE, there is no need to discuss it here.
Executing a SELECT Statement
The SELECT command retrieves data. A SELECT statement is executed in stages: the
server process executing the statement will first check whether the blocks containing
the data required are already in memory, in the database buffer cache. If they are, then
execution can proceed immediately. If they are not, the server must locate them on
disk and copy them into the database buffer cache.
EXAM TIP Always remember that server processes read blocks from datafiles
into the database buffer cache, but DBWn writes blocks from the database
buffer cache to the datafiles.
Once the data blocks required for the query are in the database buffer cache, any
further processing (such as sorting or aggregation) is carried out in the PGA of the
session. When the execution is complete, the result set is returned to the user process.
How does this relate to the ACID test? For read consistency, if the query encounters
a block that has been changed since the time at which the query started, the server
process will go to the undo segment that protected the change, locate the old version
of the data, and (for the purposes of the current query only) roll back the change.
Thus any changes initiated after the query commenced will not be seen. Clearly, if the
data needed to do this rollback is no longer in the undo segments, this mechanism
will not work. That is when you get “ORA-1555: snapshot too old.”
ch09.indd 4
6/29/2005 12:17:33 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
5
Executing an Update Statement
PART I
For any DML operation, it is necessary to work on both data blocks and undo blocks,
and also to generate redo: the A, C, and I of the ACID test require generation of undo;
the D requires generation of redo.
EXAM TIP Remember, “undo” is not the opposite of “redo”! Redo protects
all block changes, no matter whether it is a change to a block of a table segment,
an index segment, or an undo segment. As far as redo is concerned, an undo
segment is just another segment, and any changes to it must be made durable.
The first step in executing DML is the same as executing SELECT: the required
blocks must be found in memory or copied into memory from disk. The only change
is that an empty (or expired—more of that in Chapter 16) block of an undo segment
is needed too. From then on, things are a bit more complicated.
First, locks must be placed on any rows and associated index keys that will be
affected by the operation. This process is covered in Chapter 17.
Then the redo is generated: the server process writes to the log buffer the changes
that are going to be applied to the data blocks. This generation of redo is applied to
both table block changes and undo block changes: if a column is to be updated, then
the new value of the column is written to the log buffer (which is the change that will
be applied to the table block), and also the old value (which is the change that will be
applied to the undo block). If the column is part of an index key, then the changes to
be applied to the index are also written to the log buffer, together with an undo block
change to protect the index changes.
Having generated the redo, the update is carried out in the database buffer cache:
the block of table data is updated with the new version of the changed column, and the
old version of the changed column is written to the block of an undo segment. From
this point until the update is committed, all queries from other sessions addressing the
changed row will be redirected to the undo data. Only the session that is doing the
update will see the actual current version of the row in the table block. The same
principle applies to any associated index changes.
As a simple example, consider this statement:
update emp set sal=sal*1.1 where empno=7934;
To execute this statement, the block of table data containing the row for employee
number 7934 (and possibly several other rows too, if the rows are smaller than the
block) is copied into the database cache and a block of an undo segment is copied
into the cache. Then your server process writes to the log buffer the old version of the
sal column (which is the change to be applied to the block of undo) and the new
version of the sal column (which is the change to be applied to the block of table
data). Finally, the blocks themselves are updated. And remember that because SQL
is a set-oriented language, if there were many rows in the emp table with the same
empno, they would all be updated by the one statement. But because empno will be
a primary key, that can’t happen.
ch09.indd 5
6/29/2005 12:17:34 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
Executing Insert and Delete Statements
Conceptually, INSERT and DELETE are managed in the same fashion as an UPDATE.
Redo generation is exactly the same: all changes to be made to data and undo blocks
are first written out to the log buffer. The difference is in the amount of undo generated.
When a row is inserted, the only undo generated consists of writing out the new rowid
to the undo block. This is because to roll back an INSERT, the only information Oracle
requires is the rowid, so that a
delete from
where rowid=
statement can be executed. For a DELETE, the whole row is written to the undo block,
so that the deletion can be rolled back if need be by inserting the complete row back
into the table.
A more normal DELETE statement might be
delete from emp where empno=7934;
which will delete the one row (if 7934 really is unique) from the table, writing it out
to the undo block as it does it.
TIP Always include a WHERE clause in any UPDATE (or DELETE) statement;
otherwise, you will UPDATE (or DELETE) every row in the table.
Executing a Rollback
Remember that if anything goes wrong, rollback of transactions in progress is completely
automatic, carried out by background processes. For example, if the session that
initiated the transaction fails (perhaps the PC running the user process reboots, or
the network link goes down), then the PMON will detect that there is a problem,
and roll back the transaction. If the server reboots, then on startup SMON will detect
the problem and initiate a rollback. A manual rollback requires the user to issue the
ROLLBACK command. But however the rollback is initiated, the mechanism is identical:
in the case of an UPDATE, the pre-update versions of the columns are copied from the
undo block back to the table blocks. To roll back an INSERT, Oracle retrieves the rowid
of the inserted row from the undo block and uses it as the key for a delete on the table.
To roll back a DELETE, Oracle constructs a complete insert statement from the data in
the undo block. Thus, Oracle’s implementation of the ROLLBACK command is to use
undo data to construct and execute another statement that will reverse the effect of
the first statement.
TIP A rollback will itself generate more redo as it executes, perhaps rather
more than the original statement.
ch09.indd 6
6/29/2005 12:17:35 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
7
PART I
If you do omit a WHERE clause—as by saying delete from emp;—and so
delete all of the several million rows in the table, you can roll back the changes. During
the deletion, your server process will have copied the rows to an undo segment as it
deleted them from the table: ROLLBACK will insert them back into the table, and no
one will ever know you made the mistake. Unless, of course, you typed COMMIT....
Executing a Commit
Commit processing is where many people (and even some experienced DBAs) show an
incomplete, or indeed completely inaccurate, understanding of the Oracle architecture.
When you say COMMIT, all that happens physically is that LGWR flushes the log buffer
to disk. DBWn does absolutely nothing. This is one of the most important performance
features of the Oracle database.
To make a transaction durable, all that is necessary is that the changes that make
up the transaction be on disk: there is no need whatsoever for the actual data to be on
disk. If the changes are on disk, in the form of multiplexed redo log files, then in the
event of damage to the database the transaction can be reinstantiated by restoring the
datafiles from a backup taken before the damage occurred and applying the changes
from the redo log. This process is covered in detail in later chapters; for now, just hang
on to the fact that a COMMIT involves nothing more than flushing the log buffer to
disk, and flagging the transaction as complete.
This is why a transaction involving millions of updates in thousands of tables over
many minutes or hours can be committed in a fraction of a second. Because LGWR
writes in very nearly real time, virtually all the transaction’s changes are on disk already.
When you say COMMIT, LGWR actually does write in real time: your session will hang
until the write is complete. This delay will be the length of time it takes to flush the
last bit of redo from the log buffer to disk, which will take only milliseconds. Your
session is then free to continue, and from then on all other sessions will no longer
be redirected to the undo blocks when they address the changed table, unless the
principle of consistency requires it.
EXAM TIP What does DBWn do when you say commit? Absolutely nothing.
Having said that DBWn has nothing to do with commit processing, it does of
course write changed, or “dirty,” blocks to disk—eventually. The algorithm used is
intended to ensure that while changed blocks do get to disk, they will not be written
so quickly as to impact on normal working. If DBWn never wrote blocks to disk, there
would be a huge amount of work for it to do when a checkpoint was finally needed.
The exception is when a checkpoint is issued: these are the rare occasions (typically,
only during an orderly shutdown of the database and instance) when CKPT instructs
DBWn to write all dirty blocks to the datafiles.
ch09.indd 7
6/29/2005 12:17:36 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
EXAM TIP In normal running, DBWn writes only a few dirty buffers to disk;
when a checkpoint is signaled, it writes all dirty buffers to disk.
Where there is often confusion is that the stream of redo written out to the redo log
files by LGWR will contain changes for both committed and uncommitted transactions.
Furthermore, at any given moment DBWn may or may not have written out changed
blocks of data segments or undo segments to the datafiles for both committed and
uncommitted transactions. So in principle, your database on disk is corrupted: the
datafiles may well be storing uncommitted work and be missing committed changes.
But in the event of a crash, the stream of redo on disk always has enough information
to reinstantiate any committed transactions that are not in the datafiles (by use of the
changes applied to data blocks), and to reinstantiate the undo segments (by use of the
changes applied to undo blocks) needed to roll back any uncommitted transactions
that are in the datafiles.
DDL and Transaction Control
The COMMIT and ROLLBACK statements apply only to DML. You cannot roll back a
DDL statement: once executed, it is immediately durable. If it were possible to see the
source code for (for example) the CREATE TABLE command, it would be obvious why.
When you create a table, you are in fact doing a transaction against some data dictionary
tables: at the very least, you are inserting a row into SYS.TAB$, a data dictionary table
with one row to define every table in the database, and one or more rows into SYS.COL$,
a data dictionary table with one row for the definition of every column of every table
in the database. Then the command concludes with a COMMIT. This is to protect the
data dictionary: if the COMMIT were not built into the CREATE TABLE command, the
possibility of an incomplete transaction would arise, and an incomplete transaction
in the data dictionary could have appalling side effects.
The So-Called “Auto-Commit”
To conclude this discussion of commit processing, it is necessary to remove any
confusion about what is often called “auto-commit,” or sometimes “implicit commit.”
You will often hear it said that in some situations Oracle will “auto-commit.” One of
these situations is when doing DDL, as just described; another is when you exit from
a user process such as SQL*Plus.
Quite simply, there is no such thing as an automatic commit. When you execute
a DDL statement, a perfectly normal COMMIT is included in the source code that
implements the DDL command. But what about when you exit from your user process?
If you are using SQL*Plus on a Windows terminal (never mind what operating system
the database server is running) and you issue a DML statement followed by an “exit,”
your transaction will be committed. This is because a COMMIT statement is built into
the SQL*Plus “exit” command: if we could see the source code, it would be obvious.
But what if you click in the top-right corner of the SQL*Plus window? The window will
ch09.indd 8
6/29/2005 12:17:37 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
9
PART I
close, and if you log in again, you will see that the transaction has been rolled back. This
is because the programmers who wrote SQL*Plus for Microsoft Windows included a
ROLLBACK statement in the code that is executed when you close the window. By
contrast, if you are using the X Window version of SQL*Plus, you will find that closing
the window commits the transaction. So whether you get an “auto-commit” when you
exit from a program in various ways is entirely dependent on how your programmers
wrote the exit code. The Oracle server will simply do what it is told to do.
Of course, a disorderly exit from the user process, such as killing it with an operating
system utility, will be detected by PMON, and an active transaction will always be
rolled back.
Exercise 9-1: Transaction Isolation,
Read Consistency, and COMMIT
It is time to experiment with some SQL commands, and particularly to illustrate
some aspects of transaction control. For this exercise, open two SQL*Plus sessions
(or iSQL*Plus if you prefer), log on as the same user in both sessions, and run the
commands that follow in the two sessions.
In Your First Session
In Your Second Session
create table t1 as select *
from all users;
select count(*) from t1;
select count(*) from t1;
Results are the same in both sessions.
delete from t1;
select count(*) from t1;
select count(*) from t1;
Results differ because of the principle of isolation.
rollback;
select count(*) from t1;
select count(*) from t1;
Results are the same in both sessions.
delete from t1;
select count(*) from t1;
select count(*) from t1;
create view v1 as select * from
t1;
select count(*) from t1;
select count(*) from t1;
rollback;
select count(*) from t1;
select count(*) from t1;
Oh dear! The DDL statement committed the transaction, so it can’t be rolled back.
drop view v1;
drop table t1;
ch09.indd 9
6/29/2005 12:17:38 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
DML and Integrity Constraints
By default, integrity constraints are always enforced during DML, at statement execution
time. When an integrity constraint is violated by a statement, the whole statement
is rolled back. For example, a statement that attempts to update many rows might
successfully update a number of rows but then hit a problem: execution will cease,
and the successful updates already carried out by the statement will be reversed. It
makes no difference what the problem is. For instance, it could be an integrity constraint
or perhaps a space problem.
EXAM TIP If one statement in a multistatement transaction violates a
constraint, only that one statement is rolled back; the rest of the transaction
remains intact and uncommitted.
The various constraint errors that can be raised by the various DML statements are
summarized next, with examples of the messages.
Constraint
Possible Errors
Foreign key
INSERT and UPDATE on the child table: the value must exist in the parent table.
Error:
ORA-02291: integrity constraint (SCOTT.FK_DEPTNO) violated - parent key
not found
UPDATE and DELETE on the parent table: there must be no dependent rows in
the child table.
Error:
ORA-02292: integrity constraint (SCOTT.FK_DEPTNO) violated - child
record found
Not null
INSERT and UPDATE: cannot insert without a value, or modify the value to null.
Error:
ORA-01400: cannot insert NULL into (“SCOTT”.“EMP”.“EMPNO”)
Unique
INSERT and UPDATE: cannot have any value that already exists in the table.
Multiple nulls are permitted.
Error:
ORA-00001: unique constraint (SCOTT.PK_DEPT) violated
Primary key
Equivalent to a unique constraint modified with a not-null constraint: both
sets of rules apply.
Error: Same as for unique
TIP Programmers should trap these errors in their exceptions clauses and
take appropriate action to deal with the problem.
ch09.indd 10
6/29/2005 12:17:39 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
11
In the normal course of events, ordinary SELECT and DML commands are used to
extract data from the database and to insert data into it, but there are occasions when
you will need a much faster method for bulk operations. There are many reasons why
it may be desirable to extract large amounts of data and the associated object definitions
from a database in a form that will allow them to be easily loaded into another. One
obvious purpose is backup, but there are others, such as archiving of historical data
before deleting it from the live system, or to transfer data between production and test
environments, or between an online system and a data warehouse.
Historically, Oracle provided the Export and Import utilities. These were effective
(and they are still available with release 10g), but they suffer from the limitation of
being client/server tools: they are just user processes, like any other. The Export utility
connects to the database via a server process and issues SELECT statements: the data
retrieved by the server process is passed back to the Export user process, where it is
formatted and written out to a disk file. Similarly, the Import utility user process logs
onto the instance via a server process and then reads the disk file produced by Export
and constructs DDL and insert statements to create tables and other objects and load
the data into them. Release 10g introduces the Data Pump facility. Functionally, the
results are the same as the old Export/Import utilities: large amounts of data can be
extracted from one database and transferred into another. But the implementation is
totally different, and far superior. Note also that the Data Pump and Export/Import
dump file formats are completely different. Data Pump export command-line options
are shown in Figure 9-1.
PART I
Data Pump
Data Pump Architecture
Data Pump is a server-side utility. You initiate Data Pump jobs from a user process,
either SQL*Plus or through Enterprise Manager, but all the work is done by server
processes. This improves performance dramatically over the old Export/Import utilities,
because the Data Pump processes running on the server have direct access to the
datafiles and the SGA; they do not have to go via a session. Also, it is possible to launch
a Data Pump job and then detach from it, leaving it running in the background. You
can reconnect to the job to monitor its progress at any time.
There are a number of processes involved in a Data Pump job, two queues, a number
of files, and one table. First, the processes.
The user processes are expdp and impdp (for Unix) or expdp.exe and impdp.exe
(Windows). These are used to launch, control, and monitor Data Pump jobs.
Alternatively, there is an Enterprise Manager interface, which will be described later.
The expdp or impdp user process establishes a session against the database through
ch09.indd 11
6/29/2005 12:17:40 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
Figure 9-1 Data Pump export command-line options
a normal server process. This session then issues commands to control and monitor
Data Pump jobs. When a Data Pump job is launched, at least two processes are started:
a Data Pump Master process (the DMnn) and one or more worker processes (named
DWnn). If multiple Data Pump jobs are running concurrently, each will have its own
DMnn process and its own DWnn processes. As the name implies, the master process
controls the workers. If you have enabled parallelism, then each DWnn may make use
of two or more parallel execution servers (named Pnnn.)
ch09.indd 12
6/29/2005 12:17:41 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
13
PART I
Two queues are created for each Data Pump job: a control queue and a status
queue. The DMnn divides up the work to be done and places individual tasks that
make up the job on the control queue. The worker processes pick up these tasks and
execute them, perhaps making use of parallel execution servers. This queue operates
on a deliver-exactly-once model: messages are enqueued by the DMnn and dequeued
by the worker that picks them up. The status queue is for monitoring purposes: the
DMnn places messages on it describing the state of the job. This queue operates on a
publish-and-subscribe model: any session (with appropriate privileges) can query the
queue to monitor the job’s progress.
The files generated by Data Pump come in three forms: SQL files, dump files,
and log files. SQL files are DDL statements describing the objects included in the job.
You can choose to generate them (without any data) as an easy way of getting this
information out of the database, perhaps for documentation purposes or as a set of
scripts to re-create the database. Dump files contain the exported data. This is formatted
with XML tags. The use of XML means that there is a considerable overhead in dump
files for describing the data. A small table like the REGIONS table in the HR sample
schema will generate a 94KB dump file, but while this overhead may seem
disproportionately large for a tiny table like that, it becomes trivial for larger tables.
The log files describe the history of the job run.
EXAM TIP Remember the three Data Pump file types: SQL files, log files,
and dump files.
Finally, there is the control table. Created for you by the DMnn when you launch
a job, it is used both to record the job’s progress and to describe it. It is included in
the dump file as the final item of the job.
Directories
Data Pump reads and writes files in an Oracle directory. An Oracle directory gives a
layer of abstraction between the user and the operating system: you as DBA create
a directory within the database, which points to a physical path within the operating
system file system. Directories can be created either from a SQL*Plus prompt as shown
in Figure 9-2 or from within Database Control. To see information about directories,
query the view DBA_DIRECTORIES. Each directory has a name, an owner, and the
physical path to which it refers. Note that Oracle does not verify whether the path
exists when you create the directory—if it does not, or if the operating system user
who owns the Oracle software does not have permission to read and write to it, you
will only get an error when you actually use Data Pump. Having created a directory,
you must give the Oracle user who will be running Data Pump permission to read
and write to it, just as your system administrators must give the operating system user
permission to read and write to the physical path.
ch09.indd 13
6/29/2005 12:17:42 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
Figure 9-2 Creating directories from the command line
EXAM TIP Oracle directories are always owned by user SYS, but to create
them, you must have been granted the appropriate privilege, CREATE
DIRECTORY.
Directories can be contrasted with the initialization parameter UTL_FILE_DIR. This
is a parameter that allows Oracle, through PL/SQL procedures, to write to the file system
of the database server machine, but it is a far cruder method: it is not possible to grant
permissions within Oracle on UTL_FILE_DIR directories. Thus, if the parameter is set to
UTL_FILE_DIR=/tmp
ch09.indd 14
6/29/2005 12:17:42 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
15
then any Oracle user can completely fill your /tmp directory. Furthermore, if it is set to
then anyone can write to any directory that the Oracle owner has permission on, which
is a shocking security risk.
PART I
UTL_FILE_DIR=*
TIP Writing to the UTL_FILE_DIR is usually done with the PL/SQL package
UTL_FILE. Make sure that execute permissions on this package are strictly
limited.
Direct Path or External Table Path?
Data Pump has two methods for loading and unloading data: the direct path, and the
external table path. The direct path bypasses the database buffer cache. For an export,
Data Pump reads the datafiles directly from disk, extracts and formats the content, and
writes it out as a dump file. For an import, Data Pump reads the dump file, uses its
content to assemble blocks of table data, and writes them directly to the datafiles. The
write is above the “high-water mark” of the table. The high-water mark is a marker in
the table above which no data has ever been written. Once the load is complete, Data
Pump shifts the high-water mark up to include the newly written blocks, and the rows
within them are then visible to other users. This is the equivalent of a COMMIT. No
undo is generated, and if you wish, you can switch off the generation of redo as well.
Direct path is therefore extremely fast, and furthermore, it should have no impact on
your end users because interaction with the SGA is kept to a minimum.
The external table path uses the database buffer cache. Even though Data Pump is
manipulating files that are external to the database, it uses the database buffer cache
as though it were reading and writing an internal table. For an export, Data Pump reads
blocks from the datafiles into the cache through a normal SELECT process. From there,
it formats the data for output to a dump file. During an import, Data Pump constructs
standard insert statements from the content of the dump file and executes them by
reading blocks from the datafiles into the cache, where the insert is carried out in the
normal fashion. As far as the database is concerned, external table Data Pump jobs look
like absolutely ordinary (though perhaps rather large) SELECT or INSERT operations.
Both undo and redo are generated, as they would be for any normal DML statement.
Your end users may well complain while these jobs are in progress! Commit processing
is absolutely normal.
So what determines whether Data Pump uses the direct path or the external table
path? You as DBA have no control: Data Pump itself makes the decision according to
the complexity of the objects. Only simple structures, such as heap tables without
active triggers, can be processed through the direct path; more complex objects such
as clustered tables force Data Pump to use the external table path because it requires
interaction with the SGA in order to resolve the complexities. In either case, the dump
file generated is identical.
ch09.indd 15
6/29/2005 12:17:43 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
16
EXAM TIP The external table path insert uses a regular commit, like any
other DML statement. A direct path insert does not use a commit: it simply
shifts the high-water mark of the table to include the newly written blocks.
Using Data Pump in Network Mode
It is possible to use Data Pump to transfer data from one database to another, without
staging the data on disk at all. Consider this example of launching Data Pump from
the command-line utility impdp:
impdp userid=scott/tiger tables=dept,emp network_link=L1 directory=dp_dir
This command will launch a Data Pump export against the local database, logging
on as user SCOTT with password TIGER. The Data Pump job will then read two tables,
DEPT and EMP, in SCOTT’s schema and transfer them across the network to the database
identified by the database link L1, where a Data Pump import job will insert the data.
The export and the import processes will run concurrently, the one feeding the other.
Note that even though the data is never written out as an operating system file, it is
still necessary to specify a directory, in order that Data Pump can write out logging
information.
TIP A database link defines a path to a remote database.
Exercise 9-2: Using Data Pump Export Through
Enterprise Manager Database Control
This exercise will create a table and export it using the Database Control interface to
Data Pump.
1. Create a directory to be used by Data Pump. For example, from a command
prompt,
md c:\dp_dir
2. Using SQL*Plus, log on to your instance as user SYSTEM and create a table to
be used for testing Data Pump.
create table dp_test as select * from all_users;
select count * from dp_test;
ch09.indd 16
6/29/2005 12:17:44 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
17
create directory dp_dir as 'c:\dp_dir';
grant all on directory dp_dir to public;
exit;
PART I
3. Still within SQL*Plus, create the Oracle directory to be used by Data Pump
and grant all users permission to read and write to the directory.
4. Log on to Database Control as user SYSTEM.
5. From the database home page, click the Maintenance tab.
6. In the Utilities section, click the Export To Files link.
7. On the Export: Export Type window shown here, select Tables and enter an
operating system username and password with read/write permissions on the
directory specified in Step 3.
ch09.indd 17
6/29/2005 12:17:45 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
18
8. On the Export: Add Tables window shown here, click Add, and specify
SYSTEM as the schema and “DP_TEST” as the table. Click Select and Next.
9. On the Export: Options window, choose the directory DP_DIR as the location
for the logfile, and click Next.
10. On the Export: Files window, choose the directory DP_DIR as the location
and click Finish.
11. In the Export: Review window shown next, take a look at the script that has
been generated to see how you would run the job using the Data Pump API,
and click Submit Job.
ch09.indd 18
6/29/2005 12:17:46 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
19
PART I
12. On the Status window, click OK.
13. From an operating system prompt, navigate to the directory specified in Step
3. There will be a file EXPDAT01.DMP, which is the export dump file, and a
logfile, EXPDAT.LOG. Examine the logfile to check that the job did complete
successfully.
Exercise 9-3: Using Data Pump Import
Through impdp
This exercise will use the command-line utility impdp to bring the exported table
back into the database with Data Pump.
1. Log in to the instance as user SYSTEM through SQL*Plus, and drop the table
created in Exercise 9-2:
drop table dp_test;
exit;
2. From an operating system prompt, issue this command:
impdp userid=system/oracle dumpfile=expdat01.dmp directory=dp_dir
3. When the import has completed, connect to the instance with SQL*Plus as
SYSTEM and confirm that the table has been imported successfully.
select count(*) from dp_test;
ch09.indd 19
6/29/2005 12:17:46 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
20
SQL*Loader
Data Pump reads and writes files in an Oracle proprietary format: it is used to transfer
data into and out of, or between, Oracle databases. But in many cases you will be faced
with a need to do a bulk upload of datasets generated from some third-party system.
This is where SQL*Loader comes in. The input files may be generated by anything, but
so long as the layout conforms to something that SQL*Loader can understand, it will
upload the data successfully. Your task as DBA is to configure a SQL*Loader controlfile
that can interpret the contents of the input datafiles; SQL*Loader will then insert the
data, either using direct path or via the database buffer cache, in a similar fashion to
Data Pump. The crucial differences are, first, that SQL*Loader can read any file no
matter what its source, and second, that it is a user process like any other; unlike Data
Pump, it is not a server-side utility. It establishes a session against the instance and the
database via a server process.
SQL*Loader uses a number of files. The input datafiles are the source data that it
will upload into the database. These must conform to an agreed format. The controlfile
is a text file written by the DBA with directives telling SQL*Loader how to interpret the
contents of the input files, and what to do with the rows it extracts from them. Logfiles
summarize the success (or otherwise) of the job, while detailing any errors. Rows
extracted from the input files may be rejected by SQL*Loader (perhaps because they
do not conform to the format expected by the controlfile) or by the database (for
instance, insertion might violate an integrity constraint); in either case, they are written
out to a bad file. If rows are successfully extracted from the input but rejected because
they did not match some record selection criterion, they are written out to a reject file.
SQL*Loader command-line options are shown in Figure 9-3.
The SQL*Loader Controlfile
The controlfile is a text file instructing SQL*Loader on how to process the input
datafiles. It is possible to include the actual data to be loaded on the controlfile, but
you would not normally do this; usually, you will create one controlfile and reuse it,
on a regular basis, with different input datafiles. The formats that SQL*Loader can
understand are fixed record format, variable record format, and stream record format.
Remember that the examples following are very simple: the variety of input formats
that SQL*Loader can understand is limited only by your ingenuity in constructing a
controlfile.
The fixed record format is the most straightforward, as well as the fastest to process.
Each row of data is a fixed length, terminated with a carriage return character. Within the
rows, you use some character as a field delimiter. A fixed record controlfile such as this,
load data
infile 'fixed.dat' "fix 15"
into table names
fields terminated by ','
(first,last)
ch09.indd 20
6/29/2005 12:17:47 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
21
PART I
Figure 9-3 The SQL*Loader command-line options
will read the file fixed.dat, parse it into rows 15 bytes long (note that the 15 bytes
must include one for the carriage return row terminator), divide the rows into two
fields, and insert them into the columns “first” and “last” of the table “names.”
A matching input datafile, called test.dat, could be
John,Watsonaaa
Damir,Bersinic
McGraw,Hillaaa
ch09.indd 21
6/29/2005 12:17:48 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
22
Variable records include an entry at the head of each row to state how long the row
is. The length of this entry is included in the controlfile. The controlfile might be
load data
infile 'names.dat' "var 3"
into table names
fields terminated by ','
(first,last)
and a matching datafile would be
012John,Watson
015Damir,Bersinic
012McGraw,Hill
Note that the length of each row is a three-digit number, as specified in the
controlfile, and must include a character for the carriage return. Variable record
format is not as fast as fixed format but is faster than stream format.
Stream format requires SQL*Loader to do the most work. Rather than being given
any information about the length of the rows, SQL*Loader must scan each row for
the record terminator. This is the most flexible format but also the slowest to process.
The controlfile might be
load data
infile 'names.dat' "str '\n'"
into table names
fields terminated by ','
(first,last)
Note the use of the newline character, specified as “\n”. If you are familiar with the C
programming language, that will not be new. If not, note that a number of nonprintable
characters, such as the newline character, can be specified in this way: a leading
backslash, then a letter used to indicate the nonprintable character. The combination
“\n” is the most commonly used row delimiter (it indicates a line break), but tabs
or form feed characters can be used as well. A matching datafile for the preceding
controlfile might take the form
John,Watson
Damir,Bersinic
McGraw,Hill
As you can see, this format of input datafile is the easiest to generate. But it is also the
slowest to process.
TIP It may be very difficult to get a controlfile right, but once you have it, you
can use it repeatedly, with different input datafiles for each run. It is then the
responsibility of the feeder system to produce input datafiles that match your
controlfile, rather than the other way around.
ch09.indd 22
6/29/2005 12:17:49 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
23
PART I
It is necessary to study the Utilities Manual for a full description of all the formatting
capabilities of SQL*Loader, but in general you can assume that it is possible to construct
a controlfile that will understand just about any input datafile. However, do not think
that it is always easy.
Loading Methods
As with Data Pump, it is possible to use either a direct path or a conventional path
for loading data into database tables. But also as with Data Pump, there are restrictions.
Unlike when using Data Pump, you must tell SQL*Loader to use the direct path:
add the keyword DIRECT to the controlfile or optionally specify DIRECT=Y on the
SQL*Loader command line. Remember that a conventional load is a straightforward
insert, whereas for a direct load, the server process supporting the SQL*Loader session
assembles blocks in memory and writes them directly to the datafiles, bypassing the
database buffer cache. Here is a comparison of direct and conventional loads:
Conventional Path Load
Direct Path Load
Uses COMMIT to make the
insert permanent
Uses a “data save” to include the new blocks in the table
Generates undo and redo
Does not generate undo, and redo generation is optional
All constraints enforced
Only primary key, unique, and not-null constraints enforced
Insert triggers fire
Insert triggers do not fire
Works for all tables
Can be used only for heap tables
No table locks
Table is locked for DML during the duration of the load
TIP Direct Path loading is fast, but it has limitations!
Exercise 9-4: Using SQL*Loader
This exercise will insert some more rows into the table created in Exercise 9-2.
1. Using a text editor (such as Windows Notepad), create a SQL*Loader
controlfile, called STREAMIN.CTL, as follows:
load data
infile 'STREAMIN.DAT' "str \n"
append
into table dp_test
fields terminated by ','
(username,user_id)
Note that the “append” keyword allows SQL*Loader to insert into a table that
already contains rows.
ch09.indd 23
6/29/2005 12:17:49 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
24
2. Using a text editor as before, create the input datafile, to be called STREAMIN
.DAT, as follows:
John,100
Damir,200
McGraw,9999
3. From an operating system prompt, issue this command:
sqlldr userid=system/oracle control=STREAMIN.CTL
4. Log in to your instance with SQL*Plus, and confirm that the three new rows
have been inserted into the table:
select * from dp_test
Chapter Review
In this chapter you learned the internal mechanisms that Oracle uses to ensure
transactional consistency, according to the requirements of the relational database
model, and looked at what actually happens, in memory and on disk, when SQL
statements are executed. Following this investigation on executing individual DML
statements, you saw how the Data Pump and SQL*Loader utilities can be used for
bulk operations.
Questions
1. You issue a COMMIT command. Which of the following statements is correct?
(Choose two correct answers.)
A. DBWn writes the changed blocks to the datafiles.
B. LGWR writes the changes to the logfiles.
C. CKPT synchronizes the database buffer cache with the datafiles.
D. The transaction is made durable.
E. The transaction can be rolled back.
2. You issue an UPDATE command, and then a COMMIT. Put the following
actions in the correct order:
A. Data blocks are copied from the datafiles into the database buffer cache.
B. Data blocks in the cache are updated.
C. The log buffer is updated.
D. The changed blocks are flushed to disk.
E. The log buffer is flushed to disk.
3. User JOHN updates some rows and asks user DAMIR to log in and check the
changes before he commits them. Which of the following statements is true?
(Choose the best answer.)
ch09.indd 24
6/29/2005 12:17:50 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
25
B. DAMIR will not be able to see the changes.
C. JOHN must commit the changes, so that DAMIR can see them and if
necessary roll them back.
PART I
A. DAMIR can see the changes but cannot alter them because JOHN will have
locked the rows.
D. JOHN must commit the changes so that DAMIR can see them, but only
JOHN can roll them back.
4. User JOHN updates some rows but does not commit the changes. User
DAMIR queries the rows that JOHN updated. Which of the following
statements is true? (Choose three correct answers.)
A. DAMIR’s query will be redirected to the redo logs to show the original
version of the rows.
B. DAMIR’s session will roll back JOHN’s changes to show the original
version of the rows.
C. JOHN must commit the changes before DAMIR can see them.
D. DAMIR cannot see the rows that were updated, because they will be
locked.
E. If DAMIR’s query started after JOHN’s update, the principle of read
consistency means that he cannot see JOHN’s changes.
F. If DAMIR’s query started after JOHN’s update, the principle of isolation
means that he cannot see JOHN’s changes.
5. You are using Data Pump to upload rows into a table, and you wish to use
the direct path. Which of the following statements is correct? (Choose three
answers.)
A. You must include the “DIRECT” keyword in the Data Pump controlfile.
B. This is not possible if the table is in a cluster.
C. You must disable insert triggers on the table first.
D. You must enable insert triggers on the table first.
E. You have no control over this; Data Pump will use the direct path
automatically if it can.
F. Direct path is slower than the external table path because it doesn’t cache
data in memory.
6. You issue an INSERT command and then attempt to SELECT the rows you
inserted before committing them. Which of the following is true? (Choose the
best answer.)
A. You must commit the insert before you can see the rows.
B. You will see the new rows, even though they are uncommitted.
ch09.indd 25
6/29/2005 12:17:50 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
26
C. You must terminate the transaction with a COMMIT or ROLLBACK before
you can issue a SELECT statement.
D. You will see the new rows because your session will read them from an
undo segment.
7. You issue an INSERT statement, and it fails with the message “ORA-02291:
integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found.”
Which of the following statements is true? (Choose the best answer.)
A. The transaction will have been rolled back.
B. The statement will have been rolled back.
C. You must create an index on the parent table before you can find parent keys.
D. All of the above are correct.
8. Which of the following is not a Data Pump file type? (Choose the best answer.)
A. Dump file
B. Logfile
C. Controlfile
D. SQL file
9. You launch a Data Pump export job to export a number of tables, which runs
for several hours. Which of the following is true? (Choose the best answer.)
A. The tables being exported will be locked throughout the run.
B. Transactions against the tables committed during the run will be included
in the export.
C. Transactions against the tables (committed or not) during the run will not
be included in the export.
D. SQL executed against the tables during the run will be written out to
a SQL file.
E. The DDL describing the tables will be written out to a SQL file.
10. Using SQL*Loader, place these file formats in order of speed to process, from
slowest to fastest:
A. Fixed record format
B. Stream record format
C. Variable record format
11. You want to transfer a large amount of data from one database to another: both
databases are on the same machine. What should be the quickest method?
(Choose the best answer.)
A. Use the Export/Import utilities.
B. Use Data Pump to write out the data, and a SQL*Loader direct load to
bring it in.
ch09.indd 26
6/29/2005 12:17:51 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Chapter 9: Manipulating Database Data
27
C. Use Data Pump in network mode.
12. Which of the following is not a SQL*Loader file? (Choose one answer.)
PART I
D. Use Data Pump export to write out the data and then Data Pump import
to read it in.
A. Bad file
B. Controlfile
C. Discard file
D. Good file
E. Logfile
13. You create a directory with the statement
create directory dp_dir as 'c:\tmp';
but when you try to use it with Data Pump, there is an error. Which of the
following could be true? (Choose three answers.)
A. The Oracle software owner has no permissions on c:\tmp.
B. The Oracle database user has no permissions on dp_dir.
C. The path c:\tmp does not exist.
D. The path c:\tmp must exist, or the “create directory” statement would have
failed.
E. If you use Data Pump in network mode, then there will be no need for a
directory.
F. Issuing the command grant all on ‘c:\tmp’ to public; may
solve some permission problems.
14. You launch a Data Pump job with expdp and then exit from the session.
Which of the following is true? (Choose two answers.)
A. The job will terminate.
B. The job will continue running in the background.
C. You cannot monitor the job once you have exited.
D. You can reattach to the job to monitor it.
E. The job will pause but can be restarted.
15. You run SQL*Loader on your PC, to insert data into a remote database. Which
of the following is true? (Choose the best answer.)
A. The input datafiles must be on your PC.
B. The input datafiles must be on the server.
C. Direct load is possible only if the input datafiles are on the server.
D. Direct load is only possible if you run SQL*Loader on the server, not on
the PC.
ch09.indd 27
6/29/2005 12:17:52 PM
All-in-1 / Oracle Database 10g Certification All-in-One / Watson & Bersinic / 5790-3 /Chapter 9
Oracle Database 10g OCP Certification All-in-One Exam Guide
28
Answers
1. B and D. When you say commit, LGWR flushes the log buffer to disk, and the
transaction is made durable.
2. A, C, B, E, and D. Remember that everything happens in memory first, and
that your server process writes to the log buffer before writing the database
buffer cache. Then on commit, the log buffer is flushed to disk. The data
blocks may not be written for some time.
3. B. The principle of isolation means that only JOHN can see his uncommitted
transaction; DAMIR will not be able to see the changes.
4. B, C, and F. B is correct because that is how Oracle provides transaction
isolation. C is correct, again, because of isolation being maintained until
commit. F is correct because the principle of isolation, not read consistency,
means that DAMIR cannot see JOHN’s changes.
5. B, C, and E. B and C are correct because these are two of the limitations. E is
correct because this is a feature of Data Pump.
6. B. A session can always see its own transactions, committed or not.
7. B. The statement that throws an error is rolled back automatically; the rest of
the transaction remains intact and uncommitted.
8. C. The controlfile is wrong: it is used for SQL*Loader, not Data Pump. The
other three file types are those that Data Pump can generate.
9. C. Transactions against the affected tables during a long-running Data Pump
export job will not be included in the export file: the job is protected from
any changes.
10. A, C, and B. This is the correct order because SQL*Loader will process fixedlength record format faster than variable-length record format or stream
record format.
11. C. Using Data Pump in network mode avoids the need to stage data on disk:
there is no reason not to use it when the databases are on the same machine.
12. D. The “good file” is not a SQL*Loader file. SQL*Loader does not produce a
file like this—only the other four.
13. A, B, and C. A and B could be reasons: remember to distinguish between the
operating system user who owns the software, and the Oracle user who only
exists within the database. C could also be a reason: at directory creation time,
Oracle does not check that the physical path is valid.
14. B and D. Data Pump jobs run independently of the session that launched
them, making it possible to disconnect from the job and then to reconnect for
monitoring purposes.
15. A. The input datafiles must be on your PC, because it is the SQL*Loader user
process that reads the input datafiles.
ch09.indd 28
6/29/2005 12:17:53 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3/Ch10
CHAPTER 10
Programming Oracle
with PL/SQL
In this chapter you will learn how to
• Identify PL/SQL objects
• Describe triggers and triggering events
• Identify configuration options that affect PL/SQL performance
1
ch10.indd 1
7/11/2005 3:33:26 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
PL/SQL is a programming language developed specifically for the Oracle database. It
extends the SQL language by providing procedural structures, and facilities for generating
user interface code. Theoretically, a database administrator may not need to be an
expert in PL/SQL; programming work should be done by the development staff. But
in practice, the more PL/SQL a DBA knows, the better. At the very least, you will need
to be able to identify PL/SQL objects that have problems (as is detailed in Chapter 14).
Furthermore, at most Oracle installations, the DBA will be expected to assist programmers
with writing code and when necessary to create PL/SQL objects as well.
Programming Languages and the Oracle Database
The Oracle database, like all ISO-compliant relational databases, supports the use
of Structured Query Language, or SQL. SQL is a set-oriented language designed for
retrieving and manipulating data in a client/server environment. It is very efficient at
this, but there are many occasions when your programmers will want to manipulate
rows one at a time, rather than in groups. Also, SQL does not have any facilities for
designing user interfaces. By contrast, procedural languages can manipulate individual
rows. They have commands that will allow navigation from one row to another, and
can include flow control structures.
SQL and Procedural Languages
To combine the advantages of SQL’s set-oriented structures with the control facilities
of a procedural language, your programmers need to use a language with elements of
both. The universally accepted approach is to embed SQL commands in procedural
code. There are two approaches to this. The pure client/server approach is to run the
procedural code on a client machine (either a user’s terminal or an application server)
and send the SQL commands it generates to the database server for execution. An
alternative is to run the procedural code, as well as the SQL, within the database. In
some ways, the second approach is more efficient: there is no network overhead, and all
the code is centrally stored and managed. But it means that the language is proprietary:
it will run within the database that is designed to run it, and nowhere else. A second
possible problem is that all the processing workload is concentrated within the database.
PL/SQL is Oracle’s proprietary third-generation language, which runs within the
database. You can use it to retrieve and manipulate data with SQL, while using procedural
constructs such as IF...THEN...ELSE or FOR or WHILE. The PL/SQL code can be stored
on a client machine and sent to the server for execution (this is known as “anonymous”
PL/SQL), or it can be stored within the database as a named block of code.
From release 8i of the Oracle database, it is also possible to use Java within the
database. Like PL/SQL, Java can be used to provide a blend of procedural code with
SQL statements. Since Java can run either on a client machine (typically, an application
server) or within the database, it gives you the option of distributing the processing
workload—at the cost of increased network traffic. And unlike PL/SQL, it is a
nonproprietary industry standard: if your application is written in Java, it should be
ch10.indd 2
7/11/2005 3:33:56 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
3
PART I
portable to any Java-compliant database. But Java is a much lower-level language and
will often have a longer development cycle.
The choice of language is dependent on many factors, but PL/SQL should always
be considered in the Oracle environment. It is a very quick and easy language to work
with, and all DBAs should be familiar with it—if only to assist programmers.
Stored and Anonymous PL/SQL
PL/SQL runs within the database, but it can be stored on either the client or the
server. PL/SQL code can also be entered interactively from a SQL*Plus prompt. Stored
PL/SQL is loaded into the database and stored within the data dictionary as a named PL/
SQL object. When it is saved to the database, it is compiled: the compilation process
checks for syntactical errors and also picks up errors relating to the data objects the code
addresses. This saves time when the code is actually run and means that programmers
should pick up errors at compilation time, before users hit them. Code stored remotely,
or ad hoc code issued at the SQL*Plus prompt, is compiled dynamically: this impacts
on performance and also raises the possibility that unexpected errors might occur.
Figure 10-1 shows an example of running an anonymous PL/SQL block and of
creating and running a stored procedure. The anonymous block in the figure creates
a variable called INCREASE with the DECLARE statement and sets it to 10. Then the
Figure 10-1 Anonymous and stored PL/SQL
ch10.indd 3
7/11/2005 3:33:57 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
4
procedural code (within the BEGIN...END statements) uses the variable within a SQL
statement that updates the sal column of the emp table.
The second example in the figure creates a procedure called INC_SAL, stored within
the data dictionary. It takes a numeric argument called INCREASE and uses this in a
SQL UPDATE statement. Then the procedure is invoked with the EXECUTE command,
passing in a value for the argument.
These examples are very simple, but they should illustrate how anonymous PL/SQL
runs just once and therefore must be compiled at execution time, whereas stored
PL/SQL can be compiled in advance and then executed many times.
TIP Anonymous PL/SQL is less efficient than stored PL/SQL and also causes
problems with source code management, as the code may be distributed across
many machines.
PL/SQL Objects
There are five types of PL/SQL object:
• Procedure
• Function
• Package
• Package body
• Trigger
All of these are schema objects stored within the data dictionary. PL/SQL can also
be used to create object types and the methods to manipulate them, but this is beyond
the scope of the OCP examination.
Procedures, Functions, and Packages
Procedures and functions carry out user-defined actions. Packages are collections
of procedures and functions, grouped together for manageability. To create these
PL/SQL objects, you can use Enterprise Manager Database Control, SQL*Plus, or a
tool specifically designed for generating PL/SQL code, such as Oracle’s Procedure
Builder or various third-party products.
TIP SQL*Plus and Database Control are only suitable for small-scale PL/SQL
development. For real work, your programmers will need a proper IDE
(interactive development environment) tool that will assist with syntax
checking, debugging, and source code management.
ch10.indd 4
7/11/2005 3:33:58 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
5
Procedures and Functions
PART I
A procedure is a block of code that carries out some action. It can, optionally, be defined
with a number of arguments. These arguments are replaced with the actual parameters
given when the procedure is invoked. The arguments can be IN arguments, meaning
that they are used to pass data into the procedure, or OUT arguments, meaning that
they are modified by the procedure and after execution the new values are passed out
of the procedure. Arguments can also be IN-OUT, where the one variable serves both
purposes. Within a procedure, you can define any number of variables that, unlike the
arguments, are private to the procedure. To run a procedure, either call it from within
a PL/SQL block or use the interactive EXECUTE command.
A function is similar in concept to a procedure, but it does not have OUT arguments
and cannot be invoked with the EXECUTE command. It returns a single value, with
the RETURN statement.
Anything that a function can do, a procedure could also do. Functions are generally
used to support specific operations: small code blocks, that will be used many times.
Procedures are more commonly used to divide code into modules, and may contain
long and complex processes.
Figure 10-2 shows an example of creating and invoking a function. The first line is
an instruction to create the function, or if it already exists, to overwrite it. The function
takes one numeric argument and will return a varchar2 value. Within the BEGIN...END
is the procedural code, which includes the flow control construct IF…THEN...ELSE…
END IF.
Figure 10-2 Creating and using a function with SQL*Plus
ch10.indd 5
7/11/2005 3:33:58 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
6
TIP If you use CREATE, rather than CREATE OR REPLACE, you will have
to drop the object first if it already exists.
Figure 10-3 shows an example of creating and invoking a procedure. The procedure
uses a looping construct to call a statement a variable number of times, dependent on
the value of the parameter passed to the IN argument.
TIP Some people get very upset about terminology. To summarize, an
“argument” is the variable defined when you create a function or procedure;
a “parameter” is the value passed to the argument when you run the function
or procedure.
Packages
To group related procedures and functions together, your programmers create packages.
A package consists of two objects: a specification and a body. A package specification
lists the functions and procedures in the package, with their call specifications: the
arguments and their datatypes. It can also define variables and constants accessible
to all the procedures and functions in the package. The package body contains the
PL/SQL code that implements the package: the code that creates the procedures and
functions.
Figure 10-3 Creating and executing a procedure with SQL*Plus
ch10.indd 6
7/11/2005 3:33:59 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
7
ocp10g> create or replace package numbers
2 as
3 function odd_even(v1 number) return varchar2;
4 procedure ins_ints(v1 in number);
5 end numbers;
6 /
Package created.
PART I
To create a package specification, use the CREATE PACKAGE command. For
example,
Then to create the package body, use the CREATE OR REPLACE PACKAGE BODY
statement to create the individual functions and procedures.
Several hundred PL/SQL packages are provided as standard with the Oracle database.
Many are documented in the “PL/SQL Packages and Types Reference” manual. These
supplied packages are, for the most part, created when you create a database. Some of
them are for the use of the database administrator (such as the DBMS_WORKLOAD_
REPOSITORY package, which lets you manage the Automatic Workload Repository);
others are for your developers (such as the DBMS_OUTPUT package, that lets them
write to a session’s user process).
To invoke a packaged procedure, you must prefix the procedure name with the
package name. For example,
ocp10g> exec dbms_output.put_line('message to the user');
will run the PUT_LINE procedure in the DBMS_OUTPUT package.
Exercise 10-1: Creating and Using Functions,
Procedures, and Packages
Use Database Control to create PL/SQL objects and execute them from SQL*Plus.
1. Connect to your database as user SYSTEM using SQL*Plus.
2. Create a table to be used for this exercise.
ocp10g> create table integers (c1 number,c2 varchar2(5));
3. Connect to your database as user SYSTEM using Database Control.
4. From the database home page, take the Administration tab and then the
Packages link in the Schema section. Click Create.
5. In the Create Package window, enter NUMBERS as the package name, and the
source code for the package as in Figure 10-4. Click OK to create the package.
6. From the database home page, take the Administration tab and then the Package
bodies link in the Schema section. Click Create.
7. In the Create Package Body window, enter NUMBERS as the package name,
and the source code for the package body as in Figure 10-5. Click OK to create
the package body.
ch10.indd 7
7/11/2005 3:34:00 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
8
Figure 10-4 Creating a package specification with Database Control
8. In your SQL*Plus session, describe the package, execute the procedure, and
check the results.
ocp10g> desc numbers;
PROCEDURE INS_INTS
Argument Name
Type
------------------------- -----------------V1
NUMBER
FUNCTION ODD_EVEN RETURNS VARCHAR2
Argument Name
Type
------------------------- -----------------V1
NUMBER
ocp10g> execute numbers.ins_ints(5);
PL/SQL procedure successfully completed.
ocp10g> select * from integers;
C1 C2
---------- ----1 odd
2 even
3 odd
4 even
5 odd
5 rows selected.
ch10.indd 8
In/Out Default?
------ -------IN
In/Out Default?
------ -------IN
7/11/2005 3:34:00 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
9
PART I
Figure 10-5 Creating a package body with Database Control
Database Triggers
Database triggers are a special category of PL/SQL object, in that they cannot be invoked
manually. A trigger runs (or “fires”) automatically when a particular action is carried out
or a certain situation arises; this is the triggering event. There are a number of possible
triggering events. For many of them, the trigger can be configured to fire either before
or after the event. It is also possible to have both before and after triggers defined for
the same event. The DML triggers, which fire when rows are inserted, updated, or
deleted, can be configured to fire once for each affected row, or once per statement
execution.
All triggers have one factor in common: their execution is completely beyond the
control of the user who caused the triggering event. He may not even know that the
trigger fired. This makes triggers admirably suited to auditing user actions, as will be
described in Chapter 11. These are the more commonly used triggering events:
• Execution of INSERT, UPDATE, and DELETE DML commands
• Execution of CREATE, DROP, ALTER, and TRUNCATE DDL commands
ch10.indd 9
7/11/2005 3:34:01 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
10
• Session logon and logoff
• Database startup and shutdown
• Suspension of a statement because of a space problem
• Detection of a server error
Note that there is no such thing as a trigger on SELECT, though in Chapter 11 you
will see how fine-grained auditing (FGA) can be used to produce a similar effect.
There are numerous uses for triggers. Here are some examples:
• Auditing users’ actions A trigger can capture full details of what was done
and who did it, and write them out to an audit table.
• Executing complex edits An action on one row may, in business terms,
require a number of associated actions on other tables. The trigger can perform
these automatically.
• Security A trigger can check the time, the user’s IP address, the program he is
running, and any other factors that should limit what s/he can do.
• Enforcing complex constraints An action may be fine in terms of the
constraints on one table, but may need to be validated against the contents
of several other tables.
Consider an HR system. Before an employee is deleted from the current employees’
table, it is necessary to transfer all his details from a number of tables to archive tables.
This could be enforced by creating a trigger as follows:
create or replace trigger archive_emp
before delete on current_emps
for each row
begin
archive_emp(:old.employee_id);
end;
Whenever any session deletes rows from the CURRENT_EMPS table, before each row
is actually deleted the procedure ARCHIVE_EMP will execute, taking the EMPLOYEE_ID
of the row being deleted as its parameter. This procedure will do whatever is necessary
to archive an employee’s data. This illustrates an important point: it is generally
considered good practice to keep triggers small, and to do the bulk of the work with
a stored procedure.
EXAM TIP It is impossible to run a trigger by any means other than its
triggering event.
ch10.indd 10
7/11/2005 3:34:01 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
11
Create a trigger to validate data, before committing it.
1. Connect to your database as user SYSTEM using SQL*Plus.
PART I
Exercise 10-2: Using DML Triggers
2. Create a trigger on the INTEGERS table as follows:
ocp10g> create or replace trigger oe_check
2 after insert or update on integers
3 for each row
4 begin
5 if mod(:new.c1,2)=0 then
6 dbms_output.put_line(:new.c1||' is even');
7 else
8 dbms_output.put_line(:new.c1||' is odd');
9 end if;
10 end;
11 /
Trigger created.
3. Enable printing to the screen for your SQL*Plus session.
ocp10g> set serveroutput on;
4. Test the effect of the trigger as follows:
ocp10g> insert into integers values(2,'odd');
2 is even
1 row created.
ocp10g> rollback;
Rollback complete.
ocp10g> insert into integers values(3,'odd');
3 is odd
1 row created.
ocp10g> commit;
Commit complete.
Note that because triggers fire as part of the transaction, it is possible to roll
back the incorrect insertion.
5. Connect to your database as user SYSTEM using Database Control.
6. From the database home page, take the Administration tab and then the
Triggers link in the Schema section.
7. In the Search window, select Object Type as Trigger, Schema as SYSTEM, and
Object Name as OE_CHECK. Then click Go.
8. Click View to see the source code of the trigger, as in Figure 10-6. Note that
it is “Valid,” meaning that it has compiled correctly, and “Enabled,” meaning
that it will fire.
9. Tidy up.
ocp10g> drop trigger oe_check;
ocp10g> drop table integers;
ocp10g> drop package numbers;
ch10.indd 11
7/11/2005 3:34:02 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
12
Figure 10-6 Displaying a trigger with Database Control
Instance Parameters for PL/SQL
The performance of PL/SQL code can be influenced by some instance parameters:
• PLSQL_V2_COMPATIBILITY, default FALSE Setting this to TRUE forces
Oracle to allow some abnormal behavior that was legal in earlier releases.
Use this only if it is necessary for backward compatibility.
• PLSQL_DEBUG, default FALSE Setting this to true forces Oracle to compile
PL/SQL in a manner that will store additional information that may assist with
debugging. This would not normally be set on a production system.
• PLSQL_OPTIMIZE_LEVEL, default 2 Level 2, the highest, enables the use of
all the compiler’s optimization features; this gives the best run-time performance
ch10.indd 12
7/11/2005 3:34:02 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
13
PART I
but perhaps increases compilation time. Lower settings (0 or 1) will result in
quicker compilation but possibly slightly degraded execution. If the production
system is doing a large amount of compilation (anonymous PL/SQL, for
example), then it might be necessary to change this.
• PLSQL_WARNINGS, default DISABLE:ALL This controls which messages
should be displayed by the PL/SQL compiler. Other settings will cause the
compiler to generate messages that may be of value when debugging code.
This would not normally be set on a production system.
• PLSQL_CODE_TYPE, default INTERPRETED The default setting means that
PL/SQL code is compiled only down to byte code. Then when invoked, this is
interpreted. Setting this to NATIVE, in conjunction with the parameter that
follows, instructs Oracle to precompile the PL/SQL code to C code, and then
to compile and link this with the C compiler and linker provided by your
server’s operating system. This may improve performance.
• PLSQL_NATIVE_LIBRARY_DIR, default NULL Specifies the operating system
path to store the dynamic link libraries that are generated by native PL/SQL
compilation.
In most cases, the default settings for all these instance parameters will be suitable.
On a production system, you may wish to consider setting the PLSQL_CODE_TYPE
to NATIVE; this is in fact recommended for Oracle E-Business Suite running in a 10g
database. Details of how to do this are given in the PL/SQL Users Guide and Reference
manual.
Chapter Review
PL/SQL is a proprietary language for use with an Oracle database. It provides procedural
constructs that can be used in conjunction with SQL statements. PL/SQL is usually used
to write stored procedures and functions: these are compiled and stored within the data
dictionary of the database and for ease of management can be grouped into packages.
A package consists of a package specification, which publishes the call specifications
of the procedures and functions, and a package body, which implements them.
A special type of PL/SQL object is the trigger. Triggers are PL/SQL code blocks that
cannot be invoked on demand: they run automatically when their triggering event
occurs.
The default mode for running PL/SQL is through an interpreter. It is compiled down
to byte code, but no further. If you wish, and if you have a C compiler and a linker
available, you can convert your PL/SQL code to C code, compile and link it, and save
it as a dynamically linkable shared object library.
ch10.indd 13
7/11/2005 3:34:03 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
14
Questions
1. Which of the following, if any, can be PL/SQL objects? (Choose all that apply.)
A. Constraints
B. Functions
C. Package bodies
D. Package specifications
E. Procedures
F. Sequences
G. Triggers
H. Views
2. Which of the following PL/SQL objects can be invoked with the EXECUTE
command? (Choose the best answer.)
A. Functions
B. Packages
C. Procedures
D. Triggers
E. All of the above
3. Where does PL/SQL code run? (Choose the best answer.)
A. Within the session’s user process
B. Within the data dictionary
C. Within the instance
D. It depends on whether the PL/SQL is anonymous or stored
4. Which PL/SQL object types can be packaged? (Choose all that apply.)
A. Anonymous PL/SQL blocks
B. Functions
C. Procedures
D. Triggers
5. When PL/SQL is compiled, where is the resulting code stored? (Choose the
best answer.)
A. In the data dictionary
B. As an operating system file
C. In the default tablespace of the user who owns the code
D. It depends on the PLSQL_CODE_TYPE parameter
ch10.indd 14
7/11/2005 3:34:04 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Chapter 10: Programming Oracle with PL/SQL
15
Answers
2. C. Only procedures can be invoked with the EXECUTE command. Functions
are called by other statements, and triggers fire automatically. Packages can’t
be executed at all, unlike the procedures and functions they contain.
PART I
1. B, C, D, E, and G. All these are created with PL/SQL; the others, with SQL.
3. C. PL/SQL runs within the instance. It may be invoked by a user process, and
it is stored in the data dictionary. Whether the code is anonymous or stored,
it still runs in the instance.
4. B and C. Packages consist of one or more procedures and functions. Anonymous
blocks must be converted to procedures before they can be packaged, and
while triggers can call packaged code, they cannot themselves be included
within a package.
5. D. It depends on the PLSQL_CODE_TYPE setting. Native compiled code is
stored in an operating system file, while interpreted code is stored in the data
dictionary.
ch10.indd 15
7/11/2005 3:34:04 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3 Blind folio p. 16
ch10.indd 16
7/11/2005 3:34:05 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3/Ch11
CHAPTER 11
Securing the Oracle Database
In this chapter you will learn how to
• Apply the principal of least privilege
• Manage default user accounts
• Implement standard password security features
• Audit database activity
• Register for security updates
1
ch11.indd 1
7/11/2005 3:51:54 PM
All-in-1 / Oracle Database 10g OCP Certification All-in-One / Watson, Bersinic / 5790-3
Oracle Database 10g OCP Certification All-in-One Exam Guide
2
The safest principle to follow when determining access to computer systems is that of
“least privilege”: no one should have access to anything beyond the absolute minimum
needed to perform their work, and anything not specifically allowed is forbidden. The
Oracle database conforms to this, in that by default no one can do anything at all with
the exception of the two users SYS and SYSTEM. No other users can even connect, not
even those created by the standard database creation routines.
Once users are given permission to connect and to see and manipulate data, the
database provides facilities for controlling passwords and for tracking what people
are doing. But before going into that, there are certain “best practices” that should be
applied to tighten up the default security levels.
Adjusting Default Security Settings
A database created with the Database Configuration Assistant, DBCA, will, depending
on the options selected, have more than a dozen user accounts. Access to these accounts
must be controlled—by default, there is no access to most of them. The user accounts
you create subsequent to database creation should have their privileges restricted: by
default, they may have capabilities that you are not expecting. It is vital to control these
if there is any possibility of users connecting with tools (such as SQL*Plus) that let
them issue ad hoc SQL and PL/SQL commands.
Default Users
To see the users in your database and the status of the accounts, query the DBA_
USERS view:
ocp10g> select username,account_status from dba_users;
USERNAME
ACCOUNT_STATUS
-------------------- -------------------------------SYS
OPEN
SYSTEM
OPEN
OUTLN
EXPIRED & LOCKED
DIP
EXPIRED & LOCKED
DBSNMP
OPEN
WMSYS
EXPIRED & LOCKED
EXFSYS
EXPIRED & LOCKED
SI_INFORMTN_SCHEMA
EXPIRED & LOCKED
ORDPLUGINS
EXPIRED & LOCKED
ORDSYS
EXPIRED & LOCKED
MDSYS
EXPIRED & LOCKED
DMSYS
EXPIRED & LOCKED
CTXSYS
EXPIRED & LOCKED
XDB
EXPIRED & LOCKED
ANONYMOUS
EXPIRED & LOCKED
OLAPSYS
EXPIRED & LOCKED
MDDATA
EXPIRED & LOCKED
WKPROXY
EXPIRED & LOCKED
WKSYS
EXPIRED & LOCKED
WK_TEST
EXPIRED & LOCKED
SYSMAN
OPEN