Rdbms
Rdbms
Copyr ight © 2016 Pear son I ndia E ducation Ser vices Pvt. Ltd
No part of this eBook may be used or reproduced in any manner whatsoever without the
publisher’s prior written consent.
This eBook may or may not include all assets that were part of the print version. The publisher
reserves the right to remove any material in this eBook at any time.
H ead Office: A- 8 (A ), 7th Floor, Knowledge Boulevard, Sector 62, Noi da 201 309, U ttar
Pradesh, I ndia.
Registered Office: 4th Floor, Software Block, Elnet Software City, TS-140, Block 2 & 9, Rajiv
G andhi Salai, Taramani, Chennai 600 113, Tamil Nadu, India.
Fax: 080-30461003, Phone: 080- 30461060
www.pearson.co.in, Email: companysecretary.india@pearson.com
The Reader xxii The Text xxii
The Software xxiii U sing the Text
xxiii A cknowledgments xxiv
I n a Nutshell Á 17
Exercise Questions 18
D ata Modeling 21
D ependency 24
D atabase D esign 26
vi Contents
Normal Forms 26
D ependency D iagrams 28
D enormalization 32
A nother Example of Normalization 32
Personal Databases 37
Client/Server Databases 39
Oracle9i: A n Introduction 41
The SQL * Plus Environment 43
Structured Query L anguage (SQL ) 43 Logging in to SQL *
Plus 44
SQL * Plus Commands 46
Oracle E rrors and Online Help 49 Alternate Text Editors
49
SQL * PlusW orksheet 51
SQL * Plus 54 Sample D atabases 56
Constraints 72
D ropping a Table 89
Renaming a Table 89
Truncating a Table 89
Oracle’sV ariousTable Types 90
Spooling 90
E rr or Codes 91
I n a Nutshell Á 93 E xercise
Questions 94
Lab Activity 96
Sorting 122
Revisiting Substitution V ariables 125
D E F I N E C ommand 126
C A SE Structure 127 I n a Nutshell Á
128
Exercise Questions 129
Lab Activity 130
I n a Nutshell Á 153
Exercise Questions 153
Lab Activity 154
Join 157
Contents ix
I n a Nutshell Á 171
Exercise Questions 171
Lab Activity 172
Subquery 174
M E R G E Statement 185
Correlated Subquery 185
I n a Nutshell Á 188
Exercise Questions 189
Lab Activity 189
V iews 191
Sequences 196
Synonyms 200
Index 201
R OW I D Pseudocolumn 203
Transactions 204
I n a Nutshell Á 212
Exercise Questions 212
Lab Activity 213
x Contents
E
W
Contents xi
I n a Nutshell Á 241
Exercise Questions 242
Lab Activity 243
I n a Nutshell Á 264
Exercise Questions 265
Lab Activity 266
Cursors 268
SE L E C T Á F O R U PD A TE Cursor 276
W H E R E C U R R E NT O F Clause 277
Cursor with Parameters 277
Cursor Variables: A n Introduction 279
Exceptions 280
Contents xiii
I n a Nutshell Á 309
Exercise Questions 311
Lab Activity 311
Procedures 314
Functions 319
xiv Contents
Packages 323
Triggers 328
Installation 374
Connecting to the Oracle9i D atabase 375 I nstance and
D atabase 377
Working with Oracle Enterprise Manager (O E M ) 378
*
*
SQL * Plus Editing Commands 416 SQL * Plus File-
Related Commands 416
A n Object 417
SQL Queries for Objects 418
Similarly, the instructor retains the flexibility to design customized exercises that
combine one, several, or all the standardized operations discussed in lectures on rela-
tional theory. In addition, Oracle’s ease of use allows the instructor to concentrate on
the purpose of the course rather than on how to utilize the R D B M S software.
C omputer science has never been one of the “ pure” sciences, concerned solely
with theoretical constructs. Like engineering, its concern and preparation are direct-
ly and fully aimed at the practical application of knowledge. I n today’s economy, a
comprehensive grasp of database design, use, and implementation is a basic skill re-
quired of I T professionals, and as an educator and CIO, it is my opinion that any uni-
versity course or professional training seminar focusing on database concepts that
does not also provide the student with at least an introduction to Oracle is deficient.
Nilesh Shah’s includes everything that both the
educator seeking to present essential database concepts and the student wishing to
learn Oracle, either in a guided classroom or an independent study approach, would
need. I t is organized so that the beginner is presented with enough background to
quickly progress to a functional mastery of the more complex material, and the pro-
gression of topics and degree of coverage are comprehensive enough to meet the
needs of the demanding professional. In recognition of the necessity to go beyond
theory, numerous hands-on exercises are included, and examples are given of fea-
tures, such as W eb interfaces to Oracle tables, from Oracle’s most recent versions.
For those of you who are first entering the world of RD BMS, the Shah text is
a reliable vehicle that will assist you in meeting your objectives and assure that you
finish with confidence in your ability.
To the database professional, the Shah text will give you a reference and guide
that you will use frequently.
To the university professor or professional trainer, the Shah text has given you
a uniquely flexible educational tool. W ith it, you can develop, plan, and implement
your course in a manner that will give your students the necessary academic under-
standing of core database concepts while simultaneously teaching them a hugely
marketable skill within the computer industry.
As a professor of computer science at Monroe College as well as that college’s
Senior Systems Analyst, Nilesh Shah has demonstrated the dual abilities of fully com-
prehending the broad range of complexities involved in database management as well
as the gift of presenting complex subject matter in an easily understandable format. To
the reader’s benefit, these abilities come across clearly in the text before you.
This new and expanded edition provides even greater depth of instruction in the
use of those elements that have resulted in the Oracle’s huge popularity. A dditionally,
it adeptly covers a range of Oracle’s newest features and capabilities. Few texts can
genuinely be considered both a useful learning and reference tool for the experienced
professional as well as a comprehensive and understandable introduction for the data-
base beginner. W ith this text, D r. Shah appears to have achieved that difficult union.
Rarely does a text come along in the IT field that effectively blends the theoretical
framework of a topic with its practical application. E ither a text focuses on purely
theoretical concepts that leave students lacking in real-world application, or it cov-
ers the “how-to” of a tool without stressing the theoretical foundation so important
to the students’ ultimate mastery of the tool.
I n the field of relational database management systems (R D B MS), one book
stands out in its ability to blend theory and application. That book is Nilesh Shah’s
. This book covers key foundational concepts, such as
the relational database model, entity–relationship modeling, relationship types, ex-
posure to both relational algebra and relational calculus concepts, and normaliza-
tion. This text also effectively provides the necessary application to creating,
maintaining, and querying a database through the Structured Query Language
(SQL). Professor Shah’s book provides students with thorough examples, tables of
key commands and functions, data types and their uses, as well as other key infor-
mation. The appendices provide a good reference for novices and experienced users
alike in regards to SQL syntax.
This second edition also provides more extensive coverage of topics that relate
to the Oracle9i database environment. Two new topics have been introduced: em-
bedded SQL , and Java/Oracle connectivity through Java D atabase Connectivity
(JD B C ) and SQLj. A new chapter that addresses nested queries has also been
added, as well as an appendix that introduces object relational database manage-
ment systems (OR D B MS). I n addition, the treatment of various topics has been en-
hanced since the last edition, particularly in the area of PL/SQL.
Professor Shah’s teaching style is particularly well received by his students be-
cause of his effective ability to tak e complex ideas and present them in an under-
standable manner. His book has been designed in this same style. His explanations
are clear, concise, and presented in a way that even the most inexperienced database
user can understand. This is further evidenced by the “ I n a Nutshell Á ” section of
each chapter, which succinctly presents each key concept in a series of bullet points.
Similar to his classroom environment, Prof. Shah has also incorporated activi-
ties that are crucial to the students’ application of the material. Each chapter con-
tains lab activities that allow each student to apply the concepts covered in the
Foreword xxi
Oracle 9i database environment, thus giving each student practice in using those
skills that are in demand in the workplace today.
As an educator, one is not concerned solely if a teacher is teaching but, rather, if
the students are learning. Professor Shah is consistently interested in the progress of
his students, which is evident in this book. A s a user of this book, I am sure you also
will find it to be a contributor to your success in your database coursework.
THE READER
The Relational D atabase Management System (RD BM S) is the most popular data-
base model today. Oracle Corporation has established the Oracle database product
as the prime database package in the world. Structured Query Language (SQL) is
the universal query language for relational databases. Programming Language ex-
tension to SQL (PL/SQL ), an Oracle extension to SQL, brings all the benefits and
capabilities of a high-level programming language to the database environment.
This book is designed for use as a primary text in a database course at the col-
lege level or as a self-study guide for the information systems or business profes-
sional. With its in- depth coverage of relational database concepts, SQL* (Oracle’s
version of SQL), and PL/SQL , the text serves as an introductory guide as well as a
future reference resource. The proper term for Oracle SQL is SQL* , but throughout
this text, the term Oracle SQL is simply referred to as SQL. The text can be used in
a course that concentrates on database design and utilizes SQL to complement it. I t
also makes a perfect textbook with which to teach SQL only. A nother use of this
book is for an advanced database management system course, in which more ad-
vanced features of SQL, PL/SQL , connectivity through Java, and database adminis-
tration are emphasized. I n a classroom environment, it is not possible to cover all 16
chapters in one semester. A t our campus, we cover Chapters 1 through 9 in the in-
troductory database systems course. I n the advanced database course, the SQL por-
tion is reviewed, and then Chapters 10 through 16 are covered. The book serves as a
great resource to expand on the topics learned in the classroom.
THE TEXT
The second edition contains more examples, added screen shots, a new chapter on Java
with Oracle, new SQL and PL /SQL topics/statements (e.g., ME R G E, INSE RT ALL,
INSERT FIRST, correlated subqueries, CASE, Searched CA SE, and I NSTE A D OF
trigger), and more built- in functions. The first part of the book provides adequate
Preface xxiii
THE SOFTWARE
Oracle comes in many flavors. A t your business or college laboratory, Oracle might
be implemented in a W indows, U nix, Linux, Solaris, or Novell Netware environ-
ment. The version of Oracle might vary from 8 to 8i to 9i. The beauty of this text is
its versatility. The SQL and PL /SQL features covered here work with all versions,
and the exceptions are pointed out in the individual topics wherever necessary.
The reader is advised to join the Oracle Technology Network (OTN ) at
. O ne of the benefits of being a registered OTN user is access to
free downloads of Enterprise and a personal version of Oracle9i software. Oracle
support, however, is not free!
This text is designed for sequential reading from Chapter 1 through Chapter 16. I f you
are familiar with relational database concepts, you may skip the first two chapters.
xxiv Preface
From my personal experience with students, Chapter 2, on data modeling and nor-
malization, helps students tremendously in designing effective databases. Y ou will
need access to a computer system to practice SQL statements and PL/SQL pro-
grams from Chapters 3 through 14. The fourth part of the text contains material on
the architecture and administration of Oracle and on creating Java applications/ap-
plets with connectivity to an Oracle database. Many popular SQL* Plus commands
are also covered in Appendix C. A ppendix E details what is new in 9i SQL and
PL/SQL. The reader must perform exercise questions and labs at the end of each
chapter before moving on to the next chapter. W hether a programming language is
procedural or nonprocedural, you cannot learn it just by reading about it. You need
to practice to master the material.
ACKNOWLEDGMENTS
I would like to thank K ate Hargett and her staff for their support in publishing this
text. I t is my pleasure to work with a prestigious publishing company such as Pren-
tice Hall. I thank Petra Recter for her help and guidance with the first edition. G ood
luck with your new position, Petra!
I am also grateful to my employers— D eV ry University, North Brunswick,
New Jersey; and Monroe College, Bronx, New Y ork. I would like to mention three
individuals in particular: D ean Bhupinder Sran at D eV ry, who asked me to write my
first book when we could not find a suitable text for our database systems course;
Dr. A lex E phrem at Monroe, who supported and encouraged me throughout the
text’s development process (D r. Ephrem has the Japanese-language copy of this text
on his desk as an exhibit! ); and John Weber, D ean of Information Systems at D eVry,
for taking the time to write an excellent foreword for the text.
I would like to thank all my students, past and present, for being themselves.
Without my students, I would not be in a position to write a book. Their enthusiasm
in the classroom, respect toward me, and desire to learn inspired me to take up this
project. I would like to single out two students at D eV ry; James McClaran, for cre-
ating E R D for the sample databases used in this text, and Heillyn V iquez, for retyp-
ing almost 200 coding examples from existing screenshots.
I also thank all the reviewers, especially Richard J. Staron, for their honest
comments, which enabled me to address deficiencies of the first edition and to cre-
ate a better text.
Finally, I would like to thank my family for their understanding and patience
during the entire process: my 12- year-old son, Naman, an honor student and an ex-
cellent basketball player, who possesses the first copy of my book; my 6- year-old
son, Navan, a login helper, who wants to move to Philadelphia after the book is fin-
ished so he can watch Allen I verson play basketball everyday; my wife, Prena, for
putting up with me; and last but not least, my parents, Dhiraj and Hansa, for the sac-
rifice they have made in their life by sending their only son to the U nited States for
a better future.
N I L ESH SHA H
PAR T 1
DATABAS
E
CONCEPT
S
INTHISCHAPTER . . .
DATABASE: AN INTRODUCTION
● E ach entity can be described by its characteristics, which are known as att-
r ibutes. For example, some of the likely attributes for a college student are
student identification number, last name, first name, phone number, Social
Security number, gender, birthdate, and so on.
● All the related entities are collected together to form an entity set. A n enti- ty
set is given a singular name. For example, the STU D E N T entity set con- tains
data about students only. A ll related entities in the STU D E N T entity set are
students. Similarly, a company keeps track of all its employees in an entity set
called EM PL OY E E . The E M PL O Y E E entity set does not contain information
about the company’s customers, because it wouldn’t make any sense.
● A database is a collection of entity sets. For example, a college’s database
may include information about entities such as student, faculty, course, term,
course section, building, registration information, and so on.
● The entities in a database are likely to interact with other entities. The inter-
actions between the entity sets are called r elationships. The interactions are
described using active verbs. For example, a student a course section
(CR SSEC TI ON), so the relationship between STU D E NT and CRSSEC-
TI ON is . A faculty member in a building, so the relationship
between FACU LTY and B U I L D I NG is .
RELATIONSHIPS
The database design requires you to create entity sets, each describing a set of re-
lated entities. The design also requires you to establish all the relationships be-
tween the entity sets within the database. The different database management
software packages handle the creation and use of relationships in different man-
ners. Depending on the type of interaction, the relationships are classified into
three categories:
1. Does an entity in entity set have more than one matching entity in enti- ty
set ?
2. Does an entity in entity set have more than one matching entity in enti- ty
set ?
The database system consists of the following components (see Fig. 1- 1):
DBMS
transform data managed by the D BMS. The database system is utilized as a deci-
sion- making system and is also referred to as an information system (I S).
A D BMS based on the relational model is also known as a Relational Data-
base Management System (RD BM S). A n R D B MS not only manages data but is
also responsible for other important functions:
The need for data is always present. I n the computer age, the need to represent data
in an easy-to-understand, logical form has led to many different models, such as the
relational model, the hierarchical model, the network model, and the object model.
Because of its simplicity in design and ease in retrieval of data, the relational data-
base model has been very popular, especially in the personal computer environment.
E. F. C odd developed the relational database model in 1970. The model is
based on mathematical set theory, and it uses a r elation as the building block of the
database. The relation is represented by a two- dimensional, flat structure known as
a table. The user does not have to know the mathematical details or the physical as-
pects of the data, but the user views the data in a logical, two- dimensional structure.
The database system that manages a relational database environment is known as a
Relational D atabase Management System ( RD B MS). Some of the popular rela-
tional database systems are Oracle9i by Oracle Corporation, Microsoft A ccess 2000,
and Microsoft V isual Fox Pro 6.0.
A table is a matrix of rows and columns in which each row represents an entity
and each column represents an attribute. I n other words, a table represents an entity
set as per database theory, and it represents a relation as per relational database the-
ory. In daily practice, the terms , and are used interchangeably.
Figure 1- 2 shows six relational tables— PROJ2002, PROJ2003, PRJPA RTS,
PA RTS, DE PA RTMENT, and E M PL OY EE . PROJ2002 has three columns and five
entities. PROJ2003 contains three columns and four entities. PRJPA RTS has three
columns and five entities. I n relational terminology, a row is also referred to as a
tuple. I t rhymes with couple. I n a relational database, it is easy to establish relation-
ships between tables. For example, it is possible to find the name of the vendor who
supplies parts for a project.
E ach column in a relation or a table corresponds to a column of the relation,
and each row corresponds to an entity. The number of columns in a table is called
the degr ee of the relation. For example, if a table has four columns, then the table is
of degree 4.
I t is assumed that there is no predefined order to rows of a table and that no
two rows have the exact same set of values. The order of columns is also immaterial,
but correct order is used in the illustrations.
The set of all possible values that a column may have is called the domain of
that column. Two domains are the same only if they have the same meaning and use.
ProjNo, PartNo, DeptNo, and E mpN o are columns with numeric values, but their
domains are different.
6 Chap. 1 Database Concepts: A Relational Approach
PROJ2002
PRJPARTS
EMPLOYEE
Terms like tuple and degree are used here because they are relational data-
base terms, but in reality, these terms are not used in workplace.
Figure 1-3 shows a simple comparison between terminology used in relational
databases and file systems. Many times, terms are borrowed from the file system for
the relational field, and vice versa.
The Relational Database Model 7
A key is a minimal set of columns used to uniquely define any row in a table. If
a single column can be used to describe each row, there is no need to use two columns
as a key. For example, in PROJ2002, ProjNo uniquely defines each row, and in
PA RTS, PartNo uniquely defines each row. I n PRJPA RTS, none of the columns de-
fines each row uniquely by itself. The column ProjNo is not unique, and PartNo is
not unique either. I n such a table, a combination of columns can be used as a key.
For example, ProjNo and PartNo together make a key for PRJPARTS table. W hen
a single column is used as a unique identifier, it is known as a pr imar y key. W hen a
combination of columns is used as a unique identifier, it is known as a composite pr i-
mar y k ey or, simply, as a composite key.
Sometimes, a more human approach is used to identify or retrieve a row from
a table because it is not possible to remember primary key values such as the em-
ployee number, part number, department number, and so on. For example, a ven-
dor’s name, an employee’s last name, a book’s title, or an author’s name can be used
for the data retrieval. Such a key is known as a secondar y key.
If none of the columns is a candidate for the primary key in a table, sometimes
database designers use an extra column as a primary key instead of using a compos-
ite key. Such a key is known as a surr ogate key. For example, columns such as cus-
tomer identification number, term identification number, or vendor number can be
added in a table to describe a customer, term, or vendor, respectively.
I n a relational database, tables are related to each other through a common
column. A column in a table that references a column in another table is known as a
for eign key. For example, the PartNo column in PRJPARTS is a foreign key column
that references the PartNo column in PARTS.
Figure 1-4 shows typical illustrations showing the notation used for tables in a
relational database. The table name is followed by a list of columns within parenthe-
ses. The primary key or composite primary key columns are underlined. I n Oracle,
the primary key, composite key, or surrogate key is defined as a primary key only,
and a foreign key in a table can reference a primary key column only.
Oracle uses key words PR I M A R Y K E Y to define a primary, composite, or
surrogate key. I n Oracle tables, only primary and foreign keys are defined. Sec-
ondary key is not part of Oracle’s table structure, but it is a column used in search
operations. Later, you will learn to use Oracle’s D ata Dictionary to find table keys
and other table information.
INTEGRITYRULES
I n any database managed by an RD BMS, it is very important that the data in the un-
derlying tables be consistent. If consistency is compromised, the data are not usable.
This need led the pioneers of database field to formulate two integrity rules:
THEORETICALRELATIONAL LANGUAGES
E. F. C odd suggested two theoretical relational languages to use with the relational
model:
a procedural language.
a nonprocedural language.
Third- generation high- level compiler languages can be used to manipulate data
in a table, but they can only work with one row at a time. In contrast, the relational
languages can work on the entire table or on a group of rows. The multiple-row
Theoretical Relational Languages 9
manipulation does not even need a looping structure! The relational languages pro-
vide more power with a very little coding. Codd proposed these languages to embed
them in other host languages for more processing capability and more sophisticated
application development. In the database systems available today, nonprocedural
Structured Query Language (SQL ) is used as a data-manipulation sublanguage. The
theoretical languages have provided the basis for SQL.
Relational Algebra
1. Union.
2. Intersection.
3. Difference.
4. Projection.
5. Selection.
6. Product.
7. Assignment.
8. Join.
9. Division.
Union. The union of two tables results in retrieval of all rows that are in
one or both tables. The duplicate rows are eliminated from the resulting table. The
resulting table does not contain two rows with identical data values. There is a basic
requirement to perform a union operation on two tables:
TABLE_A
TABLE_B
Difference. The difference of two tables produces a table with rows that are
present in the first table but not in the second table. The difference can be per-
formed on union-compatible tables only.
I f we find the difference 1 - 2 of the same two tables used in the previ ous oper-
ations and create TA B L E _C, it will have projects for the year 2002 that are not proj-
ects for the year 2003:
PartDesc Cost
Nut 19.95
Bolt 5.00
Washer 55.99
TABLE_F
The resulting table has the same number of columns as the original table but
fewer rows. The rows that satisfy the given condition are returned.
. rows. I f the first table has columns and the second table has columns, the
resulting product has + columns.
For simplicity, let us tak e two tables with one column each and perform the
product 1 . 2 operation on them:
DEPARTMENT
DeptName
Production
Supplies
Marketing
EMPLOYEE
Ename
Carter
Albert
TABLE_G
Ename DeptName
Carter Production
Carter Supplies
Carter Marketing
Albert Production
Albert Supplies
Albert Marketing
Join. The join is one of the most important operations because of its ability to
get related data from a number of tables. The join is based on common set of val- ues,
which does not have to have the same name in both tables but does have to have
the same domain in both tables. When a join is based on equality of value, it is
Theoretical Relational Languages 13
known as a natural join. I n Oracle, you will learn about the natural join, or equij oin,
and also about other types of joins, such as outer j oin, nonequij oin, and self-j oin,
that are based on the operators other than the equality operator.
For example, if we are interested in employee information along with depart-
ment information, a join can be carried out using the E MPL OY E E and D EPA R T-
ME N T tables shown in Figure 1.2. The D eptNo column is the common column in
both tables and will be used for the join condition:
TABLE_H = join (EMPLOYEE, DEPARTMENT : DeptNo = DeptNo)
TABLE_H
ProjNo
1
2
3
PRJPARTS
ProjNo PartNo
1 11
2 33
3 11
1 22
2 11
14 Chap. 1 Database Concepts: A Relational Approach
Suppose we want to find out which parts are used in every project. W e have to
divide (/) PRJPARTS by PROJ:
TABLE_I= PRJPARTS/ PROJTABLE_I
PartNo
11
The columns of TA B L E_ I are those from the dividend PRJPARTS that are
not in the divisor PROJ. The rows of TA B L E_ I are a subset of the projection PRJ-
PA RTS (PartNo). The row (PartNo) is in TA BL E _I if and only if (ProjNo, PartNo)
is in the dividend PRJPARTS for every value of (ProjNo) in the divisor PROJ.
Summary. The nine operations provide users with a sufficient set of opera-
tions to work with the relational databases. Some of the operations are combina-
tions of other operations, as we saw in the case of the join operation, but such
operations are very useful in actual practice. I n later chapters on Oracle, you will
find the actual query statements used to accomplish the different operations out-
lined here. Y ou will learn to perform these operations using Oracle’s SQL.
Alternative solution
I n these solutions, Table C will have one entry, an employee who works
on project 1 in Miami. Relational algebra is called a procedural language, because a
user has to perform a series of operations to achieve the desired result.
Theoretical Relational Languages 15
Pr oblem 2
Referring to the tables in Figure 1.2, who has supplied parts for the project in Trenton?
Solution
D = PROJ2002 U PROJ2003
E = Sel(D: Loc = ‘Trenton’)
F=join(E, PRJPARTS :ProjNo = ProjNo) G =join(F,PARTS : PartNo = PartNo)
H = G(Vendor)
The solution uses four tables from the database. First, the union operation is
performed to put all projects together. Then, the selection operation is performed to
find all rows for projects in Trenton. Next, the result is joined with the PRJPARTS
table to merge part number with project information. Then, the PA RTS table is
merged with the resulting table to get part–vendor information. A t last, the name of
the vendor is retrieved using projection, which returns .
The solutions illustrated here show a fundamental weakness in relational alge-
bra as a programming language. For users who have not come across problems like
these before, the solutions are difficult to develop and comprehend. Relational alge-
bra cannot group related information together. Neither can it perform calculations
on numeric values or sort rows in any particular order. Printing information with
formatting is out of the question! The actual implementation of relational languages
is an integral part of fourth-generation query languages. These languages are sup-
ported by many other tools, which provide users with full application- development
capabilities.
Relational Calculus
in PRJPARTS is examined using the condition to the right of the colon. The resulting
table will contain project numbers 1, 3, and 2:
ProjNo
1
3
2
The solution for the same problem in relational algebra would look like this:
Problem 4
Referring to the tables in Figure 1.2, find employee names and salary for employees
who work in Production.
Solution
RESULT
Ename Salary
Carter 25000
Barker 75000
Problem 5
Referring to the tables in Figure 1.2, find employee names, department names, and
locations for projects in the year 2003 for all employees who are working on project 1.
Solution
RESULT
The theoretical relational languages discussed in this chapter are the basis for
the commercially available relational languages. SQL is a nonprocedural query lan-
guage based on relational calculus that is supported by many relational database
systems.
Final Note
INA NUTSHELL. . .
EXERCISE QUESTIONS
does not do the job. Many proven modeling and design tools are available for a bet-
ter database design. I n this chapter, you will learn about different pictorial methods,
techniques, and concepts to create a “near-perfect” database.
DATA MODELING
EMPLO Y EE
manages
1:1
employs
1:M
contains
M:N
The types of relationships (1:1, 1:M, and M:N) between entities are called conn-
ectivity or multiplicity. The connectivity is shown with vertical or angled lines next to
each entity, as shown in Figure 2-2. For example, an EM PL OY E E supervises a D E-
PA RTMENT, and a D EPARTMENT has one EM PL OY E E supervisor. A D IVI SION
contains many FACU LTY members, but a FA CU LTY works for one D IV ISION. A n
I NV OI CE contains many I TEMs, and an I TE M can be in more than one INVOICE.
L et us put everything together and represent these scenarios with the E - R dia-
gram. Figure 2- 3 shows entities, relationships, and connectivity.
The relationship between two entities can be given using the lower and upper
limits. This information is called the car dinality. The cardinality is written next to
each entity in the form where is the minimum number and is the maxi-
mum number. For example, (1,1) next to E M PL O Y E E means that an employee can
supervise a minimum of one and a maximum of one department. Similarly, (1,1)
next to D E PA R TM EN T says that one and only one employee supervises the de-
partment. The value (1,N) means a minimum of one and a maximum equal to any
number (see Fig. 2-4). Some modern tools do not show cardinality in an E- R diagram.
supervises
EMPLO Y EE DEPA RTMEN T
employs
DIVISION FACULTY
contains
IN VOICE ITEM
supervises
EMPLO Y EE DEPA RTMEN T
(1,1) (1,1)
employs
DIVISION FACULTY
(1,N) (1,1)
contains
IN VOICE ITEM
(1,N) (1,N)
In reality, corporations set rules for the minimum and maximum values for cardinality.
A corporation may decide that a department must have a minimum of 10 employees
and a maximum of 25 employees, which results in cardinality of (10, 25). A college
decides that a computer- science course section must have at minimum 5 students to
recover the cost incurred and at maximum 35 students, because the computer lab
contains only 35 terminals. A n employee can be part of zero or more than one depart-
ment, and an item may not be in any invoice! These types of decisions are known as
business rules.
Figure 2-4 shows the E - R diagram with added cardinality. In real life, it is possi-
ble to have an entity that is not related to another entity at all times. The relationship
becomes optional in such a case. I n the example of a video rental store, a customer
can rent video movies. In this case, there are times when the customer has not rented
any movie, and there are times when the customer has rented one or more movies.
Similarly, there can be a movie in the database that is or is not rented at a particular
time. These are called optional relationships and are shown with a small circle next to
the optional entity (see Fig. 2-5). The optional relationship can occur in 1:1, 1:M, or
M:N relationships, and it can occur on one or both sides of the relationship.
rents
CU STO MER VI DEO
(0,N) (0,N)
has is a
IN VOICE INVITEM ITEM
entity has a composite primary key with two columns, each of them being foreign
keys referencing the other two entities in the database. For example, the foreign key
I N V OI CE N O in the I N V I TE M table references the I N V OI CE N O column in the
I N V OI CE table, and the foreign key I TE M NO in the I NV I TE M table references
the I TE M NO column in the I TE M table.
I n a database, there are entities that cannot exist by themselves. Such entities
are known as weak entities. I n Chapter 3, you will be introduced to two different
sample databases. I n the employee database of that chapter, there is an entity called
E M PL OY E E with employees’ demographic information and another entity called
D E PE N D E N T with information about each employee’s dependents. The D E PE N-
D E NT entity cannot exist by itself. There are no dependents for an employee who
does not exist. I n other words, you need the existence of an employee for his or her
dependent to exist in the database. The weak entities are shown by double-lined rec-
tangles (see Fig. 2-7).
has
EMPLO Y EE DE PEN DE NT
(0,N) (1,1)
● Simple attr ibutes— attributes that cannot be subdivided; for example, last
name, city, or gender.
● C omposite attributes— attributes that can be subdivided, into atomic form;
for example, a full name can be subdivided into the last name, first name,
and middle initial.
● Single- valued attr ibutes— attributes with a single value; for example, Em-
ployee ID , Social Security number, or date of birth.
● M ultivalued attributes— attributes with multiple values; for example, degree
codes or course registration. The multivalued attributes have to be given
special consideration. They can be entered into one attribute with a value
separator mark, or they can be entered in separate attributes with names
like Course1, Course2, Course3, and so on. A lternatively, a separate, com-
posite entity can be created.
DEPENDENCY
I n C hapter 1, you learned that the primary key in a table identifies an entity. Every
table in the database should have a primary key, which uniquely identifies an entity.
For example, PartNo is a primary key in the PA RTS table, and D eptN o is a primary
key in the D E PA RTM EN T table. I n Oracle, if you create a table and do not define
Dependency 25
its primary key, Oracle does not consider it to be an error. You should define a pri-
mary key for all tables for integrity of data. Each table has other columns that do
not mak e up the primary key for the table. Such columns are called the nonkey
columns. The nonkey columns are functionally dependent on the primary key col-
umn. For example, PartD esc and Cost in the PA RTS table are dependent on the pri-
mary key PartNo, and D eptName is dependent on the primary key D eptN o in the
D EPA R TM E NT table.
Now, let us take a scenario as shown in Figure 2-8. The I NV O I C E table in
Figure 2- 8 does not have any single column that can uniquely identify an entity. The
first choice would be I nvNo. I t is not a unique value in the table, however, because
an invoice may contain more than one item and there may be more than one entry
for an invoice. CustNo cannot be the primary key, because there can be many in-
voices for a customer and CustNo does not identify an invoice. ItemNo cannot be
the primary key either, because an item may appear in more than one invoice and
I temNo does not describe an invoice. The table has a composite primary key, which
consists of InvNo and ItemNo. I nvNo and ItemNo together make up unique values
for each row. All other columns that do not constitute the primary key are nonkey
columns, and they are dependent on the primary key.
INVOICE
are not dependent on the InvNo column. Similarly, the nonkey column I nvD ate is
dependent only on I nvNo. They are on the primary key columns.
The nonkey column CustName is not dependent on any primary key column but is
dependent on another nonkey column, CustNo. I t is said to have
. The nonkey column Qty is dependent on both InvNo and I temNo, so it is said
to have .
DATABASE DESIGN
NORMAL FORMS
In Figure 2-8, data are repeated from row to row. For example, I nvD ate, CustNo, and
CustName are repeated for same InvNo. The ItemName is entered repeatedly from
invoice to invoice. There is a large amount of redundant data in a table with just eight
rows! R edundant data can pose a huge problem in databases. First of all, someone
has to enter the same data repeatedly. Second, if a change is made in one piece of the
data, the change has to be made in many places. For example, if customer Starks
changes his or her name to Starks- Johnson, you would go to the individual row in IN-
V O I C E and make that change. The redundancy may also lead to anomalies.
Anomalies
is created for a customer with that new item. A n can occur if the
item price changes to a new price. The price change is valid after the change date,
but not before the change date.
U nnecessary and unwanted redundancy and anomalies are not appropriate in
databases. Such tables are in lower normal form. Normalization is a technique to re-
duce redundancy. I t is a decomposition process to split tables. The splitting is per-
formed carefully so that no information is lost. The higher the normal form is, the
lower the redundancy. The table in Figure 2-8 is in first normal form (1NF).
A table is said to be in first normal form, or can be labeled 1NF, if the following con-
ditions exist:
● The primary key is defined. This includes a composite key if a single column
cannot be used as a primary key. I n our I N V OI CE table, InvNo and ItemId
are defined as the composite primary key components.
● A ll nonkey columns show functional dependency on the primary key compo-
nents. If you know the invoice number and the item number, you can find out
the invoice date, customer number and name, item name and price, and quan-
tity ordered. For example, if InvNo = 1001 and I temNo = 5 are known, then
I nv D ate = 04/14/03, I temName = W asher, ItemPrice = $1.99, CustNo =
212, and CustName = Starks.
● The table contains no multivalued columns. I n a single- valued column, the
intersection of a row and a column returns only one value. I n a normalized
table, the intersection of a row and a column is a single value. Some database
packages, such as U ni data and Prime I nformation, allow multiple values in a
column in a row, but Oracle does not. Figure 2-9 shows the I N V OI CE table of
Figure 2-8 in unnormalized form. I n Figure 2-9, the I temNo, I temName,
ItemPrice, and Qty columns are multivalued.
INVOICE
A table that is in 1NF may have redundant data. A table in 1NF does not show
data consistency and integrity in the long run. The normalization technique is used to
control and reduce redundancy and to bring the table to a higher normal form.
A table is said to be in third normal form, or 3NF, if the following requirements are
satisfied:
A table that has transitive dependency is not in 3NF, but it needs to be decom-
posed further to achieve 3NF. However, a table in 2NF that does not contain any
transitive dependency does not need any further decomposition and is automatical- ly
in 3NF.
Other, higher normal forms are defined in some database texts. Boyce–Codd
normal form (BCNF), fourth normal form (4NF), fifth normal form (5NF), and do-
main key normal form (D K NF) are not covered in this text. I n the following section,
you will learn the normalization process by using dependency diagrams.
DEPENDENCYDIAGRAMS
A dependency diagram is used to show total (full), partial, and transitive dependen-
cies in a table:
● The primary key components are highlighted. They are in bold letters and in
boxes with a dark er border. The primary key components are connected to
each other using a bracket.
● The total and functional dependencies are shown with arrows drawn above
the boxes.
Dependency Diagrams 29
● The partial and transitive dependencies are shown with arrows at the bottom of
the diagram.
W e see in Figure 2-10 that a composite key is in the table and 1NF-to- 2NF conver-
sion is required. I n this conversion, you remove all partial dependencies:
● First, write each primary key component on a separate line, because they will
become primary keys in two new tables. ( If a primary key component
does not have partial dependency on it, there is no need to write it on a sepa-
rate line. In other words, you don’t create a new table with that primary key.)
● W rite the composite key on the third line. I t will be the composite key in the
third table.
Transitive Dependency
Figure 2-11 shows the decomposition of one table in 1NF into three tables in 2NF.
The reason behind the decomposition is moving columns with partial dependency to the
new table along with the primary key. If only one of the two primary key columns has non-
key columns dependent on it, you will create only one new table to remove the partial de-
pendency.The InvNo, CustNo, and CustName columnswill move to the I NV OI CE table,
ITEM INVITEMItemNo
InvNo ItemNo
because they are partially dependent on InvNo. I temName and I temPrice will move to
the ITEM table, because they are partially dependent on I temNo in Figure 2-10.The Qty
column stays in INV ITEM, because it is totally dependent on the composite key. The
database will look like the one shown in Figure 2-12.
The database tables in 2NF (see Fig. 2- 12) have no partial dependency, but the IN-
V O I C E table still has transitive dependency:
I n Figure 2-13, you see the decomposition from 2NF to 3NF to remove transi-
tive dependency. A new C U STOM E R table is created with CustNo as its primary
key. The CustNo column is kept in the I NV OI C E table as a foreign key to establish
a relationship between I NV OI C E and C U STOM E R tables. The final database in
3NF looks like the one shown in Fig. 2-14.
Dependency Diagrams 31
INVOICE InvNo
ItemNo
InvNo ItemNo
CustNo CustName
DENORMALIZATION
The normalization process splits tables into smaller tables. These tables are joined
through common columns to retrieve information from different tables. The more ta-
bles you have in a database, the more joins are needed to get the desired information. I n
a multiuser environment, it is a costly overhead, and system performance is affected.
D enormalization is the reverse process. It reduces the normal form, and it increases
data redundancy. With denormalization, the information is stored with duplicate data,
more storage is required, and anomalies and inconsistent data exist.The designer has to
weigh this against performance to come up with a good design and performance.
I n Figure 2-15, a table is shown in 1NF. The table contains a composite key that is
composed of two columns, PlayerId and Year. This table contains each player’s year- ly
statistics as well as team information. A player may belong to different teams dur- ing
different years (it is assumed that a player belongs to one team during a year).
Looking at the table, the following dependencies exist:
A new table is created with a primary key column that has partial dependency on it. A
new table is created with the PlayerId column as its primary key. The original table
stays as it is with columns showing total dependency.
A new table is created with the TeamI d column as its primary key. TeamName and
TeamLoc move to this new table. TeamI d column also stays in the previous table as a
foreign key to reference the new table.
Summary
1NF to 2NF
2NF to 3NF
GamesPlayed TeamId
INA NUTSHELL. . .
● The types of relationships (1:1, 1:M, and M:N) are called connectivity.
● The cardinality shows the lower and the upper limit of a relationship.
● All entities are not related to each other at all times. Such a relationship is
known as an optional relationship. I t can occur in 1:1, 1:M, and M:N rela-
tionships, and it can occur on one or both sides of the relationship.
● M:N relationships are complex to implement. E ach M:N relationship is de-
composed into two 1:M relationships using a third entity, known as a com-
posite entity. A composite entity has a composite primary key, which is
combination of primary keys from the other two entities.
● Simple attributes cannot be divided, but composite attributes can be subdi-
vided.
● A ttributes can be single valued or multivalued.
● All nonkey columns in a table are functionally dependent on the primary
key columns of the table.
● I n partial dependency, a nonkey column is dependent on part of the com-
posite primary key.
● I n transitive dependency, a nonkey column is dependent on another nonkey
column.
● A database design involves both synthesis and analysis. Normalization is a
process of analyzing a database created with synthesis.
● Normalization is a decomposition process to reduce data redundancy and
data anomalies.
● A database in 1NF does not have any multivalued columns.
● A database in 2NF does not have any partial dependencies.
● A database in 3NF does not have any transitive dependencies.
● Higher normal forms are also possible, and the process of denormalization is
performed on a database to weigh performance against redundancy.
EXERCISE QU ESTIONS
True/F alse:
is a term used for relationships in the E-R diagram.
2. Partial dependency can exist in a table with a simple primary key.
3. In transitive dependency, a column is dependent on the primary key.
4. Higher normal form means lower redundancy.
5. Normalization is a process of converting a database design from lower to higher normal
form.
6. A 1NF table with simple primary key is already in 2NF.
36 Chap. 2 Database Design: Data Modeling and Normalization
1. Create a dependency diagram for the set of given columns for the EM P table:
● You will learn the differences between a client/server database, such as Oracle,
and PC-based database software.
● The Oracle client/server D atabase Management System (D BMS) and its
utilities are introduced.
● The Oracle development environment SQL * Plus and its various types of
commands are covered.
● A n overview of primary language SQL (Structured Query L anguage) to
communicate with the Oracle Server is given.
● SQL * Plus W orksheet and SQL * Plus environments are introduced.
● Designs of two case study databases, a college’s student registration data-
base system and a company’s employee database system, are discussed.
PERSONAL DATABASES
Per sonal database management systems, such as Microsoft A ccess and V isual Fox
Pro, are usually stored on a user’s desktop computer system or a client computer .
These database packages are developed primarily for single-user applications. When
such a package is used for a multiuser or a shared access environment, the database
38 Chap. 3 Oracle9i: An Overview
applications and the data are stored on a file server, or a ser ver , and data are trans-
mitted to the client computers over the network (see Fig. 3-1). A server is a computer
that accepts and services requests from other computers, such as client computers. A
server also enables other computers to share resources. A server’s r esour ces could
include the server’s hard- disk drive space, application programs on a server’s hard
drive, data stored on the server’s drive, or printers. A networ k is an infrastructure of
hardware and software that enables computers to communicate with each other.
(Database files)
In a network environment with a personal D BMS, the client computer must load the
entire database application along with the client database application in its memory.
If the client requires a small piece of data from the server’s large database, the server
has to transmit the entire database to the client over the network. I n some database
packages, only part of the database is transmitted. In any case, the client computer
hardware must handle heavy demand, and the network must sustain heavy traffic in
both directions. In the network environment, the system response to various client
requests depends on the speed of the network and the amount of traffic over it.
Client/Server Databases 39
Table Locking
The personal database system assumes that no two transactions will happen at the
same time on one table, which is known as optimistic lock ing. I n optimistic locking,
the tables are not locked by the database system. If one agent sells a seat for a basket-
ball game and another agent tries to sell the same seat at the same time, the data-
base system will notify the second agent about the update on the table after his or
her read— but it will go ahead and let the second agent sell the seat anyway. A ppli-
cation programmers can write code to avoid such a situation, but that requires
added effort on programmer’s part. Personal database software does not lock tables
automatically.
Client Failure
Transaction Processing
Personal databases, such as Microsoft A ccess, do not have file-based transaction log-
ging. Instead, transactions are logged in the client’s memory. If the client fails in the
middle of a batch of transactions, some transactions are written to the database and
some are not. The tr ansaction log is lost, because it is not stored in a file. If a client
writes a check to transfer money from a savings account to a checking account, the
first transaction debits money from the savings account. Now, suppose the client
fails right after that. The checking account never gets credited with the amount be-
cause the second transaction is lost!
CLIENT/SERVER DATABASES
Client/server databases, such as Oracle, run the DBMS as a process on the server
and run a client database application on each client. The client application sends a
request for data over the network to the server. W hen the server receives the client
request, the D BMS retrieves data from the database, performs the required pro-
cessing on the data, and sends only the requested data (or query result) back to the
client over the network (see Fig. 3- 2).
40 Chap. 3 Oracle9i: An Overview
(DBMS process)
The client computer does not run the entire D BMS, only the client application that
requests data from the server. The client does not store any database on its local
drive; it receives only the requested data from the server. D ata processing is per-
formed on the server’s side. The demand at the client’s end is minimal. The clients
request data from the server, and only the requested data are sent back via the net-
work, which results in less network traffic.
Table Locking
I n a client/server system, such as Oracle, when an agent reads a table to sell a seat
for a basketball game, for example, it is locked totally or partly by the D BMS. The
second agent cannot read the part of the table with available seats. Once the first
agent sells the seat and it is marked as the lock is released for the next agent.
The DBMS takes care of the locking automatically, and it involves no extra effort on
an application programmer’s part.
Client Failure
I n case of a client failure, the client/server database is not affected. The other clients
are not affected either. Only the failed client’s transactions in progress are lost. If
Oracle9i: An Introduction 41
the server fails, a centr al tr ansaction log, which keeps a log of all current database
changes, allows the D atabase Administrator (D B A ) or D BMS to complete or roll
back unfinished transactions. The rolled- back transactions are not implemented in the
database. The D B A (or D BMS) can notify clients to resubmit rolled-back transac-
tions. Most client/server database packages have fast and powerful recovery utilities.
Transaction Processing
I f a grouped transaction or batch transaction fails in the middle, all transactions are
rolled back. The D BMS will enable the bank, for example, to make sure that both
accounts’ balances are changed if the batch transaction goes through. I f the batch
transaction fails, the balance in none of the accounts is changed.
ORACLE9i: A N INTRODUCTION
Oracle9i is a client/server DBMS that is based on the relational database model dis-
cussed in C hapter 1. Oracle9i is one of the most popular database-management soft-
ware packages available today. The Oracle Corporation, incorporated in 1986, is the
second- largest software company in the world. I ts software product line includes
Oracle9i D atabase, Oracle9i A pplication Server, Oracle9i D eveloper Suite, Oracle
Collaboration Suite, and Oracle E -Business Suite. Oracle Corporation’s revenue
was $9.475 billion in the fiscal year ending May 2003, down 2 percent from the pre-
vious year. The net income for the fiscal year was $2.4 billion. Currently, the com-
mon stock trades at more than $14, with a company market capitalization of more
than $75 billion. Oracle9i database is capable of supporting over 10,000 simultane-
ous users and a database size of up to 100 terabytes! I t is preferred to the other PC-
based R D B MS packages because its client/server database qualities, failure
handling, recovery management, administrative tools to manage users and the data-
base, object-oriented capabilities, graphical user interface ( GU I ) tools, and W eb inter-
face capabilities. I t is widely used by corporations of all sizes to develop
mission-critical applications. It is also used as a teaching tool by educational institu-
tions to teach object-relational database technology, Str uctur ed Quer y L anguage
(SQL ), PL /SQL (Oracle’s procedural language extension to SQL), and interfacing
W eb and Oracle databases. Oracle has an educational initiative program to form
partnerships with educational institutions that enable these institutions to obtain
Oracle database software at a nominal membership fee.
Oracle software is installed to work in three different environments. I n a
environment, such as a laptop or desktop that is not on a network, Oracle
Enterprise database software and SQL * Plus client software are installed on same
machine. I n a environment, a two-tier architecture with a client com-
municating with a server, Oracle Enterprise database software resides on the server
side, and SQL * Plus client software resides on the client machine. In archi-
tecture, the client communicates with the Oracle database server through a middle-
tier iSQL *Plus, an interface through a W eb browser.
42 Chap. 3 Oracle9i: An Overview
W hen a user logs in to connect to the Oracle server, SQL * Plus provides the user
with the SQ L> prompt, where the user writes queries or commands. Features of
*
SQL Plus include:
● A ccepts ad hoc entry of statements at the command line prompt (i.e., SQL 7 ).
● A ccepts SQL statements from files.
● Provides a line editor for modifying SQL queries.
● Provides environment, editor, format, execution, interaction, and file
commands.
● Formats query results, and displays reports on the screen.
● Controls environmental settings.
● A ccesses local and remote databases.
The standard query language for relational databases is SQL (Structured Query Lan-
guage). It is standardized and accepted by ANSI (A merican National Standards Insti-
tute) and the ISO (International Organization for Standardization). Structured Query
Language is a fourth-generation, high-level, nonprocedural language, unlike third-
generation compiler languages such as C, COBOL, or Visual Basic, which are proce-
dural. U sing a nonprocedural language query, a user requests data from the RDBMS.
The SQL language uses English- like commands such as C RE A TE , INSERT,
D E L E TE , U PD A TE , and DROP. The SQL language is standardized, and its syntax is
the same across most R D B MS packages. The different packages have minor vari-
ations, however, and they do support some additional commands. Oracle’s SQL is
different from the A NSI SQL . Oracle’s SQL is referred to as SQL * , but we will simply
call it SQL throughout this text. Oracle9i also supportsA NSI syntax for joining tables.
Oracle9i uses the following types of SQL statements for command-line
queries to communicate with the Oracle server from any tool or application:
● — retrieves data from the database (e.g., SELECT).
● — inserts new rows, changes existing
rows, and removes unwanted rows (e.g., I NSERT, U PD A TE , and D E L E TE ).
● — creates, changes, and removes a table’s
structure (e.g., C R E A TE , A L TE R , D ROP, R E N A M E , and TRU NC A TE).
● — manages and changes logical transactions. Transactions
are changes made to the data by D M L statements that are grouped together
(e.g., COMMIT, SAV EPOI NT, and ROLLBA CK ).
● — gives and removes rights to Oracle objects(e.
g., G R A N T and RE V OK E).
44 Chap. 3 Oracle9i: An Overview
for your password. The password typed at this prompt will be masked to maintain its
integrity (see Fig 3-5).
There are a couple of common login problems. I f you enter an incorrect user-
name or password, you will receive the following er ror message from Oracle server:
ORA-01017: invalid username/password; logon denied
If there is a connectivity issue between your client PC and Oracle or the host
string has an invalid entry, you will see the following er ror message:
ORA-12154: TNS: could not resolve service name
Oracle stores host string/service values in a file called TN SN A ME S.OR A . I f you re-
ceive a TNS error, call your D BA !
After a user logs in and the default SQL 7 prompt is displayed, the user can start
a new Oracle session. A user can enter only one SQL * Plus command at the SQL 7
prompt at a time (see Fig. 3-6). SQL * Plus commands are not stored in the buffer. I f a
command is very long, you can continue the command on the next line by using a hy-
phen at the end of the current line.
The SQL queries and SQL * Plus commands are typed at the SQL 7 prompt.
The SQL * Plus commands do not have a terminator, but SQL queries are terminated
using a semicolon (;) at the end or by typing a forward slash (/) on a new line. Figure
3- 7 shows the differences between SQL statements and SQL * Plus commands.
A user may change his or her password by using SQL * Plus command PASS-
W OR D at the SQL 7 prompt. SQL * Plus prompts user to enter the old password first,
then the new password, and then to confirm new password by retyping it (see Fig. 3-8).
I n the tables of Figures 3- 9 and 3-10, file- related (see Fig. 3-9) and editor- related
(see Fig. 3-10) commands are described. The command words are in bold letters, and
user- supplied filenames and extensions are in lowercase. The abbreviations allowed
for the SQL * Plus commands are underlined. The optional parameters are enclosed
within a pair of brackets ([ ]). Note that the filename in the file-related commands
requires entire file path.
SQL *Plus Commands 47
GET [. ] Writes previously saved file to the buffer. The default extension is
SQL. Writes SQL statements, not SQL *Plus commands.
START [. ] Runs a previously saved command from file.
@ Same as START.
EDIT Invokes the default editor (e.g., Notepad), and saves buffer contents
in a file called .
EDIT [ [. ] ] Invokes editor with the command from a saved file.
SAVE [. ]REPLACE | Saves current buffer contents to a file with the option to replace or
append.
APPEND
SPOOL[ [. ] | OFF | OUT] Stores query results in a file. OFF closes the file, and O UT sends the
file to the system printer.
EXIT Leaves SQL* Plus environment. Commits current transaction.
CO MMAND DESCRIPTION
SQL* Plus
Server
SQL*Plus
Commands Result
Formatted Report
A query typed at the prompt is loaded in to the SQL * Plus buffer. W hen the
query is sent to the server, the server processes data and sends back the result to
the client computer, which can be formatted using SQL * Plus formatting commands
(see Fig. 3-11).
Alternate TextEditors 49
I n the next chapter, you will learn to write and execute SQL statements and queries at
the SQL * Plus prompt. If you make a syntax error, Oracle will display an error
message showing the line number and the error location on that line. Oracle places an
asterisk 1*2 at the location of the error and also displays an error code (e.g., OR A -
00X XX ), followed by a brief description. Just like any programming language com-
piler, some error messages are not user friendly. You will get used to some of the
common error messages as you start experimenting. Some queries tak e up a few
lines— and for a typist like me, typing mistakes are bound to happen! The online
help screens are illustrated in the next chapter.
Some errors are easy to find; some are not. To fix an error, always start at the
line where the error is shown, but keep in mind that the er ror might not be on that
line. Check for common mistakes like misspelled keywords, missing commas, mis-
placed commas, missing parentheses, invalid user- defined names, or r epeated user-
defined identifiers. I n the next chapter, we will actually go through the entire
procedure by entering an erroneous query.
E ach Oracle product has its own specific help file. The help application opens
up a window, similar to Microsoft W indows help, where you can click on the I ndex
tab and type the error code (ORA -00X X X) of interest. Oracle provides the user
with an explanation of the cause of the error and the user action required to rectify it.
If you don’t see the Oracle Help option in the programs menu, search for the
file and open it. Y ou can also access Oracle9i Release 2 online help at the
following U R L:
http://download- west.oracle.com/docs/cd/B10501_01/mix.920/a96625/toc.htm
The U R L is working at this time, but such U R L s change frequently. A nother way
would be to go through Oracle’s home page (www.oracle.com) and search for help on
your Oracle product. Y ou are required to register to Oracle Technology Net- work
(otn.oracle.com) to access this page. Registration is free, and the member- ship
benefits include free software downloads and access to online documentation. Figure 3-
12 shows the initial Web page with Oracle9i Release 2’s master index.
SQL * Plus also provides the user with Help on its various commands and SQL
language. You may use the HE L P I ND E X command at the SQL 7 prompt to list the
SQL * Plus commands.
To obtain help on one of the topics listed in the help index, type I ND EX
[TOPI C] . For example, type HE L P D E SC R I BE as shown in Figure 3-13, and
SQL * Plus returns a brief description and syntax on the topic.
The SQL * Plus editor is a line editor similar to E D L I N in MS-D OS. I t is not fun
working with line editors. The user does not have control over the screen. Line edi-
tors do not allow a user to move the cursor up and down, and clicking with a mouse is
definitely out of the question. You can use an alternate text editor such as
50 Chap. 3 Oracle9i: An Overview
Lists the column definitions for a table, view, or synonym, or the specifications for a
function or procedure.
DESC[RIBE] {[schema.] object [@connect_identifier]} SQL>
Notepad or any other text editor in W indows to type your SQL queries. The query
typed in a full- screen text editor has to be saved in a file with an extension or
copied to the clipboard. The query can be loaded from a file or pasted from the clip-
board into SQL * Plus to execute it at the SQL 7 prompt.
The E D I T (or E D ) command can be used to invoke an alternate text editor from
the SQL * Plus command prompt. SQL * Plus allows the user to select an alternate edi-
tor, and in most cases, Windows’ popular text editor, Notepad, is the default alternate
editor. The E D I T command invokes the alternate editor with contents from the buffer
or with an existing file. The user can make necessary changes to the query and transfer
the contents back to SQL * Plus. W e will see an illustration of this in Chapter 4. A n al-
ternate editor is defined or invoked with E D I T menu in SQL * Plus. The default alter-
nate editor is Notepad for the W indows environment, but this can be changed to
another text editor of user’s choice with Á menu option (see Fig. 3-14).
The SQL * Plus W orksheet is another environment available with Oracle’s Enter-
prise Manager. The SQL * Plus Worksheet enables you to enter, edit, and execute
SQL * Plus code. Y ou can also run client-side scripts. The SQL * Plus W orksheet main-
tains a history of the commands you have issued, so you can easily retrieve and exe-
cute previous commands. You can execute SQL * Plus Worksheet by double-clicking
on the SQL * Plus W orksheet icon in the Windows desktop or by selecting the fol-
lowing from the W indows STA RT button:
START |[All] Programs |Oracle – OraHome92 |Application Development |SQLPlus
Worksheet
A n Enterprise Manager login screen is then displayed.The user logs in with user-
name, password, and host string, just like logging into SQL * Plus. O n a successful login,
the user enters the SQL * Plus Worksheet with database connection (see Fig. 3-15). On
the left side, a tool bar is displayed with connection, execute, command history, previous
command, next command, and help icons from top to bottom, respectively. The user
can select these same options from the File or Worksheet menu.
52 Chap. 3 Oracle9i: An Overview
The SQL * Plus Worksheet screen has two horizontal halves. The user issues an
SQL query or SQL * Plus command in the upper half and then clicks on the lighten-
ing- bolt icon to execute. SQL * Plus Worksheet output is displayed in the lower half
(see Fig. 3-16). During a session, the user issues many commands and statements.
U nlike SQL * Plus, SQL * Plus W orksheet keeps all commands and statements in his-
tory. The user can click on the command history icon to view them in reverse order,
with the most recent command at the top. The user can then select a command/state-
ment and click G E T to load it again and execute it.
The user may save input and output in separate files with the FI L E menu and
its options Á and Á , respectively. The input is stored in
a file with the default extension , and output is stored with the default exten- sion
.
There are a few differences between SQL * Plus and SQL * Plus W orksheet. The
following settings have been set up by Oracle Enterprise Manager SQL * Plus W ork-
sheet. I t is recommended that users do not change them:
SQL* Plus
The third environment is Web based and is called SQL * Plus. To access it through a
W eb browser, enter a U R L as follows:
http://machinename.domainname:port/isqlplus
where is the machine name. The domain name is not used, because
SQL * Plus is located in the local machine. I n the login dialog, connection identifier
(or host string) is optional if the U R L points to the correct database instance. Con-
sult your IT or lab personnel for information on server name, domain name, default
port, and database name at your installation or college. Alternately, http://localhost:
Figure 3-18 SQL * Plus work screen with query and result.
56 Chap. 3 Oracle9i: An Overview
SAMPLE DATABASES
I n this textbook, each chapter uses examples and lab activities to teach various Ora-
cle query statements and utilities by using two fictitious databases. O ne database is
developed for the I ndo–U S (I U ) College, which keeps track of students, faculty,
courses offered, and enrollment by semester. The other database is designed for the
NamanNavan (N2) Corporation, which has employee, department, dependent, and
employee-level information. These databases are designed using the normalization
techniques covered in C hapter 2. E ach database table contains appropriate data to
explain the results obtained from different query statements in the later chapters.
The I ndo–U S ( I U ) College has a computerized database system in place. They have
spent a large sum of money establishing a network infrastructure. The database-
management system that resides on their icomputer system is a unnormalized data-
base. U nnormalized databases are rare in the relational database software family.Their
main feature is multivalued fields, which is a application programmer’s nightmare. This
database does support its own version of query language, but it is not common in the
business world. I t is not easy to find Information Systems personnel with experience
using such a database system. The I U administration is fed up with the “holes” in the
system because of redundant data, bad data, and lack of data integrity. Students do not
have the ability to retrieve course information, register online, or retrieve their unofficial
transcript records using computers in the laboratory or the library. Faculty members do
not have online access to their own course information, rosters, or student information.
The college has decided to use a standard relational database management
system to overcome deficiencies of the existing system. The tables for the I U Col-
lege are illustrated in Figure 3-19, and the E - R diagram is illustrated in Figure 3- 20.
The I U student database consists of 10 tables to store student master records,
faculty master records, course master records, term-by- term course offerings, and
student registration by each term. I t also uses other supporting tables for lookup and
additional information for basic entities in the database. W ith custom programming,
the faculty and students are given online access to the system to view demographic
information, course information, unofficial transcript records, availability of course
sections by term, and so on. The faculty and student logins are created by the Infor-
mation Systems department. E ach student or faculty login name consists of the first
letter of the first name, the first three letters of the last name, and the last four digits
of the Social Security number. The Social Security number data is intentionally
omitted from the STU D E N T and FA CU LTY tables. Student and faculty members
use their Social Security numbers as passwords to access the system.
Sample Databases 57
STUDENT (StudentId, Last, First, Street, City, State, Zip, StartTerm, BirthDate, FacultyId, MajorId, Phone)
StudentId Last First Street City State Zip Start Term Birth Date FacultyId MajorId Phone
00100 Diaz Jose 1 Hill NJ 08863 WN03 02/12/83 123 100 9735551111
Ford
Avenue #7
00101 Tyler Mickey 12 Bronx NY 10468 SP03 03/18/84 555 500 7185552222
Morris
Avenue
00102 Patel Rajesh 25 Edison NJ 08837 WN03 12/12/85 111 400 7325553333
River Road
#3
00103 Rickles Deborah 100 Iselin NJ 08838 FL02 10/20/70 555 500 7325554444
Main Street
00104 Lee Brian 2845 Hope NY 11373 WN03 11/28/85 345 600 2125555555
First Lane
00105 Khan Amir 213 Clifton NJ 07222 WN03 07/07/84 222 200 2017585555
Broadway
Figur e 3-19 Sample tables for the Indo–US (IU) College database.
58 Chap. 3 Oracle9i: An Overview
CRSSECTION (CsId, CourseId, Section, TermId, FacultyId, Day, StartTime, EndTime, RoomId, MaxCount)
CsId CourseId Section TermId FacultyId Day StartTime EndTime RoomId MaxCount
1101 CIS265 01 WN03 111 MW 09:00 10:30 13 30
1102 CIS253 01 WN03 123 TR 09:00 10:30 18 40
1103 MA150 02 WN03 444 F 09:00 12:00 15 25
1104 AC101 10 WN03 345 MW 10:30 12:00 16 35
1205 CIS265 01 SP03 MW 09:00 10:30 14 35
1206 CIS265 02 SP03 111 TR 09:00 10:30 18 30
1207 LA123 05 SP03 MW 09:00 10:30 15 30
1208 CIS253 21 SP03 123 TR 09:00 10:30 14 40
1209 CIS253 11 SP03 111 MW 09:00 10:30 18 40
1210 CIS253 31 SP03 123 F TBA TBA 19 2
Figur e 3-19 Sample tables for the Indo–US (IU ) College database
M AJO R
• Primary Key COU R SE
R EGISTR ATION • Primary Key
MajorId [PK1] • Primary Key
•Non-key Attributes CourseId [PK1]
StudentId [PK1] [FK] •Non-key Attributes
MajorDesc CsId [PK2] [FK] Title
• Non-key Attributes
Has Credits
MidTerm Final
Taken by RegStatus
STUDEN T
• Primary Key
StudentId [PK1] In a Is a
Starts in
• Non-key Attributes
Last First Street
City State Zip
TER M Holds
BirthDate
Phone • Primary Key CRSSECTION
FacultyId [FK] TermId [PK1] • Primary Key
MajorId [FK] •Non-key Attributes Csid [PK1]
TermDesc •Non-key Attributes
Start Term [FK]
StartDate EndDate Section
Day StartTime
EndTime MaxCount
CourseId [FK]
TermId [FK]
Advised by
Based in
FACULTY
• Primary Key
FacultyId [PK1] LOCATIO N
•Non-key Attributes •Primary Key RoomId
Names [PK1] RoomType
Phone R oomId [FK] [PK2] [FK]
R oomType [FK] •Non-key Attributes
D eptId [FK] Building
RoomNo Capacity
Teaches in Heads
Has
D EPAR TMENT
• Primary Key
D eptId [PK1] R OO M
•Non-key Attributes • Primary Key
DeptName RoomType [PK1]
FacultyId [FK] •Non-key Attributes
RoomDesc
Two of the most important tables are CR SSE CTI O N and RE GI STRA TI ON.
These tables are related to many other tables in the database, and they grow with
each term. The C RSSE C TI ON table contains courses offered during each term. I t
uses CsI d as its primary key. The table references C OU R SE , TE RM , FA CULTY ,
Sample Databases 61
and L OC A TI O N tables with the foreign keys CourseId, TermI d, FacultyId, and
RoomI d, respectively. The table helps the college administration in flagging each
section as or based on the maximum enrollment allowed and the actu-
al current enrollment.
The R E GI STR A TI ON table contains each student’s schedule for every regis-
tration term. I t can be used for printing class rosters based on student registration
status, for obtaining midterm and final grades, and for grade point averages based
on grades obtained. The database also contains three “lookup” tables, which are
MA JO R, D EPA RTMENT, and R OO M . A lookup table is the one that contains a
numeric identification column and another column for its description.
EMPLOYEE (EmployeeId, Lname, Fname, PositionId, Supervisor, HireDate, Salary, Commission, DeptId, QualId)
EmployeeId Lname Fname PositionId Supervisor HireDate Salary Commission DeptId QualId
111 Smith John 1 04/15/60 265000 35000 10 1
246 Houston Larry 2 111 05/19/67 150000 10000 4 2
123 Roberts Sandi 2 111 12/02/91 75000 10 2
433 McCall Alex 3 543 05/10/97 66500 20 4
543 Dev Derek 2 111 03/15/95 80000 20000 20 1
200 Shaw Jinku 5 135 01/03/00 24500 3000 30
135 Garner Stanley 2 111 02/29/96 45000 5000 30 5
222 Chen Sunny 4 123 08/15/99 35000 10 3
Figur e 3-21 Sample tables for NamanNavan (N2) Corporation’s employee database.
62 Chap. 3 Oracle9i: An Overview
Figur e 3-21 Sample tables for NamanNavan (N2) Corporation’s employee database
QUALIFICATION
•Primary Key
QualId [PK1]
has
• Non-key Attributes
QualDesc
EM PLOY EE
• Primary Key EM PLEV EL
•Primary Key
EmployeeId [PK1]
has LevelNo [PK1]
•Non-key Attributes
Lname • Non-key Attributes
Fname HireDate LowSalary
Salary Commission HighSalary
Supervisor [FK]
D eptId [FK]
PositionId [FK]
QualId [FK]
works in D EPT
•Primary Key
D eptId [PK1]
manages •Non-key Attributes
DeptNames
Location
EmployeeId [FK]
has
has POSITION
• Primary Key
PositionId [PK1]
D EPEND ENT •Non-key Attributes
• Primary Key PositionDesc
DependentId [PK1]
EmployeeId [PK2] [FK]
• Non-key Attributes
D epD OB
Relation
E ach employee’s dependents for purposes of the health plan and payroll taxes
are included in the D E PE N D E N T table. This table does not have a single column
that can be used as primary key. The EmployeeI d and D ependentI d together make
up the composite primary key for the table. A ge is not used as an column, because it
64 Chap. 3 Oracle9i: An Overview
does not remain the same. A ge can be a very high maintenace column, changing
every year and for different individuals on different days. The use of D epD O B col-
umn eliminates annual maintenance. Each dependent’s age can be derived from Dep-
D O B column or birth date by using available date-related functions in Oracle.
The POSI TI O N and QU A L I FI C A TI O N tables are basically lookup tables for
the E M PL O Y E E table to get descriptions based on foreign keys in the E MPLO Y -
E E table that are primary keys in the POSI TI O N and QU A L I FI C A TI O N tables.
The E M PL OY E E, D E PE N D E N T, and D E PT tables may have more columns,
but they are omitted for simplicity. Similarly, another lookup table could have been
created to look up relations based on some RelationId column in the D E PE N-
D E N T table.
IN A NUTSHELL . . .
● FA CULTY
● C OU RSE
● CR SSEC TI ON
● R EG I STRA TI O N
● R OO M
● TE RM
● L OCA TI O N
● M A JO R
● D E PA R TM E NT
● D E PT
● POSI TI ON
● E MPLE V E L
● QU A LI FI CA TI ON
● D E PE N D E N T
E X ER C I SE Q UE STI O NS
1. How are client requests served by a server in a personal database and in a client/server
database?
2. How are transactions handled by personal and client/server databases in case of a failure?
3. W hat are the advantages of client/server databases over personal databases in a multi-
user environment?
4. Name various tools provided by the Oracle9i RDBMS.
5. W hat is SQL? What are the different types of statements a user can write using SQL in
Oracle9i?
6. W hat are the functions of the SQL *Plus environment?
7. Give two examples of database applications appropriate for a personal database system.
8. Give two examples of database applications appropriate for a client/server database system.
9. W hat are the benefits of the SQL *Plus W orksheet and SQL *Plus environments over the
SQL *Plus environment?
10. W hat login problems may be encountered while logging in to SQL *Plus?
11. Name any three SQL *Plus editing commands.
12. Name any three SQL *Plus file-related commands.
66 Chap. 3 Oracle9i: An Overview
LA B AC TI VI TY
1. Log in to Oracle Server at your installation. Locate the file on your client
computer, and double-click on it or click on
START |Programs |OraHome92 |Application Development |SQL*Plus
Ask your DBA/lab personnel/professor for your login username, password, and database
name/host string. Soon, you will get the SQL 7 prompt in the SQL * Plus environment.
2. You have not learned any query statements or SQL *Plus commands yet. Try the follow- ing
statement at the prompt as given here:
The line numbers shown on the left are generated by SQL * Plus; they are not entered by the
user. A t this point, you do not know the CRE ATE TABLE statement, naming rules, data
types, or contraints. Just copy the given statement exactly. If you type this statement without
any errors, a “Table created” message will be displayed. If you make a mistake by
misspelling a key word or by missing a punctuation mark, use SQL *Plus editing com- mands
to debug the error.
3. Invoke the default full-page editor. W hat is the default editor?
4. What is display ed in the default editor when invoked?
5. Use the following SQL *Plus command at the SQL 7 prompt:
DESCRIBE dept
( the SQL *Plus command does not end with a semicolon.) What is display ed by the
command?
6. Use the following SQL *Plus command at the SQL 7 prompt:
SHOW USER
I n the previous chapters, you learned about relational terminology, database modeling,
normalization techniques, the SQL * Plus environment, and its commands. Now is the
time to put everything together. I n Oracle9i, database tables are objects stored
under a user’s account in an allocated tablespace (storage space) on the Oracle
Server’s disk. E ach table under a user’s account must have a unique table name. In
the classroom environment, each student is a user with a unique login/username.
E ach object including a table created by a user is stored under that user’s schema. In
this and subsequent chapters, you will create and use tables for the Indo–U S (I U )
College and the NamanNavan (N2) Corporation. You will learn to create tables
using SQL statements at the SQL * Plus prompt. You will also learn to use alternate
editors for easier editing of erroneous statements.
68 Chap. 4 Oracle Tables: Data Definition Language (DDL)
NA MI N G RULES A N D CONVENTIONS
A table is an object that can store data in an Oracle database. When you create a
table, you must specify the table name, the name of each column, the data type of
each column, and the size of each column. Oracle provides you with different con-
straints to specify a primary or a composite key for the table, to define a foreign key
in a table that references a primary key in another table, to set data validation rules
for each column, to specify whether a column allows N U L L values, and to specify if
a column should have unique values only.
The table and column names can be up to 30 characters long. It is possible to
have a table name that is only one character long. I n naming tables and columns, letters
(A –Z, a–z), numbers (0–9) and special characters— $ (dollar sign), _(underscore), and
# (pound or number sign)— are allowed. The table or column name, however, must
begin with a letter. The names are not case sensitive, although Oracle stores all object
names in uppercase in its data dictionary. Spaces and hyphens are not allowed in a
table or a column name. A n Oracle server–reserved word cannot be used as a table
or a column name. Remember, the most common mistake is the use of a space in
naming a table or a column. I t is always a good practice to create short but mean-
ingful names. A lso, remember that a table name must be unique in a schema or user
account; there must not be another Oracle object with same name in a schema.
Figure 4-1 shows some valid and invalid table and column names. For invalid names,
the reasons are in parentheses.
STUDENT STUDENT_COURSE_REGISTRATION_TABLE
(more than 30 characters long)
MAJO R_CODE MA JOR CO DE (spaces not allowed)
X CRE ATE (reserved word not allowed)
PROJECT2000 PROJECT *** 2000 (special character * not allowed)
STUDENT#REG#TABLE #STUDENT (must start with a letter)
DATA TYPES
When a table is created, each column in the table is assigned a data type. A data type
specifies the type of data that will be stored in that column. By providing a data type
for a column, the wrong kinds of data are prevented from being stored in the col-
umn. For example, a name such as Smith cannot be stored in a column with a NUM-
B E R data type. Similarly, a job title such as Manager cannot be stored in a column
Data Types 69
with a D A TE data type. D ata types also help to optimize storage space. Some of the
Oracle data types are described below.
Varchar2
Char
The C H A R type is a character data type to store fixed- length alphanumeric data in
a column. The default and minimum size is one character. The maximum allowable
size is 2000 characters. (This was only 255 characters in previous versions.) I f the
value is smaller than the specified size is entered, trailing spaces are added to make
its length equal to the specified length. If the value is longer than the specified size,
an error occurs. The C HA R type is appropriate for fixed-length values. For example,
PH ON E , SOC I A L _ SE CU RI TY _N U MB E R , or MI D D L E _ I NI TI A L columns can
use the C H A R type. The phone numbers and Social Security numbers have numeric
values, but they also use special characters, such as hyphens and parentheses. Both
use fixed-length values, however, so C H A R is the most appropriate type for them.
The C H A R data type uses the storage more efficiently and processes data faster
than the V A R CH A R 2 type.
I n Oracle9i, the C H A R data type can also take C HA R or BY TE parameters.
For example, CHA R(10 B Y TE ) is same as C HA R(10) because byte is the default.
If C HA R (10 C HA R ) is used, each C H A R may tak e up 1 to 4 bytes. I n this text, you
will see the default semantic only.
70 Chap. 4 Oracle Tables: Data Definition Language (DDL)
Number
The N U M B E R data type is used to store negative, positive, integer, fixed- decimal, and
floating- point numbers. The N U M B E R data type is used for any column that is going
to be employed in mathematical calculations— for example, SA LARY , COMMISSION,
or PRICE. W hen a number type is used for a column, its pr ecision and scale can be
specified. Precision is the total number of significant digits in the number, both to the
left and to the right of the decimal point. The decimal point is not counted in specifying
the precision. Scale is the total number of digits to the right of the decimal point. The
precision can range from 1 to 38. The scale can range from - 84 to 127.
A n integer is a whole number without any decimal part. To define a column
with integer values, only the scale size is provided. For example, EmployeeId in the
E M PL OY E E table has values of 111, 246, 123, 433, and so on. The data type for it
would be defined as NU M B ER (3), where 3 represents the maximum number of
digits. Remember to provide room for future growth when defining the size. I f a corpo-
ration has up to 999 employees, a size of 3 will work for now. W ith future growth, the
corporation’s number of employees may rise to 1000 or higher. By using a size of 4,
you provide room for up to 9999 employees.
A fixed-point decimal number has a specific number of digits to the right of
the decimal point. The PR I C E column has values in dollars and cents, which re-
quires two decimal places— for example, values like 2.95, 3.99, 24.99, and so on. If it
is defined as NU MBE R(4,2), the first number specifies the precision and the second
number the scale. R emember that the decimal place is not counted in the scale. The
given definition will allow a maximum price of 99.99.
A floating- point decimal number has a variable number of decimal places. The
decimal point may appear after any number of digits, and it may not appear at all. To
define such a column, do not specify the scale or precision along with the N U M B E R
type. For example, TA X RA TE , I NTE RE ST_R A TE , and STU D E NT_ GPA columns
are likely to have variable numbers of decimal places. By defining a column as a
floating- point number, a value can be stored in it with very high precision.
Date
The D A TE data type is used for storing date and time values. The range of allow-
able dates is between January 1, 4712 B.C. and D ecember 31, 9999 A .D . The day,
month, century, hour, minute, and second ar e stored in the D A TE-type column.
There is no need to specify size for the D A TE type. The default date format is D D -
MO N- Y Y, where D D indicates the day of the month, M ON represents the month’s
first three letters (capitalized), and Y Y represents the last two digits of the year.
These three values are separated by hyphens. The D D - M ON- Y Y Y Y format also
works as the default in Oracle9i. To use any other format to enter a date value, you are
required to use the TO_D A TE function. The default time format is HH:MM:SS A.M.,
Data Types 71
representing hours, minutes and seconds in a 12- hour time format. If only a date is
entered, the time defaults to 12:00:00 A.M. If only a time is entered, the date de-
faults to the first day of the current month. For example, HI R E D A TE for Employ-
eeI d 111 in the E M PL OY E E table in the N2 Corporation database is stored as
15- APR-60 12:00:00 A.M.
I n a table, it is not advisable to use columns like A GE , because age not only
changes for all entities but also changes at different times. A column like A G E can
become a very high-maintenance column. I t is advisable to use BI RTHD A TE as a
column instead. Oracle9i provides users with quite a few built- in date functions for
date manipulation. Just simple date arithmetic is enough to calculate age from the
birth date! The birth date never changes, so no maintenance on it is necessary.
Other advanced data types used in Oracle are not used in the sample databases
discussed in Chapter 3. These advanced data types are outlined her e for your infor-
mation only:
Many of the L arge Object (L OB ) data types are not supported by all versions
of Oracle and its tools. These data types are used for storing digitized sounds, for
images, or to reference binary files from Microsoft E xcel spreadsheets or Microsoft
Word documents. W e will not use L OB data types in this book. Figure 4-2 shows a
brief summary of Oracle data types and their use in storing different types of data.
72 Chap. 4 Oracle Tables: Data Definition Language (DDL)
CONSTRAINTS
Constraints enforce rules on tables. A n Oracle table can be created with the column
names, data types, and column sizes, which are sufficient just to populate them with
actual data. Without constraints, however, no rules are enforced. The constraints
help you to mak e your database one with integrity. W e learned the integrity rules in
Chapter 1. The constraints are used in Oracle to implement integrity rules of a rela-
tional database and to implement data integrity at the individual- column level.
Whenever a row/record is inserted, updated, or deleted from the table, a constraint
must be satisfied for the operation to succeed. A table cannot be deleted if there are
dependencies from other tables in the form of foreign keys.
Types of Constraints
Naming a Constraint
Oracle identifies constraints with an internal or user-created name. For a user’s ac-
count, each constraint name must be unique. A user cannot create constraints in two
Constraints 73
different tables with the same name. The general convention used for naming con-
straints is
Here, is the name of the table where the constraint is being defined,
is the name of the column to which the constraint applies, and
is an abbreviation used to identify the constraint’s type. Figure 4-3
shows popular abbreviations used for the constraint type.
Constraint Abbreviation
PR IMAR Y KEY pk
FO R EIG N KEY fk
U NIQ UE uk
CHECK ck or cc
NOT NULL nn
A constraint can be created at the same time the table is created, or it can be added
to the table afterward. There are two levels where a constraint is defined:
(I n this book, you will see the following convention for syntax: Reserved
words will be written in uppercase and user- defined identifiers in lower or
mixed case. Optional parts will be within brackets ([ ]). The pipe symbol
1|2 will represent O R situations in statement syntax.)
74 Chap. 4 Oracle Tables: Data Definition Language (DDL)
If a table uses more than one column as its primary key (i.e., a composite key),
the key can only be declared at the table level. For example, the D E PE N D E NT
table in the N2 database uses two columns for the composite primary key:
or
I n the second example, the user does not supply the constraint name, so Oracle will
name it with SYS_C format.
The composite unique key constraint can be defined only at the table level by
specifying column names separated by a comma within parentheses. Oracle implicitly
creates an index on the unique column to enforce the U NI QU E constraint.
DeptId NUMBER (2) CONSTRAINT dept_deptid_cc CHECK((DeptId >= 10) and (DeptId <= 99)),
76 Chap. 4 Oracle Tables: Data Definition Language (DDL)
The DEFAULT Value (It’s Not a Constraint). The D E FA U L T value en- sures
that a particular column will always have a value when a new row is inserted. The
default value gets overwritten if a user enters another value. The default value is used
if a null value is inserted. For example, if most of the students live in New Jer- sey, “NJ”
can be used as a default value for the State column in the STU D E NT table. A t the
column level, the value is defined by:
State CHAR(2) DEFAULT ‘NJ’,
A user creates an Oracle table in the SQL * Plus environment. You will run the Ora-
cle Client application from your PC as described in Chapter 3. A n Oracle table is
created from the SQL 7 prompt in the SQL * Plus environment. A D ata D efinition
Language ( D D L ) SQL statement, C RE A TE TA BLE, is used for table creation. A
table is created as soon as the CR E A TE statement is successfully executed by the
Oracle server. The general syntax of C R E A T E TA B L E statement is:
...),. ..);
I n the syntax,
E ach column may have zero, one, or more constraints defined at the column level.
The table level constraints are normally declared after all column definitions.
SQL is not case sensitive. I n this textbook, the reserved words are written in
capitalized letters and user- defined names in lower or mixed- case letters. The spaces,
Creating an Oracle Table 77
tabs, and carriage returns are ignored. L et us create the L OC A TI O N table in the I U
College database using the C R E A TE TA BL E statement. When the statement is ex-
ecuted and there are no syntax errors, a “Table Created” message will be displayed
on the screen (see Fig. 4-4).
Table created.SQL>
If there are errors in the C R E A TE TABLE statement, the statement does not
return the “Table Created” message when executed. Oracle displays an error message
instead (see Fig. 4-5). The error messages are not very userfriendly. I n the statement
shown, the column definition in line 3 is missing a comma— but the error message does
not really tell us that! We will discuss error codes and messages later in this chapter.
We will debug the statement using SQL * Plus commands. The error is in line 3,
and we will perform the following steps (see Fig. 4- 5):
A s you see in Figure 4-5, the statement has another error, this time in line 4.
We use to change the incorrect spelling. Then, we
execute the statement from buffer by entering a slash (/) again. There we go! Table is
created. We can edit erroneous statement with the help of an alternate editor, such as
Notepad. To load an erroneous statement in N otepad and modify it, we perform the
following steps:
I n the previous example, the TABLE SPA CE clause is used to specify the user’s ta-
blespace name. I f it is not specified, Oracle uses the default permanent tablespace any-
way. The STOR A GE clause allocates 1 megabyte initially on tablespace CIS_DA TA,
and 100 kilobytes as additional space on the same tablespace. The I N I TI A L and
N EX T parameters use values in K (kilobytes) or M (megabytes). The PCTFR E E
(percentage- free) clause is used to allow for future increment in row size. Oracle rec-
ommends the following formula in deciding initial extent size for a table:
W hen a user creates a table or many tables in his or her database, Oracle tracks them all
using its own D ata D ictionary. Oracle has SQL statements and SQL * Plus com- mands
for the user to view that information from Oracle’s D ata D ictionary tables.
A user types an SQL statement to retrieve his or her table names. Often, you use it to
review information, and often, you want to find out what has already been creat- ed and
what is to be created. To find out all tables owned by you, type the following statement:
Oracle creates system tables to store information about users and user objects.
U SER _TA B L E S is an Oracle system database table, and TA B L E _N A M E is one of its
columns. The display will include all table names you have created and any other tables
that belong to you. I f you change U SE R_ TA BL E S with AL L_TA BLES, you can get
listing of all tables you own as well as those you are granted privileges to by other
users. The U SE R_ TA BLES table has many other columns. To display all columns,
type the following statement:
(I n this case, Y ou will see more information than you need. The display rows will
wrap many times to show all columns/information related to each table.)
Y ou can get information about the STOR A GE clauses’ atributes by using the
D ata D ictionary view U SE R_ SEGM EN TS:
SQL>
Figur e 4-6 D ESCR IB E command and table structure.
The O R D E R BY clause is added to sort the constraint display by table name. For
example,
A tablespace consists of one or more physical data files. Y ou can get information
about all tablespaces available to you by using D ata D ictionary view U SER_TA BLE-
SPA CES. We will discuss types of views and the Oracle D ata D ictionary in later
chapters. Y ou can use the D E SC R I B E command and the SE L E CT statement with a
view the same way you use with tables. For example,
DESCRIBE USER_TABLESPACES SELECT * FROM USER_TABLESPACES;
When you create a table, you can add comments to the table and its columns. You
can do it for documentation purpose with a C OM ME N T statement. For example,
COMMENT ON TABLE student IS ‘Table holds students for INDO-US College’ COMMENT ON
COLUMN employee.Lname IS ‘Employee’’s last name’
You can view information about all comments on tables and columns by using
D ata Dictionary views A LL_TA B_COMMENTS and A LL_COL_COMMENTS,
respectively.
I n a perfect scenario, the table you create will not need any structural modifications.
You must try to plan and design a database that is close to perfect in all respects. I n
reality, however, this is not the case. Even perfect tables need changes. There are cer-
tain modifications that you can mak e to a table’s structure. There are other modifi-
cations that you cannot make to an existing table’s structure.
Modifications allowed without any restrictions include:
● Adding a foreign key constraint is allowed only if the current values are null or
exist in the referenced table’s primary key.
● Adding a primary key constraint is allowed if the current values are not null
and are unique.
● Changing a column’s data type and size is allowed only if there is no data in it
(Oracle8i and earlier). In Oracle9i, column size may be decreased if existing
data can be stored with the new column width.
● Adding a unique constraint is possible if the current data values are unique.
● Adding a check constraint is possible if the current data values comply with
the new constraint.
● Adding a default value is possible if there is no data in the column.
For example, if the I U College decides to track a student’s Social Security number
along with the student’s I D, a new column can be added to the STU D E NT table, as
shown in Figure 4-9. If the table already contained rows of data, you will have to use
U PD A TE statement (covered in the next chapter) for each row to add values in the
newly added column.
Table altered.SQL>
where is the new data type or the new size for the column. For example,
say the I U College wants to allow data-entry personnel to enter values with or with-
out dashes in the Social Security column. The data type can be changed from
C HA R (9) to VA RCHA R2(11) to accommodate this new format (see Fig. 4-10).
Table altered.SQL>
I n this section, we will try to add various constraints in a table using the A L TE R
TA B L E statement. A s introduced in Chapter 3, the E M PL O Y E E table in the N2
corporation database has a PositionId column, which references the POSI TI ON
table’s primary key PositionI d. To add a constraint using A L TE R TA BL E, the syn-
tax for table level constraint is used. The general syntax of A L TE R TA BL E is
…),
For example,
ALTER TABLEemployee
ADD CONSTRAINT employee_positionid_fk FOREIGN KEY (PositionId) REFERENCES position
(PositionId);
Table altered.
SQL>
to table CO U RSE. The foreign key column PreR eq references primary key column
CourseId of its own table. Such a reference is known as a cir cular refer ence.
The TE R M table in the I U College database contains two columns, StartDate
and E ndD ate. The start date for a ter m must fall before the end date for the same
term. U se of a C H E C K constraint will guarantee the necessary data integrity. The
problem is that during creation of the TE R M table, defining a constraint that com-
pares values in two columns of the same table is not possible. The constraint can be
defined with the A L TE R TA BL E statement, however, as shown in Figure 4- 11b.
Let us try to add another foreign key constraint in the STU D E NT table as
shown in Figure 4-12. As you see in Figure 4-12a, this error message is easier to under-
stand. To create a foreign key constraint, the parent table, whose primary key column
is referenced by the child table’s foreign key column, must already exist in the data-
base. Even the primary key column that is referenced must exist in the parent table
defined as the primary key. Remember that the two columns, the foreign key and the
ERROR at one 3:
ORA-00942: table or view does not exist SQL>
primary key that it references, need not have the same name. The best solution in this
situation would be to create all tables without any foreign key constraints first, then
create tables using a C RE A TE TABLE statement with F OR E I G N K E Y constraints
to the reference tables already created. A n alternate solution is to create all tables
with their constraints except for the foreign key constraint. Once all the tables are cre-
ated, use the A LTE R TA BLE statement to add the F OR E I GN K E Y constraint.
I n Figure 4- 12b, another try to create a foreign key has failed. The problem
with the query is the creation of a foreign key in the wrong table. The FacultyId col-
umn is common in the STU D E N T and FA CU LTY tables, but remember the rule! A
86 Chap. 4 Oracle Tables: Data Definition Language (DDL)
SQL>
foreign key must reference a primary key. I n our query, primary key FacultyId in the
FA CUL TY table is trying to reference a non–key column FacultyI d in the
STU D E NT table. I t will definitely won’t work in Oracle!
Once the par ent table FA CU LTY is created, the foreign key is successfully
created in the STU D EN T table (see Fig. 4- 12c).
A s you already know, Oracle8 and earlier versions do not allow you to remove a col-
umn from a table, but with Oracle8i onward, you can. Even so, only one column can
be dropped at a time. The column may or may not contain any data. W hen you drop
Altering an Existing Table 87
a column, there must be at least one column left in the table. I n other words, you
can’t remove the last remaining column from a table. I t is not possible to recover a
dropped column and its data. The general syntax is
The unused columns are like dropped columns. This is not a very good feature,
because the storage space used by unused columns is not released. They are not dis-
played with other columns or in the table’s structure, and the user can drop all unused
columns with the following statement. Setting a column to unused is quicker than
dropping a column, however, and it requires fewer system resources. Y ou can remove
all unused columns when system resources are in less demand. The general syntax is
If no columns are marked as unused, this statement does not return any error mes-
sages. Figure 4-13 shows setting a column as unused and then being dropped.
Dropping a Constraint
A s you already know, you can view constraint information from the USER_CONS-
TRA I NTS table or the U SER_CONS_COLUMNS table. A dropped constraint is
no longer enforced by Oracle, and it does not show up in the list of USER_CONS-
TRA I NTS or U SER_CONS_COLU MNS. The general syntax is
For example,
ALTER TABLEmajor
DROP PRIMARY KEY CASCADE;
88 Chap. 4 Oracle Tables: Data Definition Language (DDL)
This statement drops the primary key constraint from the M A JO R table. The
C A SC A D E clause drops the dependent foreign key constraints, if any. You can drop
a constraint by using its name, which is why it is important to name all constraints
with a standard naming convention. For example,
ALTER TABLEemployee
DROP CONSTRAINT employee_deptid_fk;
Enabling/Disabling Constraints
You may enable or disable constraints as needed. A newly created constraint is en-
abled automatically. A constraint verifies table data as they are added or updated.
This verification slows down the process, so you may want to disable a constraint if
you are going to add or update large volume of data. When you reenable the con-
straint, Oracle checks the validity of the data and for any violations.
You may disable multiple constraints with one A L TE R TA B L E statement,
but you may only enable one constraint at a time. The general syntax for enabling or
disabling constraint is
You may enable or disable a primary key constraint with the following syntax
that does not use constraint name:
You can change storage attributes of a table, such as NEX T, PCTFR EE , and so, with
the following statement:
Truncating a Table 89
DROPPING A TABLE
When a table is not needed in the database, it can be dropped. Sometimes, the exist-
ing table structure has so many flaws it is advisable to drop it and recreate it. W hen
a table is dropped, all data and the table structure are permanently deleted. The
D RO P operation cannot be reversed, and Oracle does not ask “Are Y ou Sure?” Y ou
can drop a table only if you are the owner of the table or have the rights to do so.
Many other objects based on the dropped table are affected. All associated indexes
are removed. The table’s views and synonyms become invalid. The general syntax is
For example,
DROP TABLEsample;
You can rename a table provided you are the owner of the table. The general syntax is
For example,
RENAME dept TO department;
Oracle will display a “Table renamed” message when this statement is executed.
(W e will not change the D E PT table’s name and will still refer to it by its original
name later in this textbook.) The R E N A M E statement can be used to change name
of other Oracle objects, such as a view, synonym, or sequence, which we will cover in
a later chapter.
TRUNCATING A TABLE
Truncating a table is removing all records/rows from the table. The structure of the
table, however, stays intact. Y ou must be the owner of the table with the D E L E TE
TA B L E privilege to truncate a table. The SQL language has a D E L E TE statement
that can be used to remove one or more (or all) rows from a table, and it is reversible
as long as it is not committed. The TR U N CA TE statement, on the other hand, is not
reversible. Truncation releases storage space occupied by the table, but deletion
does not. The syntax is
90 Chap. 4 Oracle Tables: Data Definition Language (DDL)
For example,
Oracle9i uses various types of tables— permanent tables, temporary tables, index-
organized tables, and external tables. Permanent tables are used for storing data.
Temporary tables are used during a session or a transaction. Temporary tables are
like permanent tables, but they are not stored permanently. They store data during a
session or a transaction. Temporary tables are created with the C R E A TE GL O BA L
TE M PO R A R Y TA B L E statement. Index- organized tables are used for tables with
primary key values that are looked up frequently. I ndex-organized tables are created
with a C RE A TE TA B LE Á OR G A N I Z A TI ON I ND E X statement.
External tables are stored “outside” the database with C R E A TE TA BL E Á
O R GA N I ZA TI O N E X TE R N A L statement. These tables are based on flat files,
such as comma-delimited, double quotes–delimited or fixed- length files, whose
directory path is made known to Oracle with a C R E A TE D I R E C TOR Y statement. I n
most cases, the end user works with permanent data tables only.
SPOOLING
Spooling is a very handy feature. D uring a session, a user can redirect all statements,
queries, commands, and results to a file for later review or printout. The spooling
method creates a text file of all actions and their results. Everything you see on your
screen is redirected to the file, which is saved with an extension by default.
To start spooling, go to the File menu in the SQL * Plus window. Then, click on
Spool and Spool File in subsequent menus (see Fig. 4-14). You will be prompted to
enter a file name, which will be created with an extension.
To stop spooling at any point, use the same menu to click on Spool Off (see
Fig. 4-14). W hen spooling is tur ned off, the file is saved to the disk and closed. The
spooled file can be opened in any text editor, such as Notepad, for viewing or print-
ing. I n the classroom environment, I ask my students to spool all their work, which
includes required queries and their results. The students can submit their disk or the
printed hard copy.
Error Codes 91
You may start and stop spooling from the SQL 7 prompt with the
SQL> SPOOL
and
SQL> SPOOL OFF
commands, respectively.
ERROR CODES
If Oracle E rror Help is installed on your system, you will be able to get to it by click-
ing on STAR T : O r acle : Or aHome92. Once the error help screen is displayed,
click on the Index tab. Then, type the error code received from Oracle in the space
provided.When you are done typing, click on the Display button to get an explanation
of the error. The explanation of the error code is straightforward. The help function
shows the cause of the error and gives hints for corrective actions.
You may use online help from Oracle’s W eb site by using the following U R L:
http://otn.oracle.com/pls/db92/db92.error_search
To use the online help with error codes, follow three steps shown in Figure 4- 15.
In step 1, type the error code in the text box (see Fig. 4- 15a). In step 2, select a result
from Oracle’s search results (see Fig. 4- 15b). In step 3, view the cause of the error and
the action required to rectify it (see Fig. 4-15c).
This online help utility requires you to sign up with The Oracle Technology
Network (OTN). The free membership to O TN has many benefits, including free
downloads of Oracle software products.
92 Chap. 4 Oracle Tables: Data Definition Language (DDL)
I n this chapter, you learned all the D ata Definition Language (D D L ) statements,
which enable you to create and modify a table’s structure. I n the next chapter, you will
learn about D ata Manipulation L anguage (D M L ) statements to populate tables with
the INSERT statement, to modify data using the U PD A TE statement, and to remove
data using the D E L E TE statement. W e will also learn to retrieve a table’s underlying
data with the SE L E CT statement and its various clauses.
IN A NUTSHELL . . .
● Oracle database tables are stored under a user’s account in an allocated table-
space on a server’s disk.
● Oracle object names can be up to 30 characters long and can use letters, num-
bers, and the $, #, and _ characters only. A ll names must start with a letter.
● E ach column in a table is assigned a data type to specify the type of data to
be stored in it. Basic data types are C H A R (fixed- length character data),
94 Chap. 4 Oracle Tables: Data Definition Language (DDL)
E X ER C I SE Q UE STI ON S
True/F alse:
1. In Oracle9i, a table name cannot be one character long.
2. If a data value entered in a V AR CHAR 2 type field is longer than the actual size, the
value is truncated.
3. The NU MB ER data type can be used for integer, fixed-point decimal, and floating-point
decimal values.
Chap. 4 Exercise Questions 95
4. Two tables may have constraints with same constraint name under a user’s database.
5. A foreign key must reference a primary key in another table, and both keys must have
same column name.
6. If you try to enter value “Database” in a CHAR (4) column, only “Data” will be stored in it.
7. The value “Basketball” will be stored with five trailing spaces in a V ARCHAR2(15) column.
8. A composite primary key can be defined at table level only.
9. A column with U N I Q U E constraint may not contain a null value.
10. The N OT NU L L constraint is defined at the table level only.
11. A CHECK constraint cannot be written to check for null values.
12. The value 9999.99 is the largest possible value for a NU MBER(6,2) column.
W r ite the Appropriate Column Name, Data Type, and Size for the F ollowing Columns:
1. Student’s date of birth.
2. Social Security number (without dashes).
3. Telephone number (with area code).
4. Employee’s gender.
5. Employee’s picture in a file.
6. L ink to a W ord document.
7. Customer’s last name.
W r ite the Constraint Definitions for the Following Constraints (Use Case-Study Tables in
Chapter 3):
1. Primary key in the D EPT table.
2. Foreign key DeptId in the EMPL OY EE table.
3. CH ECK constraint for QualId in the EMPL OY EE table.
4. N OT NU L L constraint for the MajorDesc column in the M AJO R table.
5. U NI Q U E constraint for DeptName in the DE PT table.
5. Can you change a column’s name in an existing table in Oracle9i? Can you delete a column
from a table?
6. Is it possible to add any type of constraint to an existing table? A re there any restrictions?
7. What are the differences between SQL and SQL *Plus?
8. How will you drop a table whose primary key is referenced by a foreign key in another
table? Give two possible ways to accomplish the task.
9. How will you make sure that the value used in GE N DE R CH AR (1) column is either
“M” or “F” only?
10. Name any three Oracle D ata Dictionary tables, and give their use.
11. Can you reference a table that does not exist? Can you reference a table whose primary
key is not defined? Can you reference part of a composite primary key?
12. What is the use of STO R AG E clause with IN ITI AL and N EX T attributes?
13. How do you release all storage space with T RU NCATE statement?
L AB A CTI V ITY
Before running your statements, start spooling to a file named CH4LAB1A.LST. When
all tables are created, stop spooling, and print the spooled file.
.
b Now, add the required foreign key constraints for each table. Do not add any
records yet. Spool your statements and results to the CH4LAB1B.LST file, and
print it.
.
c Spool to the CH4L AB1C.L ST file, and print all table names from your account,
each table’s structures, and constraint information for each table.
2. U se SQL statements to create all six tables from the N2 Corporation database in
Chapter 3. If you have already created a DEPT table in Chapter 3’s Lab Activity, you
will skip it. Define the PR IM AR Y K EY , F OR E I GN KEY, N OT NUL L, DEFAULT,
CH ECK , and U NI Q U E constraints in the CRE ATE TA BL E statement. If not possible,
use the AL TER TAB L E statement to add a constraint. ( The F OR EI G N
K EY constraint requires existence of the referenced table.) Spool your statements
and results to the CH4LAB2.LST file, and print each table’s structure and constraints
as well.
IN THIS CHAPTER . . .
● You will learn how to populate tables using D ata Manipulation Language
(D M L ) statements.
● You will learn to change existing data and to remove unwanted
rows/records.
● D ata retrieval queries on single tables are shown.
● Various clauses are used with data retrieval queries for filtering and sorting of
data.
● CA SE structure is introduced.
manipulate data; it only queries tables. The D ML statements are not written perma-
nently to the database unless they are committed. Many times, students do not exit
properly from SQL * Plus, and they end up losing newly inserted rows or updated in-
formation. You can enter a C OMM I T statement anytime to write D ML statements to
the disk. You can use R OL L BA CK to undo the last set of D ML statements. You will
learn more about transactions in Chapter 9.
AD DI NG A NEW ROW/RECORD
The column names are optional. I f column names are omi tted from the I NSE RT
statement, you must enter a value for each column. I f you know the correct order of
column names, you can enter values in the same order following the VA L U E S key-
word. (U se the SQL * Plus command D E SC R I B E to display the table’ s structure to
mak e sure.) I f you insert values in the incorrect order and a numeric value is entered
for a character - (C HA R) - ty pe column, Oracle will not accept the new row and will
generate an er ror message. I f y our statement is accepted, a “1 row created” message
is displayed on the screen.
If you do enter column names, they do not have to be in the same order as they
were defined in the table’s structure at the time of creation. Once you enter column
names, however, their respective values must be in the same order as the column
names. For example, let us add a new record to the STU D EN T table in the Indo–US
(I U ) College database:
INSERT INTO student (StudentId, Last, First,Street,City,State, Zip, StartTerm, BirthDate, FacultyId, MajorId,
Phone)
VALUES (‘00100’, ‘Diaz’, ‘Jose’, ‘1 FordAvenue #7’, ‘Hill’, ‘NJ’, ‘08863’, ‘WN03’, ‘12-FEB-80’,
123, 100, ‘9735551111’);
When entering values, numeric data is not enclosed within quotes. The
C HA R - and D ATE -type values are enclosed within single quotes. How do you
enter a character value that contains a single-quote character? For example,
‘D addy’s Pizza Parlor’ will result in an error. Y ou must type two single quotes to
enter a single-quote character. The solution is ‘Daddy’’s Pizza Parlor’. The first quo-
tation mark acts as an escape character for the second one.
The default format to enter the D ATE value is DD - MON-Y Y. I n Oracle8i, if a
two-digit year has a value greater than or equal to 50 (e.g., 60), it is stored as occurring
in the twentieth century (e.g., 1960). If a two-digit year has a value less than 50 (e.g., 10),
it is stored as occurring in the twenty- first century (e.g., 2010). The birth date of
Adding a New Row/Record 99
15- APR-40 will be stored with the year as 2040. The student’s calculated age will re-
turn a negative number! I n Oracle9i, the format DD -M ON- Y Y as well as D D -
MON-Y Y Y Y are default formats. Y ou are strongly advised to use a four-digit year.
If you want to enter a date in any other format, the TO_D A TE function is used for
converting a character value to the date equivalent. For example,
A D A TE-type column can store date as well as time values. I f only the date value
is entered in a D A TE-type column, the time value is set to the midnight (12:00 A .M.).
If only the time value is enter ed into a D ATE- type column, the date is set to first of
the current month. For example, a time value is enter ed in the H ireD ate column of
the E M PL O Y E E table with
Then, the information is retrieved with the following format (try it after you learn
the SE L E C T statement later in this chapter):
The result will show the date as the first of the month in which time was entered
along with the entered time.
Now, let us enter a new row into D E PT table in the NamanNavan (N2) Corpo-
ration’s database without using the column names:
The D E PT table contains four columns, and the values in the previous state-
ment are in the correct order. W hile inserting values, you must remember that the
foreign key columns in a table must either have a null value or must already exist as
a primary key value in the table referenced by the foreign key.
For example, in the STU D E NT table’s INSE RT statement, the value for Fac-
ultyId and MajorI d columns are cross-referenced by Oracle in the FA CU LTY and
M A JOR tables, respectively. I f you have not populated those two par ent tables,
your new record in the STU D E N T table will not be accepted. You must populate ta-
bles without foreign keys first; in other words, the parent tables must be populated
before their child tables.
Rounding by INSERT
If you insert value 543.876 in a NUMBER(6, 2) column, the precision is 4, and the
scale is 2. The resulting value will be 543.88, rounded to two decimal places, or a
scale of 2. The rounded value will be entered into the column.
100 Chap. 5 Working with Tables: Data Management and Retrieval
Null values are allowed in non–primary key columns that do not have a N OT
NU L L constraint. Check the ‘Null?’ display from the D E SC R I B E command before
inserting a null value.
There are two methods for inserting a NU L L value in a column:
I n this example, the Location and EmployeeId columns are not included.
The new record will be inserted into the table with no values for those two
columns. I t is allowed only if the NO T NU L L constraint is not used for
them.
I n the explicit method, the null value is used as a value
for a numeric column, and an empty string (‘’) is used for date or charac-
ter columns. For example,
You will insert null in EmployeeId if you do not know the manager’s Em-
ployeeI d for the newly created Personnel D epartment in Chicago.
Often, you do not know the value of a column and decide to use a null value
for it. I f your table has records with null values, you have to update those records
once the actual values are known. That is additional data entry. One way to avoid
null values is by using a D EFA U L T value on columns.
With Oracle9i, the INSERT statement has added syntax that lets you insert default
values with the key word D E FA U L T in place of a value for a column. If a default
value is assigned to the column during the table’s creation, that default value is in-
serted into the column. If no default value is assigned to the column, the key word
D E FA U LT will result into a null value for the column. Make sure there is no N OT
NU L L constraint on that column; otherwise, your new row will not be inserted.
Substitution Variables
Inserting rows into a table is a very tedious task. In real- life tables, we are talking
about thousands of rows per table! There are screen designers, form creators, and so
on. A n SQL statement does not have those fancy boxes or buttons. The SQL language
Adding a New Row/Record 101
does have substitution variables, which enable you to create an interactive SQL
script. When you execute the script, Oracle prompts you to enter a value for the sub-
stitution variable. The ampersand (& ) character is used before the substitution vari-
able in the query. The substitution variables for C H A R - and DA TE- type columns
are enclosed within a pair of single quotation marks. Figure 5- 1 shows the use of
substitution variables and the interactive prompts displayed by Oracle.
SQL>
Question: Y ou just ran the SQL statement in Figure 5-1. How will you insert
the next record using the same statement?
Answer : The last SQL statement is in the buffer, so you will type a slash (/) to
reexecute the statement from the buffer. I f you stored the statement in a
file, you can execute the same file again with the R U N or @ command.
If you execute an INSERT statement that contains a value containing the &
character, such as the value R & D in Figure 5-2, Oracle treats it as a substitution
variable. To avoid such a situation, you can disable the substitution-variable charac-
ter (& ) with the following SQL * Plus command:
SET DEFINEOFF
CUSTOMIZED PROMPTS
The substitution- variable prompts are standard. Oracle displays “ E nter the value
for” followed by the name of the substitution variable. The SQL * Plus command
A C C E PT is used for customized prompts. The A C CE PT command does not use an
ampersand in front of the variable name. A CC E PT, in fact, accepts values for substi-
tution variables that can be used later in other statements. If an A C CE PT statement
is used for a variable, the value of that variable, once entered, is remembered during
the session. You might not want to use the A CC E PT statement for a variable to be
used later in more than one I N SE RT statement.The general syntax is
1 row created.
SQL>
Once a variable is defined with & (substitution variable) or ACCEPT, its value
is known throughout that session. Y ou can undefine such a variable with the
SQL * Plus command U N D E FI N E.
Once data are added to the tables for various entities, they may not stay the same
forever. A female employee gets married and changes her last name, a student
changes his or her major, a customer/vendor moves to a new location, or an employee
Updating Existing Rows/Records 103
gets a salary increment. These are real- life possibilities. When you create tables, you
should use columns that are not very high maintenance. For example, you should
not use a column called A G E . The age changes every year for an individual, and it
also changes on different days for almost everybody.
In SQL, the U PD A TE statement is used for such modifications to data. Only
one table can be updated at a time, but it is possible to change more than one column
at a time. The general syntax is
The condition is optional, but in most cases, you would need to use it. If the condi-
tion is not used with U PD A TE, all rows will be updated. The conditions are created
using column names, relational operators, and values. You already know that Oracle
is case sensitive as far as the values in single quotation marks are concerned. The re-
lational operators are shown in Figure 5-4.
Suppose the student with I D 00103 in the I U College’s database switches major
from BS— Computer Science to BS— Telecommunications. We will write an update
statement to change the student’s MajorId in the STU D E NT table. Figure 5-5 first
shows an unsuccessful update operation. W e are trying to change MajorId to 700,
which did not work! There is no such value for MajorI d in the M A JO R table, which
is being referenced by the foreign key in the STU D E N T table. See Oracle’s error
code and error message, which point out the integrity constraint was violated. Then,
the figure shows that the value is changed to 600, which worked! In this figure, the
value is changed back to the original value of 500. The same U PD A TE statement
without the W H E R E clause would result in updating all students’ MajorI d to 500.
There are other operators for writing conditions like A ND , OR , B E TW E E N
Á A ND , IN, and L I K E . We will learn more about them later in this chapter.
104 Chap. 5 Working with Tables: Data Management and Retrieval
1 row updated.
SQL> 2
2* SET MajorId = 600SQL> c/600/500
2* SET MajorId = 500SQL> /
1 row updated.
SQL>
Deletion is another data maintenance operation. W hen employees leave the company
or students enroll but never start college, you might want to remove their information
from your database. I n Oracle, the SQL statement D E L E T E is used for deleting un-
wanted rows. Its general syntax is
SQL>
operation. In such cases, you may drop a constraint or temporarily disable it. A
dropped constraint is removed permanently, whereas a disabled constraint can be en-
abled later.
The main purpose of the SQL language is for querying the database. You have al-
ready learned to create, alter, insert, update, and delete by using SQL statements.
The most important statement or query is the SE L E CT query. A user retrieves data
from the underlying table or tables with a SEL E C T query. The output can be sorted
and grouped, and information can be derived with the use of mathematical expres-
sions and built-in functions. I n Chapter 1, we covered nine relational operations.
Now is the time to try those operations. The general syntax is
The columns can be listed in any order. They do not have to be in the order
106 Chap. 5 Working with Tables: Data Management and Retrieval
Select (*)
If you want to see all columns in a table, you do not have to list them all. Y ou can use
an asterisk 1* 2 in place of the column list, and all columns will be displayed in the
same order as the underlying table structure. Figure 5-9 depicts use of the character *.
SQL> SELECT *
2 FROM course;
6 rows selected.
SQL>
Figures 5-11a and 5-11b show output from a SELECT query with a default line-
size of 80 and output after changing the linesize to a higher value. You can get infor-
mation about environment variables by using the SQL * Plus command SHOW ALL.
Y ou will notice that the queries, which return less than six rows, do not get
feedback from Oracle stating the number of rows returned. By default, Oracle sends
a feedback message for queries returning six or more rows only. If you would like
feedback for all queries irrespective of number of rows returned, use the following
command in the beginning of your session:
SET FEEDBACK1
108 Chap. 5 Working with Tables: Data Management and Retrieval
6 rows selected.
SQL>
6 rows selected.
SQL>
DISTINCT Function
BUILDIN
- --- ---
Gandhi Gandhi Kennedy
KennedyNehruNehru
Gandhi Kennedy Kennedy
Gandhi Gandhi
11 rows selected.SQL>
BUILDIN
- --- ---
Gandhi Kennedy Nehru
SQL>
Column Alias
W hen a SE L E C T query is executed, SQL * Plus uses the column’s name as the col-
umn heading. Normally, the user gives abbreviated names for columns, and they are
not very descriptive. For example, in Figure 5-13, the column name Title is used for
course name and PreReq for requirement.
Column aliases are useful, because they let you change the column’s heading.
When a calculated value is displayed, the mathematical expression is not displayed
as the column heading, but the column alias is displayed. The column alias is written
right after the column name with the optional keyword A S in between. The alias
heading appears in uppercase by default. I f an alias includes spaces or special char-
acters or if you want to preserve its case, you must enclose it in double quotation
marks ( “ ”). The general syntax is
I n the example in Figure 5-13, “Course Name” is an alias for Title, and Re-
quirement is an alias for PreR eq. The case is preserved for the first two aliases only,
because they were enclosed within double quotes. Notice that the word A S is used
for the first column but is omitted for the second and third columns. This is done for
illustration purpose; you may use it in a query or omit it altogether.
COLUMN Command
In Figure 5-13, you may have noticed that the column alias R E QU I R EM E NT appeared
as R E Q U I R . Can you figure out the reason? The PreR eq column has a data type of
VA R C HA R2(6), and SQL * Plus displayed only first six character of the col umn
heading. SQL * Plus’ C OL U M N command allowsyou to specify format columnsfor
Retrieving Data from a Table 111
For example,
I n the examples above, the State column is given the alpha format with display
width of five. I n the STU D E NT table, the State column has a data type of
CH A R (2) , and that displays only the first two characters of the column name in the
output. The new format will display the entire column name as a heading and use
five columns to display state values. The numeric format applied to the Salary col-
umn will display salary values in currency format (e.g., $265,000).
I n Figure 5-14, the CourseId and Credits columns are displayed before using
formatting columns with the CO L U M N command and then after applying those
columns. The SELECT statement is in the buffer, so we could execute it with a forward
6 rows selected.
SQL> COLUMN CourseId FORMAT A8
SQL> COLUMN Credits FORMAT 9.99
SQL> /
slash (/) at the SQL 7 prompt. Though the CO L U M N command was used after ini-
tial execution of the SE LE C T statement, the C OL U MN command, being an
SQL * Plus command, did not replace it in the buffer. Notice the number of columns
used in displaying C ourseI d and also its heading before and after use of the CO L-
U M N command. For the Credits column, the change is in the way values are dis-
played after use of the C O L U M N command.
Concatenation
LNAME | | FNAME
- --- -- --- --- --- -- --- --- -- --- -
SmithJohn HoustonLarry RobertsSandi
McCallAlex DevDerek ShawJinku
GarnerStanleyChenSunny ZEESONIA
9 rows selected.SQL>
I n Figure 5-16, we have altered the output so that the names are displayed with
the last name and first name separated by a comma and a space. W e need to use a
character string to accomplish it.
Now, try this:
8 rows selected.SQL>
ARITHMETIC OPERATIONS
The arithmetic expressions are used to display mathematically calculated data. These
expressions use columns, numeric values, and arithmetic operators (see Fig. 5-17).
When arithmetic operators are used with columns in the SE L E CT query, the under-
lying data are not changed. The calculations are for output purposes only.
Operator Use
Multiplication
/ Division
+ Addition
— Subtraction
Order of Operation
A s you see in Figure 5-18, if the column alias is not used, the expression is dis-
played as the column heading. I t is optional to leave a space on both sides of an
arithmetic operator. One other peculiar thing is the total of Salary and Commission.
When a Salary value is added to a null value in the Commission column, the total is
a null value. To handle null values, the expression can be changed to salary + NVL
(Commission, 0), where NV L is a function that replaces a N U L L value with the sec-
ond argument in parentheses— in this case, a zero— for arithmetic operation. W e
will revisit the NV L function shortly. R emember that any arithmetic operation with
a null value returns a null value as result.
8 rows selected.
SQL>
When we used the SEL E C T query in Fig. 5-8 earlier, we restricted the number of
columns to only two. This was an example of a operation. Remember that
the projection operation returns “vertical slices” or columns from a table! (This was
covered in C hapter 1). I n Figure 5-9, we basically displayed all columns. I n both
cases, all rows from the table were displayed. Many times, you don’t want to see all
the rows from a table, only those rows that meet a criteria. A W HE R E clause is used
with the SE L E CT query to restrict the rows that are picked. I t is the implementa-
tion of a operation. The W HE R E clause uses a simple condition or a com-
pound condition. The rows that satisfy the supplied conditions are displayed in the
output. The syntax of SE LE C T changes a little with an added W H E R E clause. The
general syntax of the W H E R E clause is
Restricting Data with a WHERE Clause 115
The conditions are written using column names; relational (see Fig. 5-4), logical (see
Fig. 5-19), and other comparison operators (see Fig. 5-21); literal values; mathematical
expressions; and built-in functions.
You are familiar with the arithmetic operators and relational operators al-
ready. The logical operators A N D and O R work with two conditions, whereas NO T
works with only one condition. A ll three return a T R U E or a FA LSE result. The
truth table in Figure 5- 20 shows the working of A N D and O R operators.
A ND OR
T R UE AN D TR U E = TR UE T R UE OR TR U E = TR U E
T R UE A N D FALSE = FALSE T R UE O R FALSE = TR UE
FALSE A N D T R UE = FALSE FALSE O R TR U E = TR UE
FALSE A ND FALSE = FALSE FALSE O R FALSE = FALSE
NULL A N D TR U E = NULL NULL O R TR U E = TR UE
NULL A ND FALSE = FALSE NULL O R FALSE = NULL
NULL AN D NULL = NULL NULL OR NULL = NULL
Operator Meaning
IS NULL Is a null value.
BETW EEN Á AND Is between a range of values (both included).
IN Match any value from a list (an alternate way to write OR ).
LIKE Match a value using wild cards.
records in each table for simplicity. Based on the rows entered, we will get output as
given in Figure 5- 22.
SQL>
The sample STU D E NT table has six rows, but only four StartTerm values
match W N03. W hen character values are tested in conditions, Oracle is case sensi-
tive. U se of the value wn03 would have returned no rows because of the lowercase
letters. The character and date values are enclosed within single quotation marks.
I n Figure 5- 23, no rows are selected from the query, even though one depart-
ment in the N2 Corporation database is located there. The problem here is the all-
uppercase value in the query. The actual data are in proper case, or in . We
will learn character functions soon to avoid these types of problems.
SQL> SELECT *
2 FROM dept
3 WHERE Location= ’MONROE’; no rows
selected
SQL>
5 rows selected.
SQL>
W hen the relational and logical operators are used together, the order of
precedence is as follows if all operators exist:
● W hatever is in parentheses is performed first.
● Relational operators are performed second.
118 Chap. 5 Working with Tables: Data Management and Retrieval
SQL>
SQL>
5 rows selected.
SQL>
Similarly, if we want to find out the names of all students in the I U College
database who are from New Y ork and New Jersey, we can use the O R operator. W hat
if we are looking for students from New Y ork, New Jersey, Connecticut, D elaware,
and Pennsylvania? With OR , we will need five conditions, so in this case, the I N op-
er ator is preferable. Figure 5-30 shows a different example using the of I N operator
to find faculty members who belong to department 1, 2, or 3.
SQL>
SQL>
SQL>
Wild Cards
You have already seen examples of a search for a string value. There are times, how-
ever, when you do not know the exact string value. I n these cases, you can select
rows that match a patter n of characters. Such a search is known as a
. There are two wild cards for a pattern search. Figure 5-33 explains the use of
these wild cards.
A search with the wild cards requires you to use the L I K E operator. In the col-
lege’s database, we want to see the information about faculty members whose names
start with the letter . All faculty names start with an uppercase letter. Oracle is case
sensitive, so a in place of a will not r eturn any faculty names. Figure 5-34 has a
query that searches for such faculty names.
2 rows selected.SQL>
Similarly, if we want to find out the names of employees hired during the 1960s,
we can look for hire dates that fall between January 1, 1960 and D ecember 31, 1969.
Would the BE TW E E N Á A N D operator be the best choice for it? N ot really! W e
can use a combination of both wild cards to achieve the same result. We have two
employees with hire dates in the 1960s. Figure 5-35 uses ‘% 6_’, which means that the
date starts with any characters, the second- to- last character is a 6, and the last char-
acter could be anything. I n the two case-study databases, none of the tables uses a
value that actually uses the character % or_.
122 Chap. 5 Working with Tables: Data Management and Retrieval
2 rows selected.
SQL>
Figure 5-35 Wild-cards % and _.
Question: How do you look for a value that has a wild- card character embed-
ded in it?
Answer: You use an escape character. SQL does not provide any particular
character as an escape character, but you can specify one for the query. The
W H E R E clause will look like this:
WHERE LIKE ‘%/_%’ ESCAPE ‘/’;
The first % means the column value starts with any characters in the beginning. The
second % means the value ends with any characters. The characters /_ mean there is a
_ character in the value. The character / is used as the escape character, which changes
the meaning of _ from a wild card to the underscore character. Y ou may use any char-
acter as an escape character, which is defined following the key word ESCA PE .
SORTING
The order of rows in a table is arbitrary. Y ou can insert rows in any order, and you do
not have control over where rows will be inserted. W hen you type a SE L E CT query,
the or der of rows is not defined. Y ou may want to see rows in a specific order, how-
ever, based on a column or columns. I t is not necessary to display a sort column in
the SE L E CT clause. For example, you may want to see employees in alphabetical
order by their name, employees with the highest-paid employee first and the lowest-
paid employee last, or students by their major in alphabetical order.
The O R D E R BY clause is used with the SELECT query to sort rows in a table.
The rows can be sorted in ascending or descending order. The rows can also be sorted
based on one or more columns. The expanded syntax of SEL ECT given here uses an
O R D E R BY clause, which is always used last in the statement. The general syntax is
Sorting 123
I n the syntax, A SC stands for ascending order. The default order is ascending, so
there is no need to type A SC for ascending order. The keyword D E SC stands for de-
scending or reverse order.
I n an ascending sort, numeric values are displayed from the smallest to the
largest, character values are displayed in alphabetical order, and date values are dis-
played with the earliest date first (see Fig. 5-36). The null values are displayed last, in
ascending order. I n descending order, the effect is reversed for all type of values; the
null values are displayed first in the descending order.
You can display null values first in a sort in ascending order by using the NU LLS
FI RST option. Try the following two statements, and see the difference in output:
SELECT CourseId, PreReq FROM course ORDER BY PreReq;
SELECT CourseId, PreReq FROM course ORDER BY PreReqNULLS FIRST;
I n the next four examples, we will perform an ascending sort by one column
(see Fig. 5-37), a descending sort by one column (see Fig. 5- 38), a sort by column
alias (see Fig. 5- 39), and a sort by multiple columns (see Fig. 5- 40). First, let us dis-
play all students in alphabetical order. The O R D E R BY clause will use the Last
SQL>
FULLNAME MONTHLYSALARY
- --- -- -- --- -- -- --- -- --- -- -- --- -- - - - - - - - - - - - - -
Chen, Sunny 2916.66667
Roberts, Sandi 6250
Smith, John 22083.3333
3 rows selected.SQL>
8 rows selected.
SQL>
column as the sort field (see Fig. 5-37). I n this example, if the optional word A SC is
added to the O R D E R BY clause, the sort clause will look like this:
ORDER BY Last ASC;
Now, let us find employees with their salaries in descending order (see Fig. 5-38).
The employee with the highest salary will be at the top, and the employee with the
lowest salary will be at the bottom. W e will restrict it to employees belonging to de-
partment 30 only. There are only two employees in department 30, and the result
shows the employee with the higher salary first.
Next, let us use an expression in the SELECT statement and give it a column alias.
W e will use the column alias as our sort column. The alias represents the
monthly salary of each employee, and it is also used for sorting data (see Fig. 5-39).
I n our next example, we will sort by two different columns, and each column
will be sorted in a different order. I n case of a sort by multiple columns, the first
column is the primary sort column, and the second column is the secondary sort
column. The rows are sorted based on the primary sort column first. Then, the
rows with the same value in the primary sort columns are sorted within their
group using the secondary sort column. For example, in sorting the E M PL O Y E E
tabl e using D eptI d as the primary sort column in ascending order and Salary as
the secondary sort column in descending order, D eptI d will be sorted first. Then,
within each D eptI d, rows will be sorted based on Salary in reverse or der (see Fig. 5-
40).
The substitution variables can be used in statements other than the INSERT state-
ment. They can substitute for column names, table names, expressions, or text. Their
use is to generalize queries by inserting them as follows:
DEFINE C OM MA ND
A variable can be defined at the SQL 7 prompt. The variable is assigned a value that
is held until the user exits from SQL * Plus or undefines it. The general syntax is
For example,
DEFINELast =Shaw
The variable gets the value , which can be used as a substitution vari-
able in a query. For example,
The D E FI N E Last command will return the value of the variable if it already
has a value; otherwise, Oracle will display an “ U ND E FI NE D ” message.
The variable’s value can be erased with the U N D E FI N E command. For example,
UNDEFINE last
The variable is valid during a session only. If you want to use a variable every
time you log in, it can be defined in your login script file (login.sql).
CASE Structure 127
CASE STRUCTURE
CASE structure is allowed anywhere expressions are allowed in SQL statements. SQL’s
CASE strcture is similar to the SELECT Á CA SE statement in V isual Basic language
and the switch Á case statement in C + + and Java.The general syntax of CASE is
IN A NUTSHELL . . .
● A column alias can also be used for expressions. A column alias is enclosed
in double quotation marks to preserve case or to use special characters.
● The concatenation characters 1 2 join a column or a character string to an-
other column.
● The arithmetic operations are performed on number data types for data ma-
nipulation. W hatever is in parentheses is performed first. Operators * and /
have higher precedence than + and - operators.
● U se of a null value in an arithmetic expression returns a null result.
● The logical operatorsA N D and O R are used to evaluate multiple conditions.
● The special comparison operator L I K E is used when wild cards % and _ are
used for pattern matching. The wild-card % represents zero or more charac-
ters. The wild card _ represents one character only.
● The or der of rows in a table is undefined. The rows can be displayed in a
sorted order with the O R D E R BY clause in the SE L E C T statement. The
default sort order is ascending. The D E SC keyword is used for sorting in de-
scending order.
● The & & substitution variable is used to reuse a variable’s value without get-
ting prompted again.
● The D E FI N E and U ND E F I N E commands are used at the SQL * Plus
prompt to assign or erase a variable’s value.
● The CA SE structure allows a user to perform different actions based on the
supplied conditions’ outcome. I t is similar to V isual Basic’s SE L E C T Á
C A SE and to C++ and Java’s switch Á case statements. C A SE structure
can also be used with other SQL statements.
E X ER C I SE Q UE STI ON S
True/F alse:
1. In Oracle, character values are enclosed in single quotation marks, but date and number
values are not.
2. In Oracle9i, the default display format for date is DD-MM-Y YYY .
3. A null value is not defined or not known.
4. The U PDA TE statement without the W H E R E clause can update all rows in the table.
5. A column alias is enclosed in double quotation marks to display a column name in up-
percase only.
6. The A N D operator returns a T R U E result if one of the two conditions is true.
7. The substitution variable can be deleted with U N DEF I NE command.
8. The W H ER E clause restricts individual rows, but it does not filter columns.
9. There is no restriction in deleting a row from a parent table.
10. The D EL ETE statement without a W HE R E clause has the same effect as TRU NCATE.
130 Chap. 5 Working with Tables: Data Management and Retrieval
11. A null value may be inserted into a column by using NU L L or ‘’ (two single quotes).
12. The SEL ECT statement can be used to modify data in a table.
13. A search condition with wild card may not use equal 1 = 2 operator.
14. If the O R D E R BY clause is used with the DESC option on a date column, the most cur-
rent date is displayed first.
15. If the OR D ER BY clause is used with the default sort order on a character column, the
column values are displayed in alphabetical order.
L ist O utput/Message from the Following Queries/Statements (Use Tables Created in the
Chapter 4 Lab Activity):
1. SEL ECT First ‘ ‘ L ast “Name”, BirthDate F RO M student;
2. SEL ECT DISTINCT (MajorId) F RO M student;
3. SEL ECT* FR O M location O R D ER BY Building, Capacity DESC;
4. SEL ECT Lname, Fname, (Salary / 12) MONTHL YSALARY F RO M employee OR D E R
BY MONTHLY SALARY;
5. D EL ETE FR O M faculty W HE R E DeptI d = 2;
I ndicate W hich of the F ollowing Q ueries/Statements W ill Result in an Err or M essage and
W hy (U se Tables Created in the Chapter 4 L ab Activity):
1. SEL ECT LastName, FirstName FR O M student;
2. SEL ECT DeptId,* FR OM dept;
3. INSERT I NTO dept V ALU ES (77, R ESE AR CH, NU LL, NUL L);
4. U PDA TE employee SET D eptI d = 88
W H ER E EmployeeId = 111;
5. D EL ETE FR O M dept W H ER E D eptI d = 10;
L AB A C TI V I TY
W r ite Queries/Statements for the F ollowing (U se Tables Created in Chapter 4 Lab Activity):
1. Display all employee names (last name and first name separated by a comma and a
space) and salary with appropriate column aliases.
2. Display all employees who do not get any commission.
3. Display unique building names from the L OCATI ON table.
4. Display all course sections offered in Winter 2003.
5. Display names of faculty members who work in Department 1 or 2. Use the IN operator
in your query.
6. Find all New Y ork and New Jersey students.
7. Give a 10% raise to employee number 111.
8. Delete Department 30 from the department table. If this is not successful, write down
your suggestion to make it work.
9. For each CourseId, display the maximum count in descending order.
10. Insert a new term in the TER M table.
Chap. 5 Lab Activity 131
11. Create a custom prompt for the user to input any value between 50 and 99 into the
D eptI d column.
12. Find courses with no required prerequisite.
13. Display faculty names in descending order by their department but in alphabetical order
by their name within each department.
14. Find faculty members whose name start with the letter .
15. Find students who started in the year 2003. Use the start term column and wild card.
16. W rite the SQL * Plus command to display a character column in 30 columns and a
numeric column with 9,999.99 format.
IN THIS CHAPTER . . .
BUILT-IN FUNCTIONS
The built-in functions provide a powerful tool for the enhancement of a basic query. A
function takes zero or more arguments and returns a single value. Just like other
software and programming languages, the functions covered in this section are specific to
Oracle. Functions are used for performing calculations on data, converting data,
modifying individual data, manipulating a group of rows, and formatting columns. I n
Oracle’s SQL, there are two types of functions:
which work on columns from each row and return
one result per row.
or , which manipulate data in a group of
rows and return single result.
Built-In Functions 133
Single-Row Functions
The single-row functions take different types of arguments, work on a data item from
each row, and return one value for each row. The arguments are in the form of a con-
stant value, variable name, column, and/or expression. The value returned by a func-
tion may be of a different type than the argument(s) supplied. The general syntax is
U PPER(‘Oracle’) : ‘ORACLE’
LOW ER(‘DaTaBaSe SyStEmS’) : ‘database systems’ INITCA P(‘DaTaBaSe
SyStEmS’) : ‘Database Systems’
For example, Figure 6-2 shows the use of character functions U PPE R , LOW ER ,
and I NI TCA P in the SELECT clause to display columns with different cases.
Often, more than one data- entry person will populate a table. One person en-
ters names in all uppercase, and the other uses proper case. This could become a
nightmare for data retrieval query writers if not for functions. Functions are very
useful in the W H E R E clause’s conditions as well.
For example, in Figure 6-3, a query is issued with the condition
= ‘ ’, and it resulted in a “no row selected” message.The table does contain students
from New Y ork state. The problem here is the case used in entering state values. The
same query is rewritten with condition 1 2 = ‘ ’ , and it re-
turned two student names. The use of the U PPE R function converted the value in the
134 Chap. 6 Working with Tables: Functions and Grouping
8 rows selected.
SQL>
no rows selected
LAST FIRST
-- --- ---- --- --- -- ---- --- ---- --
Tyler Mickey
Lee Brian
SQL>
column to uppercase, and it was then compared to the value NY, which has same case.
The condition can be written as 1 2 = ‘ ’ instead.
A character function is used in various SE L EC T clauses, including the
O R D E R BY clause. The L E N GTH function returns the length of a character col-
umn or string literal. Suppose we want to see names in ascending order by length of
names. The clause will use instead of just
, as shown in Figure 6- 4.
LAST FIRST
-- --- ---- --- --- -- ---- --- ---- --
Lee Brian
Diaz Jose
Khan Amir
Tyler Mickey
Patel Rajesh
Rickles Deborah
6 rows selected.SQL>
I NSTR(‘abcdefg’, ‘d’) : 4
LTRIM(‘00022345’, ‘0’) : ‘22345’
RTRI M(‘0223455’, ‘5’) : ‘02234’
TRI M(‘ ‘FROM’ Monroe’) : ‘Monroe’
LENGTH(‘Oracle9i’) : 8
LPA D(265000, 9, ‘$’) : $$$265000
RPA D (265000, 9, ‘*’ ) : 265000* * *
REPLACE(‘Basketball’, ‘ket’, ‘e’) : ‘Baseball’
where we are looking for string ‘OR’ and function is asked to start at the first char-
acter from the left to look for the second occurrence of the string. The result is 5, as
the second ‘OR’ starts at position 5. If argument 1 is changed to - 3, the function will
start at the third character from right and search in the reverse direction.
Numeric Functions. The numeric functions take numeric value(s) and re- turn
a numeric value. The R OU N D function rounds the value, expression, or col- umn
to decimal places. I f is omitted, zero decimal place is assumed. If is
negative, rounding takes place to the left side of the decimal place. For example,
ROUND(25.465, 2) = 25.47
ROUND(25.465, 0) = 25
ROUND(25.465, –1) = 30
TRUNC(25.465,2) = 25.46
TRUNC(25.465, 0) =25
TRUNC(25.465, –1) = 20
POWER(2, 4) = 16
POWER(5, 3) = 125
The ABS function returns the absolute value of a column, expression, or value.
For example,
ABS( –10) = 10
Built-In Functions 137
MOD(5, 2) = 1
MOD(3, 5) = 3
MOD(8, 4) = 0
The SIGN function returns - 1 for a negative number, 1 for a positive number,
and 0 for a zero. For example,
SIGN(-50) = –1
SIGN(+43) =1
SIGN(0) = 0
FLOOR(54.7) = 54
CEIL(54.7) =55
There is a difference in C E I L function, because it always returns the next higher in-
teger value. For example,
ROUND (54.3) = 54
CEIL (54.3) = 55
Figure 6-5 shows the use of numeric functions, and Figure 6-6 explains their
use. D id you notice the table name in Figure 6-5? The table is called D U A L , which
is provided by Oracle. The D U A L table is owned by user SYS, and it is available to
all users. The D U A L table is useful when you want to find the outcome of a function
and the argument is not taken from any table. The D U A L table can also be used
perform arithmetic expressions. For example,
The D U A L table contains a single column called D U MM Y and a single row with
value X (see Fig. 6-7).
Date Functions. W e already know that Oracle stores dates internally with day,
month, year, century, hour, minute, and second information.The default date display
format is DD -MON-Y Y.There is a very useful date function called SY SD A TE that does
not take any arguments. SY SD ATE returns the system’s current date. For example,
SELECT SYSDATE FROM DUAL;
138 Chap. 6 Working with Tables: Functions and Grouping
SQL>
This query will display the current date. Y ou can get more information about day, date
and time by using a format mask with SY SD ATE function. Try the following state-
ment, which will make more sense after format masks are explained in Fig. 6-15:
SELECT TO_CHAR(SYSDATE, ’DY, MONTH DD, YYYY HH:MI:SS P.M.’) FROM DUAL;
Built-In Functions 139
Similarly, the D U A L table can be used to display the outcome of any character and
number functions or an arithmetic expression.
The date-type column is very important. Y ou can derive a lot of information
from date columns by performing “ date arithmetic.” A s you see in Figure 6- 8, you
can add or subtract a number of days to or from a date to get a new resulting date.
You can also add a number of hours to a date. If you have two dates, you can find the
gap in days between them.
I n Figure 6-9, we have an expression 1SY SD A TE - BirthD ate2 that finds the
difference in days. Then, we divide the number of days by 365 to convert it to years.
6 rows selected.
SQL>
To take leap years into consideration, we can divide by 365.25 days instead of by
365. The resulting age has a decimal value.
Y ou can truncate (with the TR U N C function) the result to zero decimal places,
and the age will be a whole number. The modified expression will look like this:
TRUNC((SYSDATE – BirthDate) / 365.25)
140 Chap. 6 Working with Tables: Functions and Grouping
MO NTH S_BETW EEN(date1, ) Finds the number of months between two dates.
ADD_MONTHS(date, ) Adds calendar months to a date.
NEX T_DAY (date, ‘day’) Finds the next occurrence of a day from the given
date.
LAST_DAY(date) Returns the last day of the month.
R OUND(date [, ‘for mat’]) Rounds the date to the nearest day, month, or
year.
TR UNC(date [, ‘for mat’ ]) Truncates the date to the nearest day, month, or
year.
EX TR ACT 1Y EAR | MONTH | D AY FRO M date2 Extracts the year, month, or day from a date
value.
NEX T_TIME ( ) Returns the date in different time zone, such as
EST or PST.
The function NEX T_DA Y returns the next occurrence of a day of the week
following the date supplied. The second argument could be a number in quotes or a
day of the week. For example,
NEXT_DAY (‘14-OCT-03’, ‘SUNDAY’) ‘19-OCT-03’
NEXT_DAY(‘14-OCT-03’, ‘TUESDAY’) ‘21-OCT-03’
The function LAST_DA Y finds the last date of the month for the date sup-
plied as an argument. If something is due by the end of this month, what is that
date? For example,
LAST_DAY(‘05-FEB-04’) ’29-FEB-04’
Built-In Functions 141
Here, the date is nearer to A ugust 1 than to July 1. I n the next example, the
date is nearest to the first of next year:
The TR U N C function truncates the date to the nearest format specified. Trun-
cation to the nearest month returns the first day of the date’s month, and truncation to
the nearest year returns the January 1 of the date’s year. For example,
The E X TRA CT function extracts year, month, or day from a date value.For
example,
SELECT EXTRACT(MONTH FROM sysdate), EXTRACT(DAY FROM sysdate),
EXTRACT(YEAR FROM sysdate) FROM dual;
The following is a list of a few more date- and time-related functions intro-
duced in Oracle9i:
If the commission amount is null, convert it to zero. I f Hi reD ate is not entered,
use ‘01-JA N-03’ for it. I f prerequisite is null, use ‘None’.
Now, we will revisit our query in Fig. 5-18, where we tried to add Salary and
Commission columns. The total was blank for employees without a value in the
Commission column. Remember, any number plus a null value is equal to null. Let
us rewrite the same query using the NV L function (see Fig. 6-11).
8 rows selected.
SQL>
For example,
NVL2(PreReq, ‘YES’, ‘NO’)
For example,
In other words, if the commission value is not null, then display it. I f commission value
is null, then display salary value. I f salary value is null, then display - 1.
The NU L LI F function generates null values. First, it compares two expressions.
Then, if their values are equal, it generates a null, or it returns the first expression.
The general syntax is
For example,
NULLIF(Supervisor, 111)
If Supervisor is equal to 111, then a null is displayed; otherwise, the supervisor’s value
isdisplayed.
The D E C O D E function is a conditional statement type of function. If you are fa-
miliar with any programming language like V isual Basic 6 (I f Á ElseIf or Select Á
Case structures) or C (if Á else if or switch Á case structures), you will understand
the function with ease. The D E C O D E function tests a column or expression and for
each of its matching value, provides an action. The general syntax is
The default action is provided for any value that does not match the values
checked within the function. If the default value is not used, a null value is returned
for nonmatching values. For example, we are displaying new salary for all employees
based on their PositionId. PositionId 1 gets a 20% raise, 2 gets 15% , 3 gets 10% , 4
gets 5% , and others get no increment at all. If the last default salary is not included
in the statement, the new salary for employees with PositionId 5 is displayed as null.
Conversion Functions. The conversion functions convert data from one data
type to another. The Oracle server follows some rules to convert data type im-
plicitly. For example, if you enter a character string that includes a valid number, the
Oracle server can successfully convert C H A R data to N U M B E R data. If you enter
a date as a string and use the default date format D D -MO N- Y Y, the Oracle server
can perform C HA R - to- D A TE conversion successfully. I t is advisable to use explicit
data conversion functions for successful and reliable queries. The three conversion
functions shown in Fig. 6- 12 are used for explicit data- type conversion in queries.
8 rows selected.
SQL>
6 rows selected.
SQL>
A s we have been saying, the default date format is set to D D- MON- Y Y in most
Oracle installations. I n Oracle-9i, DD -M ON- Y Y Y Y also works as a default. If you
enter a birth date as 15-A PR-60, it will be stored with year as 2060. That will create
undesired result. I f the default format is D D - M ON- RR, years 50 to 99 are interpreted
as 1950 to 1999 and years 00 to 49 as 2000 to 2049. If you are not sure about your ses-
sion settings, use a four-digit year with I NSERT as well as other SQL statements. In
Figure 6-17, the character date values are converted to date type with the TO_D ATE
function and format mask D D - M ON - RR . Then, it is changed back to character for-
mat with the TO_ CH A R function and format mask Y YY Y.
SQL>
to nearest month next, the A D D _MO NTHS function adds three months to it, the
NE XT_D AY function finds the date on next Tuesday, and finally, seven is added to it.
The result is the tax day, which happens to be my birthday also. (People get gifts on
their birthday, but I always have to send a gift to U ncle Sam on mine!)
Group Functions
The group functions perform an operation on a group of rows and return one result.
Look at the E MPL OY E E and STU D E NT tables:
SUM ( ) Finds the sum of all values in a column; ignores null values.
AVG ( ) Finds the average of all values in a column; ignores null
values.
MAX 1 ƒ 2 Finds the maximum value; ignores null values.
MIN1 ƒ 2 Finds the minimum value; ignores null values.
COUNT 1* ƒ ƒ 2 Counts the number of rows, including nulls, for *; counts
nonnull values if the column or expression is used as an
argument.
which means use all values (including duplicate values), is the default. The key word
DI STI NCT tells the function to use nonduplicate values only.
L et us write a query to find the total, average, highest, and lowest salaries from
the E M PL O Y E E table. Figure 6-20 shows the use of group functions on a number
column, Salary.
1 row selected.
SQL>
Now, we will try the M A X and MI N functions on a date field. W hich student
from the STU D E N T table was born first, and which was born last? Check out
Figure 6-21. The M A X of a date returns the latest date, and the MI N of a date re-
turns the earliest date. If you use the function on a character column, M A X will re-
turn the last name alphabetically, and MIN will return the first name alphabetically.
SQL>
In Figures 6-22 and 6-23, uses of the CO U N T function on an entire row and a
column are given. I n Figure 6- 22, when rows are counted in the E M PL O Y E E table,
all eight employees’ rows are counted. I n Figure 6- 23, when EmployeeId column val-
ues are counted, it returns eight employees. When Commission column values are
counted, the null values are ignored, giving us only five commissioned employees.
We can change that using the NV L function:
COUNT(NVL(Commission,0))
Grouping Data 149
COUNT(*)
--- --- -- --
8
SQL>
COUNT(EMPLOYEEID) COUNT(COMMISSION)
--- --- --- -- --- --- -- --- --- -- --- --- -
8 5
SQL>
Null values in Commission columns are replaced with 0 in the query, and the value 8
is returned from the query.
Question: W hich of the following queries will return a higher average from
the Commission column?
Answer : The first query, because it adds five commission values and divides the total
by five, whereas the second query divides the total by eight. The output
would be 14600 from the first query but 9125 from the second query.
GROUPING DATA
The rows in a table can be divided into different groups to treat each group sepa-
rately. The group functions can be applied to individual groups in the same fashion
they are applied to all rows. The G R O U P BY clause is used for grouping data. The
general syntax is
150 Chap. 6 Working with Tables: Functions and Grouping
I n the next few figures, you will see the effect of a GR O U P BY clause on queries
with group functions.
As you see in Figure 6-24, the D eptId column is automatically sorted, because it is
used in the GR O U P BY clause. The DeptId column is not necessary in the SELECT
clause, but it is a good idea to include it so the counts mak e sense.
DEPTID # of Emp
-- --- -- - --- -- -
10 3
20 2
30 2
40 1
SQL>
ERROR at line 1:
ORA-00937: not a single-group group function
SQL>
ERROR at line 3:
ORA-00934: group function is not allowed here
SQL>
HAVI NG Clause
The HA V I N G clause can restrict groups. The W H E R E clause restricts rows, the
G R OU P BY clause groups remaining rows, the Group function works on each
group, and the HA V I NG clause keeps the groups that match the group condition.
I n the sample query (see Fig. 6- 27), the W HE R E clause filters out the building
named Kennedy, the rest of the rows are grouped by the building names Gandhi and
Nehru, the group function C O U N T counts the number of rows in each group, and
the H A V I N G clause keeps groups with four or more rows— that is, the Gandhi
building with five rows/rooms.
The implied ascending sort with the GR O U P BY clause can be overriden by
adding an explicit O R D E R BY clause to the query. Figure 6-28 shows outcome sorted
in ascending or der by Building column with the G R O U P BY clause, then it is re-
versed to descending order by inserting the O R D E R BY clause in line 5.
152 Chap. 6 Working with Tables: Functions and Grouping
SQL> i
5 ORDER BY Building DESC;
BUILDIN COUNT(*)
- --- --- - --- -- --
Kennedy 4
Gandhi 5
SQL>
The single- row functions can be nested to many levels, but the group functions can
only be nested to two levels. For example,
SELECT SUM(MaxCount) FROM crssection GROUP BY CourseId;
will find the total available seats for each CourseId. I f you use this output for an
outer function in a nested scenario as follows, you will get a different answer:
SELECT MAX(SUM(MaxCount)) FROM crssection GROUP BY CourseId;
The answer returned by this query is 85, because the outer query takes totals by
each CourseId and finds the one with the largest value.
I N A NUTSHELL . . .
● Single- row functions work on each row individually. They include character
functions, number functions, date functions, data conversion functions, and
other general functions. A ll functions take zero or more arguments and re-
turn one value back.
● The NV L function converts a null value to another specified value that is
provided as its second argument.
● The D E C O D E function is similar to the if Á else if or case structures in
programming languages.
● I n an expression with nested single-row functions, the innermost function is
performed first, and the outermost function is performed last.
● The SY SD ATE function is an Oracle function that returns the current date
from the system. SY SD ATE is very useful in date arithmetic.
● The group functions work on a group of rows to return one result per group.
The rows can be grouped together by using the G R O U P BY clause with a
SE L E C T query.
● The W H E R E clause is used to restrict rows; similarly, the H A V I NG clause is
used to restrict groups.
● The group functions can be nested like single- row functions. The nesting is
limited to two functions for group functions.
E X ER C I SE Q UE STI ON S
True/F alse:
1. A single-row function may be used in the SEL ECT clause, but it is not allowed in the
W H ER E clause.
2. The SYSDATE function can return the current date but not the current time.
154 Chap. 6 Working with Tables: Functions and Grouping
State W hich of the Following Quer ies W ill R esult in an Er ror M essage and W hy (U se Tables
Created in the Chapter 4 Lab Activity):
1. SELECT UPPER(FirstName |‘‘||LastName) FROM student;
2. SELECT DeptId, COUNT (*) FROM employee;
3. INSERT INTO DEPT VALUES(90,RESEARCH, NULL, NULL);
4. SELECTDeptId, SUM(Salary) FROM employee
WHERE SUM(Salary) > 200000GROUP BY DeptId;
5. SELECT SUM(EmployeeId) FROM employee;
L AB A C TI V I TY
W r ite Queries for the Following (Use Tables Created in Chapter 4 L ab Activity):
1. Display all employee names (last name and first name separated by a comma and a space)
with proper case and salary with currency format.
2. Display all employees with their commission value. Display zero commission for employees
who do not get any commission.
Chap. 6 Lab Activity 155
I n C hapter 5, learned data retrieval techniques to obtain data from a single table
with the SEL E C T query. I n Chapter 6, learned the use of various clauses and func-
tions used in SE L EC T statements. I n this chapter, we will expand on what you have
learned in the previous chapters. Here, you will learn to create queries in which data
are retrieved from more than one table or with more than one query. For example, a
student’s demographic information is in the STU D E N T table, and his or her faculty
advisor’s information is in the FA CUL TY table. A n employee’s name is in the EM-
PL OY EE table, but his or her department’s information is in the D E PT table, any
dependents are in the D E PE ND E N T table, and the salary grade is in the EM-
PL E V E L table. Sometimes, you can accomplish tasks by joining two or more ta-
bles— or by joining a table to itself.
Join 157
JOIN
When the required data are in more than one table, related tables are joined using a
join condition. The join condition combines a row in one table with a row in anoth-
er table based on the same values in the common columns. I n most cases (but not al-
ways), the common columns are the primary key in one table and a foreign key in
another. I n this section, you will be introduced to different types of joins based on
the join condition used.
Cartesian Product
A Cartesian product results from a multitable query that does not have a W H E R E
clause. The product operation joins each row in the first table with each row in the
second table. The product normally results in an output with a large number of rows
and is not very useful. Whenever retrieving data from more than one table, you must
use one or more valid join conditions to avoid a Cartesian product! You would per-
form a Cartesian product operation only if you were looking to find all possible
combinations of rows from two tables.
I n Figure 7-1, you will see an example of a product in which all students and
faculty members are matched unconditionally. A ll resulting rows are not shown in
the figure. The last and first names are selected from the STUD ENT, table and a
Rajesh Collins
Deborah Collins
BrianAmir Collins
Collins
name is selected from the FA CUL TY table.There is no join condition issued.The result
.
is 48 rows, because the product of two tables with and rows, respectively, returns
rows. The STU D E NT table has 6 rows, and the FACU LTY table has 8 rows,
hence the result 16 . 8 rows2. If you were looking for each student’s last name and
his or her faculty advisor’s name, you would use a join condition using the STU D ENT
table’s foreign key FacultyI d and the FACU LTY table’s primary key FacultyI d to find
matching rows.
The Cartesian product is covered in this section, but it is not a join operation.
There is no join without a join condition. I n Oracle, you will perform a Cartesian
product by not providing enough join conditions in the SE L E C T query. Remember
that the number of join conditions is one less than the number of table names used
in the FR O M clause. There are four types of joins in Oracle:
1. Equijoin.
2. Nonequijoin.
3. Outer join.
4. Self- join.
Equijoin
The equijoin is a join with a join condition involving common columns from two tables.
If you need to get information about a student from the STU D E NT table and corre-
sponding information about the faculty advisor from the FA CULTY table, you would
use the following syntax:
The column names include columns from both tables separated by commas, table
names are all tables used separated by commas, and the join condition is a condition
that includes common columns from each table. The join condition normally (but
not always) includes a foreign key column from one table and the referenced pri-
mary key column from the other table. Suppose you want to get a student’s last
name, the student’s first name, the faculty advisor’s name, and the faculty advisor’s
phone number. Y ou would get them from the STU D E N T and FA CULTY tables.
The common column in both tables is FacultyId, which is the foreign key in the child
STU D E NT table and the primary key in the parent FACU LTY table. The join con-
dition will return the requested information from rows in two tables where the Facul-
tyI d value is same. The rows without a match are not selected by the query. Figure 7-2
shows the result from an equijoin.
I n Figure 7-2, you see that all students are picked from the STU D E N T table,
but faculty members are picked based on the FacultyId in the student rows. The facul-
ty member 1FacultyI d = 3332 is not selected because there is no match for it
Join 159
6 rows selected.
SQL>
The query will look like the one shown in Figure 7-3. For simplicity, we will
join three tables using two join conditions. There is no limit on the number of join
conditions within a query.
8 rows selected.SQL>
The multiple-join example selects information from three tables using a query
with two join conditions. I f you look at the query, the table qualifiers are used quite
a few times. There is a way to shorten and simplify this query.
Table Aliases
In C hapter 5, you learned about column aliases, which are used for renaming column
headings in a query. Table aliases are used to avoid using lengthy table names over
and over again in a query. A table alias can be from 1 to 30 characters long. Normally,
very short alias names are used to shorten the query and save some keystrokes. The
table alias appears in the FRO M clause of the SELE CT query. A table name is written,
followed by a space, and then a table alias is supplied. Though they appear after the
SE L E CT clause, alias names can also be used as qualifiers for column names in the
SE L E CT clause. A ll table aliases are valid only in the SE L E C T query, where they
are named and used.
I n Figure 7-4, you will see the query from Figure 7- 3 with table aliases. The
results obtained from the queries in Figures 7-3 and 7-4 are similar, but the query
in Figure 7-4 is shortened by the use of table aliases. I n this example, we joined the
Join 161
7 rows selected.SQL>
Additional Conditions
In addition to join conditions, you may use additional conditions using the A ND oper-
ator to restrict information. Suppose you want to see the information of Figure 7-4
for employees belonging to department number 10 only. Figure 7-5 shows the use of
additional condition with the A ND operator where the information is displayed for
D eptI d = 10 only. The three tables are joined for employees in D epar tment 10,
which results in three rows instead of all eight employee rows.
Nonequijoin
There is no matching column in the E M PL E V E L table for the Salary column in the
E M PL OY E E table. The only possible relationship between the two tables is be-
tween the Salary column of the E MPL OY E E table and the LowSalary and High-
Salary columns in the E M PL E V E L table. The join condition for these tables can be
written using any operator other than the = operator. That is why it is called non-
equijoin. Figure 7- 6 is an example of a nonequijoin.
The nonequijoin condition of Figure 7- 6 could have been written as
e.Salary >= l.LowSalary AND e.Salary<= l.HighSalary;
162 Chap. 7 Multiple Tables: Joins and Set Operations
8 rows selected.SQL>
If you look at the E MPL E V E L table, none of the salaries appears in more than one
level. I n other words, there is no overlapping. N one of the employees makes a salary
that is not included in the range of salaries. For these two reasons, each employee
appears once in the result. Note that none of the columns are ambiguous, so table
aliases are not necessary (though they are used here in this example).
Join 163
Outer Join
You saw in the equijoin that the rows from two tables are selected only if the common
column values are the same in both tables. If a row in one table does not have a
matching value in the other table, it is not joined. Figure 7-2 displayed all students
from the STU D E N T table and their advisors from the FACU LTY table. Some of
the faculty members are not any student’s advisor, so they did not get selected. Sup-
pose you also want to see all those faculty advisor names. Then, you would change
your query’s join condition and create a join known as an outer join.
The table that does not contai n the matching value is known as the deficient
table. In our case, the deficient table is the STU D E N T table, because it does not
contain all faculty I D s. The outer join uses the 1 + 2 operator in the join condition on
the deficient side. (You will see it soon in Figure 7-8, which compares equijoin and
outer join on these tables.) The 1 + 2 operator can be used on any side of the join
condition, but it cannot be used on both sidesin one condition. The general syntax is
The join conditi on will look different if the 1 + 2 operator is used on the right
side. For example,
WHERE = (+);
EMPLOYEE QUALDESC
-- --- -- --- --- -- --- --- -- -- --- -- --- --- -
JohnSmithLarry Houston Sandi Doctorate Masters
Roberts Alex McCall Derek Dev Masters Associates
JinkuShawStanley Garner Sunny Doctorate
Chen
8 rows selected. SQL>
High School
Bachelors
9 rows selected.
6 rows selected.
SQL>
it is the deficient table or it generates a null value for the row(s) in the E M PL OY E E
table without any qualification value. The equijoin would have returned seven
employees, but the outer join also includes one extra employee without any
qualification.
Figure 7- 8 compares outputs from outer join and equijoin on the same tables.
The equijoi n returns six students with their faculty advisors’ names, whereas the
outer join returns three extra rows with faculty names. The outer join operator 1 + 2
is used on the STU D E NT table’s side, because it generates null values for faculty
members with no match in the STU D E N T table.
Join 165
Self-Join
A self-join is joining a table to itself. I t sounds meaningless, but think about it using
the following scenario: I n the E M PL O Y E E table, EmployeeI d is the primary key
column that describes each entity. For example, E mployeeId 200 represents employee
Shaw, Jinku. The table also has another column called Supervisor, which contains
ID s of employee supervisors. How can you find name of the supervisor for an em-
ployee? You can look up the supervisor ID , go to the E mployeeI d column to find its
match, and then read the name. This is easier said than done, however. A self- join is
one join that is not so easy to understand.
When a table is joined to itself, two copies of the same table are loaded or
used. They are treated like any two different tables, and a join is produced from
those two copies. Let us explain that by using the E M PL O Y E E table. The following
operations are performed in the self- join of Figure 7-9:
• Two copies of the E MPL OY E E table are created with the aliases and .
• A n employee’s last name is picked from the table, and the corresponding
Supervisor I D is retrieved.
• The matching E mployeeI d is found from the table. The first employee in
the table does not have a supervisor and so is not picked.
• The last name from the table is retrieved based on the EmployeeId.
I n short, the table is looked at twice, once for the employee and once for the super-
visor. The Indo–US (I U ) College database also contains a table, which can be used
in self-join. Table CO U RSE contains a Pr eR eq column that references its own pri-
mary key, CourseI d. Y ou will perform this self-join in the chapter’s lab activity.
166 Chap. 7 Multiple Tables: Joins and Set Operations
SET OPERATORS
In Chapter 1, you learned about union, intersection, and difference operations. I f you
recall, these operations are possible on “union- compatible” tables. The implementa-
tion of these operations is through the use of set operators. The union compatibility
is achieved or the set operations are performed on results from two independent
queries. The output from both queries must return the same number of columns, and
respective columns must have a similar domain. Figure 7-10 lists all set operators and
their use.
The general syntax for any set operation is
SELECT- SELECT-
UNION It returns all rows from both queries, but duplicate rows are not repeated.
UNION ALL It returns all rows from both queries, and it displays all duplicate rows.
INTERSECT It returns all rows that appear in both queries’ results.
MINUS It returns rows that are returned by the first query minus rows that are
returned by the second query.
Union
The U N I O N operator takes output from two queries and r eturns all rows from
both results. The duplicate rows are displayed only once. I f you perform union on
Set Operators 167
U NIO N
IN TERSECT
MINUS
two very large tables, use a W H E R E clause to filter rows. A ll six student’s rows
ar e selected from the first query, and four rows are selected from the second
query. Two rows from the second query ar e duplicate rows (I D 00103 and I D
00105), and they are not repeated. Figure 7-12 lists all students and staff members
in the result.
Union All
ID LAST FIRST
--- -- - --- --- -- --- - -- --- -- --- ---
00100 Diaz Jose
00101 Tyler Mickey
00102 Patel Rajesh
00103 Rickles Deborah
00104 Lee Brian
00105 Khan Amir
00110 Borges Luz
00111 Bayer Julia
00103 Rickles Deborah
00113 Marte Noemi
00105 Khan Amir
ID LAST FIRST
--- -- - --- --- -- --- - -- --- -- --- ---
00107 Feliciano Sandi
12rows selected.
SQL>
Intersect
The I NTE R SE CT operation works on output from two separate queries and returns
rows that appear in both outputs. I n the student and worker example, I NTE RSE CT
will return students who are also workers at the college. In Figure 7- 14, you see only
two student rows, which are the only students appearing in the W O RK E R table.
SQL>
Minus
ID LAST FIRST
--- -- - --- --- -- --- - -- --- -- --- --- -
00100 Diaz Jose
00101 Tyler Mickey
00102 Patel Rajesh
00104 Lee Brian
4 rows selected.
SQL>
ID LAST FIRST
--- -- - --- --- -- --- - -- --- -- --- ---
00107 Feliciano Sandi
00110 Borges Luz
00111 Bayer Julia
00113 Marte Noemi
4 rows selected.
SQL>
(actually five, because E MPL OY E E table is used twice) with two equijoins, two
outer joins, one nonequijoin, and one self-join. The result contains everything we
need to know about employees!
IN A NUTSHELL . . .
● Two tables can be joined with a common column. U sually, the common
columns are a foreign key in one table and the primary key in the other
table that is referenced.
● If a join condition is not used in a multitable query, it results in a Cartesian
product.
● Four types of joins in Oracle are equijoin, nonequijoin, outer join, and self- join.
● I t is possible to join more than two tables in a database. Y ou need - 1
conditions to join tables.
● Table aliases are used in a query to avoid typing long table names. The table
aliases are known only in the query where they are defined.
● A n additional condition is used along with the join condition to filter out
some rows.
● A nonequijoin has a join condition that does not use the equality 1 = 2 operator.
● A n outer join is achieved by using the 1 + 2 operator on the deficient tabl e’s
side in the join condition. I n other words, the 1 + 2 operator is used on the
side that generates null values. The outer join also selects rows without a
matching row in another table involved in the join operation.
● A self-join joinsa table with self. This operation uses two copies of same table.
● The set operators U NI ON, U NI ON A L L , I NTERSECT, and MI NU S are
used to connect output from two individual SE L E CT queries. Both query
outputs must return the same number of columns with similar domains.
EX E RC I S E QU E STI ON S
True/False:
1. You alway s need at least two different tables for a join.
2. If a table has three rows and another table has four rows, their product will contain seven
rows.
3. The common column in two tables must have same name to join them.
4. A table alias is known in the query in which it is created.
5. In an outer join, the 1 + 2 operator can be used on any one side of the equality 1 = 2 sign,
but it cannot be on both sides of a join condition.
6. The set operator U N I ON does not repeat duplicate rows, but U N I ON A L L does.
7. TableA MINUS TableB is always the same as TableB MINU S TableA.
8. A self-join can be performed on any table, because all you need is one table.
172 Chap. 7 Multiple Tables: Joins and Set Operations
9. A n outer join usually returns more information than an equijoin on the same tables.
10. Two tables must have established foreign key–primary key relationship to perform a
nonequijoin on them.
Define the F ollowing Terms, and Give One Example of Each:
1. Equijoin.
2. O uter join.
3. Self-join.
4. Minus.
5. Cartesian product.
Answer the Following Questions:
1. W hat is the use of the set operator I NTERSECT?
2. In which situations would you use a self-join?
3. W hen is it appropriate to use an outer join?
4. W hen would you use a MINU S operation?
5. How would you join five tables in a database?
L AB A C TI V I TY
SUBQUERY
Single-Row Subquery
There are certain rules you have to follow while creating a subquery:
When a statement is written with a subquery, the inner query (subquery) is exe-
cuted first. The inner query returns a value or a set of values to the outer query.
Next, the outer query is executed with the result from the inner query.
In Figure 8-1, you see a subquery based on two tables. I t returns a result similar to
the one in Figure 7- 5. The subquery example is substituted for a join condition and an
additional condition of Figure 7-5. The inner query finds the D eptI d 10 from the
D E PT table based on D eptN ame = ‘FINANCE’. The result is used in the condition of
the outer query, which returns employees in D eptI d = 10.
A subquery can also be based on only one table. Suppose you want to find the
names of employees who mak e more salary than employee D ev 1EmployeeId
Subquery 175
= 5432. You will find the salary for the employee in the inner query first and then
use it in the outer query. For example, in Figure 8- 2, the inner query finds the salary
for employee D ev, and the outer query compares it with the salary received by other
employees with the 7 = operator. O perator 7 = is used instead of 7 to include
employee D ev in the output as well.
Similarly, we can write queries to tackle problems like finding employees who
work in the same department in which John Smith works or employees who do not
work in the same department. Figure 8-3 shows all employees who do not work in
employee John Smith’s department. For simplicity, the inner query does not contain
this multiple condition to check for the last name as well as the first name:
WHERE UPPER(Lname) = ‘SMITH’ AND UPPPER(Fname) = ‘JOHN’;
176 Chap. 8 Subqueries: Nested Queries
5 rows selected.
SQL>
When a new table is created with a subquery or a nested query, the primary
key constraint is not transferred to the new table from the existing table. The N OT
NU L L is the only type of constraint that gets transferred to the new table. Other
constraints can be added to the new table with the A L TE R TA B L E statement.
In Figure 8-5, new table TE MP is created based on the E MPLO Y E E table. The
SEL ECT query selects two employees belonging to D epartment 20 and adds them to
Subquery 177
BUILDIN ROO
- --- -- - -- -
Gandhi 103
1 row selected.SQL>
2 rows selected.
SQL>
the newly created table. The new table contains only four attributes, as selected by the
inner query. The figure also shows use of the new TE M P table with the D E SCR I BE
and SEL ECT statements. A user may add more constraints to this newly created table
with the A L TE R TA BLE statement.
The INSERT statement does not use the V AL UES clause.The subquery replaces
the V A LUE S clause and provides values for the new rows. The column list in I NSERT
is optional. The column list can be used from the nested SELECT query.
In the example of Figure 8-6, all employees in Department 10 of the EMPLOY -
E E table are selected, and the TE M P table is populated with those employees only.
The TE M P table already had two rows; three more rows are added with INSERT.
Now, the table contains five rows in all. The TE M P table contains four columns, but
values are inserted into three columns only. Employee salaries are not included for
employees from D epartment 10.
Inserting into Multiple Tables (Oracle9i Onward) I n most cases, you use the
INSERT statement to add a row into a table. Oracle9i has new feature that allows
you to enter rows into multiple tables simultaneously. This feature is useful for
transferring, archiving, and denormalizing data. The multiple INSERT statement is
faster and more flexible than many one-row, simple I NSERT statements. Two
multiple INSERT statements are:
Unconditional INSERT ALL I n this example, rows are selected from the
E M PL OY E E table and inserted into two existing tables, E MPL OY EE _SA LA RY
and E MPLO Y E E _D E PT. Notice that these two tables contain different columns.
The inner SE L E CT statement retrieves rows from the E MPL OY E E table, and
those rows are inserted into two tables. The INSERT statement does not have any
conditions:
Conditional INSERT ALL In this example, the rows are inserted into tables
based on their individual conditions. The W HE N Á TH E N clause is used with dif-
ferent conditions for inserting rows into different tables. Rows are inserted into the
E MPL O Y E E _SA L A R Y table if salary is higher than 50000. Rows are inserted into
the E M PL OY E E _D E PT table if D epar tI d is not equal to 40:
For example, the NamanNavan (N2) Corporation is very pleased with the perform-
ance of the entire FI N A N CE team and decides to raise their salary by 10% (see
Fig. 8.7). The inner query supplies D eptI d based on the department’s name, which
the outer query uses in its W H E R E clause.
UPDATEemployee
SET Salary = Salary* 1.10WHERE DeptId =
(SELECT DeptId FROM dept
WHERE UPPER(DeptName) = ’FINANCE’);
3 rows updated. SQL>
A n alternate syntax is
Multiple-Row SubQuery
A multiple- row subquery returns mor e than one row. The operators used in single-
row subqueries 1 = , 6 7 , 7 , 7 = , 6 and 6 = 2 cannot be used with multiple- row sub-
queri es. Figure 8- 10 shows special operators used with multiple- row subqueries.
Operator Use
SQL>
The inner query in Figure 8- 12 returns four values (150000, 75000, 80000, and
45000). The 7 A N Y operator checks for values larger than the minimum salary of
45000 in the list. The outer query also checks for PositionId not equal to 2. Rows
with EmployeeId 111 and 433 are selected. You may use the operator SO ME in
place of A N Y to achieve the same result.
The A L L operator can also be used with relational operators. I t serves like an
A N D operator, because it looks for a match to all values! For example:
I n Figure 8-13, the inner query returns four averages, one value per depart-
ment (125000, 73250, 34750, and 150000). The 6 A L L operator means the employee
with a salary less than the minimum in the list of values. From the original table in
C hapter 3, only one row— and E mployeeId 200 and salary of 24500— is picked. If
you change condition to =A L L , you will see the “ no rows selected” message.
TOP-N ANALYSIS
Top- N queries are used to sort rows in a table and then to find the first- N largest or
first- N smallest values. For example, you want to find the bottom five salaries in a
company, the top three room capacities, or the last 10 employees hired by a compa-
ny, you would use a Top-N query.
The Top- N query uses an O R D E R BY clause to sort rows in ascending or de-
scending order. The sorted rows are numbered with a pseudocolumn named
RO W NU M. I f the rows are sorted in ascending order by the Top- N column, the
smallest value of the Top- N column is at the top of the list. The largest value of the
Top- N column is at the top of the list if the rows are sorted in descending order by
the Top-N column. Y ou can display the required number of rows based on the
R OW NU M with 6 or 6 = operators. The 7 and 7 = operators are not allowed
with a RO W N U M pseudocolumn.
184 Chap. 8 Subqueries: Nested Queries
SQL>
SQL>
Top- N analysis is explained here in a way that is consistent with the Oracle online
training documentation. You may not use the O R D E R BY clause with an inner
subquery. If you cannot perform this analysis with the inline view, which contains an
O R D E R BY clause in the inner query, create view with the G R O U P BY clause in
the SE L E CT query. The G R O U P BY clause contains an implicit O R D E R BY op-
eration in the ascending order. Y ou will be able to select the Top- N rows from the
view based on the R OW NU M pseudocolumn. The limitation is that only 6 and
6 = operators are allowed with the pseudocolumn ROW NU M . A s the implied sort
is in the ascending order, the lowest values get moved to the top, and you will be
able to get only the bottom- N values. The Top-N analysis has worked without any
problems in Oracle9i, but I did face problems in Oracle8.The Oracle views are covered
in the next chapter.
MERGE STATEMENT
CORRELATED SUBQUERY
Correlated subqueries are different from the other subqueries explained earlier in this
chapter. I n a correlated subquery, the inner (nested) query can reference columns from
the outer query. The inner query is executed once for each row in the outer query. In
other subqueries, the inner query was executed only once. It is a complex— but very
powerful— feature. The example in Figure 8-17 performs a correlated subquery.
First, Oracle selects a row from the outer query. Then, it finds the value of the
correlated column(s). Next, it executes the inner query for each row of the outer
query, sends the result of the inner query to the outer query, and executes the outer
query. If the row satisfies the condition, it outputs the row. Then, it selects the next
row from outer query and repeats the same procedure.
I n Figure 8-17, each employee’s salary is matched with the maximum salary of
his or her department (outer.D eptI d). The result is employees with the maximum
salary in their respective departments. With a simple G R O U P BY clause, you can
find the maximum salary for each department, but you cannot find employees making
those salaries. A correlated subquery, however, enables you to find that information.
186 Chap. 8 Subqueries: Nested Queries
6 rows selected.
6 rows merged.
The EX ISTS and NO T EX I STS operators are used with correlated queries. The
EX I STS operator checks if the inner query returns at least one row. I t returns
Correlated Subquery 187
FACULTYID NAME
-- ------ -- -- ------- ------
111 Jones
222 Williams
123 Mobley
345 Sen
555 Chang
SQL>
I n Figure 8-19, the N OT E XI STS operator is the opposite of the EX ISTS op-
erator. I t checks if the inner query does not return a row. I n other words, it returns
faculty members who are not in the STU D E NT table.
188 Chap. 8 Subqueries: Nested Queries
FACULTYID NAME
- --- --- -- - -- --- --- -- --- --
235 Vajpayee
444 Rivera
333 Collins
SQL>
IN A NUTSHELL . . .
● Subqueries are also known as nested queries. I n a nested query, the inner
query is executed first. The output from the inner query is then used by the
outer query.
● A single-row subquery returns one row of data, whereas a multiple-row sub-
query returns more than one row of data.
● A single- row subquery may use relational operators, but multiple- row sub-
query may use IN, A N Y (or SOME), and A L L operators in conjunction
with relational operators.
● The inner query in the subquery is enclosed within parentheses, and it can-
not use the O R D E R BY clause.
● A subquery may be nested to multiple levels.
● A subquery can be used with the SE L E CT statement. I t can also be used
with C R E A T E to create a table and populate it with rows in another table.
● A subquery is also used with INSERT, D E L E TE , and U PD A TE data manip-
ulation queries.
● The multiple-row subqueries use the special operators IN, A L L , SOM E , and
ANY .
● Top-N analysis is used to sort rows in ascending or descending order and
then to find the Top- N rows for the N highest or lowest values. The inline
view is used for a Top- N analysis.
● A M E R G E statement performs the INSERT and U PD A TE operation to-
gether.
● I n a correlated subquery, the inner query references a column in the outer
query.
● EXI STS and NOT EXI STS are special operators used in correlated subqueries.
Chap. 8 Lab Activity 189
E X ER C I SE Q UE STI ON S
True/F alse:
1. A n inner subquery may not use the O R D ER BY clause.
2. The inner subquery does not have to be a SEL ECT statement.
3. A subquery may not be nested to more than three levels.
4. Operators A NY and SOM E are the same.
5. The = AL L operator does not return any rows in most cases.
6. Top-N analysis uses R O W I D attribute for row numbers.
7. A n inline view may use the O R D ER BY clause.
8. In correlated subqueries, the inner query can reference a column from the outer query.
9. = AN Y means IN.
1 0. 7 A L L means greater than the minimum value.
11. A table can be created with a subquery and an INSERT statement.
12. A table can be created based on another table with a subquery.
13. W hen a table is created with a subquery, it inherits all constraints from the original table.
Define the F ollowing Terms, and Give One Example of Each:
1. Single-row subquery.
2. Multiple-row subquery.
3. Inline view.
4. Top-N query.
5. Correlated subquery.
Answer the Following Questions:
1. State the various uses of a subquery.
2. In which situations would you use a three-level subquery?
3. W hat constraints are transferred to the newly created table with a subquery?
4. How does a Top-N query work?
5. W hat is the use of the INSERT AL L and INSERT FIRST statements?
6. W hy is the M E R GE statement useful?
7. A subquery returns three values: 35000, 45000, and 55000. The outer query has a condition
that tests a value of 40000 against these values. If the =A N Y , 7A N Y , 6 A L L , 7 A L L , or
6 7 A L L operator is used, when will the value 40000 satisfy the condition? U se each oper-
ator separately.
L AB A C TI V I TY
(c)
W ho has the same qualification as Stanley Garner?
(d)
W hich department has more employees than Department 20?
(e)
W hich employees have been working in the company longer than Larry Houston?
(f)
Find all employees in the Sales Department by using a nested query.
(g)
Create a new table, EMP30, and populate it with employees in Department 30 by
using an existing table and a subquery. Use EmployeeId, L name, Fname, HireDate,
and Salary columns.
(h) A dd more rows to the EMP30 table with employees in Department 40. D o not trans-
fer the employee’s salary.
(i) U pdate the salary of newly transferred employees from the EM PL O Y EE table to
the EMP30 table with a M ER G E statement, and INSERT employees who are not in
the EMP30 table.
(j) Find employees with the minimum salary in their own department with the use of a
correlated subquery.
(k) U se a multiple-level subquery to display dependent information for employees who
belong to the FI NA NCE department.
(l) U se set operator and subquery to find employees who do not have any dependents.
(m) W rite a subquery that finds the average salary by each department. Check to find if
employee 543’s salary satisfies the =A N Y , 6 AN Y , 7A N Y , 6 A L L , or 7 A L L con-
dition against those departmental average salaries.
2. U se the I U College database tables to design the following subqueries. (U se the spool-
ing method to capture all queries and results in the CHAP8SP2.LST file)
(a) Display student Jose Diaz’s faculty advisor’s name and phone number.
(b) Find the rooms with the bottom-two capacities. Do not include office rooms.
(c) Find the Spring 2003 course sections with the top-three maximum count numbers.
(d) Find all information regarding classrooms 1 RoomType = ‘C’2.
(e) Create a new table, SP03SECT, for Spring 2003 semester course sections by using a
subquery. Include CourseId, Section, FacultyId, and RoomId columns only.
(f) Delete rows from the SP03SECT table for faculty member Mobley.
(g) Find faculty members who do not teach any course in the Spring 2003 semester. Use
a correlated subquery with a NOT EX ISTS operator on the SP03SECT table.
IN THISCHAPTER . . .
You have learned to create, modify, remove, use, and manipulate an Oracle object
called a table. I n this chapter, you will learn about other objects, such as the view, se-
quence, synonym, and index. Some of these objects are based on underlying Oracle
tables, and some are independent objects. I n this chapter, you will also learn about
transactions and their advantages. Y ou will be able to grant and revoke privileges re-
garding your own objects to other users.
VIEWS
A view is an Oracle object that gives the user a logical view of data from an under-
lying table or tables. You can restrict what users can view by allowing them to see
only a few columns from a table. W hen a view is created from more than one table,
the user can view data from the view without using join conditions and complex
192 Chap. 9 Advanced Features: Objects, Transactions, and Data Control
conditions. The application programs can access data with data independence. The
same data can be viewed differently with different views. Views also hide the names
of the underlying tables, so the user does not know where the data came from. In
short, a view is a logical representation of a subset of data from one or more tables.
A view is stored as a SE L E C T statement in the D ata Dictionary. There are two
types of views: simple and complex.
Figure 9-1 shows the difference between simple and complex views. A simple
view is based on one table. I t does not contain group functions or grouped data, and
data manipulation is always possible through it. On the other hand, a complex view
is based on one or more tables. I t may contain group functions and/or grouped data,
and data manipulation is not always possible through it.
Creating a View
[column aliases]
AS SELECT-subquery
[WITH CHECK OPTION [CONSTRAINT constraintname]]
name. The W I TH R E A D ONLY option is to make sure that the data in the under-
lying table are not changed through the view.
Figure 9- 2 shows creation of a simple view. View STU 500_VU is based on the
STU DENT table for students with MajorId = 500. The column aliases are given for all
SQL>
four columns selected by the subquery. The user with access to the view can use it like
any other table. The user does not even have to know the existence of the STUD ENT
table and other columns in it. The user only sees what you let him or her see! Now,
Figure 9- 3 shows use of the newly created view like a table with D E SC R I B E and
SELECT.
I n Figure 9- 4, you will see a complex view that is created from two tables, EM-
PL OY E E and DEPT. I t uses group functions and derived data. I t is not possible to
SQL>
SQL>
modify data through this view. Notice that the column aliases are given by the sub-
query, not by the outer C R E A TE V I E W statement. I f a view by the name
DEPT_SA L_V U already existed, this statement would have overwritten the previous
view because of the C R E A TE O R R E PL A C E V I E W statement.
Other rules related to data manipulation on a view include:
SQL>
Removing a View
A user who owns a view— or who has the privilege to remove it— can remove a view.
The removal of a view does not affect data in the underlying table. W hen a view is re-
moved, a “View dropped” message is displayed (see Fig. 9-6). The general syntax is
SQL>
For example,
DROP VIEW stuvu500;
Altering a View
When you alter an underlying table, the view becomes invalid. Y ou need to recompile
that view to make it valid again. The A L TE R V I E W statement is used for the re-
compilation of a view. For example,
ALTER VIEW deptsalvu COMPILE;
The same statement is used to check validity of a view in case the underlying table is
dropped.
196 Chap. 9 Advanced Features: Objects, Transactions, and Data Control
SEQUENCES
1 rowcreated.
SQL>
Let us create another sequence to generate MajorId numbers. If you view the
M A JO R table, the last value used is 600, and each value is in steps of 100. I n the future,
you want to add numbers in steps of 10, starting with 610. The data type of the column
is NU MBER(3), so the maximum allowable value should be 999 (see Fig. 9-8).
198 Chap. 9 Advanced Features: Objects, Transactions, and Data Control
The query will result in an error message, because C U RR V A L does not have a
value yet and it is not defined.
Figure 9-9 uses the sequence first to add a new department in
the D E PT table with NEX TV AL. Then, a new row is added to the E M PL OY E E
table, generating a new EmployeeId with employee_employeeid_seq.NEXTV AL
1 row created.
SQL>
and using the newly created department’s value for the employee’s D eptI d with
dept_deptid_seq.CU RRV AL.
W hen you create a sequence and specify an increment value, you still may find
gaps in the values generated. The gaps result from one of the following reasons:
● You generated sequence values in an INSERT statement, and the row was
never written to the permanent database because of “rollback”.
● You used the C A C HE option, and the system crashed. So, the numbers
brought to memory in advance are lost.
● A sequence is used in more than one table or on more than one column.
● Rows are deleted from a table.
SQL>
You can get information about sequences you have created by using the query
shown in Figure 9- 10. The L A ST_NU MB E R column shows the next available num-
ber, and the other columns show values set at the time of creation of sequences.
Modifying a Sequence
You can modify a sequence if you own it or have the A LTE R SE QU E N C E privilege.
The modified sequence does not affect past numbers, only numbers generated in the
future. Modification of a sequence does not allow you to change the STA RT W I TH
option. The sequence has to be removed and recreated to change the starting value.
The maximum value cannot be set to a number less than the curr ent number. You
can change the I NC R E M E NT BY, M A X VA L U E ƒN O MA X VA L U E , MI N VA L-
U E ƒN OM I NVA L U E , CY C LE ƒN O CY C LE , O R D E R ƒN OO R D E R , and CA C H E ƒN O-
CA CH E options while modifying a sequence. The general syntax is
200 Chap. 9 Advanced Features: Objects, Transactions, and Data Control
For example, look at the sequence modification in Figure 9-11. Only two options are
changed for simplicity. A user may choose to modify more options.
Dropping a Sequence
SYNONYMS
Sometimes, object names are very long. I f a query uses the object’s name more than
once, the user has to type that long name many times. Y ou already know the use of
table aliases to shorten table names. Table aliases are, indeed, useful, but they are
only known in the query where they are created. They are not stored as separate ob-
jects in your database. Synonyms are Oracle objects that are used to create alterna-
tive names for tables, views, sequences, and other objects. Even when you have the
privilege to use another user’s table, you have to qualify the table name with the
user’s name. Y ou can create a synonym for The general syntax is
Synonym created.
A synonym name must be different than all the other objects owned by the
user. For example, Figure 9-12 shows the creation of a synonym for a sequence as
well as a table.
If you have rights equivalent to those of a database administrator (D BA), you
can create a PU BL I C synonym. A public synonym is available to all users. I create
PU B L I C synonyms for all sample database tables, because my tables are made
available to students for lab activities. For example,
instead of
A user can get information about synonyms and their table names by using
Oracle’s D ata D ictionary table, U SE R_ SY NON Y MS (see Fig. 9- 13).
INDEX
A n index is another Oracle object that is used for faster retrieval of rows from a
table. A n index can be created explicitly by using the C R E A TE I N D E X statement
202 Chap. 9 Advanced Features: Objects, Transactions, and Data Control
or implicitly by Oracle. Once an index exists for a table, the user does not have to
open or use the index with a command or a statement. The Oracle server uses the
index to search for a row r ather than scanning through the entire table. I ndexing re-
duces both search time and disk input/output. A ll indexes are maintained separately
from the table on which they are based. Creating and removing an index does not
affect the table at all. W hen a table is dropped, all indexes based on that table are
also removed.
Implicit indexes are created when the PR I M A R Y K E Y or U N I Q U E con-
straint is defined. Such indexes get the name of the constraint. A user can create ex-
plicit indexes based on non–primary key or nonunique columns or on any
combination of columns for faster table access. A n index based on a combination of
columns is called a or . The general syntax is
Index created.
INDEX_NAME TABLE_NAME
-- ---- ---- ---- ---- ----- ---- --- ----- ---- ---- ---- ---- ---
STUDENT_STUDENTID_PK STUDENT
STU_IDX STUDENT
SQL>
speed searching of student information when the search involves the last name and
first name as search key. The information from the U SE R _I N D E X E S table shows
two indexes in the STU D E NT table, because one index was created automatically
for the primary key constraint.
You would create an index based on a column if a column is used often in
querying or joining, has a big domain of values, or contains many Null values. W hen
an index is created, it does not store Null values, so the searching would eliminate
those rows. D o not create an index for a very small table, a column not used often in
queries, or a table that often gets updated. Every insertion and deletion in a table
ROWID Pseudocolumn 203
Rebuilding an Index
When a table goes through many changes (insertions, deletions, and updates), it is
advisable to rebuild indexes based on that table. You can drop an index and recreate
it, but it is faster to just rebuild an existing index. Rebuilding compacts index data
and improves performance. For example,
ROWID PSEUDOCOLUMN
Every row has a unique, system-generated address called the ROW ID . This address
contains the exact location of the row, and the index files store R OW I D to retrieve
rows. The row address or physical storage location of a row consists of the data object
number, data block number, number of the row within the data block, and data file
number. The RO W I D can be used in a query for faster access of a row, but it cannot
be changed. If a row is deleted and then inserted again, it gets a new ROW ID , as
shown in Figure 9-15.
SQL>
TRANSACTIONS
Oracle groups your Structured Query Language (SQL) statements into transactions. A
transaction consists of a series of D ata Manipulation Language (D M L ) statements, one
D ata Definition Language (D D L ) statement, or one D ata Control Language (D C L)
statement. Because transaction control, Oracle guarantees data consistency. The
transaction control statements give you flexibility to undo transactions or write
transactions to the disk. Transactions provide consistency in case of a system failure.
I n Oracle, your transactions start with the first executable SQL statement that
you issue. The transaction ends when one of the following occurs:
Once a transaction ends, the new transaction starts with your next executable SQL
statement.
There is also an environment variable A U TOCOM MI T. By default, it is set to
OFF. A user can set it to ON or I M M E D I A TE by typing
SET AUTOCOMMIT ON
SET AUTOCOMMIT IMMEDIATE
1 row created.
SQL> SAVEPOINT X;
Savepoint created.
SQL> UPDATE course SET credits=4 WHERE CourseId=’CIS340’; 1 row updated.
Savepoint created.
1 row created.
Rollback complete.
SQL> ROLLBACK TO SAVEPOINT X;
Rollback complete.
SQL> ROLLBACK;
Rollback complete.
of a transaction with five D M L statements. The transaction has started right after
the some C OM M I T statement and the user is at the end of the fifth D ML state-
ment. I f user types COMMIT, the results of all five D M L statements are written
permanently to the disk. If the user types R OL L B A C K TO SA V E PO I NT Y , one
INSERT after SA V EPOINT Y is rolled back, and save point Y is removed. I f the
user types RO L LB A C K TO SA VE POINT X , save point Y is removed along with
save point X . Three D ML statements— U PD A TE , D E L E TE , and I NSERT— are
rolled back. If the user types ROLLBA CK , the entire transaction is rolled back, all
save points are removed, and a new transaction begins with the new statement. In
Figure 9- 17, one by one the save points are rolled back, and eventually, the entire
transaction is rolled back. Back to square one!
Oracle implements read consistency. When any D M L statement is issued for a data-
base, the old copy of the database (before changes) is written into a rollback segment.
The user who is making changes with D M L statements can see the changes with a SE-
L E C T query from the database. All other users see the snapshot of the database be-
fore changes in the rollback segment. The data are consistent to all other users. When the
changes are committed, the changes are available to all users, because the rollback
segment copy is removed and the space is freed for another, later use. If the changes
are rolled back, the old copy of the database is loaded into the rollback segment again. A
user does not have to write any explicit statements to lock tables. Oracle usesautomatic
locking with the least restrictions to provide sharing of data with integrity. Oracle has
two lock classes; and . A n exclusive lock preventssharing a
resource until the lock is released. A share lock allows sharing for reading
purposes. Oracle also allows a manual lock on data.
When a user issues a SE L E C T query, rows are not locked. Oracle does not lock
rows for viewing. A s you know, the rows with D ML query changes are locked until
changes are committed. Suppose you want to view rows and also change them. Y ou
would want to lock those rows for future changes. You would use the SE L E C T Á
FO R U PD A TE O F statement for such manual locks. The general syntax is
Controlling Access 207
SQL>
CONTROLLING ACCESS
The D B A can create a user with the C R E A T E U SE R statement. Once a user is cre-
ated and a password assigned, the user needs privileges to do anything. The general
syntax is
Grant succeeded.
A user can change his/her own password with the PA SSW O R D command in
SQL * Plus. A D BA can change any user’s password with the A LT E R U SE R state-
ment. For example,
ALTER USER “XMAN” IDENTIFIED BY “PATRICK”;
There is a pool of more than 100 system privileges available for the D BA to grant
to users. The D B A assigns privileges based on the level of a user or on a user’s needs.
Controlling Access 209
I n a company, there are many users of different levels. Many of them from the
same level need the same privileges. It is easier to assign privileges to each level and
then to assign users to that level.The levels are called r oles. A role is similar to a group
used by network operating systems. A D BA creates a role by using a C RE A TE
R O L E statement. Privileges are then granted to the role, and the role is granted to
the users. The general syntax is
Figure 9-19 shows the roles assigned to user X MAN. Once user X M A N gets
privileges directly or through a role to go with the username and password, he or she
can use those privileges immediately. Some users can be assigned more or fewer
privileges than other users.
Object Privileges
A n object privilege specifies what a user can do with a database object, such as a
table, a sequence, or a view. There are 11 basic object privileges, and each object hasa
set of privileges out of the total of 11 privileges. The following is a list of all object
privileges on various objects (objects are listed within parentheses):
● A L TE R (table, sequence)
● INSERT (table, view)
● U PD A TE (table, view)
● D E L E TE (table, view)
● SE L E CT (table, view, sequence)
● R E FE R E N C E S (table, view)
● I N D E X (table)
● E X E C U TE (procedure, function, package, library, user- defined type)
● U ND E R (view, user-defined type)
● R E A D (directory)
● W R I T E (directory)
where are some of the 11 privileges listed before. If all privileges are
to be granted, A L L can be used instead of specifying each privilege separately.
Columns on which privileges are granted are specified by . The key
word PU BL I C grants privileges to all users. The W I TH G R A N T O PTI ON clause
allows the grantee to grant privileges to other users and roles.
Figure 9-20 illustrates two G R A N T statements.The first statement gives only SE-
L EC T privileges on table D E PT to user X MAN.The second statement gives SELECT,
INSERT, and U PD ATE privileges on table E MPL OY E E to two users, STU D EN T and
XMA N.The second statement also gives the two users privilege to pass those privileges
to other users. If user NSHA H is granting these privileges, the grantee will have to qual-
ify the table name with a username to use it (e.g., NSHAH.EMPLOY EE).
A nother approach is to create a synonym for the table, as you saw earlier in
this chapter. For example,
CREATESYNONYM emp FOR nshah.employee;
Privileges can be granted, and they can be taken away. If a user granted privi-
leges by a W I TH G R A N T OPTI ON to another user and that second user passed on
those privileges, the R E V O K E statement takes privileges not only from the grantee
but also from the users granted privileges by the grantee. The general syntax is
Controlling Access 211
Figure 9-22 shows a table with object privileges, which can be granted on vari-
ous Oracle objects. Some objects, such as operator, indextype, and so on, are not in-
cluded in this table, because they are beyond the scope of this text. You may grant
the E X E C U TE privilege to Java source, class, or resource created in Oracle with the
C RE A TE JAV A statement. Oracle treats Java objects as procedures.
Procedures,
Functions, User-Defined
Object Privilege Table View Sequence and Packages Directory Library Type
ALTER X X
D ELET E X X
EX ECUTE X X X
IN DEX X
INSERT X X
O N COMMIT
R EFR ESH
X
Q UER Y R EWR IT E X
R EA D X
R EFER ENCES X X
SELECT X X X
U ND ER X X
Figur e 9-22 Object privileges and Oracle objects.
UPDATE X X
W R ITE X
212 Chap. 9 Advanced Features: Objects, Transactions, and Data Control
IN A NUTSHELL . . .
● The Oracle objects view, sequence, index, and synonym are stored in a user’s
schema.
● A view has two types: simple and complex.
● A simple view is based on a single table and does not contain function or
grouped data. The manipulation of data is always possible from a simple
view.
● A complex view is based on one or more tables and may contain functions
and grouped data. Manipulation of data is not always possible from a com-
plex view.
● A sequence is an Oracle object that is used to generate a sequence of num-
bers. The sequence number may start at any number and have any incre-
ment value, either in chronological order or unordered.
● A sequence object can be modified with some restrictions. A gap may occur
in sequence values because of a system crash, a deletion of rows, an update
operation, or the use of a sequence on more than one column.
● A synonym is used to provide a shortened name for an object.
● Oracle automatically creates an index object for all primary key and unique
constraints. A user can create an index based on a set of columns for faster
access.
● Transactions in Oracle provide the user with more flexibility and consisten-
cy in data. A user can employ CO MM I T or RO LL B A C K transactions.
● Oracle provides read consistency and automatic locking. A user can manu-
ally lock rows for updating with the F O R U PD A TE OF clause.
● A database administrator (D B A ) has all privileges. There are more than 100
system privileges and 11 object privileges. The D B A creates users and roles,
and he or she grants them privileges.
● A user can grant privileges to other users on any object in the user’s own
schema and can also revoke those privileges.
EXERCISE QUESTIONS
True/F alse:
1. A simple view is based on a single table.
2. A complex view is always based on two or more tables.
3. In a sequence, to get the current value with CU RRVAL, at least one number must be
generated first by using NEXTV AL.
4. If a table is dropped, all indexes based on that table are automatically dropped.
Lab Activity 213
LAB ACTIVITY
INSERT INTO customer VALUES(211, ‘Garcia’, ‘NJ’, ‘732-555-1000’); INSERT INTO customer
VALUES(212, ‘Parikh’, ‘NY’, ‘212-555-2000’); INSERT INTO customer VALUES(225, ‘Eisenhauer’,
‘NJ’, ‘973-555-3333’); INSERT INTO customer VALUES(239, ‘Bayer’, ‘FL’, ‘407-555-7777’);
INSERT INTO item VALUES(1, ’Screw’, 2.25,50); INSERT INTO itemVALUES(2, ‘Nut’, 5.00, 110);
INSERT INTO item VALUES(3, ‘Bolt’, 3.99,75); INSERT INTO item VALUES(4, ‘Hammer’, 9.99,
125); INSERT INTO item VALUES(5, ‘Washer’,1.99,100); INSERT INTO item VALUES(6, ‘Nail’,
0.99, 300);
Alternate Method
SELECT *
FROM customer;
SELECT *
FROM customer
WHERE UPPER(State) = ‘FL’;
SELECT*
FROM item
WHERE ItemPrice BETWEEN 2 and 5;
or
SELECT *
FROM item
WHERE ItemPrice >= 2 AND ItemPrice <= 5;
Find Customers from the Tristate Area of New York, New Jersey,
and Connecticut
SELECT *
FROM customer
WHERE State IN (‘NJ’, ‘NY’, ‘CT’);
SELECT *
FROM customer
WHERE UPPER(CustName) LIKE ‘E%’;
SELECT *
FROM item
WHERE ItemName LIKE‘ %w%’ ;
SELECT *
FROM customer ORDER BY CustName;
SELECT *
FROM item
ORDER BY ItemPrice DESC;
SELECT *
FROM customer
ORDER BY State, CustName;
220 SQL Review: Supplementary Examples
SELECT *
FROM customer
WHERE UPPER(State) = ’NJ’
ORDER BY CustName;
Find the Payment Due Date if the Payment is Due in Two Months from
the Invoice Date
SELECT InvNo, TO_CHAR (InvDate, ‘fmMonth DD, YYYY’) “Invoice Date” FROM
invoice;
SELECT SUM (ItemPrice), AVG (ItemPrice), MAX (ItemPrice), MIN (ItemPrice) FROM
item;
Use an Outer Join to Display Items Ordered and Not Or- dered
Display Invoices, Customer Names, and Item Names To- gether (Multiple Joins)
Create a New Table for all New Jersey Customers Based on the Existing
CUSTOMER Table
CREATETABLEnj_customer AS
SELECTCustNo, CustName, Phone FROM customer
WHERE UPPER(State) = ‘NJ’;
Find Customers Who Are Not from New York or New Jersey (Set
Operator)
Delete Rows from the CUSTOMER Table that Are also in the NYNJ_CUSTOMER Table
Create a View that Displays Invoice Number and Cus- tomer Names for New
Jersey Customers
Create a Sequence that Can Be Used to Enter New Itemsinto the ITEM Table
NOCYCLENOCACHE ORDER;
Add a New Item into the ITEM Table with the ITEMNUM_SEQ
Sequence
CREATESYNONYM ii
FORinvitem;
SELECT *
FROM customer
WHERE UPPER(CustName) = ‘BAYER’
FOR UPDATE OFState,Phone NOWAIT;
Revoke the INSERT Option on the ITEM Table from User BOND
INTHISCHAPTER . . .
● D ata encapsulation.
● E rr or handling.
226 Chap. 10 PL/SQL: A Programming Language
● I nformation hiding.
● Object-oriented programming (OOP).
A BRIEFHISTORYOF PL/SQL
Before PL/SQL was developed, users embedded SQL statements into hot languages
like C++ and Java. PL/SQL version 1.0 was introduced with Oracle 6.0 in 1991. V er-
sion 1.0 had very limited capabilities, however, and was far from being a full-fledged
programming language. I t was merely used for batch processing.
W ith versions 2.0, 2.1, and 2.2, the following new features were introduced:
PL/SQL version 8.0, also known as PL/SQL8, came with Oracle8, the “object-
relational” database software. Oracle allows creation of objects that can be accessed
with Java, C++, Object C OB OL , and other languages. I t also allows objects and re-
lational tables to coexist. The external procedures in Oracle allow you to compile
procedures and store them in the shared library of the operating system— for exam-
ple, an . file in U N I X or a . (D ynamic Linked Library) file in W indows. Oracle’s
library is written in the C language. I t also supports L O B (Large Object) data types.
FUNDAMENTALSOF PL/SQL
Reserved Words
The reserved words, or key words, are words provided by the language that have a
specific use in the language. For example, D E C L A RE , BEGI N, END, IF, W HI L E,
EX CE PTI ON , PR O C E D U R E , FU NCTI ON, PA CKA GE , and TR I GG E R are some
of the reserved words in PL/SQL.
User-Defined Identifiers
I t is a good practice to create short and meaningful names. Figure 10-1 shows a
list of valid user-defined identifiers. Figure 10-2 shows a list of invalid user-defined
identifiers along with reasons why they are invalid.
228 Chap. 10 PL/SQL: A Programming Language
User-Defined Identifiers
Rate_of_pay Num
A1234567890
Dollar s$_and_cents SS#
Literals
Literals are values that are not represented by user- defined identifiers. Literals are
of three types: numeric, character, and boolean. For example:
In this list of values, ‘25- MAY-00’ looks like a date value, but it is a character string. It
can be converted to date format by using the TO_ D A TE function. The value ‘’ (two
single quotes having nothing within) is another way of entering the NU L L value.
PL/SQL is case sensitive regarding character values within single quotation
marks. The values ‘ORA CLE’, ‘Oracle’, and ‘oracle’ are three different values in
PL/SQL. To embed a single quote in a string value, two single quote symbols are
entered— for example, ‘New Y ear”s Day’.
Numeric values can be entered in scientific notation with the letter or .
Boolean values are not enclosed in quotation marks.
PL/SQLBLOCK STRUCTURE
Figure 10-3 shows the use of three sections in a PL/SQL block. Of the three sections
in a PL/SQL block, only the executable section is mandatory. The declaration and ex-
ception- handling sections are optional. The general syntax of an anonymous block is
Section Use
The D E C L A R E and EX CE PTI O N key words are optional, but the B E GI N and E ND
key words are mandatory. The declarations made within a block are local to the block.
When a block ends, all objects declared within the block cease to exist. A block
is the “scope” of objects declared in that block. W hen blocks are nested within each
other, the declarations made in the outer block are global to the inner block. The ob-
ject declarations made in the inner block, however, are local to it and cannot be ref-
erenced by the outer block. A basic PL/SQL block can be embedded in any other
PL/SQL block, named or unnamed. Figure 10-4 shows all the blocks available in the
Oracle server environment.
230 Chap. 10 PL/SQL: A Programming Language
Block Use
COMMENTS
Comments are used to document programs. They are written as part of a program, but
they are not executed. In fact, comments are ignored by the PL/SQL engine. I t is a good
programming practice to add comments to a program, because this helps in readability
and debugging of the program. There are two ways to write comments in PL/SQL:
/* This is a
multiline comment that ends here. */
DATA TYPES
E ach constant and variable in the program needs a data type. The data type decides
the type of value that can be stored in a variable. PL /SQL has four data types:
1. Scalar.
2. Composite.
3. Reference.
4. LOB.
Data Types 231
A scalar data type is not made up of a group of elements. I t is atomic in nature. The
composite data types are made up of elements or components. PL/SQL supports
three composite data types— , and , which are discussed in a
later chapter. The reference data types deal with objects, which are briefly introduced
in Appendix D .
There are four major categories of scalar data types:
1. Character.
2. Number.
3. Boolean.
4. Date.
Character
Variables with a character data type can store text. The text may include letters,
numbers, and special characters. The text in character-type variables can be manipu-
lated with built- in character functions. Character data types include C H A R and
V A R CHA R 2.
CHAR. The C H A R data type is used for fixed- length string values. The allow-
able string length is between 1 and 32,767. (If you remember, the allowable length in
the Oracle database is only 2000.) If you do not specify a length for the variable, the
default length is one. G et into the habit of specifying length along with the data type
to avoid any errors.
If you are going to declare a variable of the C H A R type in PL/SQL code and
that value is to be inserted into a table’s column, the limitation on database size is
only 2000 characters. You will have to find the substring of that character value to
avoid the error message for inserting a character string longer than the length of the
column.
If you specify a length of 10 and the assigned value is only five characters long,
the value is padded with trailing spaces because of the fixed-length nature of this
data type. The C HA R type is not storage efficient, but it is performance efficient.
VARCHAR2. The V A R CH A R 2 type is used for variable- length string val- ues.
Again, the allowable length is between 1 and 32,767. A column in an Oracle data- base
with a V A R CH A R 2 type, however, can only take 4000 characters, which is
smaller than the allowable length for the variable.
Suppose you have two variables with data type of CHA R(20) and VAR-
CHA R2(20), and both are assigned the same value, ‘Oracle9i PL /SQL’. The string
value is only 15 characters long. The first variable, with CHAR(20), is assigned a value
padded with five spaces; the variable with VA RCHA R2(20) does not get a string value
232 Chap. 10 PL/SQL: A Programming Language
padded with spaces. If the values of both variables are compared in a condition for
equality, FAL SE will be returned.
Other character data types are L ON G (32,760 bytes, shorter than VA RCHAR2),
RA W (32,767 bytes), and L ON G RA W (32,760 bytes, shorter than RA W ). The RA W
data values are neither interpreted nor converted by Oracle.
V A R CH A R 2 is the most recommended character data type.
Number
PL/SQL has a variety of numeric data types. Whole numbers or integer values can be
handled by following data types:
Y ou are familiar with the N U M B E R type from the Oracle table’s column type.
The NU M B E R type can be used for fixed-point or floating- point decimal numbers. I t
provides an accuracy of up to 38 decimal places. W hen using the NU M BE R type, the
precision and scale values are provided. The precision of a number is the total
number of significant digits in that number, and the scale is the number of signifi-
cant decimal places. The precision and scale values must be whole-number integers.
For example,
NUMBER( , )
Boolean
PL/SQL has a logical data type, Boolean, that is not available in SQL. I t is used for
Boolean data TR U E , FA LSE , or NU L L only. These values are not enclosed in single
quotation marks like character and date values.
Date
The date type is a special data type that stores date and time information. The date
values have a specific format. A user can enter a date in many different formats with
the TO _D A TE function, but a date is always stored in standard 7-byte format. A
date stores the following information:
Century Y ear Month D ay Hour Minute Second
The valid date range is from January 1, 4712 B.C., to D ecember 31, 9999 A.D .
The time is stored as the number of seconds past midnight. I f the user leaves out the
time portion of the data, it defaults to midnight (12:00:00 A .M.).
V arious D A TE functions are available for date calculations. For example, the
SYSDA TE function is used to return the system’s current date.
The National L anguage Support (NLS) data type is for character sets in which mul-
tiple bytes are used for character representation. NC H A R and N V A R C HA R2 are
examples of NLS data types.
LOB
Like Oracle9i, PL/SQL also supports Large Object (L OB ) data types to store large
values of character, raw, or binary data. The L O B types allow up to 4 gigabytes of
data. L O B variables can be given one of the following data types:
● The type contains a pointer to the large binary object inside the
database.
● The type contains a pointer to a large block of single-byte character
data of fixed width.
234 Chap. 10 PL/SQL: A Programming Language
Oracle provides users with a built- in package, D BMS_L OB, to manipulate the
contents of LOBs.
VARIABLE DECLARATION
A scalar variable or a constant is declared with a data type and an initial value assign-
ment. The declarations are done in the D E C L A R E section of the program block. The
initial value assignment for a variable is optional unless it has a N OT NU LL con-
straint. The constants and N OT NU L L type variables must be initialized. The general
syntax is
DECLARE
v_number NUMBER(2); NUMBER(1) := 1;
v_count v_state VARCHAR2(2) DEFAULT ‘NJ’;
c_pi CONSTANT NUMBER := 3.14;
v_invoicedate DATE DEFAULT SYSDATE;
I n this example, you see a naming convention that uses for variables and
for constants.
ANCHORED DECLARATION
use a variable or a column’s data type as the data type for another variable in the
program. The general syntax is
in this example, is declared with a data type NU M BE R (3). The next vari-
able, , is declared using the anchoring method and the declaration attribute
% TY PE . The variable gets the same data type as
Two variables can also be declared and assigned data types to match the col-
umn’s data type. The advantage is that you do not have to cross- reference the data
type used in the table. Oracle does that for you. For example,
DECLARE
v_empsal employee.Salary%TYPE;
v_deptname dept.DeptName%TYPE;
Suppose you do not use the anchoring method to declare variables, which are
assigned values directly from table columns. You can use the D E SC R I B E command
to list all the data types for columns. Then, you can declare variables in a program
with the same types and lengths. This will work just fine. The problem will arise when
the column lengths are increased to meet future demands. When you assign values
from those columns to variables, V A L U E _ E RR O R will occur— and you will have
to go back to all the programs to change the variable’s data length! A nchoring defi-
nitely is an advantage in such situations.
A % TY PE declaration anchors the data type of one variable based on anoth-
er variable or column at the time of a PL/SQL block’s compilation. If the source or
original column’s data type is changed, the PL/SQL block must be recompiled to re-
anchor all anchored variables.
Nested Anchoring
ASSIGNMENT OPERATION
The assignment operati on is one of the waysto assign a value to a variable. You have
already learned that a variable can be initialized at the time of declaration by using
the D E FA U LT option or : =. The assi gnment operati on is used in the executable
section of the program block to assign a literal, another variable’s value, or the result
of an expression to a variable. The general syntax is
For example,
v_num1 :=100;
v_num2 :=v_num1;
v_sum :=v_num1+ v_num2;
I n these examples, the assumption is made that three variables have already
been declared. The first example assigns 100 to the variable The second ex-
ample assigns the value of the variable to the variable The third
example assigns the result of an addition operation on and to the
variable
The following statements are examples of invalid assignment operations and
the reasons for their lack of validity:
BIND VARIABLES
Bind variables are also known as host variables. These variables are declared in the
host SQ L * Plus envi ronment and are accessed by a PL /SQL block. A nonymous
blocks do not tak e any arguments, but they can access host variables with a colon
prefix (:) and the host variable name. H ost variables can be passed to procedures
and functions as arguments. A host variable is declared at the SQ L 7 prompt with
the SQ L * Plus VA R I A B L E statement. The syntax of a host variable declaration is
For example,
SQL>
the local variable , doubles it, and stores the result in the host variable
Finally, the resulting variable is printed in the host environment with a
PR I NT statement.
The use of host variables should be minimized in a program block, because they
affect performance. Every time a host variable is accessed within the block, the PL/SQL
engine must stop to request the host environment for the value of the host variable.The
variable’s value can be assigned to a local variable to minimize calls to the host.
PL/SQL does not have any input capabilities in terms of having an input statement.
There are no explicit input/output (I /O) statements, but substitution variables of
SQL are available in PL/SQL. Substitution variables have limitations, which be-
come appar ent in a loop.
L et us rewrite the program code in Figure 10- 5 to the one in Figure 10-6. W hen
the code in Figure 10-6 is executed, a standard prompt for appears on the
screen for users to type in a value for it. A s you see in the example, there is no need
PRINT g_double
G_DOUBLE
-- --- --- -- -
20
SQL>
to declare substitution variables in the program block. The value of the bind/host
variable is printed with the PR I N T command. The value of the local variable
cannot be printed with the PR I NT command, however, because the scope of a local
variable is within the block where it is declared.
When substitution variable is used in a program, the output contains lines
showing how the substitution was done. Y ou can suppress those lines by using the
SE T V E R I FY OF F command before running the program.
PRINTINGIN PL/SQL
There is no explicit output statement in PL/SQL . Oracle does have a built- in package
called D BM S_OU TPU T with the procedure PUT_LI NE to print. A n environment
variable named SE R V E R OU TPU T must be toggled ON to view output from it.
The D B MS_ OU TPU T is the most frequently used package because of its ca-
pabilities to get lines from a file and to put lines into the buffer. The PU T_ LI NE
procedure displays information passed to the buffer and puts a new- line marker at
the end. For example,
DBMS_OUTPUT.PUT_LINE(‘This line will be displayed’);
The maximum size of the buffer is 1 megabyte. The following command enables
you to view information from the buffer by using the D B M S_OU TPU T package and
also sets the buffer size to the number of bytes specified:
SET SERVEROUTPUT ON [on size 10000];
The PL/SQL block in Figure 10- 7 shows the use of D BMS_OU TPU T.PU T_
L I NE . A nother procedure, D BMS_OU TPU T.PUT, also performs the same task of
4 :NUM := 5;
5 DOUBLE := :NUM * 2; DBMS_OUTPUT.PUT_LINE ((’
6 DOUBLE OF’||
7 TO_CHAR(:NUM) | ’IS ’ | TO_CHAR(DOUBLE));
8 END; 9 /
DOUBLE OF 5 IS 10
PL/SQL procedure successfully completed. SQL>
displaying information from the buffer, but it does not put a new- line marker at the
end. If there is another D BM S_OU TPU T.PU T or D BMS_OU TPU T.PU T_LI NE
statement following that statement, its output will be displayed on the same line.
ARITHMETICOPERATORS
Five standard arithmetic operators are available in PL/SQL for calculations. If more
than one operator exists in an arithmetic expression, the following order of prece-
dence is used:
+ Addition
— Subtraction and negation
* Multiplication
/ Division Exponentiation
**
–2 + 3 * (10 – 2 * 3)/6
Answer : 0 (The operations within the parentheses are performed first, with
multiplication followed by subtraction. The result from within the paren-
theses is multiplied by 3, and that result is divided by 6. Finally, the result is
added to - 2)
I n this chapter, you learned the basics of PL/SQL. I n the next chapter, you will
learn about three programming control structures: sequence, selection, and looping.
(Y ou already know one of them. All examples in this chapter were based on sequence
In a Nutshell .. . 241
structure.) Y ou will also learn to interface with the Oracle server by embedding
SQL statements in PL /SQL program blocks.
IN A NUTSHELL . . .
EXERCISE QUESTIONS
True/F alse:
1. PL/SQL is a nonprocedural language developed by Oracle Corporation.
2. The SQL language has built-in error checking and error handling, but PL/SQL does not.
3. Three types of variables used in a PL /SQL program are local, host, and substitution.
4. A variable with a NO T N U L L constraint and a constant must be initialized with a value
at the declaration time.
5. A n assignment statement is used in the executable section to assign value to a variable or
a constant.
6. In a declaration with the % TY PE attribute, the source is either a variable or a column in
a table.
7. If the source variable is declared with a NO T N U L L constraint, the anchored variable in-
herits the same constraint.
8. If the source column in a table has a NOT N U L L constraint, the anchored variable also
gets the NOT NU L L constraint.
9. Exponentiation is performed before addition in an expression without any parentheses.
10. The declaration and executable sections are mandatory in a PL/SQL block.
11. A bind variable is declared with a V A RI A BL E command at the SQL 7 prompt.
12. A PL /SQL block must contain B EGI N and E ND key words.
13. A substitution variable is declared under the DE CL A R E section of a PL/SQL block.
14. A bind variable is used in a PL/SQL block with a colon prefix (:).
15. A local variable used in a PL/SQL block can be printed with the PR I NT command.
LAB ACTIVITY
1. Create a program script that uses a PL/SQL anonymous block to perform the following:
U se a host variable AR EA to store the result. Declare a local variable R A DI U S with
numeric data type. Declare a constant PI with value 3.14. Assign a value to the variable
R A DI U S by using a substitution variable. Calculate area of a circle by using the formula
In the previous chapter, you learned the basics of the PL/SQL programming language.
You are now able to write simple programs using local, host, and substitution variables;
can perform simple calculations by using assignment statements; and know how to use
Oracle’s built- in package D BMS_OU TPU T.PU T_L INE in program blocks to display
results from the buffer. The sample programs and lab exercises have a series of state-
ments that are executed from the beginning to the end in a linear fashion. When an
anonymous block is executed, the code is sent to the PL/SQL engine for compilation. I n
this chapter, you will see the use of different control structures employed in a high- level
programming language.
In the last chapter, you saw how to write PL/SQL programs independent of a
database. W e start with more independent PL/SQL programs, and then show the actual
use of PL /SQL to interact with the Oracle database. A PL/SQL program block “talks” to
the Oracle database by embedding SQL statements in its executable section.
Control Structures 245
CONTROLSTRUCTURES
I n a procedural language like PL/SQL, there are three basic programming control
structures:
Selection Structure
AN D OR NOT
1. I F . . .THEN . . . E N D IF.
2. I F . . . TH E N . . . E L SE . . . E N D IF.
3. I F . . . TH E N . . . ELSI F . . . E ND IF.
4. C A SE . . . E N D CASE.
5. Searched CASE.
For example, Figure 11-4 shows a simple I F statement with an output statement,
which will be performed if the day entered is ‘SU N DA Y ’. If the condition is false,
the statement is skipped. I n this example, notice the use of the relati onal operator
equals 1= 2 in a Boolean condition and of the assignment operator 1: = 2 in the action
assignment statement.
Control Structures 247
SQL> DECLARE
2 V_DAY VARCHAR2(9) := ’&DAY’;
3 BEGIN
4 IF (V_DAY = ’SUNDAY’) THEN
5 DBMS_OUTPUT.PUT_LINE(’SUNDAY IS A HOLIDAY!’);
6 END IF;
7 END;
8 /
Enter value for day: SUNDAY
SUNDAY IS A HOLIDAY
You must have noticed the in the program code. All program
statements can start in the first column. I n fact, you can write more than one state-
ment on one line with the appropriate punctuation mark (;) separating them. Such
programming practice, however, can make your program difficult to read. I n turn, it
is a good practice to indent statements within a block or a compound statement, be-
cause it makes your program more readable. A program will work just the same
without indenting statements or without adding a to it, but good program-
ming practices mak e everybody’s life easier.
SQL> /
Enter value for age: 12 AGE: 12- MINOR
PL/SQLprocedure successfully completed.SQL>
...
Notice the word E LSI F, which does not have the last in EL SE. ELSI F is a
single word, but E N D I F uses two words. For example, let us revisit the D E C O D E
function example of Chapter 6 (see Figure 11-6). Figure 11-7 shows the ELSIF
equivalent of the D E C O D E function.
The same statement can be written with a simple IF statement, though less effi-
ciently. Y ou will need five simple I F statements to accomplish the same task as that
performed by a single compound E LSI F statement. Let us tak e another example
Control Structures 249
SQL> DECLARE
2 v_pos NUMBER(1) := &Position;
3 BEGIN
4 IFv_pos=1THEN
5 DBMS_OUTPUT.PUT_LINE(’20% increase’);
6 ELSIF v_pos=2 THEN
7 DBMS_OUTPUT.PUT_LINE(’15% increase’);
8 ELSIF v_pos=3 THEN
9 DBMS_OUTPUT.PUT_LINE(’10% increase’);
10 ELSIF v_pos=4 THEN
11 DBMS_OUTPUT.PUT_LINE(’5% increase’);
12 ELSE
13 DBMS_OUTPUT.PUT_LINE(’No increase’);
14 END IF;
15 END;
16 /
Enter value for position: 2 15% increase
PL/SQL procedure successfully completed. SQL>
with compound conditions. First, we will use a simple I F statement (see Fig. 11- 8),
and then, we will rewrite it by using E LSI F (Figure 11-9).
The example here assigns a grade of A , B, C, D, or F based on . We are
assuming that the score is within the range of 0 to 100. Y ou will need five simple IF
statements with total of 10 conditions or two conditions per each statement. Now,
suppose the value of is 95. The first statement’s condition is TR U E , so
will be assigned ‘A’. Because all simple I F statements are independent state-
ments, the execution will continue with the next I F, and so on. There is no other
TR U E condition for equal to 95, so will be ‘A’ after execution of all
five I F statements. This slows down your program’s execution. The ELSIF, on the
other hand, is one compound statement, and it stops as soon as a match is found. Let
us see how the ELSIF statement looks.
SQL> DECLARE
2 S NUMBER(3) := &SCORE;
3 GRADE CHAR;
4 BEGIN
5 IF S >= 90 AND S <= 100 THEN
6 GRADE := ’A’;
7 END IF;
8 IF S >= 80 AND S <= 89 THEN
9 GRADE := ’A’;
10 END IF;
11 IF S >= 70 AND S <= 79 THEN
12 GRADE := ’C’;
13 END IF;
14 IF S >= 60 AND S <= 69 THEN
15 GRADE := ’D’;
16 END IF;
17 IF S >= 0 AND S <= 59 THEN
18 GRADE := ’F’;
19 END IF;
20 IF S < 0 AND S > 100 THEN
21 GRADE := ’U’;
22 END IF;
23 DBMS_OUTPUT.PUT_LINE(’SCORE IS ’ | TO_CHAR(S));
24 DBMS_OUTPUT.PUT_LINE(’GRADE IS ’|| GRADE);
25 END;
26 /
Enter value for score: 93 SCORE IS 93
GRADE IS A
PL/SQL procedure successfully completed.SQL>
SQL> DECLARE
2 S NUMBER(3) := &SCORE;
3 GRADE CHAR;
4 BEGIN
5 IF S >= 90 AND S <= 100 THEN
6 GRADE := ’A’;
7 ELSIF S >= 80 AND S <= 89 THEN
8 GRADE := ’B’;
9 ELSIF S >= 70 THEN
10 GRADE := ’C’;
11 ELSIF S >= 60 THEN
12 GRADE := ’D’;
13 ELSIF S >= 0 THEN
14 GRADE := ’F’;
15 ELSIF S < 0 AND S > 100 THEN
16 GRADE := ’U’;
17 END IF;
18 DBMS_OUTPUT.PUT_LINE(’SCORE IS ’ | TO_CHAR(S));
19 DBMS_OUTPUT.PUT_LINE(’GRADE IS ’|| GRADE);
20 END;
21 /
Enter value for score: 77 SCORE IS 77
GRADE IS C
PL/SQL procedure successfully completed.SQL>
The ELSIF statement reduces the number of conditions from 10 to 5 and the
number of statements from five to one. Now, let us consider the same value, 95, as be-
fore. The condition is TR U E in the first I F clause, and is assigned value ‘A’. The
statement will not continue down anymore, because it will not enter the ELSIF part.
The rest of the statement is ignored, thus making E LSI F more efficient than its coun-
terpart (see Fig. 11-9). I n this example, there is an added ELSIF statement to check for
invalid scores (below 0 as well as above 100), which result in an undefined (‘U ’) grade.
1. Male 25 or over.
2. Male under 25.
3. Female 25 or over.
4. Female under 25.
SQL> DECLARE
2 V_GENDER CHAR := ’&SEX’;
3 V_AGE NUMBER(2) := ’&AGE’;
4 V_CHARGE NUMBER(3,2);
5 BEGIN
6 IF (V_GENDER = ’M’ AND V_AGE >= 25) THEN
7 V_CHARGE := 0.05;
8 END IF;
9 IF (V_GENDER = ’M’ AND V_AGE < 25) THEN
10 V_CHARGE := 0.10;
11 END IF;
12 IF (V_GENDER = ’F’ AND V_AGE >= 25) THEN
13 V_CHARGE := 0.03;
14 END IF;
15 IF (V_GENDER = ’F’ AND V_AGE < 25) THEN
16 V_CHARGE := 0.06;
17 END IF;
18 DBMS_OUTPUT.PUT_LINE(’GENDER: ’ | V_GENDER);
19 DBMS_OUTPUT.PUT_LINE(’AGE: ’ | TO_CHAR(V_AGE));
20 DBMS_OUTPUT.PUT_LINE(’SURCHARGE: ’ | TO_CHAR(V_CHARGE));
21 END;
22 /
Enter value for sex: FEnter value for age: 18GENDER: F
AGE: 18
SURCHARGE: .06
PL/SQL procedure successfully completed.SQL>
Now, we will rewrite the code done with a simple I F in Figure 11-12 by using
nested I F statements (see Fig. 11-13). Again, remember that the nested I F statement
will make the code more efficient than the simple I F version. The T HE N portion of
the outer I F calculates the insurance surcharge for male individuals, and the E L SE
portion calculates the same for the female individuals. The inner I F statements in
each portion check for the age.
Looping Structure
SQL> DECLARE
18 END IF;
19 DBMS_OUTPUT.PUT_LINE(’GENDER: ’ | V_GENDER);
20 DBMS_OUTPUT.PUT_LINE(’AGE: ’ | TO_CHAR(V_AGE));
21DBMS_OUTPUT.PUT_LINE(’SURCHARGE: ’||TO_CHAR(V_CHARGE)); 22 END;
23 /
Enter value for sex: F Enter value for age: 18GENDER: F
AGE: 18
SURCHARGE: .06
1. Basic loop.
2. W H I L E loop.
3. FO R loop.
E ach loop has different syntax, and each works somewhat differently.
...
You can also add a condition with the optional W H E N clause that will end the
loop when the condition becomes true. For example,
The condition is not checked at the top of the loop, but it is checked inside the
body of the loop. The basic loop is performed at least once, because the condition is
tested after entering the body of the loop. Such a loop is also called a post-test loop.
The example shown in Figure 11-14 uses a to control the number of
loop executions. There are three necessary statements in a counter-controlled loop.
The counter must be initialized, the value of the counter must change within the
loop (increment or decrement), and a proper condition must exist in the loop. If
value of the counter is not changed inside the loop, it will result in an infinite loop.
The initial value, the increment/decrement, and the condition control the total num-
ber of loop executions.
256 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL
A nswer : One time (the loop is performed once and the first check of condi-
tion returns true, so the loop ends). Tricky, isn’t it?
A nswer : The loop is infinite (the condition will never become true).
Control Structures 257
WHILE loop. The W HI L E loop is an alternative to the basic loop and is per-
formed as long as the condition is true. It terminates when the condition becomes false.
If the condition is false at the beginning of the loop, the loop is not performed at all.The
W H I L E loop does not need an E X I T statement to terminate. The general syntax is
...
I n Figure 11-15, you see the same average program of Figure 11-14 rewritten
with the W HI L E loop. There are obvious differences between the basic loop and the
W H I L E loop. Figure 11-16 explains the differences between them.
2 V_COUNT NUMBER(2);
3 V_SUM NUMBER(2) := 0;
4 V_AVG NUMBER(3,1);
5 BEGIN
6 V_COUNT :=1; /* COUNTER INITIALIZED */
7 WHILE V_COUNT <= 10 LOOP /* CONDITION */
8 V_SUM := V_SUM + V_COUNT;
9 V_COUNT := V_COUNT + 1; /* COUNTER INCREMENTED */
10 END LOOP;
11 V_AVG :=V_SUM / (V_COUNT -1);
12 DBMS_OUTPUT.PUT_LINE
13 (’AVERAGE OF1 TO 10 IS ’||TO_CHAR(V_AVG));
14 END;
15 /
AVERAGE OF 1 TO 10IS 5.5
PL/SQL procedure successfully completed. SQL>
It is performed as long as the condition is false. It is performed as long as the condition is true.
It tests the condition inside the loop It checks condition before entering the loop
(post-test loop). (pretest loop).
It is performed at least one time. It is performed zero or more times.
It needs the E X IT statement to terminate. There is no need for an EX I T statement.
FOR loop. The F OR loop is the simplest loop you can write. Unlike the basic
and W H I L E loops, you do not have to initialize, test, and increment/decrement the
loop control variable separately. Y ou do it in the loop’s header. There is no need to use
an E X I T statement, and the counter need not be declared. The counter used in the
loop is implicitly declared as an integer, and it is destroyed on the loop’s termination.
The counter may not be used within the loop body in an assignment statement as a
target variable. The general syntax is
.. .
The counter varies from the lower value to the upper value, incrementing by
one with every loop execution. The loop can also be used with the counter starting
at a higher value and decrementing by one with every loop execution. The key word
R E V E R SE is used for varying the counter in the reverse order, or from a higher to
a lower value.
The program in Figure 11-17 does not declare , and there is no condi-
tion or explicit statement to change the counter’s value. The same program with the
counter’s value in reverse order will only change by one line. The F O R statement
will look like
SQL> DECLARE
2 V_COUNT NUMBER(2);
3 V_SUM NUMBER(2) := 0;
4 V_AVG NUMBER(3,1);
5 BEGIN
6 FOR V_COUNT IN 1..10 LOOP
7 V_SUM := V_SUM + V_COUNT;
8 END LOOP;
9 V_AVG := V_SUM / 10;
10 DBMS_OUTPUT.PUT_LINE
11 (’AVERAGE OF 1 TO 10 IS ’ | TO_CHAR(V_AVG));
12 END;
13 /
AVERAGE OF 1 TO 10 IS 5.5
One important point about the loop-control variable is that it is declared, in-
cremented/decremented, and destroyed implicitly, but its value cannot be changed
explicitly within the F O R loop’s body. I t cannot be a target variable in an assign-
ment statement.
Nested loops. You can use a loop within another loop. Loops can be nest- ed
to many levels. W hen the inner loop ends, it does not automatically end the outer loop
enclosing it. You can end an outer loop from within the inner loop by labeling each
loop and then using the E X I T statement. exits the current loop, but
also exits the outer loop. The loop labels use the same
naming rules as those used for identifiers. The loops are labeled before the key word
L OO P on the same line or on a separate line. The loop label is enclosed within two
pairs of angle brackets ( V and W ). For example,
<<out_loop>> LOOP
...
EXIT WHEN condition;
<<in_loop>> LOOP
...
NESTED BLOCKS
PL/SQL block may contain another PL/SQL block; in other words, PL/SQL blocks
can be nested. The execution starts with the outer block and continues with the
inner block. The variables declared in the outer block are global to the inner block,
and they are accessible in the inner block. The variables declared in the inner block,
however, are not accessible in the outer block. For example,
SQL IN PL/SQL
The PL/SQL statements have control structures for calculations, decision making,
and iterations. You need to use SQL to interface with the Oracle database. W hen
changes are necessary in the database, SQL can be used to retrieve and change in-
formation. PL/SQL supports all D ata Manipulation Language (D ML ) statements,
such as I NSERT, U PD A TE , and D E L E TE . I t also supports the Transaction Control
Language statements ROLLBA CK, COMMIT, and SAV EPOI NT. Y ou can retrieve
data using the data retrieval statement SELE CT. A row of data can be used to as-
sign values to variables. More than one row can be retrieved and processed using
cursors (covered in the next chapter). PL/SQL statements can use single- row func-
tions, but group functions are not available for PL/SQL statements. SQL statements
in the PL /SQL block, however, can still utilize those group functions.
PL/SQL does not support D ata D efinition Language (D D L ) statements, such
as C RE A TE , A L TE R , and DROP. The D ata Control Language (D C L ) statements
G R A N T and R E V O K E also are not available in PL/SQL.
The SE LE C T statement retrieves data from Oracle tables. The syntax of SEL E C T is
different in PL/SQL, however, because it is used to retrieve values from a row into a
list of variables or into a PL/SQL record. The general syntax is
where must contain at least one column and may include arithmetic
or string expressions, single-row functions, and group functions. must
contain a list of local or host variables to hold values retrieved by the SE LE CT
clause. The variables are declared either at the SQL * Plus prompt or locally under
the D E C L A R E section (see Fig. 11- 18). The is a PL/SQL record (cov-
er ed in the next chapter). A ll the features of SE L E CT in SQL are available with an
added mandatory I NTO clause.
The I NTO clause must contain one variable for each value retrieved from the
table. The order and data type of the columns and variables must correspond. The
SE L E CT Á I NT O statement must retur n one and only one row. I t is your respon-
sibility to code a statement that returns one row of data. If no rows are returned, the
standard exception (error condition) NO _D A TA _FOU ND occurs. If more than one
row are retrieved, the TO O_M A NY _R OW S exception occurs. Y ou will learn more
about exceptions and exception handling in the next chapter.
I n Figure 11-18, a few columns from a row of the E M PL O Y E E table are re-
trieved into a series of variables. The variables can be declared with data types, but
more appropriately, attribute % T Y PE is used to avoid any data- type mismatches.
The SQL statement in PL/SQL ends with a semicolon (;). The I N TO clause is
mandatory in a SEL E C T statement when used in a PL /SQL block. Figure 11- 19
SQL IN PL/SQL 261
SQL> DECLARE
2 V_LAST EMPLOYEE.LNAME%TYPE;
3 V_FIRST EMPLOYEE.FNAME%TYPE;
4 V_SAL EMPLOYEE.SALARY%TYPE;
5 BEGIN
6 SELECT LNAME, FNAME, SALARY
7 INTO V_LAST, V_FIRST, V_SAL
8 FROM EMPLOYEE
9 WHERE EMPLOYEEID = 200;
10 DBMS_OUTPUT.PUT_LINE
11 (’EMPLOYEE NAME: ’||V_FIRST |’’||V_LAST );
12DBMS_OUTPUT.PUT_LINE 13
(’SALARY: ’||TO_CHAR(V_SAL));
14 END; 15 /
EMPLOYEE NAME: Jinku Shaw SALARY: 24500
PL/SQL procedure successfully completed. SQL>
SQL> DECLARE
2 V_ID EMPLOYEE.EMPLOYEEID%TYPE;
3 V_DEPT EMPLOYEE.DEPTID%TYPE := &DEPT_NUM;
4 BEGIN
5 SELECT EMPLOYEEID INTO V_ID
6 FROM EMPLOYEE WHERE DEPTID = V_DEPT;
7 END;
8/
Enter value for dept_num: 10DECLARE
*
ERROR at line 1:
ORA-01422: exact fetchreturns more thanrequestednumber of rows ORA-06512:
at line 5
SQL> /
Enter value for dept_num: 50DECLARE
*
ERROR at line 1:
ORA-01403: no data foundORA-06512: at line 5
SQL>
You can use all D M L statements in PL /SQL with the same syntax you used in SQL.
The three D ML statements to manipulate data are:
INSERTStatement
SQL> BEGIN
2 INSERT INTO EMPLOYEE
3 (EMPLOYEEID, LNAME, FNAME, SALARY, DEPTID)
4 VALUES
5 (EMPLOYEE_EMPLOYEEID_SEQ.NEXTVAL, ’RAI’,
6 ’AISH’, 90000, DEPT_DEPTID_SEQ.CURRVAL);
7COMMIT; 8 END;
9/
PL/SQLprocedure successfullycompleted.SQL>
DELETE Statement
We will show the use of the D E L E TE statement in the PL/SQL block to remove
some rows. Suppose the NamanNavan (N2) Corporation decides to remove the I T
D epartment. A ll the employees belonging to that department must be removed
Data Manipulation in PL/SQL 263
SQL> DECLARE
2 V_DEPTID DEPT.DEPTID%TYPE;
3BEGIN 4
5 SELECT DEPTIDINTO V_DEPTID
6 FROM DEPT
7 WHERE UPPER(DEPTNAME) = ’&DEPT_NAME’
8 DELETE FROM EMPLOYEE
9 WHERE DEPTID = V_DEPTID; COMMIT;
10
11 END;
12 /
Enter value for dept_name: IT
UPDATE Statement
SQL> DECLARE
2 V_INCREASE NUMBER := &DECIMAL_INCREASE;
3 BEGIN
4 UPDATE EMPLOYEE
5 SET SALARY = SALARY * (1 + V_INCREASE)
6 WHERE EMPLOYEEID = &EMP_ID;
7COMMIT; 8 END;
9/
Enter value for decimal_increase: 0.15 Enter value for emp_id: 545
PL/SQLprocedure successfullycompleted.SQL>
TRANSACTION CONTROLSTATEMENTS
Y ou know what a transaction is. Y ou also know the transaction control capabilities in
Oracle. (I f you don’t remember, review Chapter 9). I n Figures 11- 18, 11- 19, and
11- 20, after performing a D M L statement, the sample blocks have used a C OMM I T
statement. You do not have to commit within a PL/SQL block. If you do decide to
use it, your data will be written to the disk right away, and the locks from those rows
will be released. A ll transaction control statements are allowed in PL/SQL, and they
are as follows:
IN A NUTSHELL . . .
● The three control structures in PL/SQL are sequence, selection, and looping.
● I n a sequence structure, the instructions are performed in a linear order.
● The selection structure involves decision making based on the outcome of a
Boolean expression.
● The looping structure contains a series of instructions that are performed
repeatedly.
● Four selection structure statements in PL /SQL are IF . . . THE N . . . E N D IF,
IF . . . TH E N . . . E L SE . . . E ND I F, I F . . . TH E N . . . E L SI F . . . E N D IF,
and CA SE statements.
● A CA SE statement uses a variable as a selector and checks its value in
W H E N clauses.
● A searched C A SE statement does not use a variable as a selector, but it
does use conditions in W H E N clauses.
● Bool ean expressions or conditions use relati onal oper ators 1 = , 6 7 or ! = ,
7 , 7 = , 6 , and 6 = 2, logical operators (A ND , O R , and N OT), and other op-
erators (B E TW E E N . . .A N D , IS NU L L , and L I K E ).
● I t is good practice to add comments to a program and indent statements
within a programming block.
● The three types of loops in PL/SQL are the basic loop, W H I L E loop, and
FO R loop.
● The basic loop is performed at least once and for as long as the condition is
false. I t is known as a post- test loop. The basic loop needs the E X I T state-
ment to terminate.
ExerciseQuestions 265
● The W HI L E loop is performed zero or more times and for as long as the
condition is true. I t is a pretest loop. The W H I L E loop does not need the
EX I T statement to terminate.
● The FO R loop is the simplest loop to write. I t declares a loop- control vari-
able implicitly, and it does not need the E X I T statement to end.
● The nested loop has a loop within a loop. Termination of the inner loop does
not automatically terminate the outer loop. The loops can be labeled and
can be terminated with the E X I T statement.
● PL/SQL programming blocks can also be nested. The variables declared in
the outer block are available in the inner block, but the variables declared in
the inner block are not accessible to the outer block.
● PL/SQL does not interact directly with the Oracle database. SQL is embed-
ded in a PL/SQL block to work with tables.
● DML, data retrieval, and transaction control SQL statements are allowed in
PL/SQL. D D L and D C L statements are not allowed in PL/SQL.
● The group functions are not supported in PL /SQL statements, but they can
be used in SQL statements within a PL/SQL block.
● The SELECT- I NTO statement retrieves data from a table into a set of vari-
ables. I t must retrieve only one row at a time.
● The INSERT, D E L E TE , and U PD A TE statements in a PL/SQL block are
used to manipulate data in tables.
EXERCISE QUESTIONS
True/False:
1. IF statements are used to repeat a series of instructions.
2. The W HI L E loop is always performed at least once.
3. A basic loop is performed as long as the condition is false.
4. The W HI L E loop is performed as long as the condition is true.
5. The FO R loop exits when the EX I T statement is encountered.
6. The counter (loop-control variable) used in a F OR loop need not be declared explicitly.
7. The SELECT statement must have a mandatory INTO clause when used in a PL /SQL block.
8. The group functions are not supported in PL /SQL statements, but single-row functions are.
9. The GR A N T statement is allowed in a PL/SQL block.
10. When two PL /SQL blocks are nested, the variables declared in the outer block are acces-
sible in the inner block.
Answer the Following Questions:
1. Name and explain the control structures used in PL/SQL programming.
2. What isthe difference between IF . . .THE N . . . E L SE . . . E ND I F and I F . .. TH E N ...
ELSI F . . . E ND IF statements?
266 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL
610
0 6 = 100 5
10 7= 5 -1
1 7= 7 1
0 6 = 10 2
LAB ACTIVITY
1. W rite a PL/SQL block to find out if a year is a leap year. A leap year is divisible by 4 but
not by 100, or it is divisible by 400. For example, 2000 and 2004 are leap years, but 1900
and 2001 are not leap years. ( The function M OD( ) divides by and returns
the integer remainder from the operation)
2. W rite a PL/SQL block to print all odd numbers between 1 and 10 using a basic loop.
3. U sing a F OR loop, print the values 10 to 1 in reverse order.
4. Create a table called I TEM with one column called ItemNum with the NU MB ER type.
W rite a PL /SQL program to insert values of one to five for ItemNum.
5. Input a number with a substitution variable, and then print its multiplication table using
a W HI L E loop.
6. Input a month number between 1 and 12 and a four-digit year, and print the number of
days in that month. For February 1month = 22, check for a leap year to display the num-
ber of days as equal to 28 or 29.
7. U se a PL/SQL block to delete item number 4 from the ITEM table created in lab activity 4.
8. W rite a PL/SQL block to ask a user to input a valid employee Id. Retrieve the employ-
ee’s name, qualification description, salary, and commission. Print the name, qualification,
and sum of the salary and commission.
9. Y ou went to a video store and rented a DV D that is due in 3 days from the rental date.
Input the rental date, rental month, and rental year. Caclculate and print the return date,
return month, and return year. For example,
Rental Date Rental Month Rental Year Return Date Return Month Return Year
2 12 2003 5 12 2003
27 2 2000 1 3 2000
30 12 2003 2 1 2004
IN THISCHAPTER . . .
● You will learn about a private work area for an SQL statement and its active
set, called a cursor.
● You will be introduced to implicit and explicit cursor types.
● You will perform open, fetch, and close actions on explicit cursors.
● Use of cursor F O R loops and its implied statements are explained.
● Cursors with parameters and variable cursors are introduced.
● PL/SQL errors, known as exceptions, and their types are discussed.
● The process of declaring, raising, and handling different types of exceptions is
covered.
I n previous chapters, you learned about different control structures: sequence, se-
lection, and looping. A ll structured programming languages support these struc-
tures. Other statements are also available in most of the languages. O ne of these
additional statements is the GO TO statement, which allows you to branch uncondi-
tionally. All you have to code is G OT O V W, and the control shifts to
the statement after the label. The GO TO statement, though available, is not preferred,
however, because of its nonstructured nature. Y ou also know how to use an SQL
statement within a PL /SQL block for data retrieval, data manipulation, and transac-
tion control.
268 Chap. 12 PL/SQL Cursors and Exceptions
I n this chapter, you will learn about some advanced features of PL/SQL, such
as retrieving more than one row from a database into a work ar ea called a .
One of the strongest benefits of PL /SQL is its error- handling capabilities. The error
conditions, known as , in PL/SQL, are also covered in this chapter.
CURSORS
When you execute an SQL statement from a PL/SQL block, Oracle assigns a private
work area for that statement. The work area, called a cursor, stores the statement
and the results returned by execution of that statement. A cursor is created either
implicitly or explicitly by you.
Typesof Cursors
This chapter covers static cursors in detail. I t also introduces you to the new
concept of dynamic cursors using a cursor variable. The static cursors are of two
types as well:
IMPLICIT CURSORS
PL/SQL creates an implicit cursor when an SQL statement is executed from within
the program block. The implicit cursor is created only if an explicit cursor is not at-
tached to that SQL statement. Oracle opens an implicit cursor, and the pointer is set
to the first (and the only) row in the cursor. Then, the SQL statement is fetched and
executed by the SQL engine on the Oracle server. The PL/SQL engine closes the
Explicit Cursors 269
CURSOR deptname_cur IS
SELECT DeptName, Location FROM dept WHERE DeptId = 10;
Here, only one row is retrieved by the cursor with two column values, Finance and
Charlotte, which later can be assigned to variables by fetching that row.
EXPLICITCURSORS
1. Declare it.
2. Open it.
3. Fetch row(s) from it.
4. Close it.
where is the name of the cursor that follows identifier- naming rules. The
SE L E CT statement is any valid data-retrieval statement. The cursor declaration is
done in the D E C L A R E section of the PL/SQL block, but a cursor cannot be used in
programming statements or expressions, as with other variables.
For example, Figures 12-1 and 12- 2 show declarations of two cursors. I n Figure
12-1, the cursor is based on a SE L EC T query that will retrieve all rows from the
D E PT table in the work area. I n the Figure 12-2, two columns, EmployeeI d and
Salary, are selected into the cursor with D eptI d equal to 20.
SQL> DECLARE
2 CURSOR DEPT_CUR IS
3 SELECT * FROM
4 DEPT;
6
5 BEGIN 7 ...
8 END;
SQL> DECLARE
2 CURSOR EMPLOYEE_CUR IS
3 SELECT EMPLOYEEID, SALARY
4 FROM EMPLOYEE
5 WHERE DEPTID = 20;
6
7 BEGIN 8 ...
9 END;
Opening a Cursor. W hen a cursor is opened, its SELECT query is executed. The
active set is created using all tables in the query and then restricting to rows that meet
the criteria. The data retrieved by the SE L E C T query is brought into the cur- sor or
the work area. The cursor points to the first row in the active set. PL/SQL uses an
OPE N statement to open a cursor. The general syntax is
For example,
OPEN employee_cur;
You must open a cursor that has not been opened in the program block or is
closed to retrieve data into it. If you try to open a cursor that is already open, the fol-
lowing Oracle error message appears:
PLS-06511:PL/SQL: cursor already open
Notice the change in the er ror message prefix PLS! The errors with prefix O R A are
Oracle database errors, and the errors with prefix PLS are PL/SQL errors.You will
see later how this can be avoided using the cursor attribute % I SOPE N.
Fetching Data from a Cursor. The SE L EC T statement creates an active set
based on tables in the FR O M clause, column names in the SE L E CT clause, and rows
based on conditions in the W H E R E clause. The cursor is a virtual table that you
can work with. Y ou can retrieve a row that the cursor is pointing to, and the val- ues
from that row are retrieved into variables or into a PL/SQL record to perform
processing. A fter reading values from a row into variables, the cursor pointer moves
to the next row in the active set. The number of variables must match the number of
columns in the row. I n PL/SQL, a F E TC H statement is used for this action. The gen-
eral syntax is
For example,
CLOSEemployee_cur;
EXPLICITCURSOR ATTRIBUTES
Actions can be performed on cursors with OPEN, FE TCH , and C L OSE statements.
You can get information about the current status of a cursor or the result of the last
fetch by using cursor attributes. The four explicit cursor attributes are:
%ISOPEN
The % I SO PE N attribute is useful in making sure that you do not open a cursor that
is already open. I t is also appropriate for making sure that a cursor is open before
ExplicitCursor Attributes 273
trying to fetch from it. For example, Figure 12-3 tests to see if a cursor is open. I f it is
not open, already, the cursor is opened. Then, execution continues with a loop and a
fetch in it.
%FOUND
The statement
EXIT WHEN NOT employee_cur%FOUND;
can be written as
EXIT WHEN employee_cur%NOTFOUND;
%ROWCOUNT
IMPLICITCURSOR ATTRIBUTES
1. SQL % I SOPE N.
2. SQL % RO W CO U NT.
3. SQL % NOTFO U ND .
4. SQL % FOU N D .
CURSORFOR LOOPS
The cursor FO R loop is the easiest way to write a loop for explicit cursors. The cur-
sor is opened implicitly when the loop starts. A row is then fetched into the record
from the cursor with every iteration of the loop. The cursor is closed automatically
when the loop ends, and the loop ends when there are no more rows. The cursor
Cursor FOR Loops 275
...
where is the name of the record that is declared implicitly in the loop
and is destroyed when the loop ends and is the name of declared ex-
plicit cursor.
Figure 12-4 uses a Cursor F OR loop with a record. W hen the loop starts, the
cursor is opened implicitly. D uring the loop execution, an implicit fetch retrieves a
row into the record for processing with each loop iteration. W hen an implicit fetch
cannot retrieve a row, the cursor is closed, and the loop terminates. The OPEN,
FE TCH, and CL OSE statements are missing, because these operations are per-
formed implicitly. The record’s columns are addressed with
notation. If the record is accessed after the E ND L O OP statement, it will throw an
exception, because the record’s scope is only within the loop body.
PL/SQLprocedure successfullycompleted.SQL>
SQL> BEGIN
2 FOR EMP_RECIN
3 (SELECT FNAME, LNAME, SALARY, COMMISSION
4 FROM EMPLOYEE
5 WHERE DEPTID = 10) LOOP
6 DBMS_OUTPUT.PUT_LINE
7 (EMP_REC.FNAME |’’||EMP_REC.LNAME |’$’||
8 TO_CHAR(EMP_REC.SALARY + NVL(EMP_REC.COMMISSION, 0)));
9 END LOOP;
10 END;
11 /
John Smith$300000 Sandi Roberts $75000Sunny Chen $35000
PL/SQLprocedure successfullycompleted.SQL>
When you type a SE L E C T query, the result is returned to you without locking any
rows in the table. Row locking is kept to a minimum. You can explicitly lock rows for
update before changing them in the program. The FO R U PD A TE clause is used
with the SE LE C T query for row locking. The locked rows are not available to other
users for D M L statements until you release them with C OM MI T or RO LL BA CK
commands. Rows that are locked for update do not have to be updated. The general
syntax is
Cursor with Parameters 277
CURSORWITHPARAMETERS
A cursor can be declared with parameters, which allow you to pass values to the cur-
sor. These values are passed to the cursor when it is opened, and they are used in the
query when it is executed. With the use of parameters, you can open and close a cur-
sor many times with different values. The cursor with different values will then re-
turn different active sets each time it is opened. When parameters are passed, you
need not worry about the scope of variables. The general syntax is
can be passed through literals, PL/SQL variables, or bind variables. The parameters
in a cursor are passed in to the cursor, but you cannot pass any value out of the cur-
sor through parameters.
For example, in the PL/SQL program of Figure 12-6, the cursor
is declared with a parameter which is also used in the cursor SE L EC T
statement’s W H E R E clause. When the program executes, it asks to input a value for
department number with substitution variable D EPA RTME NT_I D , which is as-
signed to variable D_ID . The cursor is opened with parameter D _ID , which has
value of 10 as entered by the user. The format parameter D E PT_N U M gets value of
parameter D _ID . The active set is created based on D E PTI D = DEPT_ NU M.
Then, the cursor loop prints all employees for department number 10. The parameter
can be passed a value with a literal (as done in here), a bind variable, or an expression.
20 END;21 /
Enter value for department_id: 10 EMPLOYEES IN DEPARTMENT
10
Smith, JohnRoberts,Sandi Chen, Sunny
A cursor with a parameter can be opened multiple times with a different parameter
value to get a different active set.
When you declare a cursor with one or more parameters, you can initialize it
to a default value as follows:
CURSOR employee_cur (dept_id employee.DeptId%TYPE := 99) IS
A n explicit cursor is the name of the work area for an active set. A cursor variable is
a reference to the work area. A cursor is based on one specific query, whereas a cur-
sor variable can be opened with different queries within a program. A static cursor
is like a constant, and a cursor variable is like a pointer to that cursor. Y ou can also
use the action statements OPEN, FE TCH , and CL O SE with cursor variables. The
cursor attributes % I SO PEN , % F OU ND , % N OTF OU ND , and % R OW CO U NT
are available for cursor variables. Cursor variables have many similarities with stat-
ic cursors.
The cursor variable has other capabilities in addition to the features of a static
cursor. I t is a variable, so it can be used in an assignment statement. A cursor vari-
able can also be assigned to another cursor variable.
REF CURSORType
Two steps are involved in creating a cursor variable. First, you have to create a ref-
erenced cursor type. Second, you have to declare an actual cursor variable with the
referenced cursor type. The general syntax is
You assign a cursor to the cursor variable when you O PE N it. The general syntax is
If the cursor type is declared with the R E TU R N clause, the structure from the SE-
L E C T query must match the structure specified in the R E F C U R SO R declaration.
For example,
OPEN employee_cursor_var FOR SELECT * FROM employee;
I t is possible to have all three statements in one program block. The cursor variable
assumes different structures with each OPEN.
The fetching action is same as that of a cursor. The compiler checks the data struc-
ture type after the I NTO clause to see if it matches the query linked to the cursor.
The general syntax is
EXCEPTIONS
task, however. A programmer must think of all the negative situations that may arise
while the program is executed. For example, the system might run out of memory, the
database might not be accessible, or the user might type in the wrong value or press
the wrong key. The programmer must put extra effort into program design to remove
bugs and make the program error- proof with additional code to perform in case of
exceptions. PL/SQL provides ways to trap and handle errors, and it is possible to cre-
ate PL/SQL programs with full protection against errors. When exception- handling
code is written for an exception, that exception can occur anywhere in the block, and
the same handler can deal with it.
The syntax of an anony mous block is given below. Control transfers from the
execution section to the excepti on section. PL /SQL browses through the section to
look for the handl er. I f the handler is present, it is executed. The program may have
more than one exception handler, written with W HE N . . . TH E N statements like an
E LSI F or CA SE structure (as supported by Oracle9i). For example,
A n exception is handled when the exception name matches the name of the
raised exception. The exceptions are trapped by name. If an exception is raised but
no handler for it is present, the W HE N O TH E RS clause is performed (if present). If
there is no handler for an exception and no W H E N O TH E R S clause, the error
number and associated message are displayed to the user.
TYPESOF EXCEPTIONS
There are approximately 20 such exceptions. E ach has a name and associ-
ated error number.
are standard Oracle server er-
rors that are not named by the system. They can be declared in the decla-
ration section but are raised implicitly by the server. These exceptions do
not have a name, but they do have an associated er ror number.
are exceptions that are declared in the declara-
tion section and are raised by the user explicitly. The user decides which
abnormal condition is an exception. The Oracle server does not consider
these conditions to be errors.
Exceptions that are given names by PL/SQL are declared in a PL/SQL package
called STAND ARD . The exception- handling routine is also defined there. The user
does not have to declare or raise predefined server exceptions. Figure 12- 7 provides
the exception name, the error code returned by the built-in function SQL C OD E ,
and a brief description of the exception.
A nonpredefined Oracle server exception has an attached Oracle error code, but it is
not named by Oracle. You can trap such exceptions with a W H E N O THE R S clause
or by declaring them with names in the D E C L A R E section. The declared exception
284 Chap. 12 PL/SQL Cursors and Exceptions
is raised implicitly by Oracle, or you can raise it explicitly. Y ou can write exception-
handler code for it.
SQL> DECLARE
2 emp_remain EXCEPTION;
3 PRAGMA EXCEPTION_INIT (emp_remain, -2292);
4 v_deptid dept.DeptId%TYPE := &p_deptnum;
5 BEGIN
6 DELETE FROM dept
7 WHERE DeptId = v_deptid;
8 COMMIT;
9 EXCEPTION
10 WHEN emp_remain THEN
11 DBMS_OUTPUT.PUT(’DEPARTMENT ’||TO_CHAR(v_deptid));
12 DBMS_OUTPUT.PUT(’ cannot be removed - ’);
13 DBMS_OUTPUT.PUT_LINE(’Employees in department’);
14 END;15 /
Enter value for p_deptnum: 10
DEPARTMENT 10 cannot be removed - Employees in department
PL/SQL procedure successfully completed. SQL> /
Enter value for p_deptnum: 60
PL/SQL procedure successfully completed. SQL>
SQL> DECLARE
2 V_FIRST EMPLOYEE.FNAME%TYPE;
3 V_LAST EMPLOYEE.LNAME%TYPE;
4 D_ID NUMBER(2) := &DEPARTMENT_ID;
5 V_CODE NUMBER;
6 V_MSG VARCHAR2(255);
7 BEGIN
8 SELECT LNAME, FNAME
9 INTO V_LAST, V_FIRST
10 FROM EMPLOYEE
11 WHERE DEPTID = D_ID;
12 DBMS_OUTPUT.PUT_LINE(’ ’);
13 DBMS_OUTPUT.PUT_LINE(V_LAST |’, ’||V_FIRST);
14 EXCEPTION
15 WHEN OTHERS THEN
16 V_CODE :=SQLCODE;
17 V_MSG := SQLERRM;
18 DBMS_OUTPUT.PUT_LINE(’ERROR CODE: ’||SQLCODE);
19 DBMS_OUTPUT.PUT_LINE(SQLERRM);
20 END;
21 /
Enter value for department_id: 10ERROR CODE: -1422
ORA-01422: exact fetch returns more than requestednumber of rows
User-Defined Exceptions
The standard errors covered under the previous two types are in the STA ND A R D
package with an error code and an accompanying message. Often, however, you will
encounter situations that are specific to a given program. For example, a birth date
falls in the future, a quantity in an invoice is negative, a student registers for course
without satisfying prerequisite, and so on.
You are allowed to define your exceptions in PL/SQL. Y ou must perform
three steps for exceptions you want to define:
SQL> DECLARE
2 invalid_commission EXCEPTION; no_commission EXCEPTION;
3 v_commemployee.Commission%TYPE;
5 BEGIN
4
6 SELECT Commission
7 INTO v_comm
8 FROM employee
9 WHERE EmployeeId = &emp_id;
10 IFv_comm< 0 then
11 RAISE invalid_commission;
12 ELSIF v_commIS NULLTHEN
13 RAISE no_commission;
14 ELSE
15 DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_comm));
16 END IF;
17 EXCEPTION
18 WHEN invalid_commission THEN
19 DBMS_OUTPUT.PUT_LINE(’Commissionis negative.’);
20 WHEN no_commission THEN
21 DBMS_OUTPUT.PUT_LINE(’Nocommission value’);
22 WHEN OTHERS THEN
23 DBMS_OUTPUT.PUT_LINE(’NosuchID’);
24 END; 25 /
RAISE_APPLICATION_ERROR Procedure
where the is a user-specified number between - 20, 000 and - 20,999 and
is a user-supplied message that can be up to 512 bytes long. The third
Boolean parameter, TRU E/FA LSE , is optional. TR U E means “place the error on
288 Chap. 12 PL/SQL Cursors and Exceptions
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for emp_id: 123
No commission value
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for emp_id: 546 Commission is
negative.
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for emp_id: 321 No such ID
PL/SQLprocedure successfullycompleted.
SQL>
stack of other errors.” FA LSE is the default value, and it replaces all previous errors.
For example,
EXCEPTION
WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR
(–20001, ‘Department does not exist’);
I n this section, you will see the PL /SQL blocks based on the topics covered in this
chapter, such as an explicit cursor, a cursor FO R loop, a cursor with parameters,
and exception handling. The code in Figure 12-14 uses an explicit cursor
The active set contains the employee’s last name, first name, salary, and commis-
sion. The W H I L E loop is used to work with one row at a time. W ithin the loop, an
employee’s salary and commission are added together to find the total income.
A lso, note the use of a single- row function N V L in case the commission value is
NU L L. Finally, total company wages (the total of all employee salaries and com-
missions) are printed.
W hen the program in Figure 12-15 is executed, you will be prompted to enter
the date for the substitution variable When the cursor is opened with
as a parameter, it will retrieve rows that have H ireD ate after the inputted date. The
information for those employees will be printed. The program also will display the
total number of employees selected.
The program in Figure 12- 16 selects employees with PositionI d of 2 who are
managers. I t locks those rows for future update. Using a cursor FO R loop, each
manager’s salary is modified to give a 7% raise. The W H E R E C U RR E NT OF
clause is used to modify the current row fetched. The rows are released with the
C OM MI T command.
The program in Figure 12- 17 displays two customized prompts for an employ-
ee’s I D and the percentage increment/raise. First, rows are locked with the FO R
U PD A TE clause. The U PD A TE statement changes the salary if the I D is correct. If
the employee I D does not exist, a standard exception is raised implicitly. The excep-
tion is handled by displaying an appropriate message.
INA NUTSHELL. . .
● A cursor is a private work area to store a statement and its active set.
● A static cursor’s contents are known at compile time, and a dynamic cursor
uses a cursor variable, which can refer to different SQL statements at differ-
ent times.
● A n implicit cursor is declared, managed, and closed by PL/SQL.
● The programmer declares an explicit cursor for a PL/SQL block that returns
more than one row from the table.
290 Chap. 12 PL/SQL Cursors and Exceptions
2 CURSOR EMP_CUR IS
3 SELECT LNAME, FNAME, SALARY, COMMISSION
4 FROM EMPLOYEE WHERE SALARY IS NOT NULL;
5 V_FIRST EMPLOYEE.FNAME%TYPE; V_LAST
6 EMPLOYEE.LNAME%TYPE; V_SAL
7 EMPLOYEE.SALARY%TYPE;
8 V_COMM EMPLOYEE.COMMISSION%TYPE; V_TOTSAL
9 EMPLOYEE.SALARY%TYPE; V_SUM
10 EMPLOYEE.SALARY%TYPE := 0;
11 BEGIN
12 OPEN EMP_CUR;
13 FETCH EMP_CUR INTO V_LAST,V_FIRST, V_SAL, V_COMM; WHILE
14 EMP_CUR%FOUND LOOP
15 V_TOTSAL:= V_SAL + NvL(V_COMM, 0); V_SUM := V_SUM +
16 V_TOTSAL; DBMS_OUTPUT.PUT(V_LAST |’, ’||V_FIRST);
17 DBMS_OUTPUT.PUT_LINE
18 (’makes ’||TO_CHAR(V_TOTSAL,’$999,999’));
19 FETCH EMP_CUR INTO V_LAST,V_FIRST,V_SAL,V_COMM; END
20 LOOP;
21 DBMS_OUTPUT.PUT_LINE
22 (’COMPANY WAGES: ’||TO_CHAR(V_SUM, ’$999,999’));
23
24 END; 25 /
Smith, Johnmakes $300,000 Houston, Larrymakes $160,000
Roberts, Sandi makes $75,000 McCall, Alex makes $66,500Dev,
Derek makes $100,000 Shaw, Jinku makes $27,500 Garner,
Stanley makes $50,000 Chen, Sunny makes $35,000
COMPANY WAGES: $814,000
PL/SQLprocedure successfully completed.SQL>
24 END; 25 /
Enter value for p_date: 31-DEC-1995
McCall, Alex was hired on 05/10/1997in InfoSys department Shaw,
Jinku was hired on 01/03/2000 in Sales department Garner, Stanley was
hired on02/29/1996 in Sales department Chen, Sunny was hired on
08/15/1999 in Finance department TOTAL EMPLOYEES: 4
PL/SQLprocedure successfullycompleted.SQL>
SQL> /* Program uses a cursor to update salaries for any one DOC>position.It locks
rows with FOR UPDATE clause.
DOC>It updates row fetched with WHERE CURRENT OFclause */ SQL> DECLARE
2 CURSOR SAL_CUR IS
3 SELECT LNAME, SALARY
4 FROM EMPLOYEE
5 WHERE POSITIONID =
6 (SELECT POSITIONID FROM POSITION
7 WHERE UPPER(POSDESC) = ’&POSITION’)
8 FOR UPDATE;
9 BEGIN
10 FOR SAL_RECIN SAL_CUR LOOP
11 UPDATE EMPLOYEE
12 SET SALARY = SALARY * 1.07
13 WHERE CURRENT OF SAL_CUR;
14 END LOOP;
15 -- COMMIT; /* canbe uncommented for immediate update */
16 END;
17 /
Enter value for position: MANAGER
PL/SQLprocedure successfully completed.SQL>
SQL> /* Program prompts user for employeeid and percentage rise. DOC>If employeeid does not
exist, exception is raised and handled */SQL> DECLARE
2 V_EMPID EMPLOYEE.EMPLOYEEID%TYPE;
3 V_SALEMPLOYEE.SALARY%TYPE;
4 V_RAISE NUMBER(3,2) := &P_RAISE;
5 BEGIN
6 SELECT EMPLOYEEID, SALARY
7 INTO V_EMPID, V_SAL FROM EMPLOYEE
8 WHERE EMPLOYEEID = &P_EMPID FOR UPDATE NOWAIT;
9 UPDATE EMPLOYEE
10 SET SALARY = SALARY + SALARY * V_RAISE
11 WHERE EMPLOYEEID = V_EMPID;
12 DBMS_OUTPUT.PUT_LINE(’SALARY UPDATED FOR EMPLOYEE ’||V_EMPID);
13 EXCEPTION
14 WHEN NO_DATA_FOUND THEN
15 DBMS_OUTPUT.PUT_LINE(’NO SUCH EMPLOYEEID IN TABLE’);
16 END;
17 /
Enter value for p_raise: 0.05Enter value for p_empid: 999 NO SUCH EMPLOYEEID IN TABLE
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for p_raise: 0.10Enter value for p_empid: 111
SALARY UPDATED FOR EMPLOYEE 111
PL/SQLprocedure successfullycompleted.SQL>
● A cursor variable can be opened with different queries within the same pro-
gram. A ll action statements and cursor attributes can be used with a cursor
variable.
● PL/SQL errors are called exceptions, and they are handled in the exception
section of the PL/SQL block.
● Three types of exceptions are predefined Oracle server exceptions, nonpre-
defined Oracle server exceptions, and user- defined exceptions.
● Predefined Oracle server exceptions are declared in the Oracle package
called STA NDA RD. There are approximately 20 such exceptions.
294 Chap. 12 PL/SQL Cursors and Exceptions
EXERCISE QUESTIONS
True/F alse:
1. A cursor variable is a dynamic cursor that can refer to different SQL statements at dif-
ferent times.
2. A n implicit cursor is used when an SQL statement in the PL/SQL block returns more
than one row from the table.
3. The O R DE R BY clause is not allowed in the SEL ECT statement of an explicit cursor’s
declaration.
4. If a cursor F O R loop uses a subquery with an IN clause, there is no need to declare that
cursor.
5. A nonpredefined Oracle server error is declared with a PR A GM A EX CEPTIO N_I NI T
directive.
6. A user-defined exception is declared with a PR A G MA EX CEPTI ON _I NI T directive.
7. The RA I SE statement is used to raise a predefined Oracle server exception.
8. A cursor is based on a SEL ECT query, which is executed when the cursor is opened.
9. A record used in a cursor F OR loop must be declared in the DE CL A R E section.
10. A cursor F O R loop is opened, fetched from, and closed automatically.
LAB ACTIVITY
1. Create a PL/SQL block to declare a cursor to select last name, first name, salary, and hire
date from the E MPL OY EE table. Retrieve each row from the cursor, and print the
employee’s information if the employee’s salary is greater than $50,000 and the hire date is
before 31-DEC-1997 (explicit cursor problem).
2. Create a PL /SQL block that declares a cursor. Pass a parameter of the same type as the
Salary column in the EM PL O Y E E table to the cursor. Open the cursor with a value for
the parameter. Retrieve information into the cursor for a salary higher than the param-
eter value. Use a loop to print each employee’s information from the cursor (cursor with
parameter problem).
3. Create a PL/SQL block to increase the salary of employees in department 10. The salary
increase is 15% for employees making less than $100,000 and 10% for employees mak-
ing $100,000 or more. U se a cursor with a FO R U PD ATE clause. U pdate the salary with
a W H E R E CU R R EN T O F clause in a cursor F OR loop (cursor F O R loop problem).
4. W rite a PL/SQL block to retrieve employees from the EM PL O Y EE table based on a
qualification ID. If the qualification I D returns more than one row, handle the exception
with the appropriate handler, and print the message “More than one employee with such
qualification.” If the qualification I D returns no employee, handle the exception with the
appropriate handler, and display the message “No employees with such qualification.” If
the qualification I D returns one employee, print that employee’s name, qualification, and
salary (predefined server exception problem).
5. W rite a PL/SQL block that retrieves the entire CO U R SE table into a cursor. Then, ask
the user to input a course I D to search. If the course exists, print its information. If the
course does not exist, throw a user-defined exception, and display the message “Course
does not exist” in the CO U R SE table when you execute the block with a course I D such
as CIS555. (user-defined exception problem).
6. W rite a PL/SQL block that asks the user to input first number, second number, and an
arithmetic operator ( + , - , *, or /). If the operator is invalid, throw and handle a user-
defined exception. If the second number is zero and the operator is /, handle the
Z ER O _ DI V I D E predefined server exception.
IN THIS CHAPTER . . .
Composite data types are like scalar data types. Scalar data types are atomic, be-
cause they do not consist of a group. Composite data types, on the other hand, are
groups, or “collections.” Examples of composite data types are R E C OR D , TABLE,
nested TA BL E, and V ARRA Y. I n this chapter, we will talk about all four composite
data types.
PL/SQL Records 297
PL/SQL RECORDS
PL/SQL records are similar in structure to a row in a database table. A record con-
sists of components of any scalar, PL /SQL record, or PL /SQL table type. These com-
ponents are known as fields, and they have their own values. PL/SQL records are
similar in structure to “struct” in the C language. The record does not have a value as
a whole; instead, it enables you to access these components as a group. I t makes
your life easier by transferring the entire row into a record rather than each column
into a variable separately.
A PL/SQL record is based on a cursor, a table’s row, or a user-defined record
type. You learned about a record in a cursor F O R loop in the previous chapter. A
record can be explicitly declared based on a cursor or a table:
CURSOR IS
SELECT ;
CursorName%ROWTYPE;
A record can also be based on another composite data type called TABL E. W e will
examine user-defined records in the next section.
I n this section, you will learn to create a user-defined record. You create a
R E C OR D type first, and then you declare a record with that R E C OR D type. The
general syntax is
For example,
TYPE employee_rectype IS RECORD
(e_last VARCHAR2(15),
e_first VARCHAR2(15),
e_sal NUMBER(8,2));
employee_rec employee_rectype;
Now, you will look at another declaration with the % TY PE attribute. For
example,
TYPE employee_rectype IS RECORD
(e_id e_last NUMBER(3) NOT NULL :=111,
e_firste_sal employee.Lname%TYPE,
employee_rec employee.Fname%TYPE,
employee.Salary%TYPE);
employee_rectype;
The NOT N U L L constraint can be used for any field to prevent Null values, but that
field must be initialized with a value.
The record name and field name are joined by a dot (.). For example, you can refer-
ence the field from the previous declaration as
employee_rec.e_sal
You can use a field in an assignment statement to assign a value to it. For ex-
ample,
A record is known in the block where it is declared. When the block ends, the record
no longer exists. Y ou can assign values to a record from columns in a row by using
the SE L E CT statement or the FE TC H statement. The order of fields in a record
must match the or der of columns in the row. A record can be assigned to another
record if both records have the same structure.
A record can be set to NULL , and all fields will be set to NU LL. However, do
not try to assign a NU L L to a record that has fields with the NO T N U L L constraint.
For example,
Employee_rec := NULL;
I n the previous chapter, you saw the use of the % R OW TY PE attribute. The
record declared with % R OW TY PE has the same structure as the table’s row. For
example,
emp_rec employee%ROWTYPE;
PL/SQL Records 299
SQL> DECLARE
2 TYPE STUDENT_RECORD_TYPE IS RECORD
3 (S_LAST VARCHAR2(15),
4 S_FIRST VARCHAR2(15),
5 S_PHONE VARCHAR2(10));
6 STUDENT_REC STUDENT_RECORD_TYPE;
7 BEGIN
8 SELECT LAST, FIRST, PHONE INTO STUDENT_REC
9 FROM STUDENT WHERE STUDENTID = ’&STUD_ID’;
10 DBMS_OUTPUT.PUT_LINE(STUDENT_REC.S_LAST | ’, ’
11 | STUDENT_REC.S_FIRST | ’ --> ’ |
12 STUDENT_REC.S_PHONE);
13 END;
14 /
Enter value for stud_id: 00100 Diaz, Jose --> 9735551111
PL/SQL procedure successfully completed.SQL>
Nested Records
You can create a nested record by including a record into another record as a field.
The record that contains another record as a field is called the enclosing r ecor d. For
example,
DECLARE
TYPE address_rectype IS RECORD
(first VARCHAR2(15),
last VARCHAR2(15),
300 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays
street VARCHAR2(25),
city VARCHAR2(15),
state CHAR (2),
zip CHAR (5));
TYPE all_address_rectype IS RECORD
(home_address address_rectype,
bus_address address_rectype,
vacation_address address_rectype);
address_rec all_address_rectype;
PL/SQL TABLES
For example,
TYPE deptname_table_type IS TABLE OFdept.DeptName%TYPEINDEX BY BINARY_INTEGER;
TYPE major_table_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
You can declare a table type with a scalar data type (V A RC HA R 2, D ATE,
BO OL E A N , or POSI TI V E ) or with the declaration attribute % TY PE . Optionally,
you can use N OT NU L L in a declaration, which means that none of the elements in
the table may have a Null value. You must, however, add an I ND E X BY BINA -
R Y _ I NTE G E R clause to the declaration. This is the only available clause for index-
ing a table at present. Indexing speeds up the search process from the table. The
primary key is stored internally in the table along with the data column. The table
consists of two columns, the index/primary key column and the data column.
You define the actual table based on the table type declared earlier. The gen-
eral syntax is
For example,
deptname_table deptname_table_type; major_table major_table_type;
Figure 13- 2 illustrates a table’s structure. I t contains a primary key column and
a data column. Y ou cannot name these columns. The primary key has the type BI-
NA R Y _ I NTE GE R, and the data column is of any valid type. There is no limit on the
number of elements, but you cannot initialize elements of a table at declaration time.
The rows in a table are referenced in the same way that an element in an array is ref-
erenced. Y ou cannot reference a table by its name only. You must use the primary
key value in a pair of parentheses as its subscript or index:
302 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays
1. Direct assignment.
2. Assignment in a loop.
3. Aggregate assignment.
Assignment in a Loop. Y ou can use any of the three PL/SQL loops to as-
sign values to rows in a table. The program block in Figure 13-3 assigns all Sunday
dates for the year 2004 to a table. The primary key index value will vary from 1 to 52.
The table column will contain dates for 52 Sundays. If you are innovative, you can
create great applications with loops and tables.
PL/SQL Tables 303
SQL> DECLARE
2 TYPE DATE_TABLE_TYPE IS TABLE OF DATE
3 INDEX BY BINARY_INTEGER;
4 SUNDAY_TABLE DATE_TABLE_TYPE;
5 V_DAY BINARY_INTEGER := 1;
6 V_DATE DATE;
7 V_COUNT NUMBER(3) := 1;
8 BEGIN
9 V_DATE := ’01-JAN-2004’;
10 WHILE V_COUNT <= 365 LOOP
11 IF UPPER(TO_CHAR(V_DATE, ’DAY’)) LIKE ’%SUNDAY%’ THEN
12 SUNDAY_TABLE(V_DAY) := V_DATE;
13 DBMS_OUTPUT.PUT_LINE
14 (TO_CHAR (SUNDAY_TABLE (V_DAY), ’MONTH DD, YYYY’));
15 V_DAY := V_DAY +1;
16 END IF;
17 V_COUNT := V_COUNT +1;
18 V_DATE := V_DATE +1;
19 END LOOP;
20 END;
21 /
Aggr egate Assignment. Y ou can assign a table’s valuesto another table. The
data types of both tables must be compatible. W hen you assign a table’s values to
another table, the table receiving those values loses all its previous primary key
values as well as its data column values. If you assign an empty table with no rows to
another table with rows, the recipient table is cleared. I n other words, it loses all its
rows. Both tables must have the same type for such an assignment.
304 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays
The built- in table methods are procedures or functions that provide information
about a PL /SQL table. Figure 13- 4 lists the built-in table methods and their use. The
general syntax is
Now, look at another example of TA BLE, in Figure 13-5, where the program
declares two table types. The two tables based on these TA BL E types are parallel
tables. The corresponding values in the two tables are related. The program popu-
lates these two tables using a cursor FO R loop. Then, another simple FO R loop is
used to print information from the two tables.
PL/SQL Tables 305
SQL> DECLARE
2 TYPE LNAME_TABLE_TYPE IS TABLE OF EMPLOYEE.LNAME%TYPE
3 INDEX BY BINARY_INTEGER;
4 NAME_TABLE LNAME_TABLE_TYPE;
5 TYPE SALARY_TABLE_TYPE IS TABLE OF EMPLOYEE.SALARY%TYPE
6 INDEX BY BINARY_INTEGER;
7 SALARY_TABLE SALARY_TABLE_TYPE;
8 C BINARY_INTEGER := 0;
9 CURSOR C_LASTSAL IS
10 SELECT LNAME, SALARY FROM EMPLOYEE;
11 V_TOT NUMBER(2);
12 BEGIN
13 SELECT COUNT(*) INTO V_TOT FROM EMPLOYEE;
14 /* TABLE ASSIGNMENT IN LOOP */
15FOR LASTSAL_REC IN C_LASTSAL LOOP16 C:= C+1;
16 NAME_TABLE(C) := LASTSAL_REC.LNAME;
17 SALARY_TABLE(C) :=LASTSAL_REC.SALARY;
18 END LOOP;
19 /* PRINTING TABLE IN LOOP */
20 FOR C IN 1..V_TOTLOOP
21 DBMS_OUTPUT.PUT_LINE(NAME_TABLE(C) |’’||
23 TO_CHAR(SALARY_TABLE(C), ’$999,999.99’));
24 END LOOP;
25 END;
26 /
Smith $291,500.00 Houston
$160,500.00 Roberts
$80,250.00McCall
$66,500.00Dev $85,600.00 Shaw
$24,500.00
Garner $48,150.00 Chen $35,000.00
Table of Records
The PL/SQL table type is declared with a data type. Y ou may use a record type as a
table’s data type. The % R OW TY PE declaration attribute can be used to define the
record type. W hen a table is based on a record, the record must consist of fields with
306 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays
scalar data types. The record must not contain a nested record. The following exam-
ples show different ways to declare table types based on records:
•
TYPE student_record_type IS
RECORD (stu_id NUMBER(3), stu_name VARCHAR2(30)); TYPE student_table_type IS
TABLEOF student_record_type
INDEX BY BINARY_INTEGER;
Student_table student_table_type;
•
TYPE employee_table_type IS TABLEOF employee%ROWTYPE INDEX BY BINARY_INTEGER;
Employee_table employee_table_type;
For example,
Student_table(10).stu_name := ‘Ephrem’; Employee_table(13).Salary := 50000;
PL/SQL VARRAYS
A var ray is another composite data type or collection type in PL/SQL. Varray stands
for variable-size array. They are single- dimensional, bounded collections of ele-
ments with the same data type. They retain their ordering and subscripts when
stored in and retrieved from a database table. They are similar to a PL/SQL table,
and each element is assigned a subscript/index starting with 1.
PL/SQL Varrays 307
For example,
DECLARE
TYPE Lname_varray_type IS VARRAY(5) OF employee.LName%TYPE; Lname_varray
Lname_varray_type :=Lname_varray_type( );
DECLARE
TYPE varray_type1 IS VARRAY(3) OF NUMBER; TYPE varray_type2 IS VARRAY(2)
of varray_type1;
elements with the same data type. A nested table can be used in PL /SQL as well as
a database table. You can use a column that has a table type as its data type in a
database table.
SQL> DECLARE
2 CURSOR COURSE_CUR IS
3 SELECT COURSEID
4 FROM COURSE
5 WHERE ROWNUM <= 5;
6 TYPE COURSEID_VARRAY_TYPE IS VARRAY(10) OF COURSE.COURSEID%TYPE;
7 COURSEID_VARRAY COURSEID_VARRAY_TYPE := COURSEID_VARRAY_TYPE();
8 V_COUNT NUMBER(1) := 1;
9 BEGIN
10 FOR COURSE_REC IN COURSE_CUR LOOP
11 COURSEID_VARRAY.EXTEND;
12 COURSEID_VARRAY(V_COUNT) := COURSE_REC.COURSEID;
13 DBMS_OUTPUT.PUT_LINE
14 (’Courseid(’ | V_COUNT | ’): ’
15 | COURSEID_VARRAY(V_COUNT));
16 V_COUNT := V_COUNT + 1;
17 END LOOP;
18 DBMS_OUTPUT.PUT_LINE
19 (’NUMBER OF ELEMENTS: ’ | COURSEID_VARRAY.COUNT);
20 DBMS_OUTPUT.PUT_LINE
21 (’LIMIT ON ELEMENTS: ’ | COURSEID_VARRAY.LIMIT);
22 DBMS_OUTPUT.PUT_LINE
23 (’FIRST ELEMENTS: ’ | COURSEID_VARRAY.FIRST);
24 DBMS_OUTPUT.PUT_LINE
25 (’LAST ELEMENTS: ’ | COURSEID_VARRAY.LAST);
26 END;
27 / Courseid(1): EN100
Courseid(2): LA123 Courseid(3): CIS253Courseid(4): CIS265Courseid(5): MA150 NUMBER OF ELEMENTS:
5 LIMIT ON ELEMENTS: 10FIRST ELEMENTS: 1
LAST ELEMENTS: 5
PL/SQL procedure successfully completed.SQL>
SQL> DECLARE
2 TYPE V_TYPE1 IS VARRAY(3) OF NUMBER;
3TYPE V_TYPE2 IS VARRAY(2) OF V_TYPE1; 4 V1
V_TYPE1 := V_TYPE1(10, 20, 30);
4 V2 V_TYPE2 := V_TYPE2(V1);
5 BEGIN
6 DBMS_OUTPUT.PUT_LINE(’VARRAY:’);
7 FOR I IN 1..3 LOOP
9 DBMS_OUTPUT.PUT_LINE(’V1(’ | I | ’)=’ | V1(I));
10 END LOOP;
11 V2.EXTEND;
12 V2(2) := V_TYPE1(100, 200, 300);
13 DBMS_OUTPUT.PUT_LINE(’VARRAY OF VARRAY:’);
14 FOR I IN 1..2 LOOP
15 FOR J IN 1..3 LOOP
16 DBMS_OUTPUT.PUT_LINE
17 (’V2(’ | I | ’)(’ | J | ’)=’ | V2(I)(J));
18 END LOOP;
19 END LOOP;
20 END;
21 / VARRAY:
V1(1) = 10
V1(2) = 20
V1(3) = 30
VARRAY OF VARRAY:
V2(1)(1) = 10
V2(1)(2) = 20
V2(1)(3) = 30
V2(2)(1) = 100
V2(2)(2) = 200
V2(2)(3) = 300
PL/SQL procedure successfully completed.SQL>
IN A NUTSHELL . . .
● PL/SQL has composite data types, which are data types like scalar data
types. The composite data types consist of groups or collections.
● PL/SQL composite data types include records, tables, nested tables, and varrays.
310 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays
● PL/SQL records are similar in structure to rows in the database table. They
consist of components of any scalar type, PL /SQL record type, or PL/SQL
table type.
● Components in a PL/SQL record are called fields.
● A record declaration is performed in two steps. First, a record type is de-
clared. Then, a record is declared with the declared record type.
● The fields in a record are referenced with the record name as a qualifier (e.
g., ).
● A record’s fields can be assigned values using a simple assignment state-
ment with SE L E C T or FE TCH.
● A nested record is a record used as a field in another record. The record con-
taining another record is called the enclosing record.
● A PL/SQL table is another composite data type. I t is a single- dimensional
structure with a collection of elements that store the same type of values.
● A table is like an array, but a table is unbounded.
● A table declaration is performed in two steps. First, a table type is declared.
Then, a table is declared with that table type.
● A table consists of two columns, a primary key column and a data column.
The primary key is of type BI NA RY _ I NTEG ER .
● A table element is referenced by the table name with its index number
parentheses.
● There are three ways to assign values to a table’s elements: direct assign-
ment, assignment in a loop, and aggregate assignment.
● The table’s information is obtained with built- in methods, which are
PL/SQL functions and procedures. The methods are used with a table name
as a qualifier (e.g., ).
● A table of records is declared with a record type as the table’s data type. I t
can be declared with a record type as its type, with a database table and
% R OW TY PE , or with a row returned by a cursor.
● Fields in a table of records are referenced with .
● Nested tables use a column that has a table type as its data type. They are
single-dimensional, unbounded collections of elements.
● Varrays are single- dimensional, bounded collections of elements. They re-
tain their ordering and subscripts when stored and retrieved from a data-
base table.
● A varray must be initialized before referencing its elements. The E X TE N D
method is used before adding a new element to a varray.
● The COUNT, LI MIT, FIRST, and L A ST varray methods r eturn count,
upper bound, first subscript, and last subscript, respectively.
● A varray of varrays is a multilevel collection, with elements that can be ref-
erenced using two subscripts.
Lab Activity 311
E X ER C I SE Q UE STI ON S
True/F alse:
1. A database table is an example of a PL/SQL composite data type.
2. A PL/SQL record can be set to a Null value with an assignment, in which case all its fields
are set to NULL .
3. A record that contains another record as a field is called the enclosing record.
4. A PL /SQL table has a specified number of rows, which cannot be changed, at declaration
time.
5. A PL /SQL table has two columns, a primary key column and a data column.
6. A PL/SQL table’s row is referenced by the table name and a numeric index.
7. W hen a PL/SQL table is assigned to another PL /SQL table of the same type, the recipi-
ent table loses its previous rows and indexes.
8. A varray’s COU NT must be higher than its LIMIT.
9. Once declared, a varray’s size limit cannot be changed.
10. A varray must be initialized before adding an element to it.
LA B AC TI VI TY
1. Create a PL/SQL block to retrieve last name, first name, and salary from the EMPL OY EE
table into a cursor. Populate three tables with the values retrieved into the cursor: one to
store last names, one to store first names, and one to store salaries. U se a loop to retrieve
this information from the three tables, and print it to the screen using the package
DBMS_OU TPU T.PUT_LINE.
2. Declare a PL/SQL record based on the structure of the D EPT table. Use a substitution
variable to retrieve information about a specific department, and store it in the PL/SQL
record. Print the record information using DBMS_OUTPUT.PU T_LINE.
312 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays
3. U se a PL/SQL table of records to retrieve all information from the D EPT table, and
print the information to the screen. Y ou will declare a table to store names and locations
of the departments. Remember that the department number is a multiple of 10. Retrieve
all department information from the DE PT table to the PL/SQL table using a loop, and
then use another loop to print the information.
4. U se a PL/SQL cursor to retrieve all CourseId and Title information from the COU R SE
table. Create two varrays to hold CourseId and Title values, respectively. A dd elements
to both varrays, and assign values retrieved into the cursor. Display the values from both
varrays.
INTHISCHAPTER . . .
error-free program’s variables are assigned storage in the binding stage. Then, the
list of instructions, called p-code, is generated for the PL/SQL engine. P- code is
stored in the database for all named blocks.
PROCEDURES
A procedure is a named PL/SQL program block that can perform one or more
tasks. A procedure is the building block of modular programming. The general syn-
tax of a procedure is
where is a user- supplied name that follows the rules used in naming
identifiers. The parameter list has the names of parameters passed to the procedure
by the calling program as well as the information passed from the procedure to the
calling program. The local constants and variables are declared after the reserved
word I S. I f there are no local identifiers to declare, there is nothing between the re-
served words IS and BEGIN. The executable statements are written after BE G I N
and before E X C E PTI O N or END . There must be at least one executable statement
in the body. The reserved word E X C E PTI ON and the exception-handling state-
ments are optional.
Calling a Procedure
A call to the procedure is made through an executable PL/SQL statement. The pro-
cedure is called by specifying its name along with the list of parameters (if any) in
parentheses. The call statement ends with a semicolon (;). The general syntax is
For example,
monthly_salary(v_salary); calculate_net(v_monthly_salary, 0.28);
display_messages;
Procedure Header
The procedure definition that comes before the reserved word IS is called the pro-
cedure header. The procedure header contains the name of the procedure and the
parameter list with data types (if any). For example,
CREATE OR REPLACE PROCEDURE monthly_salary (v_salary_in IN
employee.Salary%TYPE)
CREATE OR REPLACE PROCEDURE calculate_net (v_monthly_salary_in IN
employee.Salary%TYPE, v_taxrate_in IN NUMBER)
CREATE OR REPLACE PROCEDURE display_messages
The procedure headers in the examples are based on the procedure calls
shown previously. The parameter list in the header contains the name of a parame-
ter along with its type. The parameter names used in the procedure header do not
have to be the same as the names used in the call. The number of parameters in the
call and in the header must match, and the parameters must be in the same order.
Procedure Body
The procedure body contains declaration, executable, and exception- handling sec-
tions. The declaration and exception-handling sections are optional. The executable
section contains action statements, and it must contain at least one.
The procedure body starts after the reserved word I S. I f there is no local dec-
laration, IS is followed by the reserved word BE GI N. The body ends with the re-
served word END . There can be more than one E ND statement in the program, so
it is a good idea to use the procedure name as the optional label after END.
Parameters
Parameters are used to pass values back and forth from the calling environment to
the Oracle server. The values passed are processed and/or returned with a procedure
execution. There are three types of parameters: IN, OUT, and I N OUT. Figure 14-1
shows the uses of these parameters.
IN Passes a value into the program; read-only type of value; it cannot be changed; default
parameter type. For example, constants, literal, and expressions can be used as IN
parameters.
OUT Passes a value back from the program; write-only type of value; cannot assign a default
value. If a program is successful, value is assigned. For example, a variable can be used
as O UT parameter.
IN OUT Passes a value in and returns a value back; value is read from and then written to. For
example, a variable can be used as a IN OU T parameter.
The parameters passed in a call statement are called the actual par ameters. The pa-
rameter names in the header of a module are called the for mal par ameter s. The ac-
tual parameters and their matching formal parameters must have the same data
types. I n a procedure call, the parameters are passed without data types. The proce-
dure header contains formal parameters with data types, but the size of the data
type is not required. Figure 14- 2 shows the relationship between actual and formal
parameters.
-- Procedure Header
PR OC ED UR E SE AR CH_EM P (EMPNO IN N UMB E R, LAST OUT VA RCHAR 2)
There are two different ways in PL/SQL to link formal and actual parameters:
For example,
EMPNO => 543
In Figure 14-3, a procedure code is shown. I f a procedure with the same name al-
ready exists, it is replaced. You can type it in any editor such as Notepad.W hen you run it,
a “Procedure created” message is displayed.The procedure named is
compiled into p-code and then stored in the database for future execution.
You can execute this procedure from the SQL * Plus environment
1SQL 7 prompt2 with the E X E C U TE command. For example,
SQL> EXECUTE dependent_info
Procedures 317
SQL> EXECUTEDEPENDENT_INFO
Dev,Derek has 2 dependents Chen, Sunny has 3 dependents
PL/SQL procedure successfully completed. SQL>
The procedure becomes invalid if the table on which it is based is deleted or al-
tered. The compiled version of the procedure is stored, and this version should be
re- compiled in case of alterations to the table(s). Y ou can recompile that procedure
with the following command:
Procedure created.
SQL>
SQL> DECLARE
2 V_LAST EMPLOYEE.LNAME%TYPE;
3 V_FIRST EMPLOYEE.FNAME%TYPE;
4 V_ID EMPLOYEE.EMPLOYEEID%TYPE := &EMP_ID;
5 BEGIN
6 SEARCH_EMP(V_ID, V_LAST, V_FIRST);
7 IFV_LAST IS NOT NULLTHEN
8 DBMS_OUTPUT.PUT_LINE(’Employee: ’||V_ID);
9 DBMS_OUTPUT.PUT_LINE(’Name: ’||V_LAST |’, ’||V_FIRST);
10 END IF;
11 END;
12 /
Enter value for emp_id: 100EmployeeId 100 does not exist
PL/SQL procedure successfully completed. SQL> /
Enter value for emp_id: 200Employee: 200
Name: Shaw, Jinku
PL/SQL procedure successfully completed. SQL>
of the employee to the calling anonymous block.The anonymous block then prints the
employee’s information.
FUNCTIONS
The R E TU R N statement does not have to be the last statement in the body of a
function. The body may contain more than one R E TU R N statement, but only one is
executed with each function call. I f you have R E TU R N statements in the excep- tion
section, you need one return for each exception.
Function Header
The function header comes before the reserved word IS. The header contains the
name of the function, the list of parameters (if any), and the R E TU R N data type.
320 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger
Function Body
The body of a function must contain at least one executable statement. I f there is no
declaration, the reserved word B E G I N follows IS. I f there is no exception handler,
you can omit the word E X CE PTI ON. The function name label next to E ND is op-
tional. There can be more than one return statement, but only one R E TU R N is ex-
ecuted in a function call.
A function can return a value with a scalar data type, such as V A RC HA R 2, NUM-
B ER , B I NA RY _I N TE G E R, or B OOL E A N. I t can also r eturn a composite or com-
plex data type, such as a PL/SQL table, a PL/SQL record, a nested table, VA RRA Y,
or LOB.
Calling a Function
A function call is similar to a procedure call. You call a function by mentioning its
name along with its parameters (if any). The parameter list is enclosed within paren-
theses. A procedure does not have an explicit R E TU R N statement, so a procedure
call can be an independent statement on a separate line. A function does return a
value, so the function call is made via an executable statement, such as an assign-
ment, selection, or output statement. For example,
v_salary :=get_salary(&emp_id); IF emp_exists(v_empid) ...
I n the first example of a function call, the function is called from an
assignment statement with the substitution variable as its actual parameter.
The function returns the employee’s salary, which is assigned to the variable
.
I n the second example, the function call to the function is made
from an I F statement. The function searches for the employee and returns a
Boolean TR U E or FAL SE to the statement.
A n anonymous block calls function of Figure 14-6 in Figure 14-7,
with an employee’s department number as a parameter. The function returns the de-
partment name back to the calling block. The calling block then prints the employ-
ee’s information along with the department name.
I n this example, the code of function is executed in SQL * Plus,
which returns a “ Function created” message if the function code has no syntactical
errors. Then, the calling anonymous block is executed, which calls the compiled
function with the par ameter of the N U MB E R type. The
function searches through the D E PT table, retrieves the corresponding department
name, and returns , which is assigned to in the anonymous
block.
Functions 321
Functioncreated.
SQL>
SQL> DECLARE
2 V_DEPTID EMPLOYEE.DEPTID%TYPE; VARCHAR2(12);
3 V_DEPT_NAME EMPLOYEE.EMPLOYEEID%TYPE := &EMP_ID;
4 V_EMPID
5 BEGIN
6 SELECTDEPTID
7 INTO V_DEPTID FROM EMPLOYEE
8 WHERE EMPLOYEEID = V_EMPID;
9 V_DEPT_NAME :=GET_DEPTNAME(V_DEPTID);
10 DBMS_OUTPUT.PUT_LINE(’Employee: ’|| V_EMPID);
11 DBMS_OUTPUT.PUT_LINE
12 (’Department Name: ’||V_DEPT_NAME);
13 EXCEPTION
14 WHEN OTHERS THEN
15 DBMS_OUTPUT.PUT_LINE(V_EMPID |’not found.’);
16 END;
17 /
SQL> DECLARE
2 V_SAL EMPLOYEE.SALARY%TYPE;
3 V_COMM EMPLOYEE.COMMISSION%TYPE;
4 V_TOTSALNUMBER(8) := 0;
5 V_TOTCOMM NUMBER(8) := 0;
6 v_TOTALNUMBER(8);
7 COUNTER NUMBER(2) :=10;
8BEGIN /* MAIN BLOCK */ 9
10
DBMS_OUTPUT.PUT_LINE(’DEPTID SALARY COMMISSION’);
11
DBMS_OUTPUT.PUT_LINE(’- --------- WHILE ----------- -------------------’);
12
COUNTER <=40LOOP
13
SELECT SUM(NVL(SALARY, 0)), SUM(NVL(COMMISSION, 0)) INTO
14
V_SAL, V_COMM FROM EMPLOYEE
15
WHERE DEPTID = COUNTER;
16
17 DBMS_OUTPUT.PUT_LINE(COUNTER |’
| TO_CHAR(V_COMM, ’$999,999’)); ’||
18 TO_CHAR(V_SAL, $
’ 999, 9 99’ ) |’
V_TOTSAL:= DO_TOTAL(V_TOTSAL, V_SAL);’
19 V_TOTCOMM := DO_TOTAL(V_TOTCOMM, V_COMM);
20 COUNTER :=COUNTER + 10;
21 END LOOP;
22 V_TOTAL:= V_TOTSAL+ V_TOTCOMM;
23 DBMS_OUTPUT.PUT_LINE(’SUBTOTAL ’ |
24 TO_CHAR(V_TOTSAL, ’$999,999’) |’ ’||
25 TO_CHAR(V_TOTCOMM, ’$999,999’));
26 DBMS_OUTPUT.PUT_LINE(’TOTAL OF SALARY AND COMMISSION: ’ |
27 TO_CHAR(V_TOTAL, ’$999,999’));
28 END; /* MAIN BLOCK */ 29 /
Functioncreated.SQL>
Figur e 14-9 This function (see Fig. 14-8) is called multiple times.
equal to 10, 20, 30, and 40. For each value of the counter, the function is
called twice, once with two salary parameters and once with two commission pa-
rameters. E ach time, adds to or to and
returns totals to and , respectively. Then, variable is used
to find the grand total of all salaries and commissions in the anonymous block. The
block then prints the total payroll for the company.
A stored function block can be called from an SQL statement, such as SELECT. For
example,
SELECT get_deptname(10) FROM dual;
This function call with parameter 10 will return the department name Finance in the
N2 example tables. Y ou can also use a substitution variable as parameter.
PACKAGES
● Cursors.
● Scalar variables.
● Composite variables.
● Constants.
● Exception names.
● TY PE declarations for records and tables.
324 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger
● Procedures.
● Functions.
Packages are modular in nature, and Oracle has many built-in packages. If you
remember, D BM S_O U TPU T is a built-in package. Y ou also know that a package
called STA ND A R D contains definitions of many operators used in Oracle. There are
many benefits to using a package.
The objects in a package can be declared as public objects, which can be refer-
enced from outside, or as private objects, which are known only to the package.Y ou can
restrict access to a package to its specification only and hide the actual programming
aspect.A package follows some rules of object-oriented programming, and it gives pro-
grammers some object-oriented capabilities. A package compiles successfully even
without a body if the specification compiles. W hen an object in the package is refer-
enced for the first time, the entire package is loaded into memory. A ll package ele-
ments are available from that point on, because the entire package stays in memory.
This one- time loading improves performance and is very useful when the functions and
procedures in it are accessed frequently. The package also follows top- down design.
Structure of a Package
A package provides an extra layer to a module. A module has a header and a body,
whereas a package has a specification and a body. A module’s header specifies the
name and the parameters, which tell us how to call that module. Similarly, the pack-
age specification tells us how to call different modules within a package.
Package Specification
A package specification does not contain any code, but it does contain information
about the elements of the package. I t contains definitions of functions and proce-
dures, declarations of global or public variables, and anything else that can be de-
clared in a PL/SQL block’s declaration section. The objects in the specification
section of a package are called public objects. The general syntax is
For example,
PACKAGE bb_team
IS total_players CONSTANT INTEGER :=12;
Packages 325
player_on_dl EXCEPTION;
FUNCTION team_average(points IN NUMBER, players IN NUMBER)
RETURN NUMBER;
END bb_team;
The package specification for the course_info package in Figure 14- 10 contains
the specification of a procedure called FI ND _TITLE and functions HA S_PR E R E Q
and F I ND _PR E R E Q. The CO U R SE _I N FO package contains three modules in all.
Package Body
A package body contains actual programming code for the modules described in
the specification section. I t also contains code for the modules not described in the
specification section. The module code in the body without a description in the spec-
ification is called a private module, or a hidden module, and it is not visible outside
the body of the package.
The general syntax of a package body is
326 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger
For example,
EXCEPTION
WHEN bb_team.player_on_dl THEN
I n Figures 14- 10 and 14-11, package specification and body, respectively, are
shown for the package. The calls to a procedure and a function in the
package are shown in Figures 14-12 and 14-13, respectively.
I n Figure 14-12, a call is made to the procedure FI ND _ TI TL E of the
CO U R SE _I NFO package in Figure 14- 11. The procedure is passed V _C OU RSE I D
as an I N parameter. I f CourseI d is invalid, the procedure throws an exception and
then handles that exception with an appropriate message. I f CourseI d is valid, the
OU T parameter V _TI TLE is assigned course title.
In Figure 14-13, a call is made to the function HA S_PRE R E Q of the COU RSE_
INFO package with one parameter, V_COURSE ID . I f course does not have a prereq-
uisite, the function displays the appropriate message. If course does not exist, an excep-
tion is thrown in the function body, and the message is displayed. The function returns
FA LSE in both cases. The function returns TR U E if the prerequisite exists. I f TR U E is
returned, another function, FI ND _PR E RE Q, is called with the V _ COU RSE I D pa-
rameter. The function returns concatenated prerequisite I D and title. Figure 14- 13
shows output from all three situations mentioned above.
You can also use the E X E C U T E command to run a package’s procedure:
Packages 327
TRIGGERS
BEFORE Triggers
1 row created.
SQL>
AFTER Triggers
Trigger created.
SQL>
1 row deleted.
In Figure 14-17, you see the workings of the A FTE R TR I GG E R of Figure 14- 16.
A row is deleted from the E MPL OY EE table, and the trigger inserts a row in the
TRA NSHI STORY table. Then, a row is updated in the E M PL OY E E table, and the
trigger inserts another row in the TRA NSHISTORY table.
INSTEAD OF Trigger
The B E F O R E and A FTE R triggers are based on database tables. From version 8i
onward, Oracle provides another type of trigger called an I NSTE A D O F trigger,
which is not based on a table but is based on a view (covered in Chapter 9). The IN-
STE A D O F trigger is a row trigger. If a view is based on a SEL E C T query that con-
tains set operators, group functions, G R OU P BY and HA V I NG clauses, DISTINCT
function, join, and/or a R OW NU M pseudocolumn, data manipulation is not possi-
ble through it.
A n I NSTE A D OF trigger is used to modify a table that cannot be modified
through a view. This trigger fires “instead of” triggering D M L statements, such as
D E L E TE , U PD A TE , or INSERT.
I n Figure 14- 18, a complex view is created with a SE L EC T query and an outer
join. FacultyI d 235, 333, and 444 are not used in the STU D E NT table; in other
words, there is no “child” row in STU D E N T table for those faculty members. Facul-
tyI d 235 and 333 are not used in the C R SSE CTI ON table either. The D E L E TE
statement to delete Faculty I d 235 in Figure 14- 18 returned an error message. W e
will accomplish deletion of row by creating an I N STE A D O F trigger.
SQL> DELETE FROM student_faculty WHERE FacultyId = 235; DELETE FROM student_faculty
WHERE FacultyId = 235
* ERROR at line 1:
ORA-01752: cannot delete from view without exactly one key-preserved table
SQL>
Trigger created.
SQL> DELETE FROM student_faculty WHERE FacultyId = 235; 1 row deleted.
SQL>
member is deleted without any error message. Notice the use of pseudorow called
:O LD in this trigger, which gets the value of FacultyI d 235 from the D E L E TE state-
ment that the user had issued.
DATA DICTIONARYVIEWS
Oracle maintains a very informative D ata D ictionary. A few D ata D ictionary views are
useful for getting information about stored PL/SQL blocks. The following are exam-
ples of queries to U SER _PRO CE D U RE S (for named blocks), U SE R _TR I GGE RS
(for triggers only), U SER _SO U RC E (for all source codes), U SER_OBJECTS(for any
object), and U SE R _E R R O RS (for current errors) views:
These views can provide information ranging from the name of an object to the en-
tire source code. U se the D E SC R I B E command to find out the names of columns in
each D ata D ictionary view, and issue SE L EC T queries according to the information
desired.
In a Nutshell .. . 335
IN A NUTSHELL . . .
● A procedure is a named PL/SQL module that can perform one or more tasks.
● A procedure call contains the name of the procedure along with the list of
parameters enclosed within parentheses.
● A procedure body, like an anonymous block, consists of declaration, exe-
cutable, and exception sections.
● There are three types of parameters: The I N type passes a value into a sub-
program, the OU T type passes a value to the calling program, and the IN
OU T type passes a value into a subprogram and returns a value.
● The formal parameters in a module’s header must match the actual parame-
ters in the call to the module, with positional or named notation.
● A function is a PL/SQL named module that always returns a value to the
calling program.
● A function can return a scalar data type, such as V A R CH A R2, NU M B ER ,
BI N A R Y _I NTE GE R , and BO OL E A N , or a complex or composite data
type, such as a table, a record, a nested table, V ARRA Y , or LOB.
● A function call is made via an executable PL/SQL statement, such as an as-
signment or an I F statement.
● A function or a procedure is stored in memory by executing it first. I t is then
called by another module.
● A package is a collection of PL/SQL objects, which are either public (can be
called by an outside module) or private (known only to the package module).
● The structure of a package includes a specification and a body. The members in
a package are referenced with the package name as a qualifier and dot
notation.
● A database trigger, or simply a trigger, is stored in the database and is called
implicitly when a triggering event occurs.
● A trigger is based on a D M L statement, such as INSERT, D E L E TE , or
U PD A TE .
● A B E FO R E trigger is fired before execution of a D M L statement, and an
A F TE R trigger is fired after execution of a D M L statement.
● A row trigger is fired once for each affected row, whereas a statement trig-
ger is fired only once, irrespective of the number of rows affected by the
D M L statement.
● A n I NSTE A D O F trigger is based on a view instead of a database table.
● Oracle provides the user with many D ata Dictionary views for named blocks,
such as U SE R _PR OC E D U RE S, U SE R _TRI GGE R S, U SE R _SOU R CE ,
USER_OBJECTS, and U SE R_ ER RO RS.
336 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger
EXERCISE QU ESTIONS
True/F alse:
1. A parameter of type IN passes a read-only value to a module.
2. A parameter of type O U T is assigned a value only if the called module is performed
successfully.
3. If a procedure has an IN parameter, it must have an O U T parameter.
4. A function always has an O U T parameter to return a value.
5. V _EM PNA ME IN V ARCHAR2(25) is a valid formal parameter definition in the head-
er of a module.
6. A procedure does not require a R ET U R N type, but a function does.
7. Control of execution shifts from a function to the calling program with the R ETU R N
statement.
8. All public procedures and functions in a package body must be declared in the package
specification.
9. A trigger is fired either before or after a triggering event.
10. A trigger based on a SEL ECT statement always fires automatically after the statement’s
execution.
LAB ACTIVITY
1. W rite a procedure that is passed a student’s identification number and returns the stu-
dent’s full name and phone number from the STU DENT table to the calling program.
Also, write an anonymous block with the procedure call.
2. W rite a function, and pass a department number to it. If the D EPT table does not con-
tain that department number, return a FALSE value; otherwise, return a TR U E value.
Print the appropriate message in the calling program based on the result.
3. W rite a package that contains a procedure and a function. The procedure is passed a
room number. If the room number exists, the procedure gets the capacity of the room
Lab Activity 337
and the building name from the L OCATI ON table. If the room number does not exist,
the procedure performs the appropriate exception-handling routine. The function is
passed a and returns the maximum number of seats available in the course section.
4. Write a trigger that is fired before the DM L statement’s execution on the EM PL OY EE
table. The trigger checks the day based on SYSDATE. If the day is Sunday, the trigger
does not allow the DML statement’s execution and raises an exception. Write the appro-
priate message in the exception-handling section.
5. Write a trigger that is fired after an INSERT statement is executed for the STU DENT
table. The trigger writes the new student’s ID, users name, and system date in a table
called TRACKING. ( Y ou must create the TR ACK I NG table first.)
6. Create a complex view EMP_D EP_ V I EW using an outer join between the EMPLOY-
EE and D EPEN DE NT tables with employee names and dependent birthdates and rela-
tions. The outer join will also return employees without any dependents. Now, create an
IN STEA D OF trigger based on EMP_D EP_ V I EW to enable you to delete employee
433 through view.
PART
MI SCELL4AN EOUS
TOPICS
INTHISCHAPTER . . .
The Java language was developed by James Gosling for Sun Microsystems. The lan-
guage was intended for the consumer electronics market but later became a general-
purpose business language and a language for W eb- based I nternet programs. Java is
a portable programming language with a broad set of predefined classes and meth-
ods that handle most of the fundamental requirements of a programmer. Some of the
features of Java include platform independence, object orientation, multithreading,
security, and the ability to connect to various database servers. With Java, you can cre-
ate stand- alone applications, applets, servlets, Java Server Pages (JSPs), and Enter-
prise Java Beans. D atabase connectivity is a very important ingredient for
server- side programming. I f you know C/C++ language, the syntax of Java is very
similar— but the similarity ends there! I have found my experience with Java to be
very positive and interesting. W hether you use the command- line Java Development
Kit (JD K ) or a GU I - based I ntegrated D evelopment Environment (I D E ), working
with Java is fun. I n this chapter, Java code is created with JBuilder8, an I D E from Bor-
land Corporation. Oracle Corporation markets a similar product called JDeveloper,
which was originally licensed from Borland Corporation.
JDBC
Java contains a rich library of classes with which to send SQL statements to the data-
base server, such as Oracle Server, for data retrieval or manipulation. Sun Microsys-
tems provides JD BC drivers with Java. Many database vendors (Oracle, Microsoft,
Sybase, and others) and some third-party vendors provide JD BC drivers, which im-
plement JD BC A PI for various database engines. The Java applications with JD B C
are portable and are independent of the database server.
The JD BC –O D B C Bridge allows applications written in the Java program-
ming language to use the JD B C A PI with many existing OD B C drivers. The Bridge
is itself a driver based on JD B C technology ( “ JD B C driver”) that is defined in the
class sun.jdbc.odbc.JdbcOdbcD river. The Bridge defines the JD B C subprotocol of
OD B C . I n this chapter, two examples of JD BC applications are given, one with
340 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
I n Java, all classes from the package are readily available. A ll other pack-
ages and their classes must be imported to make them available to the program. For
example, to import the class from the package, you would
issue the following statement:
import javax.swing.JOptionPane;
To import the entire package and all its classes, you would type
import java.sql.*;
A Java program may load many JD B C drivers to connect with different database
servers. The syntax for loading a JD B C driver is
For example,
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
or
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection conn =
DriverManager.getConnection(“jdbc:odbc:shah_ora”, userName, passWord);
where url is suited for Oracle’s oracle.jdbc.driver.OracleD river and it contains driv-
er type , server name , default port number , and database sid
. The username and password are hard coded, however, which you might not
want to do. The hard- coded fictitious password ‘india_usa’ is used in this chapter’s
examples, but it is just an example. The server name in this example
is the name of the local machine, where Oracle9i resides. I f you want to connect to
the Oracle server from your PC, you will need the server name as well as the domain
name. For example, if the server name is at domain , you
will use
When getConnection( ) method is called with a url, DriverManager locates a
suitable driver. If it does not find a suitable driver, it throws an exception. If it does
find a suitable driver, the Connection object (referenced by ) is returned, and a
connection is established. The interaction with the database is possible through this
connection object. O ne Java application may have multiple connections with the
same database, and it may have connections with different databases.
The Connection object is used to interact with the database using SQL state-
ments. There are three classes for sending SQL statements to the server:
Statement Class. This class is used for SQL statements without parame- ters.,
such as SELE CT, I NSERT, D E L E TE , U PD A TE , or C R E A TE TABLE . First,
342 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
int = stmt.executeUpdate( );
You can also use conn.commit( ), conn.setA utoCommit 1true ƒfalse2, and
conn.rollback( ) methods after using D ata Manipulation L anguage (D M L ) statements
with stmt.executeU pdate( ). These methods have same effect that you have seen with
CO MMI T, SE T A U TOC OM MI T O N ƒOFF, and R OLL BA C K statements in SQL .
where ResultSet class object contains data retrieved by the SELECT- query. The
rows in the data are retrieved in sequence, and the columns in each row are posi-
tioned. The pointer is positioned before the first row of data. W ith every call to the
next( ) method, the pointer moves to the next row. The ResultSet class contains a
few useful methods:
This class provides the user with many methods to get metadata information.
For example,
A fter pstmt is built with set ( ) methods, the executeU pdate( ) method is used
to execute the SQL statement.
CallableStatement cstmt =
conn.prepareCall(“{? =call do_total(?, ?)}”); // function call cstmt.registerOutParameter(1,
Types.NUMBER); // OUT parameter cstmt.setInt(2, v_sal); // IN parameter
cstmt.setInt(3,v_comm); // IN parameter cstmt.execute( );
344 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
Closing Connection
The JD BC session ends with closing the database connection. Before disconnecting
from the database, the stmt.close( ) method is used to close the ResultSet generated
by that statement. A t last, the conn.close( ) method is used to close the connection
and release the JD B C resources.
database is highlighted in the figure by default, but you are going to use a different
driver, which is not listed in Figure 15-1.
Second, click on the A dd button to bring up the Create New D ata Source dialog
box (see Fig. 15-2).
Third, select the Oracle in OraHome92 driver, and click on the Finish button
to bring up the Oracle OD B C D river Configuration dialog window. Type the values
for D ata Source Name, Description, TNS Service Name, and U ser I D as shown in
Figure 15- 3. Click on the Test Connection button to log in with a password, and test
the connection to the Oracle database. If the connection is successful, click on OK.
Your data source is created as shown in Figure 15-4. This data source name is
used later in the Java program for connectivity.
Figure 15-5 shows code for database connectivity to the Oracle database with Sun
Microsystem’s JD B C driver. The program loads then driver, then prompts the user
for a usename and password. The connection is established with url, username, and
password. The url includes the data source created in the previous section. The rows
are retrieved from the PH O NE table with the executeQuery( ) method. The rows
346 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
package oracle; import java.sql.*; import java.io.*; import javax.swing.*; public class
Connect {
public static void main(String[]args) throws SQLException, IOException{
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch (ClassNotFoundException e) { System.out.println(“Could not load driver”);
}
String userName, passWord;
userName = JOptionPane.showInputDialog(“Oracle username: “).trim(); passWord =
JOptionPane.showInputDialog(“Oracle password: “).trim();
Connection conn = DriverManager.getConnection(“jdbc:odbc:shah_ora”, userName,
passWord);
Statement stmt =conn.createStatement();
ResultSet rset = stmt.executeQuery
(“SELECT LAST, FIRST,PHONE, RELATION FROM PHONE”);
while (rset.next()) { System.out.println(rset.getString(1)+”\t”+rset.getString(2)+
“\t”+rset.getString(3)+”\t”+rset.getString(4));
}
stmt.close();
conn.close();
}
}
are read from the result set with the next( ) method and subsequently displayed
within the while loop.
Figure 15-6 shows rows from the PHO N E table with an SQL query. Figure 15-7
shows rows from the same table with an embedded SQL statement in the Java program
of Figure 15- 5.
SQL>
1. A fter successful installation of Oracle8i or 9i, find the home directory (folder)
for OR A CL E _H OME . I t will be C:\ORACL E\ORA 81 for Oracle8i and
OracleDriver and Oracle Driver 349
5. If you are using command- line Java, set the following classpath to use
OracleD river from the CLA SSES12.ZIP file:
C:\jbuilder8\jdk1.4\lib\classes12.zip\oracle\jdbc\driver\
6. Now, follow the steps given below to add a new library (if you did not copy
the CLA SSES12.ZI P file in the default library directory):
● G o to the Proj ects menu, and select Pr oject Pr oper ties. Click on
● the Requir ed Libr ar y tab.
● Click on the A dd button. Click on the New button.
● Change the name text- box value to shahLib (or any other name).
● Click on the A dd button.
● Click on the OK button.
●
Select the path where the CLA SSE S12.ZIP file is saved.
●
350 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
● Click on the OK button (you will see a new library path). Click on the
● O K button.
● Click on the OK button (you will see shahLib in the required library
listing).
The versions of the products mentioned in this section— Oracle9i, JBuilder8
and JDK 1.4— can be downloaded for free from Oracle.com, Borland.com, and
Sun.com, respectively, for personal use or educational purposes only. Software com-
panies introduce new software releases frequently. When you follow the instructions
given here, substitute folder or directory names acoording to the software version
installed on your system. ( : Y ou must add the OracleD river and library to each
project in JBuilder as given in Steps 5 and 6. You need not create the library again.)
Figure 15-8 shows Java code (similar to that in Figure 15-5) for database connectivity
with the Oracle database with Oracle’s JD B C driver. The program loads the driver,
then establishes a connection with the url and hard- coded username and password.
The url contains the Oracle driver. The rows are retrieved from the PH O NE
table with the executeQuery( ) method. The rows are read from the result set and
are subsequently displayed.
I n the following example, a Java applet is created with some of the classes described in
previous sections. The applet connects to a database to perform INSERT, SELECT,
and a search based on last name.
I n Figure 15- 9, LastNameSearch is used with a last name entered in a JTextField
object. The result is displayed in the jTextA rea object. The interface uses four
JTextField objects for inputting Last, First, Phone, and Relation values.A JTextField ob-
ject is used for entering the username, and a JPasswordField object is used for entering
A good knowledge of Java language and swing components is essential to understand this code.
352 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
the password for connecting to Oracle9i. These two objects are given value through
the property, and they are disabled to prevent any changes to these values. Every
connection to the database uses these values for username and password. There are
four JButton objects. The A ddRow button gets inputs from four text boxes and adds a
new row to the PHO NE table. I f any one of the four boxes is left blank, an error pops
up, and the insert operation is not performed. The LastNameSearch button gets the
last name input and searches through the table for matching rows. It displays matching
rows in the JTextA rea object. If the last name field is left blank or no matching rows
are found, an appropriate message is displayed in the JTextA rea object. The Clear-
TextOnly button clears the four JTextField objects. Finally, the D isplayPhoneList but-
ton is used to display the entire PHO NE table. The username and password can be
hard-coded in the url, or the user can be asked to input values for the same. The input
portion is present in the source given below, but it is commented out:
package dataapplet; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*;
import java.sql.*;
import java.io.*;
public class AppletData extends Applet { private boolean isStandalone = false; JTextFieldjTextField1= new
JTextField();JTextField jTextField2 = new JTextField(); JTextField jTextField3 = new JTextField();JTextField
jTextField4 = new JTextField();JButton jButton1= new JButton(); JLabel jLabel1= new JLabel();
JLabel jLabel2 = new JLabel(); JLabel jLabel3 = new JLabel(); JLabel jLabel4 = new JLabel(); JButton jButton2
=new JButton(); JButtonjButton3 =new JButton(); JLabel jLabel5 =new JLabel();
JTextArea jTextArea1 = new JTextArea(); JButton jButton4 = new JButton(); JButton jButton5 = newJButton();
JPasswordField jPasswordField1 = new JPasswordField(); JTextFieldjTextField5= new JTextField();
JLabel jLabel6 = newJLabel(); JLabel jLabel7= new JLabel();
//Get a parameter value
public String getParameter(String key,String def) { return isStandalone ? System.getProperty(key, def) :
(getParameter(key) !=null ?getParameter(key) : def);
}
Java Applet: Putting it all Together 353
pstmt.setString(3, three);
pstmt.setString(4, four);
pstmt.executeUpdate(); // INSERT executed
}
conn.commit(); // commits insert operationpstmt.close();
conn.close();
}
/*** ** *** *** *** *** CLEARS ALL TEXT FIELDS * **** ***** **** ***/ void
jButton2_actionPerformed(ActionEvent e) {
jTextField1.setText(“”); jTextField2.setText(“”); jTextField3.setText(“”); jTextField4.setText(“”
);
}
/*** ** *** *** *** *** ** * DISPLAYS ALL ROWS ** **** ***** **** ****/ void
jButton3_actionPerformed(ActionEvent e) throws SQLException{
jTextArea1.setText(“”);try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch (ClassNotFoundException ex) { System.out.println(“Could not load driver”
);
}
Connectionconn=DriverManager.getConnection(“jdbc:odbc:shah_ora”,
jTextField5.getText(), jPassordField1.getText());
Statement stmt = conn.createStatement(); ResultSet rset =stmt.executeQuery
(“SELECT Last, First,Phone, relation
Connection conn =
DriverManager.getConnection(“jdbc:odbc:shah_ora”, jTextField5.getText(),
jPasswordField1.getText());
Statement stmt =conn.createStatement();
String l = jTextField1.getText().trim().toUpperCase(); String query =
“SELECTLast, first, Phone, Relation “+ “FROM phone WHERE Upper(Last)= ’”+ l + “’”;
ResultSet rset = stmt.executeQuery(query); String s=””;
while (rset.next()) { s+=(rset.getString(1)+”\t\t”+rset.getString(2)+“\t”+rset.getString(3)+”\t”
+rset.getString(4)+”\n”);
}
if (s.equals(“”)) jTextArea1.setText
(“Last name field is left blank\nOR\ndoes not exist in table”); else
jTextArea1.setText(s); stmt.close();
conn.close();
}
}
class AppletData_jButton1_actionAdapter implements java.awt.event.ActionListener
{
AppletData adaptee;
AppletData_jButton1_actionAdapter(AppletData adaptee) throws Exception{ this.adaptee =
adaptee;
}
public void actionPerformed(ActionEvent e) { try{
adaptee.jButton1_actionPerformed(e);
}
catch(Exceptionex){ System.out.println(“Error”);
}
}
}
class AppletData_jButton2_actionAdapter implements java.awt.event.ActionListener
{
AppletData_jButton2_actionAdapter(AppletDataadaptee) { this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) { adaptee.jButton2_actionPerformed(e);
}
}
358 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
SQLj
HOSTVARIABLES
SQLj ITERATORS
When an SQL query returns more than one row in a Java program, an SQLj iterator
is used. A n iterator is similar to a JD B C result set, but columns are given data types
in the former. A n iterator is based on cursor in the SQL query. SQLj constructs an
class for iterator declaration. The instance variables and methods from the
iterator class are available in the program. There are two types iterator declarations:
Named Iterator
Iterator contains three columns with their data type. SQLj creates a class with the
same name, D eptI ter. Then, a null reference named to DeptIter class is declared,
362 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj
The next( ) method of the D eptI ter class is used to retrieve one row from the
iterator. SQLj also creates get or accessor methods with the same name as the col-
umn names to get the values of columns, such as i( ), n( ) and l( ):
while (di.next( )) {
System.out.println(di.i()+”\t”+di.n()+”\t\t”+di.l());
}
Finally, the iterator is closed with the close( ) method after it has been processed:
di.close( );
SQLj Iterators 363
Positional Iterator
A positional iterator is similar to a named iterator, but it is declared with data types
that positionally match the data types of columns retrieved with the SE L E C T query.
The general syntax of declaration is
For example, the positional iter ator is declared only with data types in
Figure 15-12 as follows:
#sql iterator DeptIter(int, String,String);
The iterator is instantiated and populated with an SQL query as given in the
following statements:
DeptIter di =null;
#sql di ={SELECT deptid, deptname, location FROM dept};
There is no need to use column aliases with an SQL query, because a fetch
statement is used to retrieve columns into host variables declared as Java variables
with appropriate data types:
int i=0;
String n=null;
String loc=null;
#sql {fetch :di into:i, :n,:loc};
The endFetch( ) method checks for row fetched, and while there is no end of
fetch, more rows are fetched in the loop with each iteration:
while (!di.endFetch()) {
System.out.println(i+”\t”+n+”\t\t”+loc); #sql {fetch:di into :i,:n,:loc};
}
di.close( );
SQLj is basically used for static SQL statements, but it is possible to use dynamic
SQL with SQLj through JD BC. A n SQLj program may contain SQLj as well as
JD B C code. JD BC’s result set and SQLj’s iterators can be assigned to each other.
PL/SQLFROM SQLj
SQLj can embed SQL statements with #sql. SQLj can also embed an entire anony-
mous block with #sql. SQLj can call PL/SQL stored procedures and functions as well.
The general syntax of anonymous block in SQLj is
I n Figure 15-13, two calls are made to PL/SQL named blocks, one to proce-
dure F I ND _ TI TL E in package CO U R SE _ I N FO and one to function FI ND _ PRE -
R E Q in the same package. I f a PL/SQL block already exists, there is no need to
reinvent the wheel in Java! The named blocks are passed I N, OU T, and I N OU T pa-
rameters in the same way that PL/SQL uses them. The procedure is passed course
I D as an I N parameter and title as an OU T parameter. The function is passed
course I D as an I N parameter, and it returns the prerequisite of the course.
IN A NUTSHELL . . .
True/F alse:
1. Java is a language for W eb-based Internet programming.
2. To connect to the Oracle database with Java, you can only use the JDB C driver provided
by Sun Microsystems.
3. Java establishes a connection with the Oracle driver, then loads the JDB C driver.
4. W hen a SEL ECT-query is executed with executeQuery( ) method, data are retrieved
into a ResultSet object.
5. ResultSetMetaData class is used to get metadata information about a ResultSet object.
6. PreparedStatement class allows execution of SQL statements with parameters.
Lab Activity 367
LAB ACTIVITY
1. Create a JD BC project with an Oracle data source to retrieve and display rows from the
CO U R SE table.
2. Create a JDB C project to add a new employee in the EM PL O Y EE table. Pass parameters
to your SQL statement.
3. Create a JD BC project to call the procedure created in lab activity 1 of Chapter 14.
4. Create an SQL j project to retrieve student name and faculty name from the STU DENT
and FACU LTY tables, respectively. U se host variables declared in a Java program, and
display the retrieved rows (iterator problem).
5. Create an SQL j project to call the function created in lab activity 2 of Chapter 14.
INTHISCHAPTER . . .
Oracle is a very complex product, and its capabilities are increasing with every new
release of the software. The D atabase A dministrator (D B A ) is the most critical po-
sition in the daily operations of the database environment. The successful imple-
mentation of a database depends on the D BA .
database tuning, troubleshooting, data security, and backup and recovery. Some of
the duties performed by the D B A are:
● Install and upgrade Oracle and its tools.
● Configure the Oracle instance.
● Create a database.
● Create, alter, and remove database users and roles.
● Gr ant and restrict access rights.
● A llocate and manage physical and logical storage structures.
● D evelop security strategies.
● D evelop backup and recovery procedures.
● Monitor system performance.
● A nalyze database performance, and implement solutions to problems.
● Communicate with Oracle support service personnel.
● Troubleshoot locking problems.
I n short, the D B A is the most trusted user in the database environment. The
D BA must possess a thorough knowledge of the operating system on which Oracle is
installed, hardware specifications needed for the server and the clients, memory
structures and Oracle processes, PL/SQL modules and their behavior in the system,
client–server architecture, and networking- related issues.
Database
Buffer Cache R edo Log Buffer Shared Pool
SGA
User Offline
Process Redo Log Filel Storage
Redo Log File2
Rollback
Data Segment Control
Segment Files
the buffer is one- third full, or a 3- second timeout occurs. A R C H archives redo log
files to offline or online storage files. CKPT maintains checkpoints.
In Figure 16- 2, D ata D ictionary view V $BGPROCESS lists process address,
process name, and description. Another column named E R R O R can also be displayed
to show error information.This statement was the first statement executed on a startup
of a new user session, and it returned 69 background processes. The processes are listed
in order of their startup, and their order is
PMON DBWR ARCH LGWR SMON
69 rows selected.
SQL>
The Oracle database consists of data files, at least two online redo log files, and
at least two control files. D ata files contain data physically stored on the disk under
an operating system’s directory structure. The Oracle instance is the System Global
A r ea (SG A ) memory and the background (shadow) processes. E ach SGA is exclu-
sively used by an instance. W hen an instance starts, memory is allocated for an SGA ,
and memory is deallocated when the instance shuts down. The Oracle Enterprise
Manager ( OE M) starts the instance. The database is mounted on the instance and
is then opened. The users connect to the instance to access the database. The data-
base is mounted on a single instance in most cases, except for the Oracle Parallel
Server (OPS) environment, where a database can be mounted on many instances.
372 Chap. 16 Oracle9i: Architecture and Administration
Per for mance can be measured in terms of time taken in the execution of a
complex query, number of users online concurrently, or time taken by a batch job.
The performance depends on the amount of memory, disk space, CPU , bus speed,
and network speed. A ll database packages are input/output (I /O) bound. The speed
of I /O affects the performance of such a system. The available resources must be
configured properly for optimum performance.
The database must be readily available to the users at all times. Safety meas-
ures are considered at the planning phase, configuration phase, and implementation
phase for the availability issue. The three configurations are replication, hot standby
database, and parallel server. The r eplication method uses separate databases by du-
plicating the entire implementation of the database on multiple computer systems,
where all updates are performed on all database implementations. The operations
can still continue if one of the databases crashes. The hot standby database method
uses only one database at a time. The other standby copy is in recover mode at all
times. The redo log files are used to recover the standby copy. If the primary copy
fails, the standby copy is recovered completely and is then brought up as the pri-
mary database. I n an Oracle par allel ser ver configuration, multiple computer sys-
tems are used with parallel processing capability to share a common database. I n the
event of a computer system failure, the operations still continue as long as the
shared database is available.
Even with an implementation having redundant hardware and a redundant
database, you still need a good backup mechanism. Oracle has utilities to perform
the logical backup or physical backup at the data level. The logical backup utility
expor t, or EX P, copies all SQL statements to recreate all database objects and to in-
sert data as well. The export can be at the database, schema, table, or user level. The
backed-up data with E X P can be recovered on different platforms with different
operating systems and different versions of Oracle. The backup format with E X P is
proprietary to Oracle. The impor t, or I M P, utility copies the logical backup of data
back to the database. A cold backup is performed on a database when it is down, or
“cold.” W hen a database is running in archive log mode, Oracle saves the redo log
into ar chive log files. These files can be used to reconstruct transactions after the last
backup. The database can also be backed up while it is running, or “hot”; such a
backup is called a hot back up. The archive log files can be used with cold as well as
hot backups. The recovery manager (R M A N ) manages cold backup, hot backup,
and the archive log files. The R MA N also enables you to perform incremental hot
backups, but it does not support export. Many third- party tools are available for
backup and recovery of a database.
The connections to Oracle databases are through services, which are processes
on an Oracle server or host. The service name is also known as a database alias,
which refers to an instance on a host. The relation between a service and an instance
is stored in a file called TNSNAM E S.O RA , which is in Oracle home’s folder
in the Windows environment. I f there is a change to TNSNA ME S.ORA , the change
has to be Enterprise-wide. The changes to TN SNA M E S.ORA are a problem during
the implementation. Oracle solves this problem with an Or acle Names ser ver , which
374 Chap. 16 Oracle9i: Architecture and Administration
INSTALLATION
Oracle9i installer software is called U niver sal I nstaller . The installer looks different
based on the platform for which it is bought. The installer is available for character
mode, Windows mode, or Motif mode. I n spite of the different look, the installer per-
forms the same task on all platforms using the following steps:
You have to select components based on your installation needs and licenses
bought from Oracle Corporation. If an installer installs a component you don’t
need, you can remove it with the installer. I f you select a component that is de-
pendent on another component, the installer automatically selects it the other
component. Many decisions ar e made before the installation process. You decide to
create or not to create a starter database; select a “ home” location for the Oracle
software; plan the directory structure for the Oracle data files; define the database
block size; specify the number, size, and location of log files; and specify the maxi-
mum number of data files allowed. ( If you are installing
downloaded trial version of Oracle, use default values wherever possible to avoid
any future problems.)
When the installer creates a starter database, the SY STEM and U SE RS table-
spaces are not allocated enough space, and the block size is very small. The block
size for a database cannot be changed. Y ou should find out the block size used by
the operating system and the hardware, and then select a block size that is a multiple
of that value. The block size should not be larger than the amount of data your op-
erating system can transfer in a single operation. Y ou should select a small block
size for a transaction-based system, which has queries involving single rows. For a
large system with bulk data retrievals and transfers, you should select a large block
Connecting to The Oracle9i Database 375
size. The block size is specified in the I NI T.O RA file with the D B _BL OC K _SI ZE
parameter.
Oracle Enterprise version has OE M bundled with it. OEM’s Console is a Win-
dows-based tool to administer Oracle resources. A D B A can connect to the Enter-
prise Manager with normal, SYSOPER, or SY SD BA privileges. The console allows
the D B A to create, start, or shut down databases; create, monitor, or lock users; cre-
ate and manage tablespaces; or execute SQL statements. Y ou can run O E M Console in
a W indows environment by using
From SQL* Plus or SQL* Plus Worksheet, you can use the following command:
CONNECT AS SYSDBA
Figure 16-4 is the login screen for connecting to OE M . The login screen pops
up when you select database from the OE M screen. Oracle creates two default users
with D B A privileges on installation, SYS and SY STEM. SY S owns Oracle’s D ata
Dictionary tables and views. SY STEM owns tables required for Oracle’s develop-
ment tools. Before version 9i, Oracle provided default passwords for SY S and SYS-
TE M accounts. I n version 9i, however, you have the ability to provide a password at
installation time. The D B A needs to connect as SYSDBA or SY SOPE R to start and
shut down databases. I n addition, the SY SD BA privilege gives full access to all data-
base objects.
When an instance shuts down, the database is closed and dismounted. The
general syntax for shutdown is
where the NO R M A L option shuts down after all users are logged out and all trans-
actions are committed or rolled back, the I MM E D I A TE option disconnects all
users and rolls back all transactions, the TR A N SA C TI ONA L option finishes all
transactions and disallows new transactions, and the A B OR T option is like a system
failure that requires recovery.
You can use D ata Dictionary views , and to
get information about user/processes, databases, and instances, respectively.
Tablespace is a logical unit of storage, which consists of physical files under an operat-
ing system. It may be made up of more than one file, and each file could be physically
located on a separate disk. A tablespace can be online or offline. It can be U ND O
(Oracle9i onward), PE RMA NENT, or TEMPORARY . A user with the D BA role or
with the CR E A TE TA BL ESPACE system privilege may create a tablespace.
Figure 16-6 illustrates use of Oracle Storage Manager in creating a new table-
space, CIS_D ATA .ora, for students in a course and its actual location on the Oracle
server. The default tablespaces are allocated inadequate space, so the tablespace
created in this figure was allocated 100 MB. The SHOW SQL button shows the gen-
erated SQL code. Figure 16- 7 shows successful creation of tablespace.
You can create a tablespace and specify the operating system file that makes
up the tablespace with a C R E A TE TA BLESPA CE statement at the command
prompt using the following general syntax:
Storage manager can be used for altering a tablespace or datafile also. Y ou can
see information about all tablespaces by using USER_TABLESPA CES data dic-
tionary view (see Fig. 16-8).
The security of a database is a very important issue for the D BA . D atabase security
prevents unauthorized access and use of objects.
The D B A assigns a unique user I D to each authorized user. The general syntax
to create a user is
You must define the quota in K or M to enable user to create tables and indexes. If
a profile is not specified, the D EF A U L T profile is used.
You can create a user with OE M’s Security M anager tool, as shown in
Figure 16- 9. I n the O E M Console, expand the Security tree by clicking on +. Y ou
will see U sers, Roles, and Profiles folders under Security. Right-click on the U sers
folder to get a pop- up menu. Then, you will select Cr eate Á from the menu to
get the screen shown in Figure 16- 9. U ser creation involves Name, Profile, Au-
thentication, Password, Confirm Password, D efault Tablespace, and Temporary
Tablespace entries. Y ou can lock a user’s account and expire a user’s password
from the same screen. If you click on the Show SQL button, you will see the SQL
code generated by your entri es in user creation screen.
If a user account is locked, the user cannot log in. The locked user gets the fol-
lowing message from the Oracle server:
ERROR:
ORA-28000: the account is locked
Once a user is created, you can use that user as a template and create another
user based on the first user. Y ou need to supply a new username and password only,
382 Chap. 16 Oracle9i: Architecture and Administration
because the new user inherits the profile, tablespaces, and system privileges from the
template user. Figure 16-10 shows the process of creating a user based on another
user. Right- click on a username to be used as a template, and select Create Like Á
A user can be removed with the following statement:
Working with Oracle Enterprise Manager (OEM) 383
where the C A SC A D E option removes all objects owned by the user and also re-
moves foreign key constraints.
The Oracle database and initialization files of various components create the
initial users at the time of installation. These users have different levels of privileges
and are granted different roles. Some of the initial users are:
● SYS— This user is granted the D B A role and owns the D ata D ictionary. The
SYS user is granted all roles.
● SYSTE M— This user can manage the database and can also manage pack-
ages and tables for additional features within the database. The SYSTEM
user is also granted the D BA role.
● SCOTT— This user has only the CO NN E CT and R E SO U R C E roles. The
SCOTT user is a user with the basic end-user privileges.
The other initial users are RMAN, CTXSYS, ORDSYS, MD SY S, and DBSN-
MP. Because the SYS and SY STEM users are granted the D BA roles, they inherit all
system privileges through the D B A role. The users CTXSYS and MD SY S are also
granted all system privileges, but not through the D B A role.
Roles are the same as groups in operating system terminology. Oracle uses
roles to grant system and object privileges to users. A D B A or anyone with the
384 Chap. 16 Oracle9i: Architecture and Administration
CR E A TE R O L E privilege can create a role. The role is granted system and object
privileges. The role is then granted to a user by the D B A or anyone with the
G R A N T A NY R O L E system privilege. There are approximately 30 Oracle roles. A
user is granted roles according to the need and level of use. W hen you grant a role to
a user, the user inherits all privileges from the role. A user needs at least the C ON-
N E CT and R E SOU R C E roles to create a table in the allocated tablespace. Most
end users and students are granted these two roles to work with their own objects.
Figure 16-11 shows the creation of a role called U SE R with two basic roles,
C ON NE C T and R E SO U RC E . Y ou can grant the U SE R role to a user called STU-
DE NT, and the user STU D E NT will get the same C O NNE C T and R E SOU R CE
roles through role U SE R .
You will follow the same procedure to create a new role in Console. First,
right-click on the Roles folder, and then select Create Á from the pop- up menu. In
the General tab (as shown in Fig. 16- 11), role and authentication are entered. I n the
Role tab, various roles are granted to the newly created role. Once a role is created,
a “Role created successfully” message is displayed.
Some default roles in the database also allow the user to take certain actions.
When a new database is created with the C R E A TE DA TA BASE command, six de-
fault roles are automatically created. The D B A can run different scripts and create
more roles. The six default roles are:
1. CO NNE C T: A user with this role can connect to the database and create
any object other than a segment.
2. RE SOU RC E : This role is an extension to the CO NN E CT role. A user
with this role can create types, procedures, triggers, and snapshots.
3. DBA : This role has all system privileges except for U NL I M I TE D
TA BL ESPACE, because that is not granted to a role.
4. DE L E TE _CA TAL O G_RO L E: This role, which allows deletion of any
object owned by SYS, is granted to the D B A and the SYS schema explicitly.
5. E XE C U TE _C ATA L OG_R OL E : This role, which allows execution of any
object owned by SY S, is granted to the D BA , SY S schema,
E X P_FU L L _D A TA BA SE role, and I MP_FU LL_DA TA BASE role.
6. SE L E C T_C ATA L OG _R OL E : This role, which allows selection from any
object owned by SY S, is granted to the D BA , SY S schema,
E X P_FU L L _D A TA BA SE role, and I MP_FU LL_DA TA BASE role.
You can use the D ata Dictionary view D BA _R OL E S to find roles and their
password. Oracle9i creates 30 roles on installation, whereas Oracle6 contained only
three roles— CONNECT, R E SO U R C E , and D BA !
Working with Oracle Enterprise Manager (OEM) 385
SYSTEM PRIVILEGES
System privileges allow a user to take certain actions within the database. Figure 16- 12
shows a few system privileges needed for certain types of actions within the database.
As you know, Oracle9i has more than 100 defined system privileges. They can be cate-
gorized into three types based on their effect:
1. Pr ivileges that affect the entir e database: The D B A or user who is granted
the D B A role has such privileges. These privileges allow the D B A to alter
the database, create users, create roles, grant roles, manage tablespace, re-
move users, and so on.
2. Pr ivilegesthat allow a user to create objects in the user’s own schema: These
privileges allow user to create tables, views, sequences, synonyms, proce-
dures, triggers, and so on. These privileges are granted to C ONN EC T and
R E SO U R C E roles. These roles are then granted to a user rather than grant-
ing individual privileges.
3. Pr ivilegesthat allow a user to manipulate obj ects in any schema: These priv-
ileges allow you to manipulate objects in other users’ schemas. The D BA
and users with the D B A role are granted these privileges— for example,
CR E A TE A NY , D R O P ANY , A L TER A NY, SELECT ANY, I NSERT
ANY , E X E C U TE ANY , and so on.
System privileges are granted carefully to users after intelligent planning. Only
DBA s and users with G R A NT A N Y PR I V I L E G E system privilege can grant sys-
tem privileges to other users. The privileges are granted through a role or granted
individually with the following statement:
Oracle Data Dictionary 387
The D ata Dictionary in Oracle consists of tables and related views. The D ata D ictio-
nary gives the structure and inside view of the Oracle database, and it has grown with
each Oracle release. You can use SQL statements with D ata D ictionary tables/views
just like you would with user tables/views. Y ou can get information about various Or-
acle objects and users of the database. The D ata D ictionary contains static Data Dic-
tionar y views, which are owned by user SYS. The static D ata D ictionary views are
based on tables that are updated with Oracle D D L statements only. I t should not be
updated with D ata Manipulation L anguage (D M L ) statements. The SYS tables,
views, and synonyms are created with the CATALOG.SQL script file. The procedur-
al objects are created with the CATAPROC.SQL file. These scripts files are provided
by Oracle and are copied into the O RA CL E \OR A 92\R D B MS\A D M I N directory
along with other script files.
388 Chap. 16 Oracle9i: Architecture and Administration
The script files also create public synonyms for D ata D ictionary views (e.g.,
synonym for user_tables and for user_sequences). Before displaying infor-
mation from a view, D E SC RI BE its structure first to avoid unnecessary information.
There are additional views known as dynamic per for mance D ata D ictionary views,
or simply V$ views. The V $ views are based on internal memory structures, or virtual
tables, which begin with the X$ prefix. The V$ views and X $ tables have in- formation
about the instance. The information in the two D ata D ictionary views is:
IN A NUTSHELL . . .
● Security is a very important issue for the DBA . The D B A creates users and
grants them privileges and roles.
● System privileges are categorized into those that affect the entire database,
those that allow users to create objects in their own schema, and those that
allow users to manipulate objects in any schema.
● Oracle creates default roles and initial users at the time of installation.
● Oracle provides a powerful set of tools, such as SQL* Plus, SQL*Plus Work-
sheet, EX P/IMP, and Enterprise Manager.
● SQL* Plus is an environment to interface with the database. I t provides
users with editing, file-related, variable-related, formatting, and environ-
ment variable commands.
● Oracle’s D ata Dictionary contains static and dynamic tables and views.
EXERCISE QU ESTIONS
True/False:
1. The file TNSNAM ES.O RA contains the names of default roles and initial users.
2. Three major areas of Oracle architecture are SGA, background processes, and physical
storage structures.
3. A user needs CON NECT and R ESOU R CE roles to create a table in his or her own
schema.
4. The replication method uses separate databases by duplicating the entire implementa-
tion of a database on multiple computer systems.
5. The hot standby database method uses only one database at a time, and the other stand- by
copy is in recover mode at all times.
6. A n Oracle instance is the SG A and physical storage structures.
7. SYS user is granted the D B A role and owns the Data Dictionary.
8. A n initial SCOTT user, created by Oracle, has all system privileges.
9. SQL *Plus Worksheet is a Web-based environment to connect to the Oracle database.
10. A n instance is first opened and then mounted.
STUDENT
State CHAR(2)
Zip CHAR(5)
StartTerm CHAR(4) FOR EI GN KEY
BirthDate DATE
FacultyId NUMBER(3) FOR EI GN KEY
MajorId NUMBER(3) FOR EI GN KEY
Phone CHAR(10)
FACULTY
CRSSECTION
COURSE
REGISTRATION
ROOM
RoomDesc VARCHAR2(9)
LOCATION
TERM
DEPARTMENT
FacultyId VARCHAR2(20)
NUMBER(3) FO R EIG N KEY
MAJOR
MajorDesc VARCHAR2(25)
EMPLOYEE
Dept
EMPLEVEL
LowSalary NUMBER(6)
HighSalary NUMBER(6)
POSITION
VARCHAR2(10)
DEPENDENT
QUALIFICATION
VARCHAR2(11)
SQL KEY WORD S
I n the syntax for various SQL statements and PL/SQL blocks, the following conven-
tion is used:
Creating a Table
...,
...,
...
...), ...)
Column-Level Constraint
Table-Level Constraint
( column, ...),
Dropping a Table
Renaming a Table
Truncating a Table
...) ]
...);
Customized Prompts
Updating Rows
...]
Deleting Rows
Dropping a Constraint
|UNIQUE (columnname) |
SQL and PL/SQL Syntax 399
Enabling|Disabling a Constraint
n(s)]
Define Command
Decode Function
Case Structure
.columnname, tablename2.columnname
Set Operation
400 App. B Quick Reference to SQL and PL/SQL Syntax
Select Subquery
Top-N Query
SQL and PL/SQL Syntax 401
Mer ge Statement
Creating a View
Altering a View
Creating a Sequence
|NOMAXVALUE] |
NOMINVALUE] |NOCYCLE]
|NOCACHE]
|NOORDER];
|NOMAXVALUE] |
NOMINVALUE] |NOCYCLE]
|NOCHACHE]
|NOORDER];
402 App. B Quick Reference to SQL and PL/SQL Syntax
Creating a Synonym
Creating an Index
...);
Rebuilding an Index
Creating a User
Revoking Privileges
Assignment Operation
IF-THEN-END IF
404 App. B Quick Reference to SQL and PL/SQL Syntax
If-Then-Else-End If
If-Then-Elsif-End If
...
Case Statement
Basic Loop
...
While Loop
...
SQL and PL/SQL Syntax 405
For Loop
...
Bind/Host Variable
Select-Into in PL/SQL
...
...
406 App. B Quick Reference to SQL and PL/SQL Syntax
Exception Section
SQL and PL/SQL Syntax 407
Raise_Application_Error Procedure
PL/SQL Procedure
Calling a Procedure
408 App. B Quick Reference to SQL and PL/SQL Syntax
Recompiling a Procedure
PL/SQL Function
PL/SQL Trigger
SQL and PL/SQL Syntax 409
Creating a Tablespace
Starting Up an Instance
Dropping a User
BTITLE. The BTI TL E command specifies the format of the title at the bot-
tom of each page. The general syntax is
where O N ƒOF F turns the title on or off. The printspecs are C O L , SK I P , L E FT,
C E N TE R, R I G HT, and B O L D . The text is a character string to be printed, and the
variable is a user- defined or system variable.
COLSEP. The C OL SE P command sets the text printed between columns re-
trieved by a SE L E C T statement. The default text is a single space. The general syn-
tax is
... ...
412 App. C Reference to SQL*Plus Commands
where
HELP. The H E L P command starts the SQL * Plus help functi on and displays
help on a specified topic; otherwise, it displays a list of topics. The general syntax is
SET. The SE T command shows and sets system and environment variables.
The general syntax is
|OFF
SPOOL. The SPOO L command with a filename starts the spooling of state-
ments and results into that file. The default file extension is . The O FF switch stops
writing to the file and closes it. The general syntax is
App. C Reference to SQL*Plus Commands 415
| |
SQLPROMPT. The SQLPROMPT command can be used to set the SQL * Plus
prompt. The default prompt is SQL 7. The general syntax is
TIME. The TI M E command, when set to ON, shows current time before the
SQL 7 prompt. The general syntax is
TIMING. The TI M I NG command, when tur ned ON, shows timing statistics.
The general syntax is
TTITLE. The TTI TLE command specifies the format of the title, which is dis-
played at the top of each page. The general syntax is
...]
|OFF
416 App. C Reference to SQL*Plus Commands
SQL*PLUSEDITING COMMANDS
Command Description
SQL*PLUSFILE-RELATED COMMANDS
Command Description
GET [.ext] Writes a previously saved file to the buffer. The default exten-
A n object reference (key word R E F) is a special data type in a table that fa-
cilitates a foreign key in the table. I t establishes a relationship between two ob-
jects— for example, an object table called SOFTW A R E _C OM PA NY _ OB J with a
primary key and a second object table, SOFTW A RE _ OB J, that has a foreign key
column that connects software to the company that makes it. This foreign key
column is defined with the data type R E F and references the object named
SOFTW A R E_ COM PA NY _OB J.
L et us tak e examples of object types, object tables, R E F columns, and tables
with object type and look at SQL statements on these objects (see Fig. D -1).
Figur e D-1 Object types, R E F column, object column, and hybrid table.
SQLQUERIESFOR OBJECTS
In Figure D- 1, the object table NA ME _TA B L E contains rows with the object type
FU LLNAME_TY PE, which in turn has two attributes of type R E F (NA ME _R EF)
and V A R C HA R 2 (MID _INITI AL ). The R E F to NAME_TY PE in turn contains two
attributes, LA ST_NAME and FI RST_NAME, of type V ARCHAR2. Y ou can write a
standard SQL query to display the contents of the object table NA ME _TA BLE. For
example,
SELECT * FROM NAME_TABLE;
SQL Queries for Objects 419
For example,
SELECT S.FULL_NAME.LAST_NAME, S.FULL_NAME.FIRST_NAME, PHONE_NUM FROM
STUDENT_TABLE S;
When you use a column related to an object, you must use a table alias. I n the
example above, STU D EN T_ TA BL E has the alias S. I f you do not use a table alias,
you get the following error message:
ORA-00904: invalidcolumnname
The value for an object is inserted by entering the name of the object and then en-
closing all values for the object’s attributes in parentheses. For example,
where FULL _NAME(‘Spencer’, ‘Karen’, ‘A’) contains values for three attributes in
the object FU L L _ NA ME , which are L A ST_ NA M E , FI RST_ NA ME , and
MI D _I NI TI A L .
Updating an Object
Suppose you want to change a student’s last name. Use the U PD A TE statement
with an alias for the table name, and qualify the attribute with the table name and
the object name. For example,
UPDATE STUDENT_TABLES
SETS.FULL_NAME.LAST_NAME =‘Martinez’ WHERE STUDENT_ID = 543;
4. E nhanced functions:
I NSTR.
L E NG TH .
SUBSTR.
2. CA SE expr essions:
New C A SE statements as alternatives for I F statements.
4. Typeevolution:
Attributes and methods can be dropped from an object type without
recreating the type and corresponding data.
8. L OB data types:
You can operate on L OB types like other similar types. Character
functions for C LO B and NCLOB.
Treat B L OB as RAWS.
Conversion from L O B to other types like L O NG made simple.
424 App. E What’s New in Oracle9i SQL and PL/SQL?
9. M ER GE statement:
A statement that combines I NSERT and U PD A TE into a single operation.
10. Bulk operations:
Y ou can perform bulk SQL operations using native dynamic SQL— for
example, E X E C U TE I MM E D I A TE statement.
Perform bulk INSERT and U PD A TE operations and, in case of errors on
some rows, continue and examine errors after the operation is complete.
I n this book, an attempt is made to provide an in- depth understanding of relational
database concepts, Oracle’s nonprocedural language SQL, and the procedural lan-
guage PL/SQL. Both language features apply to Oracle8, Oracle8i, and Oracle9i, al-
though Oracle9i has some added features. The author has examined various
resources to provide an adequate amount of knowledge to the readers while staying
within the scope of this book. This appendix lists additional sources of information
available for further reference of the topics covered in this book.
WEB SITES
1. Oracle Corporation—
Home page of Oracle Corporation.
2. Oracle M agazine—
For a free subscription to the bimonthly .
3. Oracle Technology Network (O TN)—
Oracle’s network to reach users— low-cost offers, free downloads, and so on.
4. Oracle U niversity—
426 App. F Additional References
Information about Oracle training tracks, schedules, online registration, and certi-
fications.
5. O racle User ’s Group—
The brainstorm of a number of dedicated user-group officers.
6. O racleZone—
A wide variety of Oracle information, real-life problems, discussions, and trou-
bleshooting tips posted by Oracle users.
7. O rapub—
A site founded by a former Oracle employee, Craig Shallahamer, devoted to all
Oracle-related issues.
8. M y O racle—
A portal for creating a personalized home page for U .S. news, BBC news, CNET
news, stock market quotes, and other goodies.
CONNECT Role, 384 D ata Manipulation L anguage (D ML ), D irect A ssignment, 302 D isabling a
Connectivity, 22 43, 97–105 Constraint, 88 D ISC ONNEC T
Constant D eclaration, 234 Constraints D EL ET E Statement, 97 Command, 412
Constraints Types, 72 INSERT Statement, 97 D ISTINC T K eyword, 109
D efining a Constraint, 73 Integr ity U PD A TE Statement, 97 D ivision, 13–14
Constraint, 72 Naming a Constraint, D ata M odeling, 21–22 D omain, 5
72 Value C onstraint, 72 D ata Retrieval L anguage, 43 D ata D riverManager Class, 340 D R OP
V iewing Constraint Names, 80–81 Types, 68–72 TAB LE Statement, 89 D R OP U SE R
Control File, 372 C HA R, 69 Statement, 382 D ropping a Column, 86–
Control Structures, 245 D A TE, 70
87 D ropping a C onstraint, 87–88
L ooping Structure, 245 N U M B ER , 70
V A RCHA R2, 69 D ropping a Sequence, 200 D ropping a
Selection Structure, 245 Table, 89
D atabase, 1, 2, 371
Sequential Structure, 245 C onversion D UA L Table, 137–138
D atabase Administr ator (D BA ), 41,
from 1NF to 2NF, 29–30 Conversion D ummy Column, 138
368–369
from 2NF to 3NF, 30–31 Conversion D atabase Design, 26 D ynamic Cur sor, 268
Functions, 144–145 A nalyze, 26 D ynamic Performance D ata D ictionary
COPY Command, 412 Synthesize, 26 View, 388
Correlated Subquer y, 185–188
D atabase M anagement System (D BMS), EC H O C ommand, 413
EXISTS Operator, 186–187 3–4
NOT EX ISTS Operator, 186–187 ED IT Command, 47
D atabase Security, 207
COU NT F unction, 147–149 Editing Commands, 48 Enabling a
D A TE, 70
COU NT M ethod, 304 Constraint, 88 Enclosing R ecord, 299
D ate A rithmetic, 139
Counter, 255 Entering Default V alue, 100 Entering
D ate For mat, 70, 98–99, 137
CREA TE IND EX Statement, 202 D ate F unctions, 137–141 Null V alues, 100
CREA TE SEQ U E NC E Statement, 196 D A TE V alues, 98 Explicit Method, 100
CREA TE TAB LE Statement, 76–77 D ate/Time Format, 145 Implicit Method, 100
CREA TE TA BL ESPA CE Statement, D BA , 41, 368–369 Enterprise M anager , 42
378 D BA Role, 384 Instance Manager, 42
CREA TE U SER Statement, 208, 380 D BM S, 3–4 iSQL * Plus, 42
D BM S_OU TPU T.PU T_ L INE, 239 Security M anager, 42
CREA TE V IEW Statement, 192
Creating a Sequence, 196 Creating a D B W R Process, 370 SQL W orksheet, 42
D eclaration Section, 229 Storage Manager, 42
Table, 76–78
Creating a Table with Subquery, D EC OD E Function, 143 D efault W arehouse M anager , 42 X ML
176–177 C olumn W idth, 107 D atabase Manager, 42
D efault Date Format, 70, 98–99, 144, 146 Entity, 1, 21
Creating a Tablespace, 378–379 Creating
D EFA UL T K eyword, 100 Entity Integrity, 8
a View, 192 C UR RV AL
D efault Tablespace, 380 Entity Set, 2, 21
PseudoColumn, 198 Entity-Relationship Model, 21
Cursor, 268 D EFA UL T V alue, 76
D EF I NE Command, 126, 412 Envir onment V ariables, 107
D ynamic Cur sor, 268
D efining a C onstraint, 73–74 A t Equijoin, 13, 158–161
Static Cursor , 268
C olumn L evel, 73 E-R D iagram, 21, 22, 60, 63
Cursor A ttributes, 272–274 Cur sor For A t Table L evel, 74 D egree, 5 I U College, 60
Loops, 274–276 U sing a Subquery, 276 D EL Command, 48 N2 Corporation, 63
Cursor V ariable Return Type, 279 D EL ET E Method, 304 ERD , 22
Cursor Variables, 279–280 D EL ET E Privilege, 209 Error Codes, 91
Fetching, 280 D EL ET E Statement, 104, 262–263 Error Messages, 91–93
Opening, 280 D eleting R ows, 104–105 Escape C haracter, 122
R EF Cursor Type, 279 D EL ETE Statement, 104 D eleting ESCA PE K eyword, 122
Cursor with Par ameters, 277–279 with Subquery, 180–181 D eletion Exception Declar ation, 286
Customized Prompt, 102 A nomaly, 26 Exception Handling, 281 Exception
A CCEPT, 102 D emand on Client and Networ k, 38, 40 Handling Sections, 229 Exception
PROMPT, 102 D enormalization, 32
Trapping Functions, 285
D ependency, 24–26
SQLC OD E, 285
F ull Dependency, 25
SQLERR M, 285
Partial Dependency, 25
Total D ependency, 25 Exceptions, 268, 280–289
Transitive D ependency, 25 Non-predefined Oracle Server Error,
D ata, 1, 3 283–284
D ependency Diagram, 28–29
D ata Control L anguage (D CL ), 43 Predefined Oracle Server Error,
D ESC Keyword, 123 D escending
D ata D efinition Language ( DD L ), 43 282–283
Sorting Order, 123 DESCR IBE
D ata D ictionary, 4, 79–82 Types, 281–282
C ommand, 412
D ata D ictionary V iews, 334, 387–388 D evelopers Suite, 42 U ser-defined Exception, 286–287
D ynamic Per formance Views, 388 D esigner, 42 Exclusive L ock, 206
Static V iews, 387 F orms D eveloper, 42 Executable Section, 229
U SER_ ER RORS View, 334 JD eveloper, 42 EX EC U T E C ommand, 316, 326, 413
U SER_ OBJECTS V iew, 334 Oracle Reports, 42 EX EC U T E Privilege, 209
U SE R _ PRO C ED U RE S View, 334 D ifference, 10–11 ExecuteQuer y( ) Method, 342
U SER_ SOUR CE View, 334 D ifferences, SQL * Plus and SQL * Plus ExecuteU pdate( ) Method, 343
U SE R _ TR I GGE RS V iew, 334 W orksheet, 52–53
D ata F ile, 372
Index 429
EXISTS M ethod, 304 Implicit Index, 202 Importing Package, 340 Interacting
EXISTS Operator, 186–187 Implicit Null, 100 with the Oracle
EXIT C ommand, 48, 413 Import, 373 D atabase, 341–342 Loading
EXIT Statement, 255 Import Statement, 340 JD BC D rivers, 340
EXP, 373 IN Operator, 115, 119, 181 IN OU T Java A pplications, 339
EXP/IMP, 373 Parameter, 315 IN Par ameter, 315 Java L anguage, 339
Explicit Cursor, 268–274 Indentation, 247 JD BC, 339
A ctions on, 270 Index, 201–203, 372 JD BC-OD BC B ridge D river, 339
A ttributes, 272–274 Composite Index, 202 Cr eating an JD BCOD BCD river Class, 340
D eclaring, 269 Index, 202 Explicit Index, 202 JD eveloper, 42
Fetching D ata, 271 Implicit Index, 202 R ebuilding an JD K, 339
Opening, 271 Index, 203 Join, 12–13, 157
Explicit I ndex, 272 IND EX B Y BINA RY _INTEGER Equijoin, 158–161
Explicit Null, 100 Clause, 300–301 Non-Equijoin, 161–162
Export, 373 IND EX Privilege, 209 Outer Join, 163–164
EX TEN D Method, 304 Indo-U S ( IU) College Student D atabase, Self-Join, 165
Extents, 372 56–61 Join Conditions, 159
EXTRA CT Function, 140 C OU R SE Table, 57
CRSSECTI ON Table, 58 K ey, 7
FEED BA CK C ommand, 413
D EPAR TM ENT Table, 58 Composite Key, 7
FETC H Statement, 271 File FA CU L TY Table, 57 Foreign Key, 7
System Terminology, 6 F ile-related L OC ATION Table, 59 Pr imary Key, 7
Commands, 47 F iring of Triggers, M A JOR Table, 58 Secondary K ey, 7
328 FIRST Method, 304 REGISTRA TION Table, 58 Surrogate Key, 7
First Normal F orm (1NF), 27–28 R OO M Table, 58
Fixed-length Character Value, 69 STU DENT Table, 57 L abeling L oops, 259
Fixed-point D ecimal, 70 Table Definitions, 390–393 L A ST M ethod, 304
Floating-point D ecimal, 70 L A ST_D A Y F unction, 140
TER M Table, 58
F L O OR Function, 137 Information, 3 L ENG TH Function, 134
F OR L oop, 258–259 Information System, 4 L ENG THB Function, 135
F OR U PD ATE O F Clause, 207 INIT.ORA , 372 L ENG THC Function, 135
Foreign K ey, 7 INITCA P Functions, 133 L GW R Process, 370
F OR E IG N KEY Constraint, 74 Initial Roles, 384 L IK E Operator, 115
Formal Par ameter, 316 F ormatting Initial U sers, 383 L INESIZE Command, 413
a column, 111 Forms D eveloper, Inline V iew, 184 L IST Command, 48
42 Inner Query, 174 L iterals, 228
Full D ependency, 25 Boolean, 228
Function, 230, 313, 319–323 INPU T Command, 48 INSERT A LL
Statement, 179 Character , 228
Body, 320 Number, 228
Conditional, 179
Calling a Function, 320 Calling U nconditional, 179 L OB D ata Types, 233–234 Locking,
from SQL , 323 Header, 319 INSERT FIRST Statement, 179 206–207
Parameters, 320 L ocking R ows for U pdate, 206–207
INSERT Privilege, 209
Retur n Type, 320 INSERT Statement, 98–102, 262 L ogging into SQL * Plus, 44–46 L ogical
Gateway, 374 Inserting a R ow with Subquery, Operator s, 115, 246
General F unctions, 133 178–179 L ogical Operators-Truth Table, 115, 246
GE T Command, 47 Insertion A nomaly, 26 L ogin Problems, 45–46
GO TO Statements, 267 Instance, 371 L ON G Type, 71
GR A NT Statement, 209, 386 INSTEA D OF Trigger, 333–334 L ONG-R AW Type, 71
GR O U P BY C lause, 149–150 INSTR Function, 134 L ooping Structure, 254–259
Group Functions, 132, 147–149 Integer, 70 Basic L oop, 255–256
Grouping D ata, 149–152 Integrated D evelopment Environment F O R L oop, 258
(ID E), 339 W HI L E Loop, 257
HAV ING C lause, 151–152 Integrity Constr aint, 72 L OW ER F unction, 133
HE L P C ommand, 49, 413 F OR E I GN K ey, 74 L PA D Function, 134
HE L P IND EX Command, 49–50 PRI MA RY K ey, 74 L TRIM Function, 134
HOST Command, 413 Integrity R ules, 8
Host V ariables, 237, 361 Entity Integrity, 8 M :M (Many-to-M any), 3
Hot Backup, 373 Referential Integrity, 8 M :N (Many- to-Many), 3
Hot Standby D atabase, 373 INTERSEC T Operator, 169 M any-to- Many Relationship, 23
IF. . . TH EN . . . EL SE . . . E ND IF Intersection, 10 M atching Parameter, 316
Statement, 247–248 Invalid Names, 68 Named Notation, 316
IF. . . T HEN . . . EL SIF . . . EN D IF IS NU L L Operator, 115, 120 Positional Notation, 316
Statement, 248–251 iSQL* Plus, 54–56 M AX Function, 147–148
IF. . . THEN. . . E ND IF Statement, I U C ollege Student D atabase, 390–393 M E R GE Statement, 185
246–247 Table D efinitions, 390–393 M etadata, 4
IMP, 373 M IN Function, 147–148
Implicit Cursor, 268 Java, 339–344 M INU S Operator, 169
Implicit Cur sor A ttribute, 274 Closing Connection, 344 Importing M O D Function, 137 M odifying a
SQL Prefix, 274 JDB C Class, 340 C olumn, 84 M odifying a Sequence, 199
M odifying a Table, 82
430 Index
Substitution V ariable, 238–239 R E F K eyword, 418 SEL ECT. . . INTO Statement, 260
Syntax-Quick Refer ence, 395–403 R eference Books, 426–427 Reference Selection, 11
Table A ssignment, 302–303 W eb sites, 425–426 R EF E RE NC E S Selection Operation, 114
Table Columns, 300 Privilege, 209 Referencing Fields in a Selection Structure, 245–254
Table Index, 300 PL /SQL CA SE, 251
Table Type, 300 R ecord, 298 IF -THEN-EL SE-END IF, 247–248
Tables, 300–306 R eferential Integrity, 8 IF -THEN-EL SIF -END IF, 248–251
Transaction C ontr ol Statements, 264 R elation, 5 IF -THEN-END IF, 246–247
U ser-D efined Identifiers, 227 R elational A lgebra, 8, 9–14 Nested IF, 253
V ariable Declar ation, 234 R elational Calculus, 8, 15–16 Searched C ASE, 252
V arrays, 306–309 R elational Languages, 8–16 Self-Join, 13, 165
W hat’s New in 9i, 423–424 PL /SQL R elational A lgebra, 8, 9–14 Sequence, 196–200
fr om SQL j, 364–365 R elational Calculus, 8, 15–16 Cr eating a Sequence, 196–197
PL/SQL K eywords R eference, 396 R elational Operators, 103 CU RR VA L PseudoColumn, 198
PL/SQL Records, 297–300 R elational Schema, 23 D ropping a Sequence, 200
Cr eating, 297 R elational Ter minology, 6 M odifying a Sequence, 199
Nested Records, 299 R elationship, 2–3, 21 NEXTV A L PseudoC olumn, 197
Referencing Fields, 298 M any-to- Many, 3 U sing a Sequence, 198–199
W orking with, 298 One-to-M any, 2 Sequence Structure, 245
PL/SQL Statement Syntax, 403–409 One-to-One, 2 SERV EROU TPU T Environment
PL/SQL Tables, 300–306 R E M A R K Command, 414 Removing V ariable, 239
A ssigning Values to Rows, 302–303 a V iew, 195 R EN A M E Statement, 89 Servers, 38
Built-in Methods, 304 R enaming a Table, 89 R EPL A C E SET Clause, 103
D eclaring, 300–301 F unction, 134 SET Command, 414
IND EX BY BINA RY _INTEGER R eplication, 373 SET D E FI N E OFF Command, 101
Clause, 300–301 R E SOU R C E Role, 384 SET D EF I NE ON C ommand, 101
Referencing Elements, 301–302 R esources, 38 SET FEED BA CK Command, 107
Table of Recor ds, 305–306 R estricting D ata, 114 SET L INESIZE Command, 107
PL /SQL Varray, 306–309 V array of R esultSet Class, 342 Set Operators, 166–170
V array, 307 R esultSetMetaD ata Class, 342–343 INTERSECT, 169
R etrieving D ata, 105–108 M INU S, 169–170
Plus (+) Operator, 163 Positional
SEL ECT Query, 105 U NION, 166–167
Notation, 316
POW ER F unction, 136 PR A G M A R E TU R N Statement, 319 R E U SE U NI ON A L L, 167–168 SET
EX CEPTION_ INIT, STO R A GE C lause, 90 SERV EROU TPU T ON
R E V OK E Statement, 210–211 C ommand, 239
284–285
Precision, 70 R MA N, 373 SGA , 369
R oles, 208 Share L ock, 206
Pr edefined Oracle Server Error List, R ollback Segment, 372
282 SHOW AL L Command, 107 SHOW
R OL L BA CK Statement, 98, 104, 204
Pr edefined Oracle Server Exception, C ommand, 414
R O U N D Function, 136
281–283 SHOW ER R OR C ommand, 317
R OW Trigger, 331
PreparedStatement Class, 343 SHO W M OD E Command, 414
R ow V ariable, 15
Primary K ey, 7 SHU TDOW N Command, 378, 414
R OW ID PseudoColumn, 203
PRIMA RY K EY Constraint, 74 SIGN Function, 137
R OW ID Type, 71
PRINT Command, 237–238 R OW NU M PseudoC olumn, 183 Simple A ttribute, 24
PR I O R Method, 304 R PAD Function, 134 Simple V iew, 192
Private Module, 325 R TRI M Function, 134 Single L ine C omment, 230
Procedural L anguage, 8 Single-R ow Functions, 132
R U N Command, 48
Procedure, 230, 313–315 Character , 133
Body, 315 Sample Databases, 56–64, 390–394 Conversion, 133
Calling a Procedure, 314 Creating a Indo- US (IU ) C ollege Student D ate, 133
Pr ocedure, 314 Header, 315 D atabase, 56–61 General, 133
Parameters, 315 NamanNavan (N2) C orp Employee Number, 133
Product, 11–12 D atabase, 61–64 Single-R ow Subquery, 174–181
Projection Operation, 11, 114 SAV E Command, 47 Single-V alued Attribute, 24
PROM PT C ommand, 102 SAV EPOINT Statement, 204 Scalar SMON Process, 370
PUBL IC Keyword, 201, 210 D ata Types, 230–234 Scale, 70 SOM E Oper ator, 181
Public Module, 325–326 Schema, 372 Sort B y Column Alias, 124 Sor ting,
PUBL IC Synonym, 201 SY S Schema, 372 122–125
SY STEM Schema, 372 Searched A scending (A SC), 123
R AISE Statement, 286 C ASE Statement, 252 Second Normal By Column Alias, 124
RA ISE_A PPLIC ATION_ERROR F orm (2NF), 28 Secondary Key, 7 By Multiple Columns, 124 Default,
Procedure, 287–288 Secur ity Manager, 380 123
R AW Type, 71 Segments, 372 D escending (D ESC), 123
R DB MS, 4–5, 20 SEL ECT (* ), 106 Order BY Clause, 122 SPOOL
R ead Consistency, 206 Record Name SEL ECT Statement, 97 C ommand, 48, 91, 414
Qualifier, 298 Redo L og File, 372 SEL ECT. . . F OR U PD A TE Cursor, SPOOL OF F Command, 91
R edundant Data, 26 276–277 Spooling, 90–91
R E F C U R SO R Type, 279 SQL , 17, 41, 43, 419–422
W hat’s New in 9i, 419–422 SQL IN
PL/SQL, 260–264
432 Index