Вы находитесь на странице: 1из 348

Introduction to Oracle: SQL

and PL/SQL Using Procedure


Builder
Volume Two S Participant Guide

Edition 1.1
M03990
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.

Neena Kochhar This documentation contains proprietary information of Oracle Corporation; it is


provided under a license agreement containing restrictions on use and discloĆ
Debby Kramer sure and is also protected by copyright law. Reverse engineering of the software
is prohibited. If this documentation is delivered to a U.S. Government Agency of
the Department of Defense, then it is delivered with Restricted Rights and the folĆ
lowing legend is applicable:
Technical Contributors Restricted Rights Legend
and Reviewers
Use, duplication or disclosure by the Government is subject to restrictions for
Christian Bauwens commercial computer software and shall be deemed to be Restricted Rights softĆ
ware under Federal law, and as set forth in subparagraph (c) (1) (ii) of DFARS
Debra Bowman 252.227Ć7013, Rights in Technical Data and Computer Software (October 1988).
Lenny Brunson
Jackie Collins This material or any portion of it may not be copied in any form or by any means
without the express prior written permission of the Worldwide Education Services
Ralf Durben group of Oracle Corporation. Any other copying is a violation of copyright law and
Brian Fry may result in civil and/or criminal penalties.
Anthony Holbrook If this documentation is delivered to a U.S. Government Agency not within the DeĆ
Karlene Jensen partment of Defense, then it is delivered with Restricted Rights," as defined in
Sarah Jones FAR 52.227Ć14, Rights in DataĆGeneral, including Alternate III (June 1987).
Glenn Maslen The information in this document is subject to change without notice. If you find
Sundar Nagarathnam any problems in the documentation, please report them in writing to Worldwide
Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, RedĆ
Sandra Schrick wood Shores, CA 94065. Oracle Corporation does not warrant that this document
Ulrike Schwinn is error free.
Rosemarie Truman
SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle
Jenny Tsai Server, Discoverer/2000, and Designer/2000 are trademarks or registered tradeĆ
Laura Van Deusen marks of Oracle Corporation.

All other products or company names are used for identification purposes only,
and may be trademarks of their respective owners.

Publishers
Stephanie Jones
Kimberly Lee
Jennifer Robertson
Mark Turangan
7

Specifying Variables at Runtime


7Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

You can create a command file containing a WHERE clause to restrict the rows
displayed. To change the condition each time the command file is run, you use
substitution variables. Substitution variables can replace values in the WHERE
clause, a text string, and even a column or a table name.
At the end of this lesson, you should be able to
D Create a SELECT statement that prompts the user to enter a value at runtime.
D Use the SQL*Plus ACCEPT command to define a variable.
D Define a variable that can be automatically picked up by the SELECT statement
at runtime.

Specifying Variables at Runtime 7Ć3


7Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
The reports produced so far have not been interactive in any way. In a finished
application, the user would trigger the report, and the report would run without
further prompting. The range of data reported would be predetermined by the fixed
WHERE clause in the SQL*Plus script file. However, SQL*Plus enables you to
create reports that prompt the user to supply their own values to restrict the range of
data returned.

Interactive Reports
To create interactive reports, you can embed substitution variables in a command file
or in single SQL commands. A variable can be thought of as a container in which
values are temporarily stored.

Specifying Variables at Runtime 7Ć5


7Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Substitution Variables
In SQL*Plus, you can use single ampersand substitution variable to temporarily store
values.
You can predefine variables in SQL*Plus by using the ACCEPT or DEFINE
commands. ACCEPT reads a line of user input and stores it in a variable. DEFINE
creates and assigns a value to a variable.

Examples of Restricted Ranges of Data


D Report figures for the current quarter or specified date range only.
D Report on data relevant to the user requesting the report only.
D Display personnel within a given department only.

Other Interactive Effects


Interactive effects are not restricted to direct user interaction with the WHERE
clause. The same principles can be used to achieve other goals, for example:
D Dynamically altering headers and footers.
D Obtaining input parameters from a file rather than from a person.
D Passing values from one SQL statement to another.
SQL*Plus does not support validation checks on user input. Make sure that the
prompts you write for the user are simple and unambiguous.

Specifying Variables at Runtime 7Ć7


7Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Single Ampersand Substitution Variables
When running a report, users often want to restrict the data returned dynamically.
SQL*Plus provides this flexibility by means of user variables. Use an ampersand (&)
to identify each variable in your SQL statement. You do not need to define the value
of each variable.

Notation Description
&user_variable Indicates a variable in a SQL statement; if the variable does
not exist, SQL*Plus prompts the user for a value.
SQL*Plus discards a new variable once it is used.

Example
Create a statement to prompt the user for a department number at runtime. The report
should contain each employee’s number, last name, and salary.

SQL> SELECT id, last_name, salary


2 FROM s_emp
3 WHERE dept_id = &department_number;

Enter value for department_number: 31

ID LAST_NAME SALARY
---------- ------------------------- ----------
3 Nagayama 1400
11 Magee 1400

With the single ampersand, the user is prompted every time the command is executed.

SET VERIFY Command


To confirm the changes in the SQL statement, use the SQL*Plus SET VERIFY
command. Setting SET VERIFY to ON forces SQL*Plus to display the text of a
command before and after it replaces substitution variables with values.

Specifying Variables at Runtime 7Ć9


7Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Single Ampersand Substitution Variables continued

Specifying Character and Date Values with Substitution Variables


Remember that in a WHERE clause, date and character values must be enclosed
within single quotation marks. The same rule applies to the substitution variables.
To avoid entering the quotation marks at run time, enclose the variable in single
quotation marks within the SQL statement itself.

Example
Write a query to retrieve the employee number, last name, and salary of all employees
based on the title entered at the prompt by the user.

SQL> SELECT id, last_name, salary


2 FROM s_emp
3 WHERE title = ’&job_title’;

Enter value for job_title: Stock Clerk

Specifying Variables at Runtime 7Ć11


7Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Single Ampersand Substitution Variables continued

Specifying Column Names, Expressions, and Text at Runtime


Not only can you use the substitution variables in the WHERE clause of a SQL
statement, but these variables can be used to substitute column names, expressions, or
text.

Examples
Display the number and any other column and any condition of orders. Try a couple
of variations of column names and conditions to observe the results.

SQL> SELECT id, &column_name


2 FROM s_ord
3 WHERE &condition;
Enter value for column_name: total
Enter value for condition: payment_type = ’CASH’

ID TOTAL
---------- ----------
103 377
110 1539.13
111 2770
98 595

SQL> SELECT id, &column_name


2 FROM s_ord
3 WHERE &condition;
Enter value for column_name: date_ordered
Enter value for condition: total > 300000

ID DATE_ORDE
---------- ---------
100 31-AUG-92
109 08-SEP-92

If you do not enter a value for the substitution variable, you will obtain an error when
you execute above command.

Specifying Variables at Runtime 7Ć13


7Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Defining User Variables
You can predefine user variables before executing a SELECT statement. SQL*Plus
provides two commands for defining and setting user variables: DEFINE and
ACCEPT.

Command Description
DEFINE variable = value Creates a CHAR datatype user variable and assigns
a value to it.
DEFINE variable Displays the variable, its value, and its datatype.
DEFINE Displays all user variables with value and datatype.
ACCEPT (see syntax below) Reads a line of user input and stores it in a variable.

Abridged Syntax

ACCEPT variable [datatype][FORMAT][PROMPT text][HIDE]

where: variable is the name of the variable that stores the value.
If it does not exist, SQL*Plus creates it.
datatype is either NUMBER, CHAR, or DATE. CHAR
has a maximum length limit of 240 bytes.
DATE checks against a format model, and the
datatype is CHAR.
FOR[MAT] specifies the format model, for example A10 or
9.999.
PROMPT text displays the text before the user can enter the
value.
HIDE suppresses what the user enters, for example a
password.
Note: Do not prefix the SQL*Plus substitution parameter with the ampersand (&)
when referencing the substitution parameter in the ACCEPT command.

Specifying Variables at Runtime 7Ć15


7Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Defining User Variables continued

Guidelines
D Both the ACCEPT and DEFINE commands will create a variable if the variable
does not exist; these commands will automatically redefine a variable if it exists.
D When using the DEFINE command, use single quotation marks (‘ ’) to enclose a
string that contains an embedded space.
D Use the ACCEPT command to
D Give a customized prompt when accepting user input. Otherwise, you will see
the default “Enter value for variable.”
D Explicitly define a NUMBER or DATE datatype variable.
D Hide user input for security reasons.

Example
Display the region number and name for a specified department name. Create a script
file called l7prompt.sql, and use the ACCEPT command to prompt the user with a
customized message.

SET ECHO OFF


ACCEPT p_dname PROMPT ’Provide the department name: ’
SELECT d.name, r.id, r.name ”REGION NAME”
FROM s_dept d, s_region r
WHERE d.region_id = r.id
AND UPPER(d.name) LIKE UPPER(’%&p_dname%’)
/
SET ECHO ON

SQL> START l7prompt


Provide the department name: sales

SET ECHO Command


The ECHO variable controls whether START and @ commands list each command in
a command file as the command is executed. Setting the ECHO variable to ON lists
the command and setting it to OFF suppresses the listing.

Specifying Variables at Runtime 7Ć17


7Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Defining User Variables continued

Variables are defined until you either


D Issue the UNDEFINE command on a variable.
D Exit SQL*Plus.
When you undefine variables, you can verify your changes with the DEFINE
command. When you exit SQL*Plus, variables defined during that session are lost.
To define those variables for every session, modify your login.sql file so that those
variables are created at startup.

Example
Create a variable to hold the department position. Display all department names that
match the position in the variable.

SQL> DEFINE dname = sales


SQL> DEFINE dname
DEFINE dname = ”sales” (CHAR)
SQL> SELECT name
2 FROM s_dept
3 WHERE lower(name) = ’&dname’;
NAME
--------------------
Sales
Sales
Sales
Sales
Sales
SQL> UNDEFINE dname
SQL> DEFINE dname
symbol dname is UNDEFINED

Specifying Variables at Runtime 7Ć19


7Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Passing Values into a Script File
A parameter is a value that you can pass to a report by means of the command line.
To create and run a parameterized report, follow these steps:
1. Create a script file to include the SELECT statement.
2. In the SELECT statement, use the notation &number for each variable reference.
3. In the command line, specify a value following the filename. Use a space to
separate values.

Example
Create a script file, l7param.sql, to produce a series of reports by job title. Instead of
prompting you for the title, you enter the job title on the command line when you
start the file.

SET ECHO OFF


SELECT id, last_name, salary
FROM s_emp
WHERE title = ’&1’
/
SET ECHO ON
SQL> START l7param President

Guidelines
D You can use the DEFINE command to associate meaningful names with
parameters.
D A prefix can be used to differentiate column names (no prefix), simple variables
(for example, v_test), and parameterized variables (for example, p_name).
D The position of each parameter value in the command line is significant. The first
value corresponds to &1, the second parameter to &2, and onward.
D Reports can accept a maximum of nine parameters that are named from &1 to &9.
D SQL*Plus retains report parameters and their values until you redefine them,
undefine them, or terminate your SQL*Plus session.

Specifying Variables at Runtime 7Ć21


7Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Substitution variables are useful for running reports. They allow flexibility to replace
values in a WHERE clause, column names, and expressions. You can customize
reports by writing script files with
D Single ampersand substitution variables.
D The ACCEPT command.
D The DEFINE command.
D The UNDEFINE command.
D Substitution variables in the command line.

Specifying Variables at Runtime 7Ć23


7Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice gives you the opportunity to create files that can be run interactively by
using substitution variables to create runtime selection criteria.

Practice Contents
D Creating a query to display values using substitution variables
D Starting a command file containing substitution variables
D Using the ACCEPT command

Specifying Variables at Runtime 7Ć25


Practice 7
Determine whether the following statements are true or false.
1. A single ampersand substitution variable prompts only once.
True / False
2. The ACCEPT command is a SQL command.
True / False
The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables.
3. Write a script file to display the user name, first and last names concatenated
together, and start dates of employees within a specified range. Prompt the user
for the two ranges by using the ACCEPT command. Use the format MM/DD/YY.
Save the script file as p7q3.sql. Your result should look like the output below.

Enter the low date range (’MM/DD/YY’): 09/01/91


Enter the high date range (’MM/DD/YY’): 09/01/92

USERID EMPLOYEE START_DAT


-------- ------------------------------ ---------
acatchpo Antoinette Catchpole 09-FEB-92
hgiljum Henry Giljum 18-JAN-92
mnguyen Mai Nguyen 22-JAN-92
adumas Andre Dumas 09-OCT-91
emaduro Elena Maduro 07-FEB-92

7Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 7 continued

4. Write a script to search for customer names and numbers. The search condition
should allow for case-insensitive name searches. Save the script file as p7q4.sql.
Your result should look like the output below.

Please enter the customer’s name: sport

ID CUSTOMER NAME
------ ----------------------------------------
201 Unisports
203 Delhi Sports
204 Womansport
205 Kam’s Sporting Goods
206 Sportique
207 Sweet Rock Sports
208 Muench Sports
211 Kuhn’s Sports
212 Hamada Sport
213 Big John’s Sports Emporium
215 Sporta Russia

Specifying Variables at Runtime 7Ć27


Practice 7 continued

If you have time, complete the following exercises.


5. Write a report containing the sales representative name, customer name, and each
customer’s total sales order. Prompt the user for a region number. Save the script
as p7q5.sql.

SQL> START p7q5


Please enter a region number: 1

EMPLOYEE CUSTOMER SALES


––––––––––– –––––––––––––––––––––––––––– ––––––––––
Colin Magee Beisbol Si! $2,722
Colin Magee Big John’s Sports Emporium $1,020,935
Colin Magee Ojibway Retail $1,539
Colin Magee Womansport $603,870

7Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


8

Overview of Data Modeling and


Database Design
8Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

Before you build your tables, you design your database. In this lesson, you
examine the data modeling process and relational database concepts, and define
normalization. You also translate an entity relationship model into a relational
database design.
At the end of this lesson, you should be able to
D Describe the stages of system development.
D List and define basic types of data relationships.
D Define a relational database and its components.
D Read an entity relationship model.
D Translate an entity relationship model into a relational database design.

Overview of Data Modeling and Database Design 8Ć3


8Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
When you create a database, you need to carefully consider its components. For
assistance with the design, you can follow the concepts outlined in this lesson.

System Development Cycle


In order to logically and successfully create the database objects in the Oracle7
Server, you complete the system development cycle. Each stage of the cycle contains
specific activities that you perform to achieve the best possible database design.

Database Design
Database design is just one of the stages of the development cycle. Through good
database design, you can achieve a reliable, high-performance system.

Challenges to Managing Data


There are many challenges you face as you design your system. They range from
controlling data redundancy to enhancing communications with users. By meeting
each of these challenges through good database design, you improve the performance
of your database.

Overview of Data Modeling and Database Design 8Ć5


8Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
System Development Cycle
From concept to production, develop a database by using the system development
cycle. The cycle contains multiple stages of development. This top-down, systematic
approach to database development transforms business information requirements into
an operational database.

Stages of Development

Strategy and Analysis


D Study and analyze the business requirements. Interview users and managers to
identify the information requirements. Incorporate the enterprise and application
mission statements as well as any future system specifications.
D Build models of the system. Transfer the business narrative developed in the
strategy and analysis phase into a graphical representation of business information
needs and rules. Confirm and refine the model with the analysts and experts.

Design
D Design the database. The entity relationship model maps entities to tables,
attributes to columns, relationships to foreign keys, and business rules to
constraints.

Build and Document


D Build the prototype system. Write and execute the commands to create the tables
and supporting objects for the database.
D Develop user documentation, help-screen text, and operations manuals to support
the use and operation of the system.

Transition
D Refine the prototype. Move an application into production with user acceptance
testing, conversion of existing data, and parallel operations. Make any
modifications required.

Production
D Roll out the system to the users. Operate the production system. Monitor its
performance, and enhance and refine the system.

Overview of Data Modeling and Database Design 8Ć7


8Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Database Design
Designing a relational database system involves converting a model into a workable
software representation. The entities (or objects) perceived by the user are
transformed into tables in the database. All forms of design involve a mixture of
rules, judgements, and common sense, and relational design is no different.
During a design effort, your goal is to design reliable, high-performance systems
using the deliverables from the analysis effort. The following key factors describe in
detail why you should bother to design at all.

Performance
The initial design of a system has an enormous impact on its final performance.
Generally the impact is much greater than any remedial tuning.

Integrated Application
Application systems are typically developed by teams of developers. Without some
design specification from which to work, developers will each build in their own
style. Not only does good design promote a cohesive look and feel, but it also helps
ensure that all components of the resulting application system are integrated with
each other.

Integration with Other Systems


Often, there are requirements that a new system integrate with existing systems, or
even with systems yet to be built. Good design extends the integration benefits
mentioned above into corporate or worldwide systems.

Documentation and Communication


A major part of a designer’s job is to communicate design decisions to others. At the
very least, these decisions need to be documented.

Scalability
Tackle performance issues during design rather than during production. For example,
developing an application in a small, controlled environment does not test real-world
situations or a large set of data, factors that can reveal design flaws.

Avoid Reinventing the Wheel


Many of the problems you will face will have been encountered by others before you.
Use existing successful design solutions wherever you can.

Overview of Data Modeling and Database Design 8Ć9


Server

ÉÉ ÉÉ
ÉÉ ÉÉ

8Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Data Model
Models are a cornerstone of design. Engineers build a model of a car before putting it
into production to work out any details. In the same manner, system designers
develop models to explore ideas and improve the understanding of the database
design.

Purpose of Models
Models help communicate the concepts in people’s minds. They can be used for the
following purposes:
D Communicate
D Categorize
D Describe
D Specify
D Investigate
D Evolve
D Analyze
D Imitate
The objective is to produce a model that fits a multitude of these uses, can be
understood by an end user, but contains sufficient detail for a developer to build a
database system.

Overview of Data Modeling and Database Design 8Ć11


8Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Entity Relationship Modeling
Entity relationship models are derived from business specifications or narratives. This
model is a graphical representation of business information needs and rules.

Entity Relationship Models


Entity relationship models separate the information required by a business from the
activities performed within a business. Although businesses can change their
activities, the type of information tends to remain constant. Therefore, the data
structures also tend to be constant.

Benefits of Entity Relationship Models


D Documents information requirements for the organization in a clear, precise
format
D Provides an easily understood pictorial map for the database design
D Develops and refines the model easily
D Provides a clear picture of the scope of the information requirements
D Offers an effective framework for integrating multiple applications, development
projects, and purchased application packages

Key Components

Component Description
Entity A thing of significance about which information needs to
be known.
Attribute Something that describes or qualifies an entity.
Relationship A named association between entities showing optionality
or degree.

Overview of Data Modeling and Database Design 8Ć13


8Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Entity Relationship Model Concepts
An entity relationship model is composed of entities, attributes, and relationships.

Entities
An entity represents a thing of significance about the business system, or a discrete
category or collection of related data. Examples are customer, orders, and employees.
To represent an entity in a model, use the following conventions:
D Soft box with any dimensions
D Singular, unique entity name
D Entity name in uppercase
D Optional synonym names in uppercase within parentheses “()”

Attributes
An attribute describes entities and holds the specific information that should be
known about an entity. For example, for the customer entity, the attributes would be
customer number, name, phone number, and address.
If an entity does not have attributes that need to be known from the business
viewpoint, then it is not within the scope of the system requirements, and should not
appear in the model.
Each of the attributes is either required or optional. This state is called optionality.
To represent an entity in a model, use the following conventions:
D Use singular names in lowercase.
D Tag mandatory attributes, or values that must be known, with an asterisk “*”.
D Tag optional attributes, or values that may be known, with an “o”.

Unique Identifiers
A unique identifier (UID) is any combination of attributes or relationships, or both,
that serves to distinguish occurrences of an entity. Each entity occurrence must be
uniquely identifiable.
D Tag each attribute that is part of the UID with a number symbol (#).
D Tag secondary UIDs with a number sign in parentheses (#).

Overview of Data Modeling and Database Design 8Ć15


8Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Entity Relationship Model Concepts continued

Relationships
Each entity must have a relationship that represents the information requirements and
rules of the business. The relationship is a two-directional association between two
entities, or between an entity and itself. When an entity has a relationship with itself,
it is recursive.
Each direction of the relationship contains
D A name, for example, taught by or assigned to.
D An optionality, either must be or may be.
D A degree, either one and only one or one or more.
Note: Cardinality is a synonym for the term degree.

Relationship Syntax
Each source entity {may be | must be} relationship name {one and only one | one or
more} destination entity.
Note: Convention is to read clockwise.

Relationship Diagramming Conventions

Symbol Description
Dashed line Optional element indicating “may be.”
Solid line Mandatory element indicating “must be.”
Crow’s foot Degree element indicating “one or more.”
Single line Degree element indicating “one and only one.”

Overview of Data Modeling and Database Design 8Ć17


8Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Entity Relationship Model Concepts continued

Unique Identifier Through the Relationship


An entity may be uniquely identified through a relationship. Use a UID bar to
indicate that a relationship is part of the entity’s unique identifier. The relationship
included in a UID must be mandatory and one and only one in the direction that
participates in the UID.

Example
When you order items, you have an order number and an item with a unique line item
number. But when another order is placed, that item number is no longer unique.
Therefore, the item is uniquely identified by its attribute number and the specific
order number to which the item is related.

Order number Item number Product number


100 1 209
100 2 399
100 3 876
101 1 630
101 2 297

Recursive Relationship
A relationship between an entity and itself is called a recursive relationship. It is
represented by a “pig’s ear.”

Relationship Types

Type Description
One-to-one Degree of one and only one in both directions. These types
are rare, and may really be the same entity, or an attribute
of the entity.
Many-to-one Degree of one or more in one direction and a degree of one
and only one in the other direction. Very common.
Many-to-many Degree of one or more in both directions. Very common.
Resolve them with an intersection entity.

Overview of Data Modeling and Database Design 8Ć19


8Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Entity Relationship Model Concepts continued

Normalization
Before creating the database design, you want to eliminate the problems of data
redundancy by normalizing the data model. Modify the data model to support
different functional requirements and alternate database designs by normalizing the
storage of data before you create the database.

Benefits of Normalization
D Minimizes data redundancy
D Reduces integrity problems
D Identifies missing entities, relationships, and tables

Normalization Rules

Rule Description
First normal form (1NF) All attributes must be single-valued and not
repeating.
Second normal form (2NF) An attribute must depend upon its entity’s entire
unique identifier.
Third normal form (3NF) No non-UID attribute can be dependent upon
another non-UID attribute.

Overview of Data Modeling and Database Design 8Ć21


8Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Integrity Constraints and Keys
Ensure that users perform only operations that leave the database in a correct and
consistent state by enforcing data integrity constraints. All data integrity constraints
should be enforced by the database server or the application software. Keys
correspond to integrity constraints. The three types of keys are primary key, unique
key, and foreign key.

Integrity Constraint Type Description


Entity No part of a primary key can be NULL and the
value must be unique.
Referential Foreign key values must match a primary key or be
NULL.
Column Values in the column must match the defined
datatype.
User-defined Values must comply with the business rules.

Examples of UserĆDefined Data Integrity Constraints


D An employee in the finance department cannot have a title of programmer.
D A salesperson’s commission cannot exceed 50% of the base salary.
D Customers can only have Excellent, Good, or Poor credit rating values.

Overview of Data Modeling and Database Design 8Ć23


8Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Integrity Constraints and Keys continued

Primary Keys
Each row in the table is uniquely identified by a column or set of columns called a
primary key (PK). The primary key is defined as allowing no duplicate values and
cannot be NULL.
A primary key consisting of multiple columns is called a composite primary key or a
compound primary key. The columns of a composite primary key must be unique in
combination, although the individual columns can have duplicates. No part of a
primary key can contain a null value.

Candidate Keys
A table can have several candidate keys. A candidate key is a column or combination
of columns that can serve as the primary key for the table.
Select one candidate key to be the primary key for the table. The other candidates
become alternate keys or unique keys. They must be UNIQUE and NOT NULL.

Overview of Data Modeling and Database Design 8Ć25


8Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Integrity Constraints and Keys continued

Foreign Keys
A foreign key (FK) is a column or combination of columns in one table that refers to
a primary key or unique key in the same table or in another table. Foreign keys are
based on data values and are purely logical, not physical pointers. A foreign key
value must match an existing primary key value or unique key, or else be NULL. If a
foreign key is part of a primary key, it cannot contain a null value because no part of
a PK can be NULL.

Example
In the S_ITEM table, the ORD_ID cannot contain a null value because it is part of the
PK.
Foreign Key
Primary Key

ORD_ID ITEM_ID PRODUCT_ID ...


100 1 10011
100 2 10013
101 1 30421
101 3 41010
102 1 20180
S_ITEM Table
Primary Key

ID CUSTOMER_ID DATE_ORDERED ...


100 204 31-AUG-92
101 205 31-AUG-92
102 206 01-SEP-92
103 208 02-SEP-92
S_ORD Table

Overview of Data Modeling and Database Design 8Ć27


8Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Designing the Database
The database design stage produces design specifications for a relational database,
including definitions for relational tables, indexes, views, and storage space.

Map the Entity Relationship Model to a Table Instance Chart


1. Map the simple entities to tables.
2. Map the attributes to columns and document sample data. Clearly label the
column names and their associated generic datatypes; for example, character,
number, or date.
3. Map the unique identifiers to a primary key. Be sure to include any foreign key
components of the primary key.
4. Map relationships to foreign keys.

Additional Requirements
D Design the indexes, which are database objects that provide direct, quick access to
rows. You may want to create indexes for alternate keys, foreign keys, and
columns frequently used in the search condition.
D Establish view definitions, which are logical tables based on one or more tables or
views. Views can restrict access, provide improved presentation of information,
and can contain a pre-packaged complex query.
D Plan the physical storage space, which is the amount of space required to store the
data of a table in the database.
D Redefine integrity constraints.
For more information, see
Develop Complex Data Models and Design Databases course description.

Overview of Data Modeling and Database Design 8Ć29


1

2
3

1 Map entities to tables 2 Map attributes to 3 Map the unique


columns identifiers to a primary
key

4 Map relationships to
foreign keys

8Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Designing the Database continued

Symbols Used to Document the Table Instance Chart

Symbol Definition
PK Primary key column
FK Foreign key column
FK1, FK2 Two foreign keys within the same table
FK1, FK1 Two columns within the same composite foreign key
NN Not null column
U Unique column
U1, U1 Two columns that are unique in combination

Guidelines
D The table name should be easy to trace back to the entity name. The plural of the
entity name is sometimes used because the table will contain a set of rows.
D Column names should be easily traced to the entity relationship model. Short
column names will reduce the time required for SQL command parsing.
D You should develop your own naming conventions and standards.

Overview of Data Modeling and Database Design 8Ć31


8Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Designing the Database continued

Map the Entities to Tables


1
Create a table instance chart for the new table. The table instance chart should contain
columns for the name of the table, the names of the columns, the key types, null and
unique references, foreign key information, column datatype and maximum length,
and sample data. Record the name of the table.

Map the Attributes to Columns


2
Map each attribute in the entity relationship model to a column name in the table.
Add sample data to the chart to show the contents of the table in a visual form. Map
mandatory attributes, tagged with an asterisk (*), to columns defined as NOT NULL
(NN).
Do not name columns with SQL reserved words, such as NUMBER. Name columns
with consistent abbreviations, such as NO or NUM (but not both) to avoid
programmer and user confusion.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Object Names and Qualifiers” section
for reserved words, naming rules, and guidelines.

Overview of Data Modeling and Database Design 8Ć33


8Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Designing the Database continued

Map the Unique Identifiers to Primary Keys


3
Map the UIDs identified in the entity relationship model by a number symbol (#) to
primary key columns and label the key type as PK. Map a UID containing a single
attribute to a single-column PK. Label the not null and unique references as NN and
U. Map a UID that includes multiple attributes to a composite PK. Label those
columns NN and U1. If you have an alternate primary key, label it as NN and U, but
choose only one PK.
If the entity’s UID includes the relationship (indicated by the UID bar), add a FK
column for each relationship and label it as PK and FK key types. Add FK columns
to the end of the table instance chart or to the right of all columns, even if the FK is
part of the PK. Choose a unique name for each FK column and add sample data.

ITEM ORDER
in
#* id #* id
o price o date ordered
o quantity made o date shipped
o quantity shipped up of o payment type

Overview of Data Modeling and Database Design 8Ć35


8Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Designing the Database continued

Map Relationships to Foreign Keys


4
The last step is to map relationship to foreign keys. There are two types of
relationships to consider: Many-to-one and one-to-one. If your relationship is part of
the unique identifier, you have already mapped it. Be sure to label mandatory
relationships with the NN reference. Choose a unique name for the foreign key
column.

ManyĆtoĆOne Relationships
Map the many-to-one relationship by taking the primary key at the one end and
putting it in the table at the many end as a foreign key. This technique also applies to
recursive relationships.

OneĆtoĆOne Optional Relationships


You can place the foreign key in the table at either end of the relationship for an
optional one-to-one relationship. Be sure to add the U reference.

PET PEN
#* id assigned
to #* id
o name o location
o date of birth o size
o weight the
* species temporary
home for

OneĆtoĆOne Mandatory Relationships


Place the unique foreign key in the table at the mandatory end and label it NN to
enforce the mandatory requirement and U to enforce the one-to-one relationship.

PET PEN
assigned
#* id to #* id
o name o location
o date of birth the o size
o weight temporary
* species home for

Overview of Data Modeling and Database Design 8Ć37


8Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Logically and successfully create database objects in the Oracle7 Server by
completing the system development cycle. Each stage helps you to achieve the best
possible database design.

Stages of Development
D Study and analyze the business requirements.
D Build models of the system.
D Design the database.
D Build the prototype system.
D Write the user documentation.
D Refine the prototype.
D Roll out the system to the users.

Entity Relationship Model


D Entities are things of significance.
D Attributes describe or qualify two entities.
D Relationships associate two entities.
D Establish unique identifiers.
D Follow normalization rules.

Database Design
D Create a table instance chart.
D Map all entity relationship model components to the chart.
D Add other supporting information and objects.

Overview of Data Modeling and Database Design 8Ć39


8Ć40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
9

Creating Tables
9Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

In this lesson, you will create tables. You will also build integrity constraints,
which are rules governing what can and cannot be done with the data.
At the end of this lesson, you should be able to
D Create a table containing integrity constraints.
D Identify table naming conventions.
D Describe the datatypes that can be used when specifying column definitions.
D Recognize the indexes that are created automatically by constraints.
D Create a table by populating it with rows from another table.

Creating Tables 9Ć3


9Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
An Oracle7 database can contain multiple data structures. Each structure should be
outlined in the database design so that it can be created during the build stage of
database development.

Data Structures

Structure Description
Table Stores data.
View Logically represents subsets of data from one or more tables.
Sequence Generates primary key values.
Index Improves the performance of some queries.

Summary of Oracle7 Table Structures


D Tables can be created at any time, even while users are using the database.
D You do not need to specify the size of any table. The size is ultimately defined by
the amount of space allocated to the database as a whole. It is important, however,
to estimate how much space a table will use over time.
D Table structure can be modified online.

Creating Tables 9Ć5


9Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating Tables
Create tables to store data by executing the SQL CREATE TABLE command. This
command is one of the data definition language (DDL) commands, which you will
cover in the next several lessons. DDL commands are a subset of SQL commands
used to create, modify, or remove Oracle7 database structures. These commands have
an immediate effect on the database, and they also record information in the data
dictionary.
In order to create a table, a user must have the CREATE TABLE privilege and a
storage area in which to create objects. The database administrator uses data control
language (DCL) commands, which are covered in a later lesson, to grant privileges to
users.

Abridged Syntax

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr][column_constraint],
...
[table_constraint]);

where: schema is the same as the owner’s name.


table is the name of the table.
DEFAULT expr specifies a default value if a value is omitted in
the INSERT statement.
column is the name of the column.
datatype is the column’s datatype and length.
column_constraint is an integrity constraint as part of the column
definition.
table_constraint is an integrity constraint as part of the table
definition.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “CREATE TABLE.”

Creating Tables 9Ć7


9Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating Tables continued

Referencing Another User's Tables


A schema is a collection of objects. Schema objects are the logical structures that
directly refer to the data in a database. Schema objects include tables, views,
synonyms, sequences, stored procedures, indexes, clusters, and database links.
The tables referenced in a constraint must exist in the same database. If the table does
not belong to the user creating the constraint, the owner’s name must be prefixed to
the table referenced in the constraint.

The DEFAULT Option


A column can be given a default value by using the DEFAULT option. This option
prevents null values from entering the columns if a row is inserted without a value for
the column. The default value can be a literal, an expression, or SQL function, such
as SYSDATE and USER, but the value cannot be the name of another column or a
pseudocolumn, such as NEXTVAL or CURRVAL. The default expression must
match the datatype of the column.

Creating Tables 9Ć9


9Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating Tables continued

Naming Rules
Name database tables and columns according to the standard rules for naming any
Oracle7 database object.
D Table names and column names must begin with a letter and can be 1–30
characters long.
D Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $ and #
(legal characters, but their use is discouraged).
D Names must not duplicate the name of another object owned by the same Oracle7
Server user.
D Names must not be an Oracle7 Server reserved words.

Naming Guidelines
D Use descriptive names for tables and other database objects.
D Name the same entity consistently in different tables. For example, the
department number column is called DEPT_ID in both the S_EMP table and the
S_REGION table.
Note: Names are case-insensitive. For example, EMP is treated as the same name as
eMP or eMp.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Object Names and Qualifiers.”

Creating Tables 9Ć11


9Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Oracle7 Datatypes
There are many different column types. The Oracle7 Server can treat values of one
datatype differently from values of other datatypes. The basic datatypes are character,
number, date, and RAW.

Sample Oracle7 Datatypes

Datatype Description
VARCHAR2(size) Variable length character values up to maximum length
size. Minimum length is 1, maximum length is 2000.
CHAR(size) Fixed length character values of length size. Default
length is 1, maximum length is 255.
NUMBER Floating point number with precision of 38 significant
digits.
NUMBER(p,s) Number value having a maximum precision of p
ranging from 1 to 38 and a maximum scale of s; the
precision is the total number of decimal digits, and the
scale is the number of digits to the right of the decimal
point.
DATE Date and time values between January 1, 4712 B.C.
and December 31, 4712 A.D.
LONG Variable length character values up to 2 gigabytes.
Only one LONG column is allowed per table.
RAW and LONG RAW Equivalent to VARCHAR2 and LONG, respectively,
but used to store byte-oriented or binary data that is not
to be interpreted by the Oracle7 Server.

Note: The column width determines the maximum number of characters for values
in the column. You must specify the size for VARCHAR2 columns. You can
specify the size for NUMBER and CHAR columns, but default values are
available (38 for NUMBER and 1 for CHAR).
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Datatypes.”

Creating Tables 9Ć13


9Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Constraints
Constraints have been available with the Oracle7 Server since Version 6. In Oracle7,
constraints are enforced at the database level.
You can use constraints to
D Enforce rules at the table level whenever a row is inserted, updated, or deleted
from that table. The constraint must be satisfied for the operation to succeed.
D Prevent the deletion of a table if there are dependencies from other tables.
D Provide rules for Oracle tools, such as Developer/2000.

Data Integrity Constraints

Constraint Description
NOT NULL Specifies that this column may not contain a null value.
UNIQUE Specifies a column or combination of columns whose
values must be unique for all rows in the table.
PRIMARY KEY Uniquely identifies each row of the table.
FOREIGN KEY Establishes and enforces a foreign key relationship
between the column and a column of the referenced
table.
CHECK Specifies a condition that must be true.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “CONSTRAINT clause.”

Creating Tables 9Ć15


9Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Constraints continued

Constraint Naming Conventions


All constraints are stored in the data dictionary. Constraints are easy to reference if
you give them a meaningful name. Constraint names must follow the standard object
naming rules. If you do not name your constraint, Oracle7 generates a name with the
format SYS_Cn, where n is an integer to create a unique constraint name.

Creating Constraints
Constraints are usually created at the same time as the table. Constraints may be
added to a table after its creation and also temporarily disabled, and will be covered
in another lesson.

Defining Constraints
Constraints can be defined at one of two levels.

Constraint Level Description


Column References a single column and is defined within a
specification for the owning column. Can define any type
of integrity constraint.
Table References one or more columns and is defined separately
from the definitions of the columns in the table. Can define
any constraints except NOT NULL.

SyntaxĊColumnĆConstraint Level

column [CONSTRAINT constraint_name] constraint_type,

SyntaxĊTableĆConstraint Level

column,
[CONSTRAINT constraint_name] constraint_type
(column, ...),

Creating Tables 9Ć17


9Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Constraints continued

The NOT NULL Constraint


The NOT NULL constraint ensures that null values are not allowed in the column.
Columns without the NOT NULL constraint can contain null values by default. This
constraint can only be specified at the column-constraint level, not at the
table-constraint level.

Examples
This example applies the NOT NULL constraint to the PHONE column, which is a
variable character column that holds 15 characters. Because this constraint is
unnamed, Oracle7 will create a name for it.

CREATE TABLE friend...


phone VARCHAR2(15) NOT NULL, ...

This example applies the NOT NULL constraint to the LAST_NAME column, which
is a variable length character column that holds up to 25 characters. In this case, the
constraint name is FRIEND_LAST_NAME_NN.

CREATE TABLE friend...


last_name VARCHAR2(25)
CONSTRAINT friend_last_name_nn NOT NULL, ...

The UNIQUE Constraint


A UNIQUE constraint designates a column or combination of columns as a unique
key. No two rows in the table can have the same value for this key. Null values are
allowed if the unique key is based on a single column.
Unique constraints can be defined at the column- or table-constraint level. A
composite unique key is created by using the table-level definition.
A UNIQUE index is automatically created for a unique key column.
A UNIQUE constraint is not the same as or synonymous to a PRIMARY KEY
constraint.

Creating Tables 9Ć19


9Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Constraints continued

The PRIMARY KEY Constraint


A PRIMARY KEY constraint creates a primary key for the table. Only one primary
key can be created for a each table. The PRIMARY KEY constraint is a column or set
of columns that uniquely identifies each row in a table. This constraint enforces
uniqueness of the column or column combination and ensures that no column that is
part of the primary key can contain a null value.
PRIMARY KEY constraints can be defined at the column-constraint level or
table-constraint level. A composite PRIMARY KEY is created by using the
table-level definition.
A UNIQUE index is automatically created for a PRIMARY KEY column.

The FOREIGN KEY Constraint


The FOREIGN KEY, or referential integrity constraint, designates a column or
combination of columns as a foreign key and establishes a relationship between a
primary key or a unique key in the same table or between tables.
A foreign key value must match an existing value in the parent table or be NULL.
FOREIGN KEY constraints can be defined at the column- or table-constraint level. A
composite foreign key is created by using the table-level definition.
Foreign keys are based upon data values and are purely logical, not physical, pointers.

A foreign key that is part of a primary key cannot be a null value because no part of a
primary key can be NULL.
Continued

Creating Tables 9Ć21


9Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Constraints continued

The FOREIGN KEY ConstraintĊcontinued


The foreign key is defined in the child table, and the table containing the referenced
column is the parent table. The foreign key is defined using a combination of the
following keywords:
D FOREIGN KEY is used to define the column in the child table at the
table-constraint level.
D REFERENCES identifies the table and column in the parent table.
D ON DELETE CASCADE indicates that when the row in the parent table is
deleted, the dependent rows in the child table will also be deleted.
Without the ON DELETE CASCADE option, the row in the parent table cannot be
deleted if it is referenced in the child department.

The CHECK Constraint


The CHECK constraint defines a condition that each row must satisfy. The condition
can use the same constructs as query conditions, with the following exceptions:
D References to the CURRVAL, NEXTVAL, LEVEL, or ROWNUM
pseudocolumns
D Calls to SYSDATE, UID, USER, or USERENV functions
D Queries that refer to other values in other rows
CHECK constraints can be defined at the column-constraint level or table-constraint
level. The constraint syntax can apply to any column in the table, not only on the
column on which it is defined.

Creating Tables 9Ć23


9Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Table from a Table Instance Chart
Create your tables, based on the table instance chart from the database design, by
using the CREATE TABLE syntax. You might find it useful to create the syntax in a
script file for documentation and ease of use.

Create a Table
1. Create a script file. Start the CREATE TABLE syntax and specify the table name.
2. Map the column names, datatypes, and lengths from the table instance chart to the
script file. Separate each column definition with a comma (,).
3. Map the NOT NULL constraints, except for the PRIMARY KEY constraint
columns, as column constraint.
4. Map the PRIMARY KEY constraint either as a column constraint if the constraint
constitutes only one column or as a table constraint if the constraint constitutes
more than one column.
5. Map the UNIQUE, CHECK, and FOREIGN KEY constraints.
6. Save and execute the script file.

Creating Tables 9Ć25


9Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Table from a Table Instance Chart continued

Example
Create the S_DEPT database table based on the table instance chart.

SQL> CREATE TABLE s_dept


2 (id NUMBER(7)
3 CONSTRAINT s_dept_id_pk PRIMARY KEY,
4 name VARCHAR2(25)
5 CONSTRAINT s_dept_name_nn NOT NULL,
6 region_id NUMBER(7)
7 CONSTRAINT s_dept_region_id_fk REFERENCES
8 s_region (id),
9 CONSTRAINT s_dept_name_region_id_uk UNIQUE
10 (name, region_id));

Defining the Constraints


D The S_DEPT_ID_PK column constraint identifies the ID column as the primary
key of the S_DEPT table. This constraint ensures that no two departments in the
same table have the same department number and that no department number is
NULL.
D The S_DEPT_NAME_NN column constraint ensures that each department
number in the table has a name.
D The S_DEPT_REGION_ID_FK column constraint ensures that any region
number entered in the S_DEPT table has a corresponding value in the
S_REGION table. Before defining this constraint, the S_REGION table,
including a PRIMARY KEY or UNIQUE constraint on the ID column, must be
created.
D The S_DEPT_NAME_REGION_ID_UK table constraint identifies the NAME
column and the REGION_ID column as a composite unique key to ensure that the
same combination of department name and region number does not appear in the
table more than once.

Creating Tables 9Ć27


9Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Table from a Table Instance Chart continued

Example
Create the S_EMP database table based on the table instance chart. Also, enforce the
business constraint that the legal values for commission percent are 10, 12.5, 15,
17.5, and 20.

Column START_ COMMISSION_


Name ID LAST_NAME USERID DATE PCT DEPT_ID

Key Type PK FK
Nulls/ NN, U NN NN, U
Unique
FK Table S_DEPT
FK ID
Column
Datatype NUM CHAR CHAR DATE NUM NUM
Length 7 25 8 6 7

Note: The above table displays a subset of columns found in the S_EMP table.

Constraint Description
S_EMP_ID_PK Establishes the ID column as the table’s primary key.
This constraint ensures that a value is entered and
that it is unique.
S_EMP_LAST_NAME_NN Ensures that each row in the table contains a last
name value.
S_EMP_USERID_NN Ensures that there is a value in the USERID column.
S_EMP_USERID_UK Ensures that each value in the USERID column is
unique.
S_EMP_DEPT_ID_FK Ensures that the S_EMP table does not contain
department number not already stored in the S_DEPT
table.
S_EMP_COMMISSION_ Restricts commission percentages.
PCT_CK

Creating Tables 9Ć29


9Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Table from Rows in Another Table
A second method to create a table is to apply the AS subquery clause to both create
the table and insert rows returned from the subquery.

Syntax

CREATE TABLE table


[column(, column...)]
AS subquery;

where: table is the name of the table.


column is the name of the column, default value, and
integrity constraint.
subquery is the SELECT statement that defines the set of
rows to be inserted into the new table.

Guidelines
D The table will be created with the specified column names, and the rows retrieved
by the SELECT statement will be inserted into the table.
D The column definition can contain only the column name, default value, and
integrity constraints, not the datatype or referential integrity constraint.
D If column specifications are given, the number of columns must equal the number
of columns in the subquery SELECT list.
D If no column specifications are given, the column names of the table are the same
as the column names in the subquery.
D Only the NOT NULL constraint is inherited from the subquery table to
corresponding columns in the new table.

Creating Tables 9Ć31


9Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Confirming Table Creation
You can verify the existence of a database table and check the column definitions by
using the SQL*Plus DESCRIBE command.

Example
Confirm the creation of the S_EMP table.

SQL> DESCRIBE s_emp


Name Null? Type
----------------------------- -------- -------------
ID NOT NULL NUMBER(7)
LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
USERID NOT NULL VARCHAR2(8)
START_DATE DATE
COMMENTS VARCHAR2(255)
MANAGER_ID NUMBER(7)
TITLE VARCHAR2(25)
DEPT_ID NUMBER(7)
SALARY NUMBER(11,2)
COMMISSION_PCT NUMBER(4,2)

Note: Only the NOT NULL constraint is identified in the DESCRIBE command. All
constraints can be viewed in the data dictionary.

Creating Tables 9Ć33


9Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
The Oracle7 Server stores data in tables. Create a table by using the SQL CREATE
TABLE command. You can create a table based on the definition of another table by
using the AS subquery option in the CREATE TABLE command.

Table Features
D Table name
D Column names, datatypes, and lengths
D Integrity constraints
UNIQUE indexes are created automatically when you create PRIMARY KEY and
UNIQUE constraints.

Constraint Types
D NOT NULL
D UNIQUE
D PRIMARY KEY
D FOREIGN KEY
D CHECK

DESCRIBE Command
Review the structure of a table using the SQL*Plus DESCRIBE command.

Creating Tables 9Ć35


9Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
Create new tables containing constraints by using the CREATE TABLE command.
Confirm that the new table was added to the database. Create the syntax in the
command file, then execute the command file to create the table.

Practice Contents
D Creating new tables containing constraints
D Verifying that the tables exist

Creating Tables 9Ć37


9Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 9
1. Are the following examples syntactically correct? If not, why?

SQL> CREATE TABLE T_3000


2 (id NUMBER(7),
3 name VARCHAR2(25)
4 CONSTRAINT table_id_pk PRIMARY KEY(id));

a. Correct/Incorrect

SQL> CREATE TABLE 1995_orders


2 (id NUMBER(7),
3 customer_id NUMBER(7),
4 CONSTRAINT ord_cust_id_nn NOT NULL,
5 total NUMBER(11,2),
6 filled CHAR(1)
7 CONSTRAINT ord_filled_ck CHECK
8 (filled IN (’Y’,’N’)),
9 CONSTRAINT ord_id_pk PRIMARY KEY);

b. Correct/Incorrect

Creating Tables 9Ć39


Practice 9 continued

2. Create the DEPARTMENT table based on the table instance chart given below.
Enter the syntax in a script p9q2.sql, then execute the script to create the table.
Confirm that the table is created. You will add data to the table in another lesson.

Table name: DEPARTMENT

Column Name ID NAME


Key Type PK
Nulls/ Unique NN, U
FK Table
FK Column
Datatype NUMBER CHAR
Length 7 25

3. Create the EMPLOYEE table based on the table instance chart given below. Enter
the syntax in a script p9q3.sql, then execute the script to create the table. Confirm
that the table is created. You will add data to the table in another lesson.

Table name: EMPLOYEE

Column ID LAST_NAME FIRST_NAME DEPT_ID


Name
Key Type PK FK
Nulls/ Unique NN, U NN NN
FK Table DEPARTMENT
FK Column ID
Datatype NUMBER CHAR CHAR NUMBER
Length 7 25 25 7

9Ć40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


10

Oracle Data Dictionary


10Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

The Oracle data dictionary is one of the most important components of the
Oracle7 Server. It consists of a set of tables and views that provide a read-only
reference to the database.
At the end of this lesson, you should be able to
D Describe the data dictionary views a user may access.
D Query data from the data dictionary.

Oracle Data Dictionary 10Ć3


10Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
The Oracle data dictionary is one of the most important components of the Oracle7
Server. It is created when a database is created. Whenever the database is in
operation, the data dictionary is updated and maintained by the Oracle7 Server. All
data dictionary tables are owned by the SYS user. The base tables are rarely accessed
directly because the information in them is not easy to understand. Therefore, users
typically access data dictionary views because the information is presented in a
format that is easy for them to understand.

Tables Within the Oracle7 Database

Tables Description
User tables Collection of tables created and maintained by the user,
such as S_EMP, that contain user information.
Data dictionary Collection of tables created and maintained by the Oracle7
Server, such as USER_OBJECTS, that contain information
about the database.

Example Data Dictionary Contents


D Names of Oracle7 Server users
D Privileges granted to users
D Database object names (for example, tables, views, and indexes)
D Table constraints
D Auditing information, such as who has accessed or updated specified database
objects

Data Dictionary Uses


The data dictionary is a reference for all database users. It is a valuable source of
information for end users, application designers, and DBAs. The data dictionary is
also critical for the operation of the Oracle7 Server because the database relies on the
data dictionary to record and verify information about itself.

Oracle Data Dictionary 10Ć5


10Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Querying the Data Dictionary
You can query the data dictionary by issuing a SQL SELECT statement. Depending
on your privileges, you can query various views.

View Classes
Data dictionary view names reflect their intended use. There are four categories of
views; each category has a distinct prefix.

Prefix Description
USER_ Contains objects owned by the user. For example, views with this prefix
allow the user to display information about tables created by the user and
privileges granted by the user.
ALL_ Accesses objects to which the user has been granted access rights, in
addition to objects owned by the user.
DBA_ Allows users with the DBA privilege to access any object in the
database.
V$ Displays database server performance and locking. Initially available
only to the DBA.

Additional Views
Several data dictionary views do not use the prefixes listed above. These include
synonyms for views with long names.

View Name Description


DICTIONARY Lists all data dictionary tables, views, and synonyms.
TABLE_PRIVILEGES Grants on objects for which the user is the grantor,
grantee, or owner.
IND Is a synonym for USER_INDEXES.

Oracle Data Dictionary 10Ć7


10Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Querying the Data Dictionary continued

Example
The DICTIONARY view lists all data dictionary views accessible to the user with a
brief description of the object in a comment column. You can also reference the
synonym for the view, DICT.

SQL> SELECT *
2 FROM DICTIONARY;

Example
You can display the structure of any data dictionary view by using the SQL*Plus
DESCRIBE command. Display the structure of USER_OBJECTS.

SQL> DESCRIBE user_objects


Name Null? Type
------------------------------ -------- ------------
OBJECT_NAME VARCHAR2(128)
OBJECT_ID NUMBER
OBJECT_TYPE VARCHAR2(13)
CREATED DATE
LAST_DDL_TIME DATE
TIMESTAMP VARCHAR2(75)
STATUS VARCHAR2(7)

Example
To view a description of each column in data dictionary tables and views, query the
DICT_COLUMNS view.

SQL> SELECT column_name, comments


2 FROM dict_columns
3 WHERE table_name = ’USER_OBJECTS’;

For more information, see


Oracle7 Server SQL Language Quick Reference, Release 7.3.

Oracle Data Dictionary 10Ć9


10Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Querying the Data Dictionary continued

Example
Display the types of objects that the user owns.

SQL> SELECT DISTINCT object_type


2 FROM user_objects;

Example
You can search the data dictionary for a specific topic by querying the COMMENTS
column in the DICTIONARY view. Find all data dictionary views pertaining to the
keyword Grant.

COLUMN table_name FORMAT A20


COLUMN comments FORMAT A30

SQL> SELECT *
2 FROM dictionary
3 WHERE LOWER(comments) LIKE ’%grant%’;

TABLE_NAME COMMENTS
-------------------- ------------------------------
ALL_COL_PRIVS Grants on columns for which th
e user is the grantor, grantee
, owner,
or an enabled role or PUBLIC i
s the grantee

ALL_COL_PRIVS_MADE Grants on columns for which th


e user is owner or grantor

ALL_COL_PRIVS_RECD Grants on columns for which th


e user, PUBLIC or enabled role
is the grantee
...
20 rows selected.

Oracle Data Dictionary 10Ć11


10Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Checking Constraints on a Table
After creating a table, you can confirm its existence by issuing a DESCRIBE
command. The only constraint you can verify is the NOT NULL constraint. To view
all constraints on your table, you can check the USER_CONSTRAINTS table.

Example
Confirm the constraints on the S_EMP table.

SQL> SELECT constraint_name, constraint_type,


2 search_condition, r_constraint_name
3 FROM user_constraints
4 WHERE table_name = ’S_EMP’;

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAINT_NA


----------------------- - --------------------- ---------------
S_EMP_MANAGER_ID_FK R S_EMP_ID_PK
S_EMP_LAST_NAME_NN C LAST_NAME IS NOT NULL
S_EMP_USERID_NN C USERID IS NOT NULL
S_EMP_ID_PK P
S_EMP_USERID_UK U
S_EMP_COMMISSION_PCT_CK C commission_pct IN (10, 12
.5, 15, 17.5, 20)
S_EMP_DEPT_ID_FK R S_DEPT_ID_PK
S_EMP_TITLE_FK R S_TITLE_TITLE_PK

8 rows selected.

Note: The above display has been formatted to fit the page.

Oracle Data Dictionary 10Ć13


10Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Checking Constraints on a Table continued

View the names of the columns involved in constraints by querying the


USER_CONS_COLUMNS data dictionary view. This view is especially useful for
constraints that use the system-assigned name.

Example
Display the column constraint information in the data dictionary for the S_EMP table.

SQL> SELECT constraint_name, column_name


2 FROM user_cons_columns
3 WHERE table_name = ’S_EMP’;

CONSTRAINT_NAME COLUMN_NAME
----------------------- -----------------------
S_EMP_COMMISSION_PCT_CK COMMISSION_PCT
S_EMP_DEPT_ID_FK DEPT_ID
S_EMP_ID_PK ID
S_EMP_LAST_NAME_NN LAST_NAME
S_EMP_MANAGER_ID_FK MANAGER_ID
S_EMP_TITLE_FK TITLE
S_EMP_USERID_NN USERID
S_EMP_USERID_UK USERID

8 rows selected.

Oracle Data Dictionary 10Ć15


10Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
The data dictionary is a set of tables that the user can query through views. The data
dictionary holds all the data about the database. Write a SELECT statement to display
the contents of the data dictionary views.

Frequently Accessed Data Dictionary Views


D DICTIONARY
D DICT_COLUMNS
D USER_OBJECTS
D USER_CONSTRAINTS
D USER_CONS_COLUMNS

Oracle Data Dictionary 10Ć17


10Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
In this practice, you will access the data dictionary views to verify information about
your tables.

Practice Contents
D Querying the data dictionary to view table information
D Viewing constraint information from the data dictionary

Oracle Data Dictionary 10Ć19


10Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 10
1. Select all the views from the data dictionary pertaining to Table. You can adjust
the column formats by using the SQL*Plus COLUMN command.
If you want to interrupt your query, you can cancel it by pressing [CTRL]+[C] on
your PC keyboard.
2. If a query is very lengthy, what SQL*Plus command can you set before you
execute the query to show only one page at a time?

Note: If you did not complete Practice 9, Exercise 2 and Exercise 3, you can invoke
scripts p9q2.sql and p9q3.sql to create DEPARTMENT table and
EMPLOYEE table respectively.
3. Query the USER_OBJECTS data dictionary to see information about the tables
you created in Practice 9, DEPARTMENT and EMPLOYEE tables.
4. Create a script to execute a generic query to confirm the constraints for the tables
you have created. You can use a substitution parameter for the table name. Save
the query as p10q4.sql. Execute the script to confirm the constraints for the tables
you created in Practice 9, DEPARTMENT and EMPLOYEE tables.

Oracle Data Dictionary 10Ć21


10Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
11

Manipulating Data
11Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

Once your tables have been created, you will need to add new rows, make
changes to rows in a table, or delete rows by using data manipulation
commands. This lesson covers using SQL commands to make changes to data. A
number of these data manipulation commands make up a transaction, which
you may either save or delete using transaction controls.
At the end of this lesson, you should be able to
D Insert new rows into a table.
D Update existing rows in a table.
D Delete rows from a table.
D Explain transaction controls and their importance.

Manipulating Data 11Ć3


11Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
Data manipulation language (DML) is a core part of SQL. When you want to add,
update, or delete data in the database, you execute a DML statement. A collection of
DML statements that have not yet been made permanent is called a transaction, or a
logical unit of work.

Manipulating Data 11Ć5


11Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a New Row to a Table
You can add new rows to a table by issuing the INSERT command.

Syntax

INSERT INTO table [(column [, column...])]


VALUES (value [, value...]);

where: table is the table name.


column is the name of the column in the table to
populate.
value is the corresponding value for the column.
Note: This command with the VALUES clause adds only one row at a time to a
table.

Inserting a Row into a Table


Because you can insert a new row that contains values for each column, therefore the
column list is not required in the INSERT clause. However, the values must be listed
according to the default order of the columns in the table.

SQL> DESCRIBE s_dept


Name Null? Type
------------------------- -------- --------------
ID NOT NULL NUMBER(7)
NAME NOT NULL VARCHAR2(25)
REGION_ID NUMBER(7)

SQL> INSERT INTO s_dept


2 VALUES (11, ’Finance’, 2);
1 row created.

For clarity, use the column list in the INSERT clause.

Enclose character and date values within single quotation marks; do not enclose
numeric values within single quotation marks.

Manipulating Data 11Ć7


11Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a New Row to a Table continued

Inserting Null Values

Method Description
Implicit Omit the column from the column list.
Explicit Specify the NULL keyword in the VALUES list.
Specify the empty string (‘’) in the VALUES list; for
character strings and dates only.

Example
Enter a new department omitting the region number. Because the region number is
not listed in the INSERT clause, a null value is entered implicitly for the region
number in this row.

SQL> INSERT INTO s_dept (id, name)


2 VALUES (12, ’MIS’);
1 row created.

Example
Alternatively, you can enter a null value into a row explicitly by using the NULL
keyword for the value.

SQL> INSERT INTO s_dept


2 VALUES (13, ’Administration’, NULL);
1 row created.

Be sure that the targeted column allows null values by verifying the Null? status from
the SQL*Plus DESCRIBE command.

Manipulating Data 11Ć9


11Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a New Row to a Table continued

Inserting Special Values by Using SQL Functions


You can use pseudocolumns to enter special values in your table. Specify USERID to
enter the current user name. SYSDATE enters the current date and time.

Example
Record information for the student in the S_EMP table. Supply the current user name
for the USERID column and the current date and time in the START_DATE column.

SQL> INSERT INTO s_emp (id, first_name,


2 last_name, userid, salary, start_date)
3 VALUES (26, ’Donna’,
4 ’Smith’, USER, NULL, SYSDATE);
1 row created.

Confirming Additions to the Table


To verify that the rows were inserted into the table, you can write a SELECT
statement.

Example

SQL> SELECT id, last_name, first_name,


2 userid, start_date, salary
3 FROM s_emp
4 WHERE id = 26;

ID LAST_NAME FIRST_NAME USERID START_DAT


-- --------- ---------- -------- ---------
SALARY
------
26 Smith Donna SFCL26 01-JAN-96

Manipulating Data 11Ć11


11Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a New Row to a Table continued

Inserting Specific Date and Time Values


When inserting a date value, the format DD-MON-YY is usually used. With this
format, recall that the century defaults to the current century. Because the date also
contains time information, the default time is midnight (00:00:00).
If a date is required to be entered in another century and a specific time is also
required, use the TO_DATE function.

Example
Record information for the student in the S_EMP table. Supply the current user name
for the USERID column. Set the START_DATE to be January 1, 1996, 8:00 A.M.

SQL> INSERT INTO s_emp (id, first_name,


2 last_name, userid, salary, start_date)
3 VALUES (26, ’Donna’,
4 ’Smith’, USER, NULL,
5 TO_DATE(’01-JAN-96 08:00’,
6 ’DD-MON-YY HH:MI’));
1 row created.

If the RR format is set, the century may not be the current one.

Manipulating Data 11Ć13


11Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a New Row to a Table continued

Inserting Values by Using Substitution Variables


You can produce an INSERT command that allows the user to add values
interactively by using SQL*Plus substitution variables.

Example
Record information for a department in the S_DEPT table. Prompt the user for the
department number, department name, and region number.

SQL> INSERT INTO s_dept (id, name,


2 region_id)
3 VALUES (&department_id, ‘&department_name’,
4 &region_id);
Enter value for department_id: 61
Enter value for department_name: Accounting
Enter value for region_id: 2

1 row created.

For date and character values, the ampersand and the variable name are enclosed in
single quotation marks.

Manipulating Data 11Ć15


11Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a New Row to a Table continued

Creating a Script to Manipulate Data


You can save your command with substitution variables to a file and execute the file.
Each time you execute the command, it will prompt you for new values. Customize
the prompts by using the SQL*Plus ACCEPT command.

Example
Record information for a department in the S_DEPT table. Prompt the user for the
department number, department name, and region number. Customize the prompt
messages.

ACCEPT department_id PROMPT ’Please


enter the department number:’
ACCEPT department_name PROMPT ’Please
enter the department name:’
ACCEPT region_id PROMPT ’Please
enter the region number:’
INSERT INTO s_dept (id, name, region_id)
VALUES (&department_id, ’&department_name’,
&region_id);

Please enter the department number: 61


Please enter the department name: Accounting
Please enter the region number: 2

1 row created.

Do not prefix the SQL*Plus substitution parameter with the ampersand (&) when
referencing it in the ACCEPT command. Use a dash (-) to continue a SQL*Plus
command on the next line.

Manipulating Data 11Ć17


11Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Copying Rows from Another Table
You can use the INSERT statement to add rows to a table where the values are
derived from existing tables. In place of the VALUES clause, you use a subquery.

Syntax

INSERT INTO table [column (, column)]


subquery;

where: table is the table name.


column is the name of the column in the table to
populate.
subquery is the subquery that returns rows into the table.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “SELECT,” Subqueries section.

Example
Copy selected rows from the S_EMP table into the HISTORY table.

SQL> INSERT INTO HISTORY (id, last_name, salary,


2 title, start_date)
3 SELECT id, last_name, salary,
4 title, start_date
5 FROM s_emp
6 WHERE start_date < ’01-JAN-94’;
10 rows created.

The number of columns in the column list of the INSERT clause must match the
number of values in the subquery.

Manipulating Data 11Ć19


11Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Updating Rows
You can modify existing rows by using the UPDATE command.

Syntax

UPDATE table
SET column = value [, column = value...]
[WHERE condition];

where: table is the table name.


column is the name of the column in the table to
populate.
value is the corresponding value or subquery for the
column.
condition identifies the rows to be updated and is
composed of column names, expressions,
constants, subqueries, and comparison
operators.
Confirm the update operation by querying the table to display the updated rows.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “UPDATE.”

Manipulating Data 11Ć21


11Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Updating Rows continued

Example
Transfer employee number 2 to department 10. Transfer employee number 1 to
department 32 and change the employee’s salary to 2550.

SQL> UPDATE s_emp


2 SET dept_id = 10
3 WHERE id = 2;
1 row updated.

SQL> UPDATE s_emp


2 SET dept_id = 32, salary = 2550
3 WHERE id = 1;
1 row updated.

Confirm both data changes.

SQL> SELECT id, last_name, salary, dept_id


2 FROM s_emp
3 WHERE id IN (1,2);

ID LAST_NAME SALARY DEPT_ID


------- --------- ------ -------
2 Ngao 1450 10
1 Velasquez 2550 32

Manipulating Data 11Ć23


11Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Updating Rows continued

If you do not include a WHERE clause in your UPDATE command, all rows in the
table will be updated.

Example
Give a commission of 10 percent to every employee in the company. Confirm the
changes.

SQL> UPDATE s_emp


2 SET commission_pct = 10;
25 rows updated.

SQL> SELECT id, commission_pct


2 FROM s_emp;

ID COMMISSION_PCT
------- --------------
1 10
2 10
3 10
4 10
5 10
6 10
...
25 rows selected.

Manipulating Data 11Ć25


11Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Updating Rows continued

Integrity Constraint Error


If you attempt to update a record with a value that is tied to an integrity constraint,
you will experience an error.

Example
If the value you specify does not exist in the parent table, then you receive the “parent
key” violation ORA-02291.

SQL> UPDATE s_emp


2 SET dept_id = 60
3 WHERE dept_id = 10;
update s_emp
*
ERROR at line 1:
ORA-02291: integrity constraint (USR.S_EMP_DEPT_ID_FK)
violated - parent key not found

Manipulating Data 11Ć27


11Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Deleting Rows
You can remove existing rows by using the DELETE command.

Syntax

DELETE [FROM] table


[WHERE condition];

where: table is the table name.


condition identifies the rows to be deleted and is
composed of column names, expressions,
constants, subqueries, and comparison
operators.
Confirm the delete operation by displaying the deleted rows by using the SELECT
command.
If the WHERE clause is omitted, all rows in the table will be deleted.

Example
Remove all information about employees who started after January 1, 1996.

SQL> DELETE FROM s_emp


2 WHERE start_date >
3 TO_DATE(’01.01.1996’,’DD.MM.YYYY’);
1 row deleted.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “DELETE.”

Manipulating Data 11Ć29


11Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Deleting Rows continued

If you do not include a WHERE clause in your DELETE command, all rows in the
table will be deleted.

Example
Eliminate all data from the TEST table.

SQL> DELETE FROM test;


25,000 rows deleted.

Confirm the deletions.

SQL> SELECT *
2 FROM test;
no rows selected

Manipulating Data 11Ć31


11Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Deleting Rows continued

Integrity Constraint Error


If you attempt to delete a record with a value that is tied to an integrity constraint, you
will experience an error.

Example
Attempt to delete all departments in region number 1.

SQL> DELETE s_dept


2 WHERE region_id = 1;
delete from s_region
*
ERROR at line 1:
ORA-02292: integrity constraint
(USR.S_EMP_DEPT_ID_FK) violated - child record found

If the parent record you attempt to delete has child records, then you receive the
“child record found” violation ORA-02292.

Manipulating Data 11Ć33


11Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Transaction Processing
The Oracle7 Server ensures data consistency based on transactions. Transactions give
you more flexibility and control when changing data, and assure data consistency in
the event of user process failure or system failure.
Transactions consist of DML commands that make up one consistent change to the
data. For example, a transfer of funds between two accounts should include the debit
to one account and the credit to another account in the same amount. Both actions
should either fail or succeed together. The credit should not be committed without the
debit.

Transaction Types

Type Description
Data manipulation (DML) Consist of any number of DML statements that the
Oracle7 Server treats as a single entity or a logical unit
of work.
Data definition (DDL) Consist of only one DDL statement.
Data control (DCL) Consists of only one DCL statement.

When Does a Transaction Start and End?


A transaction begins when the first executable SQL command is encountered and
terminates when one of the following occurs:
D A COMMIT or ROLLBACK command is issued.
D A DDL command, such as CREATE, or DCL command is issued.
D Certain errors are detected, such as deadlocks.
D The user exits SQL*Plus.
D A machine fails or the system crashes.
After one transaction ends, the next executable SQL statement will automatically start
the next transaction.
A DDL command or a DCL command is automatically committed and therefore
implicitly ends a transaction.

Manipulating Data 11Ć35


11Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Transaction Processing continued

Explicit Transaction Control Statements


Control the logic of transactions by using the COMMIT, SAVEPOINT, and
ROLLBACK statements.

Command Description
COMMIT Ends the current transaction by making all pending
data changes permanent.
SAVEPOINT name Marks a savepoint within the current transaction.
ROLLBACK [TO Ends the current transaction by discarding all pending
SAVEPOINT name] data changes.

Implicit Transaction Processing

Status Circumstance
Automatic commit DDL command or DCL command is issued.
Normal exit from SQL*Plus, without explicitly issuing
COMMIT or ROLLBACK.
Automatic rollback Abnormal termination of SQL*Plus, or system failure.

Manipulating Data 11Ć37


11Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Committing Changes
Every data change made during the transaction is temporary until the transaction is
committed.

State of the Data Before COMMIT or ROLLBACK


D Data manipulation operations primarily affect the database buffer; therefore, the
previous state of the data can be recovered.
D The current user can review the results of the data manipulation operations by
querying the tables.
D Other user cannot view the results of the data manipulation operations for the
current user. Oracle7 institutes read consistency to ensure that each user sees data
as it existed at the last commit.
D The affected rows are locked; other users cannot change the data within the
affected rows.

Manipulating Data 11Ć39


11Ć40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Committing Changes continued

Make all pending changes permanent by using the COMMIT command. Following a
COMMIT
D Data changes are written to the database.
D The previous state of the data is permanently lost.
D All users can view the results of the transaction.
D The locks on the affected rows are released; the rows are now available for other
users to perform new data changes.
D All savepoints are erased.

Example
Create a new Education department with at least one employee. Make the data change
permanent.

SQL> INSERT INTO s_dept (id, name, region_id)


2 VALUES (54, ’Education’, 1);
1 row created.

SQL> UPDATE s_emp


2 SET dept_id = 54
3 WHERE id = 2;
1 row updated.

SQL> COMMIT;
Commit complete.

Manipulating Data 11Ć41


11Ć42 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Rolling Back Changes
Discard all pending changes by using the ROLLBACK statement. Following a
ROLLBACK
D Data changes are undone.
D The previous state of the data is restored.
D The locks on the affected rows are released; the rows are now available for other
users to perform new data changes.

Example
While attempting to remove a record from the TEST table, accidentally empty the
table. Correct the mistake, then reissue the proper command, and make the data
change permanent.

SQL> DELETE FROM test;


25,000 rows deleted.

SQL> ROLLBACK;
Rollback complete.

SQL> DELETE FROM test


2 WHERE id = 100;
1 row deleted.

SQL> SELECT *
2 FROM test
3 WHERE id = 100;
no rows selected

SQL> COMMIT;
Commit complete.

Manipulating Data 11Ć43


11Ć44 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Rolling Back Changes to a Savepoint

You can create a marker within the current transaction by using the SAVEPOINT
command. The transaction therefore can be divided into smaller sections. You can
then discard pending changes up to that marker by using the ROLLBACK TO
SAVEPOINT statement.

Example
Update the salary for all Stock Clerks by 10 percent. Create a savepoint named
UPDATE_DONE.

SQL> UPDATE s_emp


2 SET salary = salary * 1.1
3 WHERE title = ’Stock Clerk’;
10 rows updated.
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT INTO s_region (id, name)
2 VALUES (8, ’Central’)
1 row inserted.
SQL> SELECT *
2 FROM s_region
3 WHERE id = 8
ID NAME
------- --------------------
8 Central
SQL> ROLLBACK TO update_done;
Rollback complete.
SQL> SELECT *
2 FROM s_region
3 WHERE id = 8
no rows selected

If you create a second savepoint with the same name as an earlier savepoint, the
earlier savepoint is deleted.

Manipulating Data 11Ć45


11Ć46 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Statement Level Rollback
Part of a transaction may be discarded by an implicit rollback if a statement execution
error is detected. If a single DML statement fails during execution of a transaction, its
effect is undone by a statement-level rollback, but the changes made by the previous
DML statements in the transaction will not be discarded. They can be committed or
rolled back explicitly by the user.
Oracle issues an implicit COMMIT before and after any Data Definition Language
statement. So, even if your DDL statement does not execute successfully, you cannot
rollback the previous statement because the server issued a commit.
Terminate your transactions explicitly by executing a COMMIT or ROLLBACK
statement.

Manipulating Data 11Ć47


11Ć48 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Manipulate data in the Oracle database by using the INSERT, UPDATE, and
DELETE statements. Control data changes by using the COMMIT, SAVEPOINT, and
ROLLBACK commands.

Data Manipulation and Transaction Control Commands

Command Description
INSERT Adds a new row to the table.
UPDATE Modifies existing rows in the table.
DELETE Removes existing rows from the table.
COMMIT Makes all pending data changes permanent.
SAVEPOINT Allows a rollback to that savepoint marker.
ROLLBACK Discards all pending data changes.

Manipulating Data 11Ć49


11Ć50 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice builds on a prior lesson with the DEPARTMENT and EMPLOYEE
tables. In this practice, you will add rows to the tables, update, and delete data from
the tables, and control your transactions.

Practice Contents
D Inserting rows into the tables
D Updating and deleting rows in the tables
D Controlling transactions

Manipulating Data 11Ć51


11Ć52 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 11
1. Insert data into the DEPARTMENT and EMPLOYEE tables.
Note: If you did not complete Practice 9, Exercise 2 and Exercise 3, you can invoke
scripts p9q2.sql and p9q3.sql to create DEPARTMENT table and
EMPLOYEE table respectively.
a. Describe the DEPARTMENT and EMPLOYEE tables to identify the column
names.
b. View the constraints on each table to identify the primary key and any other
constraints. Execute the script p10q4.sql, which is a generic query to confirm
constraints.
c. Add a row of data to the DEPARTMENT table. The department number is 10
and the department name is Finance. Do not list the columns in the INSERT
clause.
d. Add two rows of data to the EMPLOYEE table. Write a script named
p11q1d.sql that prompts you for each column value. The first employee is
Donna Smith in department number 10, and her employee number is 200. The
second employee is Albert Jones in department number 54, and his employee
number is 201. What was the result and why?

e. Insert into the DEPARTMENT table department number 10 and department


name of Marketing. What was the result and why?

f. Confirm your additions to the tables.


g. Write a script named p11q1g.sql to add the following rows to the
DEPARTMENT table: Marketing as number 37; Sales as number 54; and
Personnel as number 75.
h. Execute the p11q1d.sql script to add the following rows to the EMPLOYEE
table: Albert Jones in department number 54, and employee number 201;
Harry Chin in department 75 and employee number 202; Rey Guiliani in
department 37 and employee number 203.
i. Confirm your additions to the tables.
j. Make the data additions permanent.

Manipulating Data 11Ć53


Practice 11 continued

2. Update and delete data in the DEPARTMENT and EMPLOYEE tables.


a. Change the name of the Personnel department to Human Resources.
b. Change the last name of employee 202 to Korsgaard.
c. Verify your changes to the tables.
d. Attempt to delete department 54. What was the result and why?

e. Delete Albert Jones from the EMPLOYEE table.


f. Attempt to delete department 54 from the DEPARTMENT table again. What
was the result and why?

g. Verify the changes to your tables.


h. Commit all pending changes.
3. Control data transactions to the DEPARTMENT and EMPLOYEE tables.
a. Execute the p11q1g.sql script to reinstate the Sales department as department
number 54.
b. Verify your addition.
c. Mark a transaction processing savepoint.
d. Empty the entire EMPLOYEE table.
e. Verify that the EMPLOYEE table is empty.
f. Discard the most recent DELETE operation without discarding the most
recent INSERT operation.
g. Verify that the new row in the DEPARTMENT table is still intact. Verify that
the EMPLOYEE table has all three rows.
h. Make the data addition permanent.

11Ć54 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


12

Altering Tables and Constraints


12Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

After you create your tables, you may need to change the table structures
because you omitted a column, your column definition needs to be changed, or
you want to enable or disable constraints. This lesson will demonstrate how you
can amend table structures as well as add and remove constraints.
At the end of this lesson, you should be able to
D Add and modify table columns.
D Add, enable, disable, or remove constraints.
D Drop a table.
D Remove all rows leaving the table definition intact.
D Change object names.
D Add comments to objects and view comments from the data dictionary.

Altering Tables and Constraints 12Ć3


12Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
Once you have created your tables, you can modify their structure by using the
ALTER TABLE command. Add columns, modify the column length, add or drop
constraints, and enable or disable constraints by using this command.
If you want to remove a table, both the rows and the data structure of a table, invoke
the DROP TABLE command. Other commands that affect tables that are covered in
this lesson are
D RENAME, to change a database object name.
D TRUNCATE, to remove all rows from a table.
D COMMENT, to add a comment about a database object to the data dictionary.
All of these commands are data definition commands (DDL). When you issue these
statements, an automatic commit occurs. You cannot roll back DDL commands.
Therefore, be very careful when you execute them.

Altering Tables and Constraints 12Ć5


12Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a Column
You can add columns to a table by using the ALTER TABLE command with the
ADD clause.

Syntax

ALTER TABLE table


ADD (column datatype [DEFAULT expr][NOT NULL]
[, column datatype]...);

where: table is the name of the table.


column is the name of the new column.
datatype is the datatype and length of the new column.
DEFAULT expr specifies the default value for a new column.
NOT NULL adds a NOT NULL constraint to the new
column.

Guidelines
D You can add or modify columns, but you cannot drop them from a table.
D You cannot specify where the column is to appear. The new column becomes the
last column.

Altering Tables and Constraints 12Ć7


12Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Modifying a Column
You can modify a column definition by using the ALTER TABLE command with the
MODIFY clause. Column modification can include changes to a column’s datatype,
size, default value, and NOT NULL column constraint.

Syntax

ALTER TABLE table


MODIFY (column datatype [DEFAULT expr][NOT NULL]
[, column datatype]...);

where: table is the name of the table.


column is the name of the column.
datatype is the datatype and length of the column.
DEFAULT expr specifies the default value for a new column.
NOT NULL adds a NOT NULL constraint to the new
column.

Guidelines
D Increase the width or precision of a numeric column.
D Decrease the width of a column if the column contains only null values or if the
table has no rows.
D Change the datatype if the column contains null values.
D Convert a CHAR column to the VARCHAR2 datatype or convert a VARCHAR2
column to the CHAR datatype if the column contains null values or if you do not
change the size.
D A change to the default value of a column only affects subsequent insertions to
the table.
D Add a NOT NULL constraint only if there are no null values in the column.

Altering Tables and Constraints 12Ć9


12Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding and Dropping a Constraint
You can add or drop constraints for existing tables by using the ALTER TABLE
command with the ADD or DROP clause.

Syntax

ALTER TABLE table


ADD [CONSTRAINT constraint] type (column);

where: table is the name of the table.


constraint is the name of the constraint.
type is the constraint type.
column is the name of the column affected by the
constraint.
The constraint name syntax is optional, although recommended. If you do not name
your constraints, the system will generate constraint names.

Guidelines
D You can add, drop, enable, or disable a constraint, but you cannot modify its
structure.
D You can add a NOT NULL constraint to an existing column by using the
MODIFY clause of the ALTER TABLE command.

Altering Tables and Constraints 12Ć11


12Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding and Dropping a Constraint continued

To drop a constraint, you can identify the constraint name from the
USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views.
Then, use the ALTER TABLE command with the DROP clause. The CASCADE
option of the DROP clause causes any dependent constraints also to be dropped.

Syntax

ALTER TABLE table


DROP PRIMARY KEY | UNIQUE (column) |
CONSTRAINT constraint [CASCADE];

where: table is the name of the table.


column is the name of the column affected by the
constraint.
constraint is the name of the constraint.
When you drop an integrity constraint, that constraint is no longer enforced by the
Oracle7 Server and is no longer available in the data dictionary.

Altering Tables and Constraints 12Ć13


12Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Disabling and Enabling a Constraint
You can enable or disable constraints without dropping them or recreating them by
using the ALTER TABLE command with the ENABLE or DISABLE clause.

Syntax

ALTER TABLE table


DISABLE | ENABLE CONSTRAINT constraint [CASCADE];

Guidelines
D If you enable a constraint, that constraint applies to all the data in the table. All
the data in the table must fit the constraint.
D If you enable a UNIQUE or PRIMARY KEY constraint, a UNIQUE or
PRIMARY KEY index is automatically created.
D You can use the ENABLE and DISABLE clauses in both the CREATE TABLE
command and the ALTER TABLE command.
D The CASCADE clause disables dependent integrity constraints.

Altering Tables and Constraints 12Ć15


12Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Dropping a Table
The DROP TABLE command removes the definition of an Oracle7 table. When you
drop a table, the database loses all the data in the table and all the indexes associated
with it. The CASCADE CONSTRAINTS option will also remove dependent
referential integrity constraints.

Syntax

DROP TABLE table [CASCADE CONSTRAINTS];

where: table is the name of the table.

Guidelines
D All data is deleted from the table.
D Any views, synonyms, stored procedures, functions, or packages will remain, but
are invalid.
D Any pending transactions are committed.
D Only the creator of the table or a user with the DROP ANY TABLE privilege can
remove a table.
The DROP TABLE command, once executed, is irreversible. The Oracle7 Server
does not question the action when you issue the DROP TABLE command. If you own
that table or have a high level privilege, then the table is immediately removed. All
DDL commands issue a commit, therefore making the transaction permanent.

Altering Tables and Constraints 12Ć17


12Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Renaming and Truncating a Table
Additional DDL commands include the RENAME command, which is used to
rename a table, view, sequence, or synonym, and the TRUNCATE TABLE command,
which is used to remove all rows from a table and to release the storage space used by
that table.

SyntaxĊRENAME Command

RENAME old_name TO new_name;

You must be the owner of the object you rename.

SyntaxĊTRUNCATE Command

TRUNCATE TABLE table;

You must be the owner of the table or have DELETE TABLE system privileges to
truncate a table.

The DELETE command can also remove all rows from a table, but it does not release
storage space.

Altering Tables and Constraints 12Ć19


12Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Adding a Comment to a Table
You can add a comment of up to 2000 bytes about a column, table, view, or snapshot
by using the COMMENT command. The comment is stored in the data dictionary
and can be viewed in one of the following data dictionary views in the COMMENTS
column:
D ALL_COL_COMMENTS
D USER_COL_COMMENTS
D ALL_TAB_COMMENTS
D USER_TAB_COMMENTS

Syntax

COMMENT ON TABLE table | COLUMN table.column


IS ’text’;

where: table is the name of the table.


column is the name of the column in a table.
text is the text of the comment.

Examples
Add a comment on the S_EMP table.

SQL> COMMENT ON TABLE s_emp IS ’Employee Information’;


Comment created.

Remove a comment from a column.

SQL> COMMENT ON COLUMN s_emp.last_name IS ’’;


Comment created.

Altering Tables and Constraints 12Ć21


12Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Data definition commands (DDL) allow you to create, modify, remove, and rename
objects. When you issue a DDL command, an autocommit occurs. You cannot roll
back your commands.

CREATE TABLE
D You can create a table and the indicated constraints.
D Create a table based on another table by using a subquery.

ALTER TABLE
D Modify table structures and constraints.
D Change column widths, change column datatypes, add columns, add or drop
constraints, and enable or disable constraints.

DROP TABLE
D Remove rows and a table structure.
D Once executed, this command cannot be rolled back.

RENAME
D Rename a table, view, sequence, or synonym.

TRUNCATE
D Remove all rows from a table and release the storage space used by the table.
D DELETE command only removes rows.

COMMENT
D Add a comment to a table or a column.
D Query the data dictionary to view the comment.

Altering Tables and Constraints 12Ć23


12Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
In this practice, you will create, modify, and drop tables related to the EMPLOYEE
and DEPARTMENT tables using the commands covered in this lesson.

Practice Contents
D Creating a new table by using the CREATE TABLE AS syntax
D Adding constraints
D Modifying column definitions
D Dropping tables
D Adding a comment to a table
D Displaying information in data dictionary views

Altering Tables and Constraints 12Ć25


12Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 12
1. Create a WORKER table, which copies the data from the EMPLOYEE table.
Describe the table to confirm its structure.
2. View the constraints for this new table. Save this command to a script named
p12q2.sql. Note the types and names of the constraints.

3. Compare these constraints to those in the EMPLOYEE table. Note the types and
names of the constraints.

4. Add a table level PRIMARY KEY constraint to the WORKER table using the ID
column. The constraint should be immediately enabled.
5. Add a foreign key reference from the DEPARTMENT table to the DEPT_ID
column in the WORKER table. Confirm that the constraints were added by
re-executing p12q2.sql.
6. Display the object names and types from the USER_OBJECTS data dictionary
view. You may want to format the columns for readability. Notice that the new
table and a new index were created.
7. Drop the EMPLOYEE table, while leaving the WORKER table in the database.
If you have time, complete the following exercises.
8. Modify the WORKER table. Add a TITLE column of VARCHAR2 datatype,
length 30.
9. Add a comment to the WORKER and DEPARTMENT table definitions
describing the tables. Confirm your additions in the data dictionary.

TABLE_NAME COMMENTS
--------------- ------------------------------
DEPARTMENT Departmental Listing
WORKER Employee Information

Altering Tables and Constraints 12Ć27


12Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
13

Creating Sequences
13Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

Many applications require the use of unique numbers as primary key values.
You can either build code into the application to handle this requirement or use
a sequence to generate unique numbers. This lesson covers creating and using
sequences that create unique numbers.
At the end of this lesson, you should be able to
D Explain the use of sequences.
D Create a sequence.
D Use a sequence.
D Modify a sequence definition.
D Remove a sequence.

Creating Sequences 13Ć3


13Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
A sequence generator can be used to automatically generate sequence numbers for
rows in tables. A sequence is a database object created by a user and can be shared by
multiple users.
A typical usage for sequences is to create a primary key value, which must be unique
for each row. The sequence is generated and incremented (or decremented) by an
internal Oracle7 routine. This can be a time saving object because it can reduce the
amount of application code needed to write a sequence generating routine.
Sequence numbers are stored and generated independently of tables. Therefore, the
same sequence can be used for multiple tables.

Creating Sequences 13Ć5


13Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Sequence
Define a sequence to generate sequential numbers automatically by using the
CREATE SEQUENCE command.

Abridged Syntax

CREATE SEQUENCE sequence


[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}]

where: sequence is the name of the sequence generator.


INCREMENT BY n specifies the interval between sequence numbers
where n is an integer. If this clause is omitted,
the sequence will increment by 1.
START WITH n specifies the first sequence number to be
generated. If this clause is omitted, the sequence
will start with 1.
MAXVALUE n specifies the maximum value the sequence can
generate.
NOMAXVALUE specifies a maximum value of 1027. This is the
default option.
MINVALUE n specifies the minimum sequence value.
NOMINVALUE specifies a minimum value of 1.
CYCLE | NOCYCLE specifies that the sequence continues to generate
values after reaching either its maximum or
minimum value or does not generate additional
values. NOCYCLE is the default option.
CACHE n | NOCACHE specifies how many values the Oracle7 Server
will preallocate and keep in memory. By
default, the Server will cache 20 values.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “CREATE SEQUENCE.”

Creating Sequences 13Ć7


13Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Sequence continued

Example
Create a sequence named S_DEPT_ID to be used for the DEPT_ID column of the
S_DEPT table. Start the sequence at 51. Do not allow caching and do not allow the
sequence to cycle.

SQL> CREATE SEQUENCE s_dept_id


2 INCREMENT BY 1
3 START WITH 51
4 MAXVALUE 9999999
5 NOCACHE
6 NOCYCLE;
Sequence created.

Do not use the CYCLE option if the sequence is used to generate primary key values.

Creating Sequences 13Ć9


13Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Sequence continued

Confirming Sequences
Once you have created your sequence, it is documented in the data dictionary. Since a
sequence is a database object, you can identify it in the USER_OBJECTS data
dictionary table.
You can also confirm the settings of the sequence by selecting from the data
dictionary’s USER_SEQUENCES table.

Example
Display information about all the sequences that you own.

SQL> SELECT sequence_name, min_value, max_value,


2 increment_by, last_number
3 FROM user_sequences;

SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER


--------------- --------- --------- ------------ -----------
S_CUSTOMER_ID 1 9999999 1 216
S_DEPT_ID 1 9999999 1 51
S_EMP_ID 1 9999999 1 26
S_IMAGE_ID 1 9999999 1 1981
S_LONGTEXT_ID 1 9999999 1 1369
S_ORD_ID 1 9999999 1 113
S_PRODUCT_ID 1 9999999 1 50537
S_REGION_ID 1 9999999 1 6
S_WAREHOUSE_ID 1 9999999 1 10502

9 rows selected.

Creating Sequences 13Ć11


13Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Using a Sequence
Once you create your sequence, you can use the sequence to generate sequential
numbers for use in your tables. Reference the sequence values by using the
NEXTVAL and CURRVAL pseudocolumns.

NEXTVAL and CURRVAL Pseudocolumns


The NEXTVAL pseudocolumn is used to extract successive sequence numbers from a
specified sequence. You must qualify NEXTVAL with the sequence name. When you
reference sequence.NEXTVAL, a new sequence number is generated and the current
sequence number is placed in CURRVAL.
The CURRVAL pseudocolumn is used to refer to a sequence number that the current
user has just generated. NEXTVAL must be used to generate a sequence number in
the current user’s session before CURRVAL can be referenced. You must qualify
CURRVAL with the sequence name. When sequence.CURRVAL is referenced, the
last value returned to that user’s process is displayed.

Rules for Using NEXTVAL and CURRVAL


You can use NEXTVAL and CURRVAL in
D The SELECT list of a SELECT statement that is not part of a subquery.
D The SELECT list of a subquery in an INSERT statement.
D The VALUES clause of an INSERT statement.
D The SET clause of an UPDATE statement.
You cannot use NEXTVAL and CURRVAL in
D A SELECT list of a view.
D A SELECT statement with the DISTINCT keyword.
D A SELECT statement with the GROUP BY, HAVING, or ORDER BY clauses.
D A subquery in a SELECT, DELETE, or UPDATE statement.
D A DEFAULT expression in a CREATE TABLE or ALTER TABLE command.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Pseudocolumns” section and “CREATE
SEQUENCE.”

Creating Sequences 13Ć13


13Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Using a Sequence continued

Caching Sequence Values


Cache sequences in the memory to allow faster access to those sequence values. The
cache is populated at the first reference to the sequence. Each request for the next
sequence value is retrieved from the cached sequence. After the last sequence is used,
the next request for the sequence pulls another cache of sequences into memory.

Beware of Gaps in Your Sequence


Although sequence generators issue sequential numbers without gaps, this action
occurs independent of a commit or rollback. Therefore, if you roll back a command
containing a sequence, the number is lost.
Another event that can cause gaps in the sequence is a system crash. If the sequence
caches values in the memory, then those values are lost if the system crashes.
Because sequences are not tied directly to tables, the same sequence can be used for
multiple tables. If this occurs, each table can contain gaps in the sequential numbers.

Viewing the Next Available Sequence Value Without Incrementing It


It is possible to view the next available sequence value without incrementing it, only
if the sequence was created with NOCACHE, by querying the USER_SEQUENCES
table.

Creating Sequences 13Ć15


13Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Altering a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values from the
sequence will be allocated and you will receive an error indicating the sequence
exceeds the MAXVALUE. To continue to use the sequence, you can modify it by
using the ALTER SEQUENCE command.

Syntax

ALTER SEQUENCE sequence


[INCREMENT BY n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}]

Guidelines
D You must own or you have the ALTER privilege for the sequence in order to
modify it.
D Only future sequence numbers are affected by the ALTER SEQUENCE
command.
D Some validation is performed. For example, a new MAXVALUE cannot be
imposed that is less than the current sequence number.
D The START WITH option cannot be changed using ALTER SEQUENCE. The
sequence must be dropped and re-created in order to restart the sequence at a
different number.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “ALTER SEQUENCE.”

Creating Sequences 13Ć17


13Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Removing a Sequence
To remove a sequence from the data dictionary, use the DROP SEQUENCE
command. You must be the owner of the sequence or have the DROP ANY
SEQUENCE privilege to remove it.

Syntax

DROP SEQUENCE sequence;

where: sequence is the name of the sequence generator.


For more information, see
Oracle7 Server SQL Reference, Release 7.3, “DROP SEQUENCE.”

Creating Sequences 13Ć19


13Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
The sequence generator can be used to automatically generate sequence numbers for
rows in tables. This can be time saving, and can reduce the amount of application
code needed.
A sequence is a database object that can be shared with other users. Information
about the sequence can be found in the USER_SEQUENCES table of the data
dictionary.
To use a sequence, reference it with either the NEXTVAL or the CURRVAL
pseudocolumns.
D Retrieve the next number in the sequence by referencing sequence.NEXTVAL.
D Return the current available number by referencing sequence.CURRVAL.

Creating Sequences 13Ć21


13Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
In this practice, you will create a sequence to be used when populating your
DEPARTMENT and WORKER tables.

Practice Contents
D Creating a sequence
D Modifying a sequence
D Using a sequence

Creating Sequences 13Ć23


13Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 13
1. Create a sequence to be used with the DEPARTMENT table’s primary key
column. The sequence should start at 76 and have a maximum value of 80. Be
sure that it increments by one number. Name the sequence DEPT_ID_SEQ.
2. Create another sequence. This sequence will be used with the WORKER table’s
primary key column. Start this sequence at 204, and set the maximum value to be
9999999. Be sure that it increments by one number. Allow the sequence to cache
5 numbers. Name the sequence WORKER_ID_SEQ.
3. Write a script to display the following information about your sequences:
sequence name, cache size, maximum value, increment size, and last number
generated. Name the script p13q3.sql.
4. Write an interactive script to insert a row into the DEPARTMENT table. Name
your script p13q4.sql. Be sure to use the sequence you created for the ID column.
Create a customized prompt to enter the department name. Execute your script.
Add two departments named Education and Administration. Confirm your
additions.
5. Display information about your sequences by executing the p13q3.sql script.
Notice that the WORKER_ID_SEQ last number does not match the highest
primary key value in Exercise 6. Why?
If you completed Practice 12, Exercise 8, you can do the following two exercises.
6. Write a script to insert two rows into the WORKER table. Name your script
p13q5.sql. Use the sequence you create for the ID column. Execute your script.
Add Tomas Lira as the President in the last department you just added to the
table. The other employee is Anna Seigher who is the Vice President in the
Finance department.
7. Confirm your additions to the DEPARTMENT table and WORKER table. Note
the highest primary key values for each table.

Creating Sequences 13Ć25


Practice 13 continued

If you have time, complete the following exercises:


8. Execute p13q4.sql to insert four additional departments named Accounting,
Warehouse, Operations, and Research. What happened and why?

9. Modify your department sequence to allow no maximum value. Verify the change
to the sequence by executing the p13q3.sql script.
10. Add the Research department by using your script named p13q4.sql. Make this
addition permanent.
11. Display the contents of the DEPARTMENT table and WORKER table.

13Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


14

Creating Views
14Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

In this lesson, you will see how views can be used to present data to users in a
variety of ways. In addition, you will see how integrity constraints can be
enforced, if using a view to insert, update, or delete data.
At the end of this lesson, you should be able to
D Explain the concept of a view.
D Use data dictionary views.
D Create simple and complex views.
D Create a view with an option to enforce constraints.
D Modify a view.
D Remove a view.

Creating Views 14Ć3


14Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
Present logical subsets or combinations of data by creating views of tables.

What Is a View?
A view is a logical table based on a table or another view. A view contains no data of
its own, but is rather like a “window” through which data from tables can be viewed
or changed. The tables upon which a view is based are called base tables. The view is
stored as a SELECT statement in the data dictionary.

Advantages of Views
D Restrict access to the database because the view can display a selective portion of
the database.
D Allow users to make simple queries to retrieve the results from complicated
queries. For example, views allow users to query information from multiple tables
without knowing how to write a join statement.
D Provide data independence for ad hoc users and application programs. One view
can be used to retrieve data from several tables.
D Provide groups of users access to data according to their particular criteria.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “CREATE VIEW.”

Creating Views 14Ć5


14Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a View
Create a view by embedding a subquery within the CREATE VIEW statement.

Abridged Syntax

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view


[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY]

where: OR REPLACE recreates the view if it already exists.


FORCE creates the view regardless of whether the base
tables exist or not.
NOFORCE creates the view only if the base tables exist.
This is the default.
view is the name of the view.
alias specifies names for the expressions selected by
the view’s query. The number of aliases must
match the number of expressions selected by the
view.
subquery is a complete SELECT statement. You can use
aliases for the columns in the SELECT list.
WITH CHECK OPTION specifies that only rows accessible to the view
may be inserted or updated.
constraint is the name assigned to the CHECK OPTION
constraint.
WITH READ ONLY ensures that no DML operations can be
performed on this view.

Guidelines
D The query that defines a view can contain complex SELECT syntax, including
joins, groups, and subqueries.
D The query that defines the view cannot contain an ORDER BY clause.
D If you do not specify a constraint name, the system will assign a default name in
the format SYS_Cn.
D You can use the OR REPLACE option to change the definition of the view
without dropping and re-creating it, or regranting object privileges previously
granted on it.

Creating Views 14Ć7


14Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a View continued

There are two classifications for views: simple and complex. The basic difference is
related to the DML operations.

Simple Views Compared to Complex Views

Characteristic Simple Views Complex Views


Number of tables Only one One or more
Contain functions No Yes
Contain groups of data (DISTINCT No Yes
or group functions)
DML through the view Yes No

Example
Create a view containing the employee number, last name, and job title for employees
in department 45. Display the contents.

SQL> CREATE VIEW empvu45


2 AS SELECT id, last_name, title
3 FROM s_emp
4 WHERE dept_id = 45;
View created.

SQL> SELECT *
2 FROM empvu45;

ID LAST_NAME TITLE
------ ------------ ---------------------
10 Havel Warehouse Manager
24 Dancs Stock Clerk
25 Schwartz Stock Clerk

Creating Views 14Ć9


14Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a View continued

Control the column names by including column aliases within the subquery.

Example
Create a view containing the employee number, first name with the alias FIRST, last
name with the alias LAST, and salary with the alias MONTHLY_SALARY for
department 41.

SQL> CREATE VIEW salvu41


2 AS SELECT id, first_name FIRST, last_name LAST,
3 salary MONTHLY_SALARY
4 FROM s_emp
5 WHERE dept_id = 41;
View created.

Alternatively, control the column names by including column aliases in the CREATE
VIEW clause. To change the view definition, use the CREATE OR REPLACE
clause.

Example
Modify EMPVU45 view. Change the employee number to have a heading
ID_NUMBER, last name to a heading EMPLOYEE, and title to a heading JOB.

SQL> CREATE OR REPLACE VIEW empvu45


2 (id_number, employee, job)
3 AS SELECT id, last_name, title
4 FROM s_emp
5 WHERE dept_id = 45;
View created.

Note: When assigning column aliases in the CREATE VIEW clause, remember that
the aliases are listed in the same order as the columns in the subquery.

Creating Views 14Ć11


14Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a View continued

Create a complex view that contains group functions to display values from two
tables.

Example
Create a view of the department names, minimum salary, maximum salary, and
average salary by department. Display the structure of the view and its contents.

SQL> CREATE VIEW dept_sum_vu


2 (name, minsal, maxsal, avgsal)
3 AS SELECT d.name, min(e.salary),
4 max(e.salary), avg(e.salary)
5 FROM s_emp e, s_dept d
6 WHERE e.dept_id = d.id
7 GROUP BY d.name;
View created.

SQL> DESCRIBE dept_sum_vu


Name Null? Type
------------------------------- -------- ----
NAME NOT NULL VARCHAR2(25)
MINSAL NUMBER
MAXSAL NUMBER
AVGSAL NUMBER

SQL> SELECT *
2 FROM dept_sum_vu;

NAME MINSAL MAXSAL AVGSAL


-------------------- ---------- ---------- ----------
Administration 1550 2500 2025
Finance 1450 1450 1450
Operations 750 1450 1086.8
Sales 795 1525 1367.85714

Creating Views 14Ć13


14Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Performing DML Operations on a View
You can perform DML operations on data through a view provided those operations
follow the rules outlined below:
D You can remove a row from a view unless it contains any of the following:
D Group functions
D A GROUP BY clause
D The DISTINCT command
D You can modify data in a view unless it contains any of the above and any of the
following:
D Columns defined by expressions, for example, SALARY * 12.
D The ROWNUM pseudocolumn.
D You can add data through a view unless it contains any of the above and there are
NOT NULL columns in the base table that are not selected by the view. All
required values must be present in the view. Remember that you are adding values
directly into the underlying table through the view.
For more information, see
Oracle 7 Server SQL Reference, Release 7.3, “CREATE VIEW.”

Creating Views 14Ć15


14Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Performing DML Operations on a View continued

You can ensure that when you add or update data in a simple view, the added or
updated data can be queried through the view.

Example
Create a view that contains all columns from the S_EMP table for department 45.
Add the WITH CHECK OPTION clause.

SQL> CREATE OR REPLACE VIEW empvu41


2 AS SELECT *
3 FROM s_emp
4 WHERE dept_id = 41
5 WITH CHECK OPTION CONSTRAINT empvu41_ck;
View created.

Attempt to change the department number for employee 16 to department 42 through


the view.

SQL> UPDATE empvu41


2 SET dept_id = 42
3 WHERE id = 16;
ERROR at line 3:
ORA-01402: view WITH CHECK OPTION where-clause
violation

Note: No rows are updated because if the department number were to change to 42,
the view would no longer be able to see that employee. Therefore, with the
WITH CHECK OPTION clause, the view can only see department 41
employees, and does not allow the department number for those employees to
be changed through the view.

Creating Views 14Ć17


14Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Performing DML Operations on a View continued

You can ensure that no DML operations occur on your view by creating it with the
WITH READ ONLY option.

Example
Modify the EMPVU45 view. Do not allow DML operations to occur on this view.
Attempt to remove a row from the view.

SQL> CREATE OR REPLACE VIEW empvu45


2 (id_number, employee, job)
3 AS SELECT id, last_name, title
4 FROM s_emp
5 WHERE dept_id = 45
6 WITH READ ONLY;
View created.

SQL> DELETE FROM empvu45


2 WHERE id_number = 10;
ERROR at line 1:
ORA-01732: data manipulation operation not legal on
this view

Creating Views 14Ć19


14Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Confirming View Names and Structures
You can confirm the names and defining SELECT statements of views by querying
the USER_VIEWS data dictionary table.

Example
Describe the structure of the USER_VIEWS data dictionary table. Display the names
and contents of all views currently owned by the user.

SQL> DESCRIBE user_views


Name Null? Type
------------------------------- -------- ----
VIEW_NAME NOT NULL VARCHAR2(30)
TEXT_LENGTH NUMBER
TEXT LONG

SQL> SELECT *
2 FROM user_views;

VIEW_NAME TEXT_LENGTH TEXT


--------------- ----------- -----------------------------------
DEPT_SUM_VU 121 SELECT d.name, MIN(e.salary), MAX(e
.salary), AVG(e.salary)
FROM s_emp e, s_dept

EMPVU41 179 SELECT ”ID”,”LAST_NAME”,”FIRST_NAM


E”,”USERID”,”START_DATE”,”COMMENTS”
,”MANAGER_

EMPVU45 56 SELECT id, last_name, title


FROM s_emp
WHERE dept_id=45

SALVU41 97 SELECT id, first_name first, last_n


ame last, salary monthly_salary
FROM s_emp
WH

Creating Views 14Ć21


14Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Removing a View
Use the DROP VIEW command to remove a view. The command removes the view
definition from the database. Dropping views has no affect on the tables on which the
view was based. Views or other applications based on deleted views become invalid.
Only the creator or a user with the DROP ANY VIEW privilege can remove a view.

Syntax

DROP VIEW view;

where: view is the name of the view.

Creating Views 14Ć23


14Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
A view is based on a table or another view and acts as a window through which data
on tables can be viewed or changed. A view does not contain data. The definition of
the view is stored in the data dictionary. You can see the definition of the view in the
USER_VIEWS data dictionary table.

Advantages of Views
D Restrict database access
D Simplify queries
D Provide data independence
D Allow multiple views of the same data
D Remove views without affecting the underlying data

View Options
D Can be a simple view based on one table
D Can be a complex view based on more than one table, or contain groups or
functions
D Can be replaced if one of the same name exists
D Contain a check constraint
D Can be read-only

Creating Views 14Ć25


14Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
In this practice, you will create simple and complex views, and attempt to perform
DML statements to the views.

Practice Contents
D Creating a simple view
D Creating a complex view
D Creating a view with a check constraint
D Attempting to modify data in the view
D Displaying view definitions
D Removing views

Creating Views 14Ć27


14Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 14
1. Create a view called EMP_VU based on the employee number, last name, and
department number from the WORKER table. Change the heading for the last
name to EMPLOYEE.
a. Display the content of the EMP_VU view.
b. Write a script to display the definition of a view. Pass the name of the view to
the script. Save the script as p14q1.sql. Execute the script to view the
definition of the EMP_VU view.
c. Change the department number for Smith to 37 in the EMP_VU view.
d. Confirm that Smith is now assigned to department 37.
2. Create a view called MNS_VU that contains the employee number, full name, and
department name for all employees in the Marketing and Sales departments in the
WORKER and DEPARTMENT tables.
a. Display the structure and contents of the MNS_VU view.
b. Display the definition of the MNS_VU view by executing the p14q1.sql
script.
c. Display the department name and number of employees in each department.
3. Modify EMP_VU view contain only those employees in department 37. Add a
check constraint so that the department number cannot be modified.
a. Display the contents of the EMP_VU view.
b. Change the department number for Smith back to 54 through the EMP_VU
view. Was your operation successful? Why or why not?

If you have time, complete the following exercises:


4. Modify the MNS_VU so that the rows can only be seen between 1:00 P.M. and
4:00 P.M. You can edit the script named p14q1.sql. Execute the script. Display
the contents of the view.
5. Remove all views from the data dictionary. Confirm that no views exist in the
data dictionary.

Creating Views 14Ć29


14Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
15

Creating Indexes
15Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

If you want to improve the performance of some queries, you should consider
creating an index. You can also use indexes to enforce uniqueness on a column or
a collection of columns.
At the end of this lesson, you should be able to
D Distinguish between the indexes that are created automatically and those that are
created manually.
D Identify the uses for indexes.
D Explain the index structure and why it improves query speed.
D Create a non-unique index.
D Remove an index from the data dictionary.
D Evaluate guidelines for creating and using indexes.

Creating Indexes 15Ć3


15Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
An Oracle7 Server index is a database object that can speed up the retrieval of rows
by using a pointer. Indexes can be created explicitly or automatically. They are
transparent to the user. If you do not have an index on the column, then a full table
scan will occur.

What Is an Index?
An index is a database object that provides direct and fast access to rows in a table.
Its purpose is to reduce the necessity of disk I/O by using a B*Tree indexed path to
locate data quickly. The index is automatically used and maintained by the Oracle7
Server. Once an index is created, no direct activity is required by the user.
Indexes are logically and physically independent of the table they index. This means
that they can be created or dropped at any time and have no effect on the base tables
or other indexes.

How Are Indexes Created?


Two types of indexes can be created. One type is a unique index. The Oracle7 Server
automatically creates this index when you define a column in a table to have a
PRIMARY KEY or a UNIQUE constraint. The name of the index is the name given
to the constraint.
The other type of index a user can create is a non-unique index. For example, you can
create a FOREIGN KEY column index for a join in a query to improve retrieval
speed.
For more information, see
Oracle7 Server Concepts Manual, Release 7.3, “Schema Objects” section, “Indexes”
topic.

Creating Indexes 15Ć5


15Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
When Is the Index Used?
Once the index has been created, the Oracle7 Server will use it whenever possible to
speed up access to the data. Note that this use is automatic and usually requires no
action by the user. A brief guideline is provided below on how the Server determines
to use the index.

Optimization Techniques
When an index is used depends partly on the Oracle Optimizer being used at the time.
The Oracle7 Server uses both rule-based and cost-based optimization.
Rule-based optimization is when the Oracle7 Server decides when it is appropriate to
use an index based on its internal rules. The Server identifies the columns that are
indexed and the index types.
The cost-based optimization method uses statistics about tables along with
information about available indexes to select an execution plan for the SQL
statements.
For more information, see
Tune Oracle7 Applications course description.

Creating Indexes 15Ć7


15Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Index Structure
An index is an optional structure that is independent of the table structure. Each index
is composed of column values that the index is on and pointers (or ROWIDs) to the
row containing that value. The pointer directly points to the appropriate row in the
table, therefore avoiding a full table scan.

B*Tree
The Oracle7 Server uses a balanced B*tree index structure. This is a binary,
self-balancing search structure to equalize access times to any row. It is an efficient
method of ensuring that access to any specified value will take approximately the
same time whether the row is at the beginning, middle, or end of the table.
Each index that the Oracle7 Server builds consists of a number of pages (or branches)
of storage arranged in a tree. Each page (or branch) holds a series of key values and
pointers to pages (or branches) lower in the structure until eventually the key values
indicate the location of the data itself. The location identifier at the database level is
called a ROWID.

Creating Indexes 15Ć9


15Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Index Structure continued

Index Types

Type Description
Unique Ensures that values in specified columns are
unique.
Non-unique Ensures fastest possible results when querying
data.
Single column Only one column exists in the index.
Concatenated or composite Can contain up to 16 columns in the index for
either performance or uniqueness check
purposes. The columns need not be adjacent.

Index types are not mutually exclusive. For example, you can create a unique,
concatenated index.

Creating Indexes 15Ć11


15Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating an Index
Create an index on one or more columns by issuing the CREATE INDEX command.

Abridged Syntax

CREATE INDEX index


ON table (column[, column]...);

where: index is the name of the index.


table is the name of the table.
column is the name of the column in the table to be
indexed.

Example
Create an index to improve the speed of query access on the LAST_NAME column
in the S_EMP table.

SQL> CREATE INDEX s_emp_last_name_idx


2 ON s_emp(last_name);
Index created.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “CREATE INDEX.”

Creating Indexes 15Ć13


15Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating an Index continued

More Is Not Always Better


More indexes on a table does not mean it will speed up queries. Each DML operation
that is committed on a table with indexes means that the indexes must be updated.
The more indexes you have associated with a table, the more effort the Server must
make to update all the indexes after a DML.

When to Create an Index


D The column is used frequently in the WHERE clause or in a join condition.
D The column contains a wide range of values.
D The column contains a large number of null values.
D Two or more columns are frequently used together in a WHERE clause or join
condition.
D The table is large and most queries are expected to retrieve less than 2–4% of the
rows.
Remember that if you want to enforce uniqueness, you should define a unique
constraint in the table definition. Then, a unique index is automatically created.

When to Not Create an Index


D The table is small.
D The columns are not often used as a condition in the query.
D Most queries are expected to retrieve more than 2–4% of the rows.
D The table is updated frequently.

Creating Indexes 15Ć15


15Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Confirming Indexes
Confirm the existence of indexes from the USER_INDEXES data dictionary view.
You can also check the columns involved in an index by querying the
USER_IND_COLUMNS view.

Example
Display all previously created indexes, affected column names, and uniqueness on the
S_EMP table.

SQL> SELECT ic.index_name, ic.column_name,


2 ic.column_position col_pos, ix.uniqueness
3 FROM user_indexes ix, user_ind_columns ic
4 WHERE ic.index_name = ix.index_name
5 AND ic.table_name = ’S_EMP’;

INDEX_NAME COLUMN_NAME COL_POS UNIQUENESS


–––––––––––––––––––– ––––––––––– –––––––– ––––––––––
S_EMP_ID_PK ID 1 UNIQUE
S_EMP_LAST_NAME_IDX LAST_NAME 1 NONUNIQUE
S_EMP_USERID_UK USERID 1 UNIQUE

Creating Indexes 15Ć17


15Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Removing an Index
You cannot modify indexes. To change an index, you must drop it and then re-create
it. Remove an index definition from the data dictionary by issuing the DROP INDEX
command. In order to drop an index, you must be the owner of the index or have the
DROP ANY INDEX privilege.

Syntax

DROP INDEX index;

where: index is the name of the index.

Creating Indexes 15Ć19


15Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Indexes are used to improve the query retrieval speed. They are database objects and
therefore take up disk space. Indexes use the B*tree search method to retrieve the
pointer to the rows in the tables.
Unique indexes for the PRIMARY KEY and UNIQUE KEY constraints in a table
definition are created automatically.
Users can create non-unique indexes to speed up searches by using the CREATE
INDEX command.
Indexes are maintained automatically by the Oracle7 Server. Users can view the
definitions of the indexes in the USER_INDEXES data dictionary view.
An index can be dropped by the creator or a user with the DROP ANY INDEX
privilege by using the DROP INDEX command.

Creating Indexes 15Ć21


15Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
In this practice you will create an index on the WORKER table.

Practice Contents
D Creating non-unique indexes
D Displaying data dictionary information about the index
D Dropping indexes

Creating Indexes 15Ć23


15Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 15
1. Would any indexes specified be used with the following queries and why?
a. Non-unique index on LAST_NAME.
Yes/No

SQL> SELECT *
2 FROM s_emp
3 WHERE last_name = ’Biri’;

b. Unique index on ID and non-unique index on CUSTOMER_ID.


Yes/No

SQL> SELECT id, customer_id, total


2 FROM s_ord
3 WHERE date_ordered = ’31-AUG-92’;

c. Unique index on S_DEPT.ID and non-unique index on S_EMP.DEPT_ID.


Yes/No

SQL> SELECT e.last_name, d.name


2 FROM s_emp e, s_dept d
3 WHERE e.dept_id = d.id;

Creating Indexes 15Ć25


Practice 15 continued

2. Create a non-unique index on the foreign key column in the WORKER table.
3. Since users will frequently query on the employee last name, create a non-unique
index on that column in the WORKER table.
4. Display the indexes and uniqueness that exist in the data dictionary for the
WORKER and DEPARTMENT tables. Save the command into a script named
p15q4.sql.
5. Remove the primary key constraint on the WORKER table.
6. Re-display the indexes and uniqueness that exist in the data dictionary for the
WORKER and DEPARTMENT tables by executing the p15q4.sql script. What
changes do you observe and why?

If you have time, complete the following exercises:


7. Re-create the primary key constraint on the WORKER table. Confirm the
constraint in the data dictionary by executing pl2q2.sql. Confirm the unique index
in the data dictionary by executing pl5q4.
8. Remove the index on the employee last name from the WORKER table.

15Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


16

Controlling User Access


16Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

This lesson describes the Oracle7 Server decentralized security system. Using
the commands covered in this lesson, you can control database access to specific
objects and add new users with different levels of access privileges. You can
provide alternative names for objects by using the CREATE SYNONYM
command.
At the end of this lesson, you should be able to
D Explain the concept of the database security model.
D Describe system privileges.
D Set up and maintain database access by using roles.
D Identify object privileges.
D Change a password.
D Grant and revoke object privileges.
D Create synonyms for ease of table access.

Controlling User Access 16Ć3


Server

É ÉÉ

16Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Overview
In a multiple-user environment, you want to maintain security of the database access
and use. Oracle7 Server database security allows you to
D Control database access.
D Give access to specific objects in the database.
D Confirm given and received privileges with the Oracle data dictionary.
D Create synonyms for database objects.
Database security can be classified into two categories: system security and data
security. System security covers access and use of the database at the system level,
such as username and password, disk space allocated to users, and system operations
allowed by the user. Database security covers access and use of the database objects
and the actions that those users can have on the objects.

Privileges
Privileges are the right to execute particular SQL statements. The database
administrator is a high level user with the ability to grant users access to the database
and its objects. The users require system privileges to gain access to the database and
object privileges to manipulate the content of the objects in the database. Users can
also be given the privilege to grant additional privileges to other users or to roles,
which are named groups of related privileges.

Schema
A schema is a collection of objects, such as tables, views, and sequences. The schema
is owned by a database user and has the same name as that user.
For more information, see
Oracle7 Server Application Developer’s Guide, Release 7.3, “Establishing a Security
Policy” section and Oracle7 Server Concepts Manual, “Database Security” topic.

Controlling User Access 16Ć5


16Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
System Privileges
There are more than eighty system privileges available for users and roles. System
privileges are typically provided by the database administrator.

Typical DBA Privileges

System Privilege Operations Authorized


CREATE USER Allows grantee to create other Oracle users (a
privilege required for a DBA role).
DROP USER Drops another user.
DROP ANY TABLE Drops a table in any schema.
BACKUP ANY TABLE Backs up any table in any schema with the export
utility.

Creating a User
The DBA creates a new Oracle7 Server user by allocating a number of system
privileges to that user. These privileges in turn determine what the user can do at the
database level. The DBA creates the user by executing the CREATE USER
command. The user does not have any system privileges.

Abridged Syntax

CREATE USER user IDENTIFIED BY password;

where: user is the name of the user to be created.


password specifies that the user must log in with this
password.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “GRANT” (System Privileges and
Roles) and “CREATE USER.”

Controlling User Access 16Ć7


16Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
System Privileges continued

Now that the DBA has created a user, the DBA can assign privileges to that user.

Typical User Privileges

System Privilege Operations Authorized


CREATE SESSION Connect to the database.
CREATE TABLE Create tables in the user’s schema.
CREATE SEQUENCE Create a sequence in the user’s schema.
CREATE VIEW Create a view in the user’s schema.
CREATE PROCEDURE Create a stored procedure, function, or package in
the user’s schema.

Granting System Privileges


The DBA uses the GRANT command to allocate system privileges to the user. Once
the user has been granted the privileges, the user can immediately use those
privileges.

Syntax

GRANT privilege [, privilege...] TO user [, user...];

where: privilege is the system privilege to be granted.


user is the name of the user.
Note: The above syntax is abridged.

Controlling User Access 16Ć9


16Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
What Is a Role?
A role is a named group of related privileges that can be granted to the user. This
method makes granting and revoking privileges easier to perform and maintain.
A user can have access to several roles, and several users can be assigned the same
role. Roles typically are created for a database application.

Creating and Assigning a Role


First, the DBA must create the role. Then, the DBA can assign privileges to the role
and users to the role.

Syntax

CREATE ROLE role;

where: role is the name of the role to be created.


Now that the role is created, the DBA can use the GRANT command to assign users
to the role as well as assign privileges to the role.

Example
Allow the managers to create tables and views. Give these privileges to Velasquez
and to Ropeburn.

SQL> CREATE ROLE manager;


Role created.
SQL> GRANT create table, create view TO manager;
Grant succeeded.
SQL> GRANT manager TO cvelasqu, aropebur;
Grant succeeded.

Controlling User Access 16Ć11


16Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Changing Your Password
Every user has a password that is initialized by the DBA when the user is created.
You can change your password by using the ALTER USER command.

Syntax

ALTER USER user IDENTIFIED BY password;

where: user is the name of the user.


password specifies the new password.
Note: Although this command can be used to change your password, there are many
other options. You must have the ALTER USER privilege to change any other
option.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “ALTER USER.”

Controlling User Access 16Ć13


16Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Granting Object Privileges
The DBA can allow users to perform a particular action on a specific table, view,
sequence, or stored procedure by granting them object privileges. The object
privileges vary from object to object. The table on the facing page outlines the
privileges. An object owner has all privileges on the object. To give another user
access to your database objects, execute the GRANT command.

Syntax

GRANT {object_priv(, object_priv...)|ALL}[(columns)]


ON object
TO {user[, user...]|role|PUBLIC}
[WITH GRANT OPTION];

where: object_priv is an object privilege to be granted.


ALL all object privileges.
columns specifies the column from a table or view on
which privileges are granted.
ON object is the object on which the privileges are granted.
TO identifies to whom the privilege is granted.
PUBLIC grants object privileges to all users.
WITH GRANT OPTION allows the grantee to grant the object privileges
to other users and roles.
Note: A procedure refers to standalone procedures and functions, and public
package constructs. The INDEX and REFERENCES privileges cannot be
granted to a role.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “GRANT.”

Controlling User Access 16Ć15


16Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Granting Object Privileges continued

Guidelines
D To grant privileges on an object, the object must be in your own schema or you
must have been granted the object privileges WITH GRANT OPTION.
D An object owner can grant any object privilege on the object to any other user or
role of the database.
D The owner of an object automatically acquires all object privileges on that object.

Examples
Grant users Sue and Rich the privilege to query your S_EMP table.

SQL> GRANT select


2 ON s_emp
3 TO sue, rich;
Grant succeeded.

Grant UPDATE privileges on specific columns in the S_DEPT table to Scott and to
the manager role.

SQL> GRANT update (name, region_id)


2 ON s_dept
3 TO scott, manager;
Grant succeeded.

Controlling User Access 16Ć17


16Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Granting Object Privileges continued

The WITH GRANT OPTION Keyword


A privilege that is granted WITH GRANT OPTION can be passed on to other users
and roles by the grantee. Object privileges granted WITH GRANT OPTION are
revoked when the grantor’s privilege is revoked.

Example
As user Alice, allow user Scott to access your S_DEPT table with the privileges to
query the table and add rows to the table. Allow Scott to give others these privileges.

SQL> GRANT select, insert


2 ON s_dept
3 TO scott
4 WITH GRANT OPTION;
Grant succeeded.

The PUBLIC Keyword


An owner of a table can grant access to all users by using the PUBLIC keyword.

Example
As user Scott, allow all users on the system to query data from Alice’s S_DEPT table.

SQL> GRANT select


2 ON alice.s_dept
3 TO PUBLIC;
Grant succeeded.

Controlling User Access 16Ć19


16Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Confirming Privileges Granted
If you attempt to perform an unauthorized operation, for example, deleting a row
from a table for which you do not have the DELETE privilege, the Oracle7 Server
will not permit the operation to take place.
If you receive the Oracle7 Server error message “table or view does not exist,” you
have done either of the following:
D Named a table or view that does not exist
D Attempted to perform an operation on a table or view for which you do not have
the appropriate privilege

What Privileges Do You Have?


You can access the data dictionary to view the privileges you have.

Data Dictionary Table Description


ROLE_SYS_PRIVS System privileges granted to roles.
ROLE_TAB_PRIVS Table privileges granted to roles.
USER_ROLE_PRIVS Roles accessible by the user.
USER_TAB_PRIVS_MADE Object privileges granted on the user’s objects.
USER_TAB_PRIVS_RECD Object privileges granted to the user.
USER_COL_PRIVS_MADE Object privileges granted on the columns of the
user’s objects.
USER_COL_PRIVS_RECD Object privileges granted to the user on specific
columns.

Controlling User Access 16Ć21


16Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Revoking Object Privileges
Remove privileges granted to other users by using the REVOKE command. When
you use the REVOKE command, the privileges you specify are revoked from the
users you name, and from any other users to whom those privileges may have been
granted.

Syntax

REVOKE {privilege [, privilege...] | ALL}


ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS]

where: CASCADE are required to remove any referential integrity


CONSTRAINTS constraints made to the object by means of the
REFERENCES privilege.

SQL> REVOKE select, insert


2 ON s_dept
3 FROM scott;
Revoke succeeded.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “REVOKE.”

Controlling User Access 16Ć23


16Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Synonym for an Object
To refer to a table owned by another user, you need to prefix the table name with the
name of the user who created it followed by a period. Creating a synonym eliminates
the need to qualify the object name with the schema, and provides you with an
alternative name for a table, view, sequence, procedure, or other objects. This method
can be especially useful with lengthy object names, such as views.

Syntax

CREATE [PUBLIC] SYNONYM synonym


FOR object;

where: PUBLIC creates a synonym accessible to all users.


synonym is the name of the synonym to be created.
object identifies the object for which the synonym is
created.

Guidelines
D The object cannot be contained in a package.
D A private synonym name must be distinct from all other objects owned by the
same user.

Example
As user Scott, create a private synonym named S_DEPT for Alice’s S_DEPT table.

SQL> CREATE SYNONYM s_dept


2 FOR alice.s_dept;
Synonym created.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “CREATE SYNONYM.”

Controlling User Access 16Ć25


16Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Synonym for an Object continued

Examples
Create a synonym for the DEPT_SUM_VU for quicker reference.

SQL> CREATE SYNONYM d_sum


2 FOR dept_sum_vu;
Synonym created.

The DBA can create a public synonym accessible to all users.

SQL> CREATE PUBLIC SYNONYM s_dept


2 FOR alice.s_dept;
Synonym created.

Remove a Synonym
To drop a synonym, use the DROP SYNONYM command. Only the DBA can drop a
public synonym.

Example

SQL> DROP SYNONYM s_dept;


Synonym dropped.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “DROP SYNONYM.”

Controlling User Access 16Ć27


16Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
DBAs establish initial database security for users by assigning privileges to the users.
D The DBA creates users who must have a password. The DBA is also responsible
for establishing the initial system privileges for a user.
D Once the user has created an object, the user can pass along any of the available
object privileges to other users or to all users by using the GRANT command.
D A DBA can create roles by using the CREATE ROLE command to pass along a
collection of system or object privileges to multiple users. Roles make granting
and revoking privileges easier to maintain.
D Users can change their password by using the ALTER USER command.
D You can remove privileges from users by using the REVOKE command.
D DBAs can create public synonyms, and users can create private synonyms for
convenience by using the CREATE SYNONYM command. They permit short
names or alternative names for objects. Remove synonyms by using the DROP
SYNONYM command.
D Data dictionary views allow users to view the privileges granted to them and that
are granted on their objects.

Controlling User Access 16Ć29


16Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
Team up with other students for this exercise of controlling database object access.

Practice Contents
D Granting other users privileges to your table
D Modifying another user’s table through the privileges granted to you
D Creating a synonym
D Querying the data dictionary views related to privileges

Controlling User Access 16Ć31


16Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 16
1. What privilege should a user be given to log in to the Oracle7 Server? Is this
privilege a system or object privilege?

2. What privilege should a user be given to create tables?

3. If you create a table, who can pass along privileges to other users on your table?

4. You are the DBA. You are creating many users who require the same system
privileges. What would you use to make your job easier?

5. What command do you use to change your password?

6. Grant other users query access to your S_REGION table. Have them grant you
query access to their S_REGION table.
7. Query all the rows in your S_REGION table.
8. Add a new row to your S_REGION table. Team 1 should add Central America as
region number 6. Team 2 should add Micronesia as region number 7. Make the
changes permanent.
9. Query the other team’s S_REGION table.
10. Create a synonym for the other team’s S_REGION table.
11. Display the other team’s S_REGION table contents by using your synonym.
12. Confirm the privileges for your team’s tables.
13. Revoke the SELECT privilege from the other team.
14. Attempt to SELECT from the other team’s S_REGION table.
15. Drop the synonym you created.

Controlling User Access 16Ć33


16Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
17

Summary of SQL and SQL*Plus


Foreign Key
Table

Row

Column

Primary Key

17Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Summary of SQL and SQL*Plus
The SQL and SQL*Plus module of the Introduction to Oracle course covered
relational database concepts, the SQL command language, and SQL*Plus commands
to execute and format SQL commands.

Database Terminology

Concept Description
Table A table is the basic storage structure of an RDBMS, consisting
of one or more columns and zero or more rows.
Row A row is a combination of column values in a table; for
example, the information about one department in the table
S_DEPT. A row is sometimes called a “record.”
Column A column represents one kind of data in a table; for example,
the department name in the example table S_DEPT. It is
described with a column name and holds data of a specific type
and size.
Field At the intersection of a row and a column, you find a field. The
field can contain data. If there is no data in the field, it is said to
contain a null value.
Primary key A primary key is the column or set of columns that uniquely
identifies each row in a table; for example a department
number. It must contain a value.
Foreign key A foreign key is a column or set of columns that refers to a
primary key in the same table or in another table. You create
them to enforce relational database design rules.

Summary of SQL and SQL*Plus 17Ć3


17Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary of SQL and SQL*Plus continued

Structured Query Language, SQL*Plus, and PL/SQL commands are used to access
and manipulate data stored in an Oracle database.

SQL*Plus, SQL, and PL/SQL

Language or Tool Description


SQL A command language for communication with the
Oracle7 Server from any tool or application. Oracle
SQL contains many extensions.
SQL*Plus An Oracle tool that recognizes and executes SQL and
PL/SQL statements and contains its own command
language.
PL/SQL An Oracle procedural language for writing application
logic and manipulating data outside the database.

SQL Commands
There are many commands available in SQL. The table below describes the
commands covered in this course.

Command Description
SELECT Retrieves data from the database. Most commonly used
command.
INSERT Enters new rows, changes existing rows, and removes unwanted
UPDATE rows from tables in the database, respectively. Collectively
DELETE known as Data Manipulation Language (DML) commands.
CREATE Sets up, changes, and removes data structures from tables.
ALTER Collectively known as Data Definition Language (DDL)
DROP commands.
RENAME
TRUNCATE
COMMIT Manage the changes made by DML statements. Changes to the
ROLLBACK data can be grouped together into logical transactions.
SAVEPOINT
GRANT Gives or removes access rights to both the Oracle database and
REVOKE the structures within it. Collectively known as Data Control
Language (DCL) commands.

Summary of SQL and SQL*Plus 17Ć5


17Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary of SQL and SQL*Plus continued

Oracle Data Dictionary


The data dictionary is a set of tables that the user can access through views. The data
dictionary holds all the data about the database. Whenever the database is in
operation, the data dictionary is updated and maintained by the Oracle7 Server. Write
a SELECT statement to view the contents of the data dictionary views.
The following are some frequently accessed data dictionary tables:
D DICTIONARY
D USER_OBJECTS
D OBJ (alias for USER_OBJECTS)
D USER_CONSTRAINTS
D USER_SEQUENCES

SQL*Plus Commands
SQL*Plus commands may be divided into the following main categories:

Category Purpose
Environment Affects the general behavior of SQL statements for the
session.
Format Formats query results.
File manipulation Saves, loads, and runs script files.
Execution Sends SQL or PL/SQL commands from SQL buffer to
Oracle7 Server.
Edit Modifies SQL commands in the buffer.
Interaction Allows users to create and pass variables to SQL
statements, print variable values, and print messages to
the screen.
Miscellaneous Various commands to connect to the database,
manipulate the SQL*Plus environment, and display
column definitions.

Summary of SQL and SQL*Plus 17Ć7


17Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice has you build a set of database tables for a video application. Once you
create the tables, you will insert, update, and delete records in a video store database,
and generate a report. The database contains only the essential tables.

Practice Contents
D Creating tables and sequences based on a database design
D Modifying data in the tables
D Modifying a table definition
D Creating a view
D Writing scripts containing SQL and SQL*Plus commands
D Generating a simple report
Note: If you want to build the tables, you can execute the buildtab.sql script in
SQL*Plus. If you want to drop the tables, you can execute the dropvid.sql
script in SQL*Plus. Then, you can execute the buildvid.sql script in SQL*Plus
to create and populate the tables.

Summary of SQL and SQL*Plus 17Ć9


17Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 17
1. Create the tables based on the entity relationship diagram on the previous page
and the table instance charts below. Choose the appropriate datatypes and be sure
to add the integrity constraints.
a. Table name: MEMBER

Column MEMBER_ LAST_ FIRST_


Name ID NAME NAME ADDRESS CITY PHONE JOIN_DATE
Key Type PK

Null/ NN, U NN NN
Unique
Default System date
Value
Datatype number char char char char char date
Length 10 25 25 100 30 15

b. Table name: TITLE


Note: Do not create the PRICE column while creating the TITLE table. You
would be modifying the TITLE table, in Exercise 7, to add the PRICE
column.

Column TITLE_ DESCRIP– RELEASE_


Name ID TITLE TION RATING CATEGORY DATE
Key Type PK
Null/ NN, U NN NN
Unique
Check G, PG, R, DRAMA,
NC17, NR COMEDY,
ACTION,
CHILD, SCIFI,
DOCUMENTA
RY
Default Value DRAMA

Datatype number char char char char date


Length 10 60 400 4 20

Summary of SQL and SQL*Plus 17Ć11


Practice 17 continued

1.—continued
c. Table name: TITLE_COPY

Column
Name COPY_ID TITLE_ID STATUS
Key Type PK PK, FK
Null/ NN, U NN, U NN
Unique
Check AVAILABLE, DESTROYED, RENTED,
RESERVED
FK Ref Table title
FK Ref Col title_id
Datatype number number char
Length 10 10 15

d. Table name: RENTAL

Column BOOK_ MEMBER_ ACT_RET_ EXP_RET_


Name DATE ID COPY_ID DATE DATE TITLE_ID
Key Type PK FK PK, FK PK, FK
Null/ NN,U NN NN,U NN,U
Unique
Default System 2 days after
Value date book date
FK Ref member title_copy title_copy
Table
FK Ref Col member_id copy_id title_id
Datatype date number number date date number
Length 10 10 10

17Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 continued

1.—continued
e. Table name: RESERVATION

Column Name RES_DATE MEMBER_ID TITLE_ID


Key Type PK PK, FK PK, FK
Null/Unique NN,U NN,U NN,U
FK Ref Table member title
FK Ref Col member_id title_id
Datatype date number number
Length 10 10

2. Verify that the tables and constraints were created properly by checking the data
dictionary.
3. Create sequences to uniquely identify each row in the MEMBER table and the
TITLE table.
a. Member number for the MEMBER table, start with 101, do not allow caching
of the values.
b. Title number for the TITLE table, start with 92, no caching.
c. Verify the existence of the sequences in the data dictionary.

Summary of SQL and SQL*Plus 17Ć13


Practice 17 continued

4. Add data to the tables. Create a script for each set of data to add.
a. Add movie titles to the TITLE table. Write a script to enter the movie
information. Save the script as p17q4a.sql. Use the sequence to uniquely
identify each title. Remember that single quotation marks in a character field
must be specially handled. Verify your additions.

Title Description Rating Category Release date


Willie and All of Willie’s friends made a G CHILD 05-OCT-95
Christmas Christmas list for Santa, but
Too Willie has yet to add his own
wish list.
Alien Again Yet another installment of R SCIFI 19-MAY-95
science fiction history. Can
the heroine save the planet
from the alien life form?
The Glob A meteor crashes near a NR SCIFI 12-AUG-95
small American town and
unleashes carnivorous goo in
this classic.
My Day Off With a little luck and a lot of PG COMEDY 12-JUL-95
ingenuity, a teenager skips
school for a day in New
York.
Miracles on A six-year-old has doubts PG DRAMA 12-SEP-95
Ice about Santa Claus. But she
discovers that miracles really
do exist.
Soda Gang After discovering a cache of NR ACTION 01-JUN-95
drugs, a young couple find
themselves pitted against a
vicious gang.

17Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 continued

4.—continued
b. Add data to the MEMBER table. Write a script named p17q4b.sql to prompt
users for the information. Execute the script. Be sure to use the sequence to
add the member numbers.

First
name Last name Address City Phone Join date
Carmen Velasquez 283 King Seattle 206-899-6666 08-MAR-90
Street
LaDoris Ngao 5 Bratislava 586-355-8882 08-MAR-90
Modrany
Midori Nagayama 68 Via Sao Paolo 254-852-5764 17-JUN-91
Centrale
Mark Quick-To-See 6921 King Lagos 63-559-7777 07-APR-90
Way
Audry Ropeburn 86 Chu Hong 41-559-87 18-JAN-91
Street Kong
Molly Urguhart 3035 Quebec 418-542-9988 18-JAN-91
Laurier
Blvd

Summary of SQL and SQL*Plus 17Ć15


Practice 17 continued

4.—continued
c. Add the following movie copies in the TITLE_COPY table:

Title Copy number Status


Willie and Christmas Too 1 Available
Alien Again 1 Available
2 Rented
The Glob 1 Available
My Day Off 1 Available
2 Available
3 Rented
Miracles on Ice 1 Available
Soda Gang 1 Available

d. Add the following rentals to the RENTAL table:

Copy Date return Date


Title number Customer Date rented expected returned
92 1 101 3 days ago 1 day ago 2 days ago
93 2 101 1 day ago 1 day from
now
95 3 102 2 days ago Today
97 1 106 4 days ago 2 days ago 2 days ago

5. Create a view named TITLE_AVAIL to show the movie titles and the availability
of each copy and its expected return date if rented. Query all rows from the view.

17Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 continued

6. Make changes to data in the tables.


a. Add a new title. The movie is “Interstellar Wars”, which is rated PG, and
classified as a SCIFI movie. The release date is 07-JUL-77. The description is
“Futuristic interstellar action movie. Can the rebels save the humans from the
evil Empire?” Be sure to add a title copy record for two copies.
b. Enter two reservations. One reservation is for Carmen Velasquez who wants
to rent “Interstellar Wars.” The other is for Mark Quick-To-See who wants to
rent “Soda Gang”.
c. Customer Carmen Velasquez rents the movie “Interstellar Wars”, copy 1.
Remove her reservation for the movie. Record the information about the
rental. Allow the default value for the expected return date to be used. Verify
the rental was recorded by using the view you created.
7. Make a modification to one of the tables.
a. Add a PRICE column to the TITLE table to record the purchase price of the
video. The column should have a total length of eight digits and two decimal
places. Verify your modification.
b. Create a script named p17q7b.sql to update each video with a price according
to the following list:

Title Price
Willie and Christmas Too 25
Alien Again 35
The Glob 35
My Day Off 35
Miracle on Ice 98
Soda Gang 35
Interstellar Wars 29
c. Ensure that in the future all titles will contain a price value. Verify the
constraint.
8. Create a report titled Customer History Report. This report will contain each
customer’s history of renting videos. Be sure to include the customer name,
movie rented, dates of the rentals, and duration of rentals. Count up the total
number of rentals for all customers for the reporting period. Save the script in a
file named p17q8.sql.

Summary of SQL and SQL*Plus 17Ć17


17Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder