0% found this document useful (0 votes)
295 views457 pages

Rdbms

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

Rdbms

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

Nilesh Shah

Copyr ight © 2016 Pear son I ndia E ducation Ser vices Pvt. Ltd

Published by Pearson India Education Services Pvt. L td, CI N: U72200TN2005PTC057128,


formerly known as TutorVista Global Pvt. Ltd, licensee of Pearson Education in South A sia.

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.

ISBN 978-93- 325-4972-2


eI SBN 978-93- 325-7309-3

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

Part 1: Database Concepts

D atabase: A n I ntroduction 1 Relationships 2


D atabase Management System (D BMS) 3 The
Relational D atabase Model 5 I ntegrity Rules 8
Theoretical Relational L anguages 8

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

I n a Nutshell Á 34 E xercise Questions 35

Part 2: Oracle SQL 37

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

I n a Nutshell Á 64 E xercise Questions 65


Lab Activity 66
Contents vii

Naming Rules and Conventions 68 D ata Types 68

Constraints 72

Creating an Oracle Table 76

D isplaying Table I nformation 79

A ltering an E xisting Table 82

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

D ata Manipulation Language ( D ML ) 97 Adding a


New Row/Record 98
viii Contents

Customized Prompts 102


U pdating Existing Rows/Records 102
D eleting E xisting Rows/Records 104
Retrieving D ata from a Table 105
*

A rithmetic Operations 113

Restricting D ata with a W H E R E Clause 114

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

Built-I n Functions 132

Grouping D ata 149

I n a Nutshell Á 153
Exercise Questions 153
Lab Activity 154

Join 157
Contents ix

Set Operators 166

I n a Nutshell Á 171
Exercise Questions 171
Lab Activity 172

Subquery 174

Top-N Analysis 183

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

Locking Rows for U pdate 206

Controlling A ccess 207

I n a Nutshell Á 212
Exercise Questions 212
Lab Activity 213
x Contents

Script for Creation of Tables 216


Script for I nsertion of Rows into Tables 217 Insertion of Rows with
Substitution Variables 217

E
W
Contents xi

Part 3: PL/SQL 225

A Brief History of PL /SQL 226


Fundamentals of PL /SQL 227

PL/SQL Block Structure 228 Comments 230


D ata Types 230

O ther D ata Types 233

V ariable D eclaration 234


A nchored D eclaration 234

A ssignment Operation 236


Bind Variables 237
Substitution Variables in PL/SQL 238 Printing in
PL/SQL 239
A rithmetic Operators 240
xii Contents

I n a Nutshell Á 241
Exercise Questions 242
Lab Activity 243

Control Structures 245

Nested Blocks 259 SQL in PL/SQL 260

D ata Manipulation in PL/SQL 262

Transaction Control Statements 264

I n a Nutshell Á 264
Exercise Questions 265
Lab Activity 266

Cursors 268

I mplicit Cursors 268


Explicit Cursors 269

Explicit Cursor A ttributes 272

I mplicit Cursor A ttributes 274 Cursor


F O R Loops 274

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

Types of Exceptions 281

M ore Sample Programs 289 I n a Nutshell Á


289
Exercise Questions 294
Lab Activity 295

Composite D ata Types 296 PL/SQL Records 297

PL/SQL Tables 300

PL/SQL V arrays 306

I n a Nutshell Á 309
Exercise Questions 311
Lab Activity 311

Procedures 314

Functions 319
xiv Contents

Packages 323

Triggers 328

D ata Dictionary V iews 334 I n a Nutshell Á 335


Exercise Questions 336
Lab Activity 336

Part 4: Miscellaneous Topics 338

Java: A Programming L anguage 339 JD B C 339

Sun’s JD B C Driver and the Oracle D ata Source 344

OracleDriver and Oracle D river 348

Java Applet: Putting I t A ll Together 351 SQLj 358

Host V ariables 361


SQL j Iterators 361

PL/SQL from SQL j 364 I n a Nutshell Á


365

Exercise Questions 366


Lab Activity 367

D atabase Administrator ( D B A ) 368 Oracle A rchitecture: A n


Overview 369
Contents xv

Installation 374
Connecting to the Oracle9i D atabase 375 I nstance and
D atabase 377
Working with Oracle Enterprise Manager (O E M ) 378

System Privileges 386 Oracle D ata Dictionary 387 I n


a Nutshell Á 388

Exercise Questions 389

The Indo–U S (I U ) College Student D atabase 390


The NamanNavan (N2) Corporation Employee D atabase 393

SQL K ey Words 395 PL/SQL K ey Words 396


SQL and PL/SQL Syntax 396
xvi Contents
Contents xvii

*
*
SQL * Plus Editing Commands 416 SQL * Plus File-
Related Commands 416

A n Object 417
SQL Queries for Objects 418

New Features in SQL 420 New Features in PL/SQL


423

Web Sites 425


Books and O ther Published Material 426
Computer science educators and I T administrators are— and, traditionally, have
been— faced with a common problem. I n an industry characterized by rapid and
dramatic changes, the manager must determine how he or she can maintain state- of-
the- art skills among the IT staff. I n a similar vein, the educator, must be able to
judge how students can be best prepared to work as professionals in a field that may
have gone through revolutionary transitions between the time that student first en-
tered college and the time that he or she graduates.
Certainly, a technical education must incorporate a strong foundation in the core
concepts of operating systems, file or database structure, computer architecture, and
general programming theory. The difficulty arises when the educator seeks to select an
application or a development platform to use for introducing these concepts and for
providing students with practical, functional, and marketable hands-on skills. As the
ones responsible for such preparation, we often look for a package that not only will
give students the most vivid demonstration of the theoretical concepts we are attempt-
ing to portray but will also offer students an opportunity to use that knowledge almost
immediately in a variety of environments. In addition, we seek packages that are in
heavy and common demand, with a “track record” of success, reliability, and longevity.
The area of relational database management systems (R D B MS) is crowded
with a vast number of quality R D B MS products. Only one, however, addresses the
many concerns the educator has for students. That product, of course, is Oracle. I t
has been on the market for more than 20 years, and it holds a major portion of the
mar ket share, which accounts for Larry Ellison’s position among the world’s wealth-
iest men and Oracle’s position among the largest global corporations. There are ver-
sions of the product for nearly every hardware platform, from personal computers
through minicomputers and supercomputers, and for operating systems from D OS,
Windows, and L inux through MVS, OS/400, PI CK, and the multitudinous flavors of
Unix. Of all the R D B MS systems available, Oracle is the one the student is most
likely to encounter on the job— and the one in which employers most eagerly seek
expert applicants and employees.
From an educator’s perspective, Oracle, as a truly relational database, incorpo-
rates virtually all the relational operations that any database theory course must en-
compass. This allows the student to actually see the results of such operations.
Foreword xix

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

knowledge of relational concepts and database design techniques to allow students to


design and implement accurate and effective database systems. The second part con-
centrates on the primary nonprocedural relational database language, SQL, which is
supported by most relational database software packages. The book primarily concen-
trates on Oracle9i and points out those features that were not available in previous re-
leases. (I n reality, the SQL part of the book can be utilized in Oracle release 7.x, 8, 8i, or
9i.) The third part of the textbook is devoted to the procedural language PL/SQL,
which is Oracle’s proprietary language extension to SQL . PL/SQL features data en-
capsulation, error handling, and information hiding, which are typical capabilities of a
high-level programming language. The fourth part of the textbook introduces the ar-
chitecture and administration of Oracle9i as well as connectivity to Oracle from Java.
Throughout the text, the general syntax of SQL and PL/SQL are supplement-
ed by simple examples, screen captures, and illustrations. Each chapter includes a
brief summary, exercise questions, and lab activities. The textbook is supported by
sample databases— one a typical college’s student database with demographic,
schedule, and registration information, and the other a corporation’s employee
database with employees’ demographic and job-related data. I n most cases, the ex-
amples are based on one of the sample databases and the lab activity on the other,
to test a student’s ability to apply queries in a different scenario. A separate section
with a third sample database is included at the end of the SQL portion of the text-
book, which summarizes most SQL statements covered in Chapters 3 through 9.
Because the book is primarily designed as a college text, it also includes (ex-
clusively for instructors) answers to the exercise questions as well as SQL queries
and PL/SQL blocks for the lab activities. The script to create both sample databases
is also included for the instructors.

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!

USING THE TEXT

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 . . .

● Y ou will learn about basic database terminology.


● Relational database concepts are covered.
● The D atabase Management System (DBMS) and its functions are outlined.
● I ntegrity rules and types of relationships are explained.
● Two theoretical relational languages for data retrieval, relational algebra
and relational calculus, are introduced.

DATABASE: AN INTRODUCTION

A database is an electronic store of data. I t is a repository that stores information


about different “things” and also contains relationships among those different
“things.” L et us examine some of the basic terms used to describe the structure of a
database:

● A person, place, event, or item is called an entity.


● The facts describing an entity are known as data. For example, if you were a
registrar in a college, you would like to have all the information about the
students. E ach student is an entity in such a scenario.
2 Chap. 1 Database Concepts: A Relational Approach

● 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. One- to-one r elationship: A one-to-one relationship is written as 1: 1 in


short form. I t exists between two entity sets, and , if an entity in entity
set has only one matching entity in entity set , and vice versa. For ex-
ample, a department in a college has one chairperson, and a chairperson
chairs one department in a college. A n employee manages one depart-
ment in a company, and only one employee manages a department.
2. One- to-many r elationship: A one- to-many relationship is written as 1:M. I t
exists between two entity sets, and , if an entity in entity set has
many matching entities in entity set but an entity in entity set has only
one matching entity in entity set In such a situation, a 1:M relationship ex-
ists between entity sets and . For example, a faculty teaches for one divi-
sion in a college, but a division has many faculty members. The relationship
Database Management System (DBMS) 3

between D I V I SI ON and FACU LTY is 1:M. A n employee works in a de-


partment, but a department has many employees. The relationship be-
tween D E PA R TME N T and E MPL OY E E is 1:M.
3. Many-to-many r elationship: A many-to-many relationship is written as
M: N or M: M. I t exists between two entity sets, and , if an entity in en-
tity set has many matching entities in entity set and an entity in entity
set has many matching entities in entity set . For example, a student
takes many courses, and many students take a course. A n employee works
on many projects, and a project has many employees.

Many times, students find it difficult to determine the type of a relationship.


You need to ask the following two questions to make the determination:

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 ?

If your answers to both questions ar e “No,” the relationship is a 1:1 relationship. I f


one of the answers is “Y es” and the other answer is “No,” it is a 1:M relation- ship.
If both answers are “Y es,” you have an M:N relationship. L ater, you will see that
the M:N relationship is not easy to i mplement and is decomposed into two 1:M
relationships.

DATABASE MANAGEMENT SYSTEM (DBMS)

The database system consists of the following components (see Fig. 1- 1):

● A database management System (D BMS) software package such as Mi-


crosoft Access, Visual Fox Pro, Microsoft SQL-Server, or Oracle.
● A user- developed and implemented database or databases that includes ta-
bles, a data dictionary, and other database objects.
● Custom applications such as data-entry forms, reports, queries, blocks, and
programs.
● C omputer hardware— personal computers, minicomputers, and mainframes in
a network environment.
● Software— an operating system and a network operating system.
● Personnel— a database administrator, a database designer/analyst, a pro-
grammer, and end users.

D ata are the raw materials. I nformation is processed, manipulated, collected, or


organized data. The information is produced when a user uses the applications to
4 Chap. 1 Database Concepts: A Relational Approach

DBMS

Figure 1-1 Database system.

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:

● I t manages the data and relationships stored in the database. I t creates a


D ata Dictionary as a user creates a database. The D ata D ictionary is a system
structure that stores M etadata (data about data). The Metadata include table
names, attribute names, data types, physical space, relationships, and so on.
● I t manages all day-to-day transactions.
● I t performs bookkeeping duties, so the user has data i ndependence at the
application level. The applications do not have information about data
characteristics.
● I t transforms logical data requests to match physical data structures. W hen a
user requests data, the RD BM S searches through the D ata D ictionary, fil-
ters out unnecessary data, and displays the results in a readable and under-
standable form.
● I t allows users to specify validation rules. For example, if only M and F are
possible values for the attribute gender, users can set validation rules to
keep incorrect values from being accepted.
● I t secures access through passwords, encryption, and restricted user rights.
● I t provides backup and recovery procedures for physical security of data.
● I t allows users to share data with data-locking capabilities.
● I t provides import and export utilities to use data created in other database or
spreadsheet software or to use data in other software.
The Relational Database Model 5

● I t enables users to join tables to view information stored in different tables


within the database. The user is able to design a database with less redun-
dancy, which means fewer data-entry errors, fewer data corrections, better
data integrity, and a more efficient database.

THE RELATIONAL DATABASE MODEL

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

ProjNo Loc Customer PROJ2003

1 Miami Stocks ProjNo Loc Customer


3 Trenton Smith 1 Miami Stocks
5 Phoenix Robins 2 Orlando Allen
6 Edison Shaw 3 Trenton Smith
7 Seattle Douglas 4 Charlotte Jones

PRJPARTS

ProjNo PartNo Qty


PARTS
1 11 20
2 33 5 PartNo PartDesc Vendor Cost
3 11 7 11 Nut Richards 19.95
1 22 10 22 Bolt Black 5.00
2 11 3 33 Washer Mobley 55.99

EMPLOYEE

EmpNo Ename DeptNo ProjNo Salary


DEPARTMENT
101 Carter 10 1 25000
DeptNo DeptName 102 Albert 20 3 37000
10 Production 103 Breen 30 6 50500
20 Supplies 104 Gould 20 5 23700
30 Marketing 105 Barker 10 7 75000

Figur e 1-2 Relational database tables.

Relational Terminology File System Terminology

Entity Set or Table or Relation File


Entity or Row or Tuple Record
Attribute or Column Field

Figur e 1-3 Terminology comparison.

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.

PROJ2002 (ProjNo, Loc,Customer) PROJ2003(ProjNo,Loc,


Customer) PRJPARTS(ProjNo, PartNo, Qty) PARTS(PartNo,
PartDesc, Vendor, Cost) DEPARTMENT(DeptNo, DeptName)
EMPLOYEE (EmpNo, Ename, DeptNo, ProjNo, Salary)

Figur e 1-4 Notation used for tables.


8 Chap. 1 Database Concepts: A Relational Approach

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:

N o column in a primary key may be null. The primary


key provides the means of uniquely identifying a row or an entity. A null
value means a value that is not known, not entered, not defined, or not ap-
plicable. A zero or a space is not considered to be a null value. If the pri-
mary key value is a null value in a row, we do not have enough information
about the row to uniquely identify it. The R D B M S software strictly fol-
lows the entity integrity rule and does not allow users to enter a row with-
out a unique value in the primary key column.
A foreign key value may be a null value, or it must
exist as a value of a primary key in the referenced table.

Referential integrity is not fully supported by all commercially available sys-


tems, but Oracle supports it religiously! Oracle does not allow you to declare a for-
eign key if it does not exist as a primary key in another table. I t allows you to leave
the foreign key column value as a null. If a user enters a value in the foreign key col-
umn, Oracle cross-references the referenced primary key column in the other table
to confirm the existence of such a value.
It is not a good practice to use null values in any non–primary key columns, be-
cause this results in extra overhead on the system’s part in search operations. The pro-
grammers or query users have to add extra measures to include or exclude rows with
null values. In certain cases, it is not possible to avoid null values. For example, an em-
ployee does not have a middle initial, an employee is hired but does not have an as-
signed department, or a student’s major is undefined. I n Oracle, a default value can be
assigned to a column, and a user does not have to enter a value for that column.

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

Relational algebra is a procedural language, because the user accomplishes desired


results by using a set of operations in a sequence. I t uses set operations on tables to
produce new resulting tables. These resulting tables are then used for subsequent se-
quential operations. I n Oracle, all operation names are not actually used as pro-
gramming terms, and most of these operations do not create a new resulting table, as
shown in the following examples using relational algebra.
The nine operations used by relational algebra are:

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:

● Both tables must have the same degree.


● The domains of the corresponding columns in two tables must be same.

Such tables are said to be . I n mathematical set theory, a


union can be performed on any two sets, but in relational algebra, a union can be
performed only on union- compatible tables.
Suppose we want to see all the projects from years 2002 and 2003. W e obtain it
by performing a union 1U 2 on the PROJ2002 and PROJ2003 tables as given in
Figure 1-2.
10 Chap. 1 Database Concepts: A Relational Approach

If we call the resulting table TA BL E _A , the operation can be denoted by

TABLE_A= PROJ2002U PROJ2003

TABLE_A

ProjNo Loc Customer


1 Miami Stocks
2 Orlando Allen
3 Trenton Smith
4 Charlotte Jones
5 Phoenix Robins
6 Edison Shaw
7 Seattle Douglas

Intersection. The intersection of two tables produces a table with rowsthat


are in both tables. The two tables must be union compatible to perform an in-
tersection on them.
If we use the same two tables that were used in the union operation, the inter-
section will give us the projects that appear in the year 2002 and in the year 2003.
L et us call the resulting table, which is produced by the intersection 1Æ2 operation,
TABLE_B:
TABLE_B = PROJ2002 PROJ2003

TABLE_B

ProjNo Loc Customer


1 Miami Stocks
3 Trenton Smith

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:

TABLE_C= PROJ2002 – PROJ2003 TABLE_C

ProjNo Loc Customer


5 Phoenix Robins
6 Edison Shaw
7 Seattle Douglas
Theoretical Relational Languages 11

Now, just as in mathematics, - is not equal to - . If we perform the


same operation to find projects from the year 2003 that did not exist in year 2002,

TABLE_D =PROJ2003– PROJ2002

the resulting TA BL E _D will look like this:


TABLE_D

ProjNo Loc Customer


2 Orlando Allen
4 Charlotte Jones

Projection. The projection operation allows us to create a table based on


desirable columns from all existing columns in a table. The undesired columns are
ignored. The projection operation returns the “vertical slices” of a table. The projec-
tion is indicated by including the table name and a list of desired columns:
TABLE_E =PARTS (PartDesc, Cost) TABLE_E

PartDesc Cost
Nut 19.95
Bolt 5.00
Washer 55.99

Selection. The selection operati on selects rows from a table based on a


condition or conditi ons. The conditional operators 1 = , 6 7 , 7 , 7 = , 6 , 6 = 2 and
the logical operators ( A N D , O R , NO T) are used along with columns and values to
create conditions. The selection operation returns “ hori zontal slices” from a table.
L et us apply the selection (Sel) operation to the PA RTS table:

TABLE_F =Sel (PARTS: Cost>10.00)

TABLE_F

PartNo PartDesc Vendor Cost


11 Nut Richards 19.95
33 Washer Mobley 55.99

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.

Product. A product of two tables is a combination everything in both ta-


bles. I t is also known as a Car tesian pr oduct. I t can cause huge results with big tables.
If the first table has rows and the second table has rows, the resulting product has
12 Chap. 1 Database Concepts: A Relational Approach

. 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 = EMPLOYEE • DEPARTMENT

TABLE_G

Ename DeptName
Carter Production
Carter Supplies
Carter Marketing
Albert Production
Albert Supplies
Albert Marketing

I n this example, E M PL O Y E E has two rows and D E PA RTM EN T three rows,


so TA BL E _G has 2 . 3 = 6 rows. E M PL O Y E E has one column and D E PA RT-
ME N T one column, so TA BL E _G has 1 + 1 = 2 columns.

Assignment. This operation creates a new table from existing tables. W e


have been doi ng it throughout all the other operations. A ssignment 1 = 2 gives us an
ability to name new tables that are based on other tables. N ote that assignment is
not an O racl e term.
For example,

TABLE_A = PROJ2002 U PROJ2003 TABLE_C= PROJ2002– PROJ2003

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

EmpNo Ename DeptNo ProjNo Salary DeptName


101 Carter 10 1 25000 Production
102 Albert 20 3 37000 Supplies
103 Breen 30 6 50500 Marketing
104 Gould 20 5 23700 Supplies
105 Barker 10 7 75000 Production

The expression is read as “join a row in the E M PL OY E E table with a row in


the D E PA RTM E NT table, where the D eptNo value in the E M PL O Y E E table is
equal to the D eptNo value in the D E PA R TME NT table.”
The join operation is an overhead on the system, because it is accomplished
using a series of operations. A product is performed first, which results in 5 3. = 15
rows. A selection is performed next to select rows where the D eptNo values are
equal. Finally, a projection is performed to eliminate duplicate D eptNo columns.
Division. The division operation is the most difficult operation to compre-
hend. I t is not as simple as division in mathematics. I n relational algebra, it identifies
rows in one table that have a certain relationship to all rows in another table. L et us
consider the following two tables:
PROJ

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.

Applications of Relational Algebra

Relational algebra is a procedural language in the sense that a user is required to


use a series of operations to obtain a certain result. This language has its capabilities
and limitations.
Pr oblem 1
Referring to the tables in Figure 1.2, which employee is working on a project in Miami
during the year 2003?
Solution

A = join(PROJ2003, EMPLOYEE : ProjNo = ProjNo) B =Sel(A :Loc =‘Miami’)


C = B(Ename)

Alternative solution

A = Sel(PROJ2003: Loc = ‘Miami’)


B = join(EMPLOYEE, A : ProjNo= ProjNo) C = B(Ename)

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

Relational calculus is a nonprocedural language. The programmer specifies the data


requirement, and the system generates the operations needed to produce a table
with the required data. I n this section, we will try to understand relational calculus
briefly with sample examples using the general syntax
Result =(column list) :Expression
The list of columns is on the left of the colon, and the expressions (and condi-
tions) are on the right.
Pr oblem 3
Referring to the tables in Figure 1.2, find projects where part number 11 is used.
Solution

(r.ProjNo) : r in PRJPARTS and r.PartNo = 11

In this expression, is known as a r ow variable. The expression is read as “ProjNo in


row , where is a row in the PRJPARTS table and PartNo in row is 11.” Each row
16 Chap. 1 Database Concepts: A Relational Approach

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:

M = Sel (PRJPARTS :PartNo =11)


N = M (ProjNo)

Problem 4
Referring to the tables in Figure 1.2, find employee names and salary for employees
who work in Production.
Solution

(r.Ename, r.Salary) : r in EMPLOYEE and


s in DEPARTMENT ands.DeptName = ‘Production’ and r.
DeptNo =s.DeptNo

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

(r.Ename, s.DeptName, t.Loc) : r in EMPLOYEE and


s in DEPARTMENT and t inPROJ2003and r.ProjNo=
1 and r.ProjNo = t.ProjNo andr.DeptNo =s.DeptNo

RESULT

Ename DeptName Loc


Carter Production Miami
In a Nutshell .. . 17

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

A relational database is an electronic data repository that is supposed to satisfy


users’ data requests correctly, quickly, and efficiently. Most end users execute appli-
cations that work on databases. The most important task for the database designer is
to create a properly designed database. I f the database is not designed well, it will
not be implemented well. The result is a nightmare for application developers. Even if
the application is well written, a defective database may result in incorrect and
sometimes meaningless results.
I n the first half of C hapter 2, we will study the fundamentals of database de-
sign and modeling techniques. I n the second half, we will learn the normalization
process to control data redundancies. If you have learned a programming language
before, you should be familiar with the tools used in the program development
cycle. I f you use a shortcut and create a wrong algorithm for a problem, you have to
start the cycle all over again to rectify your logic. D atabase design is also like pro-
gramming. The designing tools are aids for creating a “good” database. R emember
that the database is a collection of tables. D o not build individual tables; rather, de-
sign a database as a whole.

INA NUTSHELL. . .

● A database is an electronic store of data.


● A n entity is a person, place, event, or item.
● D ata are the facts describing an entity.
● A n entity’s characteristics are known as columns.
● A n entity set is a collection of related entities.
● A database is a collection of entity sets.
● Relationships are interactions between entity sets.
● Three types of relationships are one-to- one (1:1), one-to-many (1:M), and
many-to-many (M:N or M:M).
● I n a relational model, a row is known as a tuple.
● The degree is the number of columns in a table, and the domain is a set of all
possible values for a column.
● A primary key is a minimal set of columns used to uniquely define a row.
W hen a single column is used as a key, it is known as a primary key. When a
18 Chap. 1 Database Concepts: A Relational Approach

combination of columns is used as a key, it is known as a composite primary


key or a composite key.
● The foreign key is a column in a table that references a primary key in an-
other table.
● Two integrity rules of relational model are entity integrity (the primary key
may not be null) and referential integrity (the foreign key value may be null
or must exist as a primary key value in another table).
● Relational algebra is a theoretical procedural language for data retrieval. It
provides users with a set of operations such as union, intersection, differ-
ence, selection, projection, product, join, assignment, and division.
● Relational calculus is a nonprocedural relational language, which is the basis
for today’s popular relational database language Structured Query Language
(SQL).

EXERCISE QUESTIONS

1. Define the following terms:



a Entity.

b Entity set.

c Attribute.

d Tuple.

e Domain.

f K ey.

g Null.
2. W hat are two integrity rules of the relational model?
3. W hat are different types of keys? What is their use?
4. Identify the primary key and foreign key for the following tables. Also, specify the table
referenced by the foreign key. If a table does not have a foreign key, leave the entry
blank. ( Some tables have a composite primary key. Identify all composite key
columns for such tables.)

STUDENT (StudentId, Last, First,StartTerm, Birthdate, FacultyId, MajorId, Phone)


FACULTY (FacultyId,Name, RoomId, Phone,DeptId)
COURSE(CourseId, Title, Credits)
CRSSECTION (CsId, CourseId, Section, TermId,FacultyId, Day, RoomId)
REGISTRATION (StudentId, CsId, Midterm, Final)
ROOM (RoomType, RoomDesc)
TERM (TermId,TermDesc, StartDate, EndDate)
LOCATION (RoomId, Building, RoomNo, Capacity, RoomType)
MAJOR (MajorId, MajorDesc)
DEPARTMENT (DeptId, DeptName, FacultyId)
Chap. 1 ExerciseQuestions 19

Table Primar y Key For eign Key Tables R efer enced


STUDENT FACULTY COUR SE CRSSECTION R EGISTR ATIO N R OOM
TER M LOCATION MA JO R DEPARTMENT

5. Discuss different types of relationships, and provide examples.


6. W hat do we mean by union compatible? Which operations require tables to be union
compatible with each other?
7. State the difference between the following:

a U nion and intersection.

b Product and join.

c Selection and projection.
8. U sing the tables given in Figure 1-2, the relational database notation of tables is

PROJ2002(ProjNo, Loc,Customer) PROJ2003 (ProjNo, Loc, Customer) PARTS(PartNo, Vendor, Cost)


PRJPARTS(ProjNo, PartNo,Qty) DEPARTMENT (DeptNo, DeptName)
EMPLOYEE (EmpNo, Ename, DeptNo, ProjNo, Salary)

Retrieve the following information by using a series of relational algebraic operations


and also by using a relational calculus statement:

a All employee names.

b All employees working in department 20.

c All employees who are making $50,000 or more.

d All employees who are working in department 20 and also making more than $25,000.

e V endors who supplied parts for the project in Miami during the year 2003.
IN THISCHAPTER . . .

● Y ou will learn about database modeling techniques.


● Y ou will work with symbols and E - R diagrams (E R D ) for representation of
entities and relationships.
● Types of dependencies within a table are examined and illustrated by using
dependency diagrams.
● Reduction of data redundancy and the process of normalization are covered.

I n Chapter 1, you learned about relational database management system


(RD BM S) concepts. You also learned about theoretical languages and operations on
tables. The relational model is very popular because of its simplicity. I t shows data
to the user in a very simple, logical view as a two- dimensional table. A nyone can
create tables, but the strongest characteristic of the relational model is its ability to
establish relationships among tables, which helps to reduce redundancy. Your
queries are as good as the database you create. The first and foremost step in data-
base creation is database design, which involves a certain degree of common sense. I f
the given list of columns describes different entities, you would create a separate table
for each entity type. Y ou would use foreign keys to establish relationships. To join
two tables, you need at least one common or redundant column in both tables. A ll
situations are not the same. There are complex cases in which common sense
Data Modeling 21

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

A model is a simplified version of real-life, complex objects. D atabases are complex,


and data modeling is a tool to represent the various components and their relation-
ships. The entity- relationship (E - R ) model is a very popular modeling tool among
many such tools available today. Many tools are available for data modeling with E -R.
A ll tools have some variations in representation of components. The E - R model
provides:

● A n excellent communication tool.


● A simple graphical representation of data.

The E - R model uses E - R diagr ams (E R D ) for graphical representation of the


database components. A n entity (or an entity set) is represented by a rectangle. The
name of the entity (set) is written within the rectangle. Some tools prefer to use up-
percase letters only for entities. The name of an entity set is a singular noun. For ex-
ample, E MPL O Y E E , C U STO ME R , and D E PA R TME N T are singular entity set
names (see Fig. 2-1).
A line represents relationship between the two entities. The name of the relation-
ship is an active verb in lowercase letters. For example, and
are active verbs. Passive verbs can be used, but active verbs are preferable (see Fig. 2-2).

EMPLO Y EE

Figur e 2-1 Entity representation in an E-R diagram.

manages
1:1

employs
1:M

contains
M:N

Figur e 2-2 Representation of relationship in an E-R diagram.


22 Chap. 2 Database Design: Data Modeling and Normalization

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

Figur e 2-3 Entity, relationship, and connectivity.

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)

Figur e 2-4 Cardinality.


Data Modeling 23

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)

Figur e 2-5 Optional relationships.

I n relational databases, many- to-many (M:N) relationships are allowed, but


they are not easy to implement. For example, an invoice has many items, and an item
can be in many invoices. Refer to the I NV OI CE and I TE M relationship in Figure 2-4.
A t this point, you will be introduced to the relational schema, a graphical represen-
tation of tables, their column names, key components, and relations between the pri-
mary key in one table and the foreign key in another. Y ou will also see the
decomposition of an M:N relationship into two 1:M relationships. The decomposi-
tion from M:N to 1:M involves a third entity, known as a composite entity or an ass-
ociative entity. The composite entity is created with the primary key from both
tables with M:N relationships. The new entity has a composite key, which is a combi-
nation of primary keys from the original two entities. I n the E - R diagram, a com-
posite entity is drawn as a diamond within a rectangle (see Fig. 2- 6). The composite

has is a
IN VOICE INVITEM ITEM

(1,N) (1,1) (1,1) (1,N)

INVOI CENO INVOICENO ITEMN O


INVOICEDATE I TEMNO ITE MNAME

Figur e 2-6 Composite entity and relational schema.


24 Chap. 2 Database Design: Data Modeling and Normalization

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)

Figur e 2-7 Weak entity.

Some of the other elements considered in the database design are:

● 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

InvNo InvDate CustNo ItemNo CustName ItemName ItemPrice Qty


1001 04/14/03 212 1 Starks Screw $2.25 5
1001 04/14/03 212 3 Starks Bolt $3.99 5
1001 04/14/03 212 5 Starks Washer $1.99 9
1002 04/17/03 225 1 Connors Screw $2.25 2
1002 04/17/03 225 2 Connors Nut $5.00 3
1003 04/17/03 239 1 Kapur Screw $2.25 7
1003 04/17/03 239 2 Kapur Nut $5.00 1
1004 04/18/03 211 4 Garcia Hammer $9.99 5

Figure 2-8 I NVO ICE table and its columns.

There are three types of dependencies in a table:

A nonkey column dependent on all primary key


columns shows total dependency.
I n partial dependency, a nonkey column is dependent
on part of the primary key.
I n transitive dependency, a nonkey column is de-
pendent on another nonkey column.

For example, in the I N V O I C E table, ItemName and ItemPrice are nonkey


columns that are dependent only on a part of the primary key column ItemNo. They
26 Chap. 2 Database Design: Data Modeling and Normalization

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

Relational database design involves an attempt to the database structure


to get the “first draft.” The initial draft goes through an phase to improve
the structure. Mor e formal techniques are available for the analysis and improve-
ment of the structure. I n the synthesis phase, entities and their relationships are
identified. The characteristics or the columns of all entities are also identified, and
the designer defines the domains for each column. The candidate keys are picked,
and primary keys are selected from them. The minimal set of columns is used as a
primary key. I f one column is sufficient to uniquely identify an entity, there is no
need to select two columns to create a composite key. Avoid using names as primary
keys, and break down composite columns into separate columns. For example, a
name should be split into last name and first name. Once entities, columns, domains,
and keys are defined, each entity is synthesized by creating a table for it. A process
called nor malization analyzes tables created by the synthesis process.

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

A results when the deletion of information about one entity leads


to the deletion of information about another entity. For example, in Figure 2-8, if an
invoice for customer Garcia is removed, information about item number 4 is also
deleted. A n occurs when the information about an entity cannot
be inserted unless the information about another entity is known. For example, if
the company buys a new item, this information cannot be entered unless an invoice
Normal Forms 27

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).

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

InvNo InvDate CustNo ItemNo CustName ItemName ItemPrice Qty


1001 04/14/03 212 1 Starks Screw $2.25 5
3 Bolt $3.99 5
5 Washer $1.99 9
1002 04/17/03 225 1 Connors Screw $2.25 2
2 Nut $5.00 3
1003 04/17/03 239 1 Kapur Screw $2.25 7
2 Nut $5.00 1
1004 04/18/03 211 4 Garcia Hammer $9.99 5

Figur e 2-9 Unnormalized table with multivalued columns.


28 Chap. 2 Database Design: Data Modeling and Normalization

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.

Second Normal Form (2NF)

A table is said to be in second normal form, or 2NF, if the following requirementsare


satisfied:

● A ll 1NF requirements are fulfilled.


● There is no partial dependency.

A s you already know, partial dependency exists in a table in which nonkey


columns are partially dependent on part of a composite key. Suppose a table is in
1NF and does not have a composite key. Is it in the second normal form also? Y es, it is
in 2NF, because there is no partial dependency. Partial dependency only exists in a table
with a composite key.

Third Normal Form (3NF)

A table is said to be in third normal form, or 3NF, if the following requirements are
satisfied:

● A ll 2NF requirements are fulfilled.


● There is no transitive dependency.

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.

Conversion from 1NF to 2NF

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.

InvNo InvDate CustNo CustName ItemNo ItemName ItemPrice Qty

Partial Dependency Partial Dependency

Transitive Dependency

Figur e 2-10 Dependency diagram.

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,

INVO ICE InvNo

ITEM INVITEMItemNo

InvNo ItemNo

Figur e 2-11 1NF-to-2NF decomposition.


30 Chap. 2 Database Design: Data Modeling and Normalization

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.

InvNo InvDate CustNo CustName

ItemNo ItemName ItemPrice

InvNo ItemNo Qty

Figur e 2-12 Tables in 2NF.

Conversion from 2NF to 3NF

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:

● Move columns with the transitive dependency to a new table.


● Keep the primary key of the new table as a foreign key in the existing table.

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

CUSTOMER ITEM INVITEM


CustNo

ItemNo

InvNo ItemNo

Figur e 2-13 2NF-to-3NF decomposition.

InvNo InvDate CustNo

CustNo CustName

ItemNo ItemName ItemPrice

InvNo ItemNo Qty

Figur e 2-14 Tables in 3NF.


32 Chap. 2 Database Design: Data Modeling and Normalization

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.

ANOTHER EXAMPLE OF NORMALIZATION

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:

● Total dependency— JerseyNum, PointsScoredI nYear, GamesPlayed, TeamI d,


TeamName, and TeamLoc columns are dependent on primary key columns
PlayerI d and Year. A player may wear a different jersey number with same
team or with a different team. Player may play for different team every year.
● Par tial dependency— PlayerName and BirthD ate columns are dependent on
primary key column PlayerId only.
● Tr ansitive dependency— TeamName and TeamLoc columns are dependent on
non–key column TeamId. Fig 2-16.

1NF to 2NF (Removing Partial Dependencies)

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.

2NF to 3NF (Removing Transitive Dependencies)

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

The normalization process is not very easy to understand. I n my classroom, some


students find it very difficult. The process is based on common sense. A table is
Playerid Playername Year JerseyNum BirthDate PointsScoredinYear GamesPlayed Teamid TeamName TeamLoc
1 JOHNSON 2001 32 4/15/1980 150 5 1 MUSTANGS BRONX
1 JOHNSON 2002 32 4/15/1980 174 6 1 MUSTANGS BRONX
1 JOHNSON 2003 32 4/15/1980 115 5 1 MUSTANGS BRONX
2 NAMAN 2001 10 12/2/1985 100 3 1 MUSTANGS BRONX
2 NAMAN 2002 10 12/2/1985 149 6 2 DEVILS PRINCETON
2 NAMAN 2003 10 12/2/1985 185 6 5 EAGLES BRUNSWICK
3 SHAW 2001 11 5/10/1986 99 5 4 BEARCATS FORDS
3 SHAW 2002 11 5/10/1986 97 6 4 BEARCATS FORDS
3 SHAW 2003 3 5/10/1986 115 6 6 KINGS MANHATTAN
4 ALBERT 2003 33 5/19/1983 29 3 3 BULLDOGS MONROE
5 ANTHONY 2001 21 1/19/1979 110 6 3 BULLDOGS MONROE
5 ANTHONY 2002 21 1/19/1979 78 4 3 BULLDOGS MONROE
5 ANTHONY 2003 33 1/19/1979 111 5 1 MUSTANGS BRONX
6 RICHARDS 2003 33 7/10/1977 63 6 2 DEVILS PRINCETON
7 ROBERTS 2003 55 6/6/1981 44 6 5 EAGLES BRUNSWICK
8 JONES 2001 2 12/31/1981 123 6 6 KINGS MANHATTAN
8 JONES 2002 2 12/31/1981 100 6 4 BEARCATS FORDS
9 JORDAN 2003 23 2/17/1986 101 2 1 MUSTANGS BRONX

Figur e 2-15 Table in 1NF.


33
34 Chap. 2 Database Design: Data Modeling and Normalization

1NF to 2NF

PLAY ER PlayerId PlayerName BirthDate

PLAY ERY EAR PlayerId Y ear JerseyNum PointsScored GamesPlayed


InY ear

TeamId TeamName TeamLoc

2NF to 3NF

PLAY ER Player Id PlayerName BirthDate

TEAM TeamId TeamName TeamLoc

PLAY ERY EAR PlayerId Year JerseyNum PointsScored


InY ear

GamesPlayed TeamId

Figur e 2-16 Tables in 2NF and 3NF.

supposed to describe one entity. If a table describes multiple entities, it needs to be


decomposed. W hen tables are decomposed, there should be enough foreign keys to
establish relationships among tables. Y ou should not end up with a table that is not
related to any other table in the database. A player’s name has nothing to do with
the year or the team he or she plays for, so it depends on the player’s I D only. (In
professional sports like the NBA , there are players who have changed their name!
W e have to treat those cases as exceptions, and we do not design something just to
support such exceptions.) How many points did Jordan scored in 2002? To get that
information, you need the player’s I D as well as the year. W e find new things to be
complicated at first, but practice makes a man (or a woman) perfect. There is anoth- er
problem on normalization in the exercise section. G o ahead and give it a try.

INA NUTSHELL. . .

● A model is a simplified version of real-life, complex objects.


● The entity- relationship (E - R ) diagram is an excellent communication tool
that represents a database graphically.
● I n an E- R diagram, an entity (set) is represented by a rectangle with the
name of the entity set written as an uppercase, singular noun.
● A n E - R diagram represents a relationship as an active verb inside a dia-
mond- shaped box.
Chap. 2 Exercise Questions 35

● 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

Define the Following Ter ms:


1. Partial dependency.
2. Transitive dependency.
3. Normalization.
4. D ata anomalies.
5. Cardinality.

E-R Diagram Exercise:


1. A student takes many courses, and many students take a course. Create an E-R diagram
to represent the entities, connectivity, and cardinality. Decompose the E- R diagram with
a composite entity to reduce each M:N relationship to two 1:M relationships. Also, draw
the relational schema for the database.

Dependency Diagram Exercise:


EMP

EMPID LAST FIRST DEPTID DEPTNAME DEPENDENTNO DEPENDENTSSN DEPENDENTDOB

1. Create a dependency diagram for the set of given columns for the EM P table:

EM PI D LAST FIRST Employee’s ID Employee’s last name


D EPTI D Employee’s first name
D EPTNA ME Employee’s department number
D EPEN DEN TNO Employee’s department name
D EPEN DENTSSN Employee’s number of dependents
D EPE NDE NTD OB Dependent’s Social Security number
Dependent’s date of birth

The primary key columns are EM PI D and DEPEND EN TNO.

Normalization Exer cise:


1. U sing the dependency diagram of the EMP table from the previous exercise, normalize
the table to 3NF. U se 1NF-to-2NF and then 2NF-to-3NF conversion.
PART 2
ORACLE
SQL

IN THIS CHAPTER ...

● 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)

- Gets file requests from clients


- Sends files to clients
- Receives files back

Client Computer #1 Client Computer #2

(DBMS, Client Application) (DBMS, Client Application)

- Sends file request - Sends file request


- Receives files - Receives files
- Adds, deletes, updates data - Adds, deletes, updates data
- Sends files back - Sends files back

Figur e 3-1 A personal database system in a multiuser environment.

Demand on Client and Network

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

When a client is performing record insertions, deletions, or updates, those records


are locked by that client and are not available to the other clients. Now, if the client
with all the record locks fails because of software or hardware malfunction or a
power outage, the locked records stay locked. The transactions in progress at the
time of failure are lost. The database can get corrupted and needs to be repaired. To
repair the database, all users have to log off during the repair, which can take any-
where from a few minutes to a few hours! I f the database is not repairable, data can
be restored from the last backup, but the transactions since the last backup are lost
and have to be reentered.

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)

- Gets data requests from clients


- Adds, deletes, updates, filters data

Client Computer #1 Client Computer #2

(Client Application) (Client Application)

- Sends data request - Sends data request


- Receives results - Receives results
- Sends new data - Sends new data

Figur e 3-2 A client/server database system in a multiuser environment.

Demand on Client and Network

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

Oracle9i components include Oracle9i Database, Oracle9i A pplication Server,


and Oracle9i Developer Suite. Oracle9i D atabase introduces Oracle9i R eal A ppli-
cation Cluster, which replaces Oracle Parallel Server, and features integrated sys-
tem management, high availability, powerful disaster recovery, system fault
recovery, planned downtime, and high security. Oracle9i A pplication Server is in-
dustry’s preferred application server for database- driven W eb sites, with an innova-
tive and comprehensive set of middle- tier services. Oracle9i D eveloper Suite, an
integrated product, provides a high- performance development environment with
tools like Oracle Forms D eveloper, Oracle D esigner, Oracle JDeveloper, Oracle
R eports Developer, and Oracle D iscoverer. Some of the Oracle9i tools include:

● * — The SQL * Plus environment is for writing command- line SQL


queries to work with database objects such as tables, views, synonyms, and
sequences.
● — PL/SQL is Oracle’s extension to SQL for creating procedural
code to manipulate data.
● — This tool is used for developing database applications and
includes:
● — a Java development tool.
● — to model business processes and generate Enterprise applica-
tions.
● — a developement tool for I nternet and client/server–
based environments.
● — a report generation tool.
● — A tool for managing users and databases. Enterprise
Manager uses the following tools:
● — to create and manage “tablespaces.”
● — to start, stop, or tune databases.
● — to create and manage users, profiles, and roles.
● — to manage data warehousing applications.
● — to render traditional database data as XML
for e-business support.
● — to enter, edit, and execute SQL * Plus code or to run client-
side scripts.
● i * — a W eb-based environment to execute SQL * Plus code.
● — A tool for creating a W eb site
that allows users to access Oracle databases through W eb pages. I t includes:
● .
Structured Query Language (SQL) 43

THE SQL* PLUS ENVIRONMENT

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.

STRUCTURED QUERY LANGU AGE (SQL)

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

I n a few books, the SEL E C T statement is treated as a subset of D ML lan-


guage. I have chosen to separate the SE L E C T statement from other D M L state-
ments, because it does not perform any manipulation on data.
The SQL queries are typed at the SQL 7 prompt. If a query exceeds one line,
the SQL * Plus environment displays the next line number on the line editor. A n SQL
query is sent to the server by ending a query with a semicolon (;). A query can also
be sent to the server by using a forward slash (/) on a new line instead of ending the
query with a semicolon.

LOGGING IN TO SQL* PLUS

I n the Windows environment, click Star t | Pr ogr ams | Or acle - O rahome92


| A pplication Development | SQ L Plus (see Fig. 3-3). A Log on window will pop
up. E nter your Username, Password, and H ost String as provided by your D atabase
A dministrator (see Fig 3- 4).
I n a command- line environment such as DOS, type sqlplus [user name [/pass-
wor d [ @host/database]] ] to log in. If the entire command is typed, the password will
be visible on the screen. If you enter your username only, a prompt will be displayed

Figure 3-3 Running SQL *Plus.


Logging in to SQL *PLUS 45

Figure 3-4 SQL * Plus Log On window.

Figur e 3-5 Running SQL *Plus from MS-DOS prompt.

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

User should consult D BA (students should consult their instructor or academic


computing personnel) to resolve username/password problems.
46 Chap. 3 Oracle9i: An Overview

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.

Figure 3-6 SQL* Plus environment— SQL prompt.

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).

SQL* PLUS C OMM A ND S

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

SQL SQL* Plus

1. A nonprocedural language to communicate with 1. A n environment for executing SQL statements.


the Oracle server.
2. ANSI standard. 2. Oracle’s proprietary environment.
3. Key words cannot be abbreviated. 3. Key words can be abbreviated.
4. Last statement is stored in the buffer. 4. Commands are not stored in the buffer.
5.Statements manipulate data and table structures 5.Commands do not allow manipulation of data in
in the database. the database.
6.Uses a termination character to execute the 6. Commands do not need a termination character.
command immediately.

Figure 3-7 SQL queries versus SQL * Plus commands.

Figur e 3-8 PASSWORD command.

COM MAND DESCRIPTION

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.

Figure 3-9 SQL* Plus file-related commands.


48 Chap. 3 Oracle9i: An Overview

CO MMAND DESCRIPTION

APPEND Adds text to the end of the current line.


CHANGE / / Changes old text to new text in the current line.
CHANGE / / Deletes text from the current line.
CLEAR BUFFER Deletes all lines from the SQL buffer.
DEL Deletes current line.
DEL Deletes line .
DEL Deletes lines through .
INPUT Inserts an indefinite number of lines.
INPUT Inserts a line of text.
LIST Lists all lines from the SQL buffer.
LIST Lists line .
LIST Lists lines through .
RUN Displays and runs an SQL statement in the buffer.
Makes line current.
Replaces line with text.
Inserts a line before line 1.
CLEAR SCREEN Clears screen.

Figur e 3-10 SQ L* Plus editing commands.

SQL Queries SQL Queries


Buffer

SQL* Plus
Server

SQL*Plus
Commands Result

Formatted Report

Figur e 3-11 Interaction between SQL* Plus and SQL.

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

ORACLE ERRORS A ND ONLINE HELP

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.

ALTERNATE TEXT EDITORS

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

Figur e 3-12 Oracle9i online documentation— index page.

SQL> HELP INDEX


Enter Help [topic] for help.
@ COPY PAUSE SHUTDOWN
@@ DEFINE PRINT SPOOL
/ DEL PROMPT SQLPLUS
ACCEPT DESCRIBE QUIT START
APPEND DISCONNECT RECOVER STARTUP
ARCHIVE LOG EDIT REMARK STORE
ATTRIBUTE EXECUTE REPFOOTER TIMING
BREAK EXIT REPHEADER TTITLE
BTITLE GET RESERVED WORDS (SQL) UNDEFINE
CHANGE HELP RESERVED WORDS (PL/SQL) VARIABLE
CLEAR HOST RUN WHENEVER OSERROR
COLUMN INPUT SAVE WHENEVER SQLERROR
COMPUTE LIST SET
CONNECT PASSOWORD SHOW
SQL> HELP DESCRIBE DESCRIBE

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>

Figur e 3-13 SQL * Plus help.


SQL *Plus Worksheet 51

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).

Figure 3-14 Alternate editor.

SQL* PLUS WORKSHEET

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

Figure 3-15 SQL* Plus worksheet.

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:

● The sqlplus system variable SQL PR OMPT is disabled by default.


● The sqlplus system variable SQL N U M B ER is set to OF F by default.
SQL *Plus Worksheet 53

Figure 3-16 Input/output in SQL* Plus worksheet.

● The sqlplus system variable PA GE SI ZE is set to its maximum by default.


● The sqlplus system variable TA B is set to OF F by default.
● If there are any prompt characters “ & ” in a script, SQL * Plus treats it as a
“define” prompt. (Y ou will see more on D E FI N E later.)
● The HO ST command is not supported in SQL * Plus W orksheet.
● The SQL * Plus user variable _ E D I TO R is disabled by default. If you enable
it by using “ D E FI N E _ E D I TO R = ‘editorname’,” the specified editor
launches on the server when you type the E D I T command. A s a result, you
are unable to access normal SQL * Plus Worksheet functionalities.
● R emote execution is not supported.
● R emote load and save of script files is not supported.
54 Chap. 3 Oracle9i: An Overview

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

I n this U R L , is your machine, but port number is not required in all


versions.
I n Figure 3- 17, the following U R L is used:
http://nshah-monroe/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-17 SQL* Plus login screen.


iSQL*Plus 55

port/isqlplus or https://localhost:port/isqlplus U R L can be used. Oracle installer pro-


vides the port number to access HTTP (Apache) server at the installation time.
I n Figure 3-18, a sample SQL query is executed in the SQL * Plus work screen.
The output is at the bottom. This environment also provides the user with options to
execute- commands, save or load scripts, check command history, and more. A nother
benefit of this environment is the buttons on the top right, such as the Help buttton to
connect to Oracle’s online help, the History button to browse and select com-
mand history, and so on.
I n this text, most of the screen shots are from the SQL * Plus environment. The
SQL Plus W orksheet and SQL * Plus environments are migrations to graphical and
*

Figure 3-18 SQL * Plus work screen with query and result.
56 Chap. 3 Oracle9i: An Overview

Web-based environments, respectively, which are more popular environments than


the command-based predecessors.

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 Indo–US (IU) College Student Database

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

FACULTY (FacultyId, Name, RoomId, Phone, DeptId)


FacultyId Name RoomId Phone DeptId
111 Jones 11 525 1
222 Williams 20 533 2
123 Mobley 11 529 1
235 Vajpayee 12 577 2
345 Sen 12 579 3
444 Rivera 21 544 4
555 Chang 17 587 5
333 Collins 17 599 3

COURSE (CourseId, Title, Credits)

CourseId Title Credits PreReq


EN100 Basic English 0
LA123 English Literature 3 EN100
CIS253 Database Systems 3
CIS265 Systems Analysis 3 CIS253
MA150 College Algebra 3
AC101 Accounting 3

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

TERM (TermId, TermDesc, StartDate, EndDate) ROOM (RoomType, RoomDesc)

TermId TermDesc StartDate EndDate RoomType RoomDesc


SP02 Spring 2002 04/28/2002 08/16/2002 L Lab
FL02 Fall 2002 09/08/2002 12/20/2002 C Classroom
WN03 Winter 2003 01/05/2003 04/18/2003 O Office
SP03 Spring 2003 04/27/2003 08/15/2003
FL03 Fall 2003 09/07/2003 12/19/2003

REGISTRATION (StudentId, CsId, Midterm, Final, DEPARTMENT (DeptId, DeptName, FacultyId)


RegStatus)
DeptId DeptName FacultyId
StudentId CsId Midterm Final Status 1 Computer Science 111
00100 1103 C F R 2 Telecommunications 222
00100 1102 B B R 3 Accounting 333
00100 1104 B A R 4 Math & Science 444
00102 1102 F D R 5 Liberal Arts 555
00102 1103 A A R
00103 1101 F W W
00103 1104 D D R MAJOR (MajorId, MajorDesc)
00100 1207 X
00103 1206 W MajorId MajorDesc
00104 1206 X 100 AAS-Accounting
00104 1207 R 200 AAS-Computer Science
00104 1210 R 300 AAS-Telecommunications
00105 1208 R 400 BS-Accounting
00105 1209 X 500 BS-Computer Science
00101 1205 X 600 BS-Telecommunications
00102 1210 R
00102 1207 X
00102 1206 R
Figur e 3-19 Sample tables for the Indo–US College database
Sample Databases 59

LOCATION (RoomId, Building, RoomNo, Capacity, RoomType)

RoomId Building RoomNo Capacity RoomType


11 Gandhi 101 2 O
12 Gandhi 103 2 O
13 Kennedy 202 35 L
14 Kennedy 204 50 L
15 Nehru 301 50 C
16 Nehru 309 45 C
17 Gandhi 105 2 O
18 Kennedy 206 40 L
19 Kennedy 210 30 L
20 Gandhi 107 2 O
21 Gandhi 109 2 O

Figur e 3-19 Sample tables for the Indo–US (IU ) College database

The STU D E N T table contains demographic information. StudentId is used as


a primary key field. Social Security numbers could have been used as the primary
key, but a system- generated StudentI d is used instead. Because of security issues, all
student- related reports use StudentId instead of Social Security number. The table
contains FacultyId as a foreign key, which references the FA CULTY table to keep
track of student advisors’ information throughout the curriculum. A nother foreign
key, MajorId, uses the M A JOR table for a description of students’ majors. A third
foreign key, StartTerm, keeps track of each student’s entry term into the college.
The FA CUL TY table contains location, phone extension, and department infor-
mation for faculty members identified by a FacultyI d, the table’s primary key. To get
further information, the D eptI d foreign key field is used for departmental or chair-
person’s data from the D E PA RTM E NT table. Similarly, the RoomI d field is used to
get the building and room number of the faculty offices.
The C OU R SE table (primary key, CourseId) is the course master, with course
title and credit information. The prerequisite information is kept in the Pr eR eq col-
umn, which serves as a foreign key and references the primary key of the same
C OU R SE table. I t is not very common for a foreign key to reference the primary
key of its own table. A self- join operation is used to join such a table to self.
E ach term and its dates are enter ed in the TE R M table. A n abbreviated term
and year are used together to create four- character primary key, such as W N03 for
the W inter 2003 term. Normally, numeric columns are prefered for the primary key,
but for our purposes, we are intentionally using a character column as a primary
key. The L OC A TI O N table with a unique R oomI d serves multiple purposes by
keeping all types of rooms: I t helps academic departments in locating an available
room for a new course section, and the room capacity helps the academic adminis-
tration in scheduling classes with maximum allowable enrollment less than or equal
to the room capacity.
60 Chap. 3 Oracle9i: An Overview

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

Figure 3-20 Indo–US (IU) College database E-R diagram.

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.

The NamanNavan (N2) Corporation Employee Database

The NamanNavan (N2) Corporation is an up-and-coming name in the Information


Systems field. They are distributors of computer hardware and software and
providers of computer-related services. Recently, they have joined the W eb market-
ing community with a broad product line. The management feels it is the right time
for a changeover from an existing hard copy, paper-only system to a more sophisti-
cated system to track their employees’ basic information and the company’s organi-
zational structure, payroll, raises, and promotion-related issues. The tables shown in
Figure 3-21 are created for the corporation’s database, and Figure 3-22 illustrates
the E - R diagram.
The N2 Corporation database contains six tables to describe all employee- related
information. The E M PL O Y E E table describes each employee in the company. Each
employee is identified by a unique EmployeeI d, which is the primary key for the
table. The basic columns for the employee include the employee’s last name, first
name, immediate supervisor, date of hire for keeping track of anniversary and sen-
iority, yearly salary, commission for the year, and other company-related informa-
tion. This table includes four foreign keys. PositionId is a foreign key that references
a lookup POSI TI O N table to retrieve an employee’s position/job title in the compa-
ny. The D eptI d is another foreign key to retrieve a department’s name, location, and
information about the manager. The third foreign key field, QualId, enables the

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

POSITION (PositionId, PosDesc) DEPT (DeptId, DeptName, Location, EmployeeId)

PositionId PosDesc DeptId DeptName Location EmployeeId


1 President 10 Finance Charlotte 123
2 Manager 20 InfoSys New York 543
3 Programmer 30 Sales Woodbridge 135
4 Accountant 40 Marketing Los Angeles 246
5 Salesman

QUALIFICATION (QualId, EMPLEVEL(LevelNo, LowSalary,


QualDesc) HighSalary)

QualId QualDesc Level-No LowSalary HighSalary


1 Doctorate 1 1 25000
2 Masters 2 25001 50000
3 Bachelors 3 50001 100000
4 Associates 4 100001 500000
5 High School

DEPENDENT (EmployeeId, DependentId, DepDOB,


Relation)

EmployeeId DependentId DepDOB Relation


543 1 09/28/58 Spouse
543 2 10/14/88 Son
200 1 06/10/76 Spouse
222 1 02/04/75 Spouse
222 2 08/23/97 Son
222 3 07/10/99 Daughter
111 1 12/12/45 Spouse

Figur e 3-21 Sample tables for NamanNavan (N2) Corporation’s employee database

company to keep a record of an employee’s highest qualification. The fourth foreign


key, Supervisor, references the E mployeeId column in the same table, another can-
didate for the self- join.
The D E PT table, another important table in the database, includes demograph-
ic information about the department’s name and primary location as well as the man-
ager responsible for managing day-to-day operation. Each department is identified
by a unique D eptI d as a primary key. The D E PT table also contains an EmployeeI d
column as a foreign key to keep information about the department’s manager.
The E M PL E V E L table has different grades based on the salary range as de-
fined by the company. A n employee belongs to a certain level or grade based on his or
her salary. There is no direct relationship between the E M PL EV E L and EMPLOY -
E E tables, but a type of join called nonequijoin enables user to join these two tables.
Sample Databases 63

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

Figur e 3-22 N2 Corporation database E-R diagram.

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 . . .

● Personal database management systems (DBMSs) are stored on a client


computer and are meant for single users.
● A client/server D BMS runs on a server, and user applications run on the
client computers.
● Personal databases are characterized by heavy hardware demands, heavy
network traffic, database corruption, transaction losses, and poor recovery
mechanisms.
● Client/server databases have better recovery mechanisms.
● Client/server databases provide automatic tables and record- level locking.
● Client/server databases provide file-based transaction logging for recovery of
transactions in case of a failure.
● Oracle9i is a popular client/server database management system that is
based on the relational model.
● The Oracle9i environment provides utilities to work with database tables;
developing forms, reports, and graphs; managing users and databases; and
interfacing the Web and databases.
● Structured Query Language (SQL ) is a standard, nonprocedural language to
work with relational database tables.
● SQL * Plus is Oracle’s proprietary environment to enter SQL queries.
● SQL is a language with data retrieval, D ML, D D L , DCL, and transaction
control query statements.
● SQL * Plus is an environment that provides users with editing, file, format-
ting, execution, and interaction commands.
● The SQL * Plus Worksheet environment is an alternative to the line-based
SQL * Plus environment, with full- page editing and G U I features.
● SQL * Plus is a W eb- based alternative to SQL * Plus that can be used through a
W eb browser.
Chap. 3 Exercises Questions 65

● The I U College’s student database system contains student, faculty, course,


course section, and registration information. I t includes the following tables:
● STU D E N T

● 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

● The NamanNavan (N2) Corporation’s employee database system contains


employee, department, and dependent information in the following tables:
● E MPLO Y E E

● 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:

SQL> CREATE TABLE dept (DeptId NUMBER (2),


2 DeptName VARCHAR2 (15) NOT NULL,
3 Location VARCHAR2 (12),
4 EmployeeId NUMBER (4),
5 CONSTRAINT dept_deptid_pk PRIMARY KEY (deptid));

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

What is displayed by the command?


7. Exit from the SQL *Plus environment. How will you exit? Do you click on X to close win-
dow or use an SQL *Plus command?
IN THIS CHAPTER. . .

● Y ou will learn about D ata Definition Language ( D D L ) statements to work


with the structure of an Oracle database table.
● V arious data types used in defining columns in a database table are dis-
cussed.
● I ntegrity and value constraints and their inclusion in a C RE A TE TA B L E
statement at the column and table level are outlined.
● V iewing, modifying, and removing a table’s structure are also covered.

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.

Valid Names Invalid Names

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)

Figur e 4-1 Valid/invalid table and column names.

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

The V A R C HA R 2 type is a character data type to store variable- length alphanu-


meric data in a column. Currently, V A R C H A R is synonymous with V A RC HA R 2,
but it could be a separate data type with different semantics in the future. U sers
ar e advised to use V A R C HA R 2 only. A maximum size must be specified for this
type. The default and mini mum size is one character. The maximum allowable
size is 4000 characters in Oracle9i. (The maximum size was 2000 characters
in previous versions.) The size is specified within parentheses— for example,
V A R C HA R 2(20). If the data are smaller than the specified size, only the data
value is stored, and trailing spaces are not added to the value. For example, if a col-
umn N A M E is assigned a data type V A R CHA R2(25) and the name entered is
Steve Jones, only 11 characters are stored. Four teen spaces are not added to make
its length equal to the size of the column. If a value longer than the specified size
is entered, however, an error is generated. The longer values are not truncated.
V A R C HA R 2 is the most appropriate type for a column whose values do not have
a fixed length.
In Oracle9i, the V A RC HA R2 data type can also take C H A R or B Y TE param-
eters. For example, V A R CH A R2(10 B Y TE ) is same as VA RCHA R2(10) because
byte is the default. If V A RC HA R 2(10 C H A R ) is used, each C HA R may take up 1
to 4 bytes. I n this text, you will see the default semantic only.

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:

L ONG. The L O NG type is used for variable-length character data up to 2


gigabytes. There can be only one L O NG- type column in a table. I t is used to
store a memo, invoice, or student transcript in the text format. W hen defining
to L O NG type, there is no need to specify its size.
NC HA R . The N C HA R type is similar to C H A R but uses 2- byte binary
encoding for each character. The C HA R type uses 1- byte A SCII encoding for
each character, giving it the capability to represent 256 different characters.
The N C H A R type is useful for character sets such as Japanese Kanji, which
has thousands of different characters.
CL O B. The Character Large Object data type is used to store single-byte
character data up to 4 gigabytes.
BL OB. The Binary Large Object data type is used to store binary data up to
4 gigabytes.
NC L OB. The character Large Object type uses 2-byte character codes.
BFI L E . The Binary File type stores references to a binary file that is external
to the database and is maintained by the operating system’s file system.
RA W (size) or L ONG_R AW . These are used for raw binary data.
RO W I D . For unique row address in hexadecimal format.

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)

Data Type Use

VARCHAR2 (size) Variable-length character data: 1 to 4000


characters
CHAR (size) Fixed-length character data: 1 to 2000 characters
NUMBER (p) Integer values
NUMBER (p, s) Fixed-point decimal values
NUMBER Floating-point decimal values
DATE Date and time values
LONG Variable-length character data up to gigabytes
NCHAR Similar to CHAR; uses 2-byte encoding
BLOB Binary data up to 4 gigabytes
CLOB Single-byte character data up to 4 gigabytes
NCLOB Similar to CLOB ; supports 2-byte encoding
BFILE Reference to an external binary file
RAW (size) Raw binary data up to 2000 bytes
LONG_RAW Same as RAW; stores up to 2 gigabytes
ROWID Unique address of a row in a table

Figur e 4-2 Data types and their use.

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

There are two types of constraints:


define both the primary key and the foreign key
with the table and primary key it references.
define if NU L L values are disallowed, if U N I QU E val-
ues are required, and if only certain set of values are allowed in a column.

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

Figure 4-3 Popular constraint abbreviations.

For example, a constraint name refers to a constraint in table


E M P on column D eptNo of type foreign key. A constraint name is
for a primary key constraint in table D E PT on column DeptNo.
If you do not name a constraint, the Oracle server will generate a name for it
by using format, where is any unique number. For example,
is an Oracle server–named constraint. These names are not user friendly like user-
named constraints.

Def ining a Constraint

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:

1. A column-level constraint references a single column and is


defined along with the definition of the column. A ny constraint can be de-
fined at the column level except for a FO R E I G N K E Y and composite pri-
mary key constraints. The general syntax is

(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)

2. A table-level constraint references one or more columns and


is defined separately from the definitions of the columns. Normally, it is
written after all columns are defined. A ll constraints can be defined at the
table level except for the N OT N U L L constraint. The general syntax is:

The PRI MARY KEY Constraint. The PRI M A RY K E Y Constraint is also


known as the entity integrity constraint. I t creates a primary key for the table. A
table can have only one primary key constraint. A column or combination of
columns used as a primary key cannot have a null value, and it can only have unique
values. For example, the D E PT table in the N2 Corporation database used the DeptI d
column as a primary key. A t the column level, the constraint is defined by

DeptId NUMBER (2) CONSTRAINT dept_deptid_pk PRIMARY KEY,

A t the table level; the constraint is defined by

CONSTRAINT dept_deptid_pk PRIMARY KEY(DeptId),

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:

CONSTRAINT dependent_emp_dep_pk PRIMARY KEY(Employeeld, DependentId),

The FOREIGN KEY Constraint. The FO R E I GN K E Y constraint is also


known as the referential integrity constraint. I t uses a column or columns as a foreign
key, and it establishes a relationship with the primary key of the same or another
table. For example, FacultyId in the STU D E NT table in the I U College database
references the primary key FacultyId in the FA CU LTY table. The STU D E N T table
is known as the dependent or child table, and the FA CU LTY table is known as the
referenced or parent table.
To establish a foreign key in a table, the other referenced table and its primary
key must already exist. Foreign key and referenced primary key columns need not
have the same name, but a foreign key value must match the value in the parent
table’s primary key value or be NULL . For example, the foreign key FacultyId can-
not have value 999 in the STU D E NT table, because it does not exist in the FACU LTY
(parent) table’s primary key FacultyId.
Oracle does not keep pointers for relationships, but they are based on con-
straints and data values within those columns. The relationship is purely logical and
is not physical in Oracle. A t the table level (in the STU D E NT table),

CONSTRAINT student_facultyid_fk FOREIGN KEY(FacultyId) REFERENCES faculty(FacultyId),

Before ending a FO R E I GN K E Y constraint, ON D E L E T E C A SCA D E can


be added to allow deletion of a record/row in the parent table and deletion of the
Constraints 75

dependent rows/records in the child table. Without the ON D E L E TE CA SC A D E


clause, the row/record in the parent table cannot be deleted if the child table references
it. For example, the row for FacultyId 111 cannot be deleted from the FACU LTY table,
because it is referenced by a row in the STU D E N T table.

The NOT NULL Constraint. The NO T NU L L constraint ensures that the


column has a value and the value is not a null (unknown or blank) value. A space or
a numeric zero is not a null value. There is no need to use the not null constraint for
the primary key column, because it automatically gets the not null constraint. The
foreign key is permitted to have null values, but a foreign key is sometimes given the
not null constraint. This constraint cannot be entered at the table level. For example,
the name column in FACU LTY table is not a key column, but you don’t want to
leave it blank. A t the column level, the constraint is defined by:

Name VARCHAR2(15) CONSTRAINT faculty_name_nn NOT NULL,

or

Name VARCHAR2(15) NOT NULL,

I n the second example, the user does not supply the constraint name, so Oracle will
name it with SYS_C format.

The UNIQUE Constraint. The U NI QU E constraint requires that every


value in a column or set of columns be unique. If it is applied to a single column, the
column has unique values only. I f it is applied to a set of columns, the group of
columns has a unique value together. The unique constraint allows null values un-
less NO T NU L L is also applied to the column. For example, the D eptName column
in the D E PT table should not have duplicate values. A t the table level, the con-
straint is defined by:

CONSTRAINT dept_dname_uk UNIQUE(DeptName),

A t the column level, the constraint is defined by

DeptName VARCHAR2(12) CONSTRAINT dept_dname_uk UNIQUE,

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.

The CHECK Constraint. The CH E C K constraint defines a condition that


every row must satisfy. There can be more than one C HE CK constraint on a col-
umn, and the C HE C K constraint can be defined at the column as well as the table
level. A t the column level, the constraint is defined by

DeptId NUMBER (2) CONSTRAINT dept_deptid_cc CHECK((DeptId >= 10) and (DeptId <= 99)),
76 Chap. 4 Oracle Tables: Data Definition Language (DDL)

A t the table level, the constraint is defined by


CONSTRAINT dept_deptid_cc CHECK((DeptId >= 10) and (DeptId <= 99)),

The NOT NULL CHECK Constraint. A NO T N U L L constraint can be de- clared


as a C H E C K constraint. Then, it can be defined at column or table level. For example,
Name VARCHAR2(15) CONSTRAINT faculty_name_ck CHECK(Name IS NOT NULL),

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’,

CREATING A N ORACLE TABLE

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,

is optional, and it is same as the user’s login name.


is the name of the table given by the user.
is the name of a single column.
is the column’s data type and size.
is the name of constraint provided by the user as per the con-
ventions discussed earlier in this chapter.
is the integrity or value constraint.

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).

SQL> CREATETABLE location(RoomId NUMBER(2),


2 Building VARCHAR2(7) CONSTRAINT location_building_nn NOT NULL,RoomNo
3 CHAR(3) CONSTRAINT location_roomno_nn NOT NULL, CapacityNUMBER(2)
4 CONSTRAINT location_capacity_ck CHECK(Capacity>0), RoomType CHAR,
5 CONSTRAINT location_roomid_pk PRIMARY KEY(RoomId), CONSTRAINT
6
location_roomno_uk UNIQUE(RoomNo);
7
8
9

Table created.SQL>

Figur e 4-4 CR EA TE TABLE statement.

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

SQL> CREATETABLE emplevel (LevelNo NUMBER(1),


2 LowSalaray Number(6), Number(6)
3 HighSalary emplevel_levelno_pk PRIMARY KEY(LevelNo));
4 CONSRAINT (LevelNo NUMBER(1),
CREATETABLE emplevel
ERROR at line 1:
ORA-00922: missing or invalid option
SQL> 3
3* HighSalary Number(6)
SQL> A,
3* SQL> HighSalary Number(6),
/
CONSRAINT emplevel_levelno_pk PRIMARY KEY(LevelNo)) ERROR at line 4:
ORA-00907: missing right parenthesis SQL> C/CONSRAINT/CONSTRAINT/
4* CONSTRAINT emplevel_levelno_pk PRIMARY KEY(LevelNo)) SQL>
/
Table Created. SQL>

Figur e 4-5 CR EAT E TABLE statement with error.


78 Chap. 4 Oracle Tables: Data Definition Language (DDL)

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):

1. Go to line 3 ( * is displayed next to the current line number).


2. Replace the character ) in line 3 with ), or append a comma (,) to the line.
3. Execute the debugged statement using a slash (/).

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:

1. A t the SQL 7 prompt, we type E D (or E D I T) to invoke Notepad.


2. We make required corrections to the script.
3. We save our statement on the disk using the Save opti on from the File
menu in N otepad, and we name our statement A : \C R E A TE . N otepad
adds the extension to the filename. To suppress N otepad’ s default
extension, type the file name in a pair of double quotes, and use the
extension .sql (e.g., “ A :\C RE A TE.SQL ” ).
4. We exit Notepad to go back to the SQL * Plus environment.
5. We can run the saved statement with @ or the R U N command.

The “Table Created” message is displayed when the statement is error-free. A t


this point, the table is created, and its structure is saved. W e created the L OCA -
TI ON and E M PL E V E L tables with PRI MA RY K EY , U N I Q U E , CH EC K , and
NO T NU L L constraints. Once a table is created, more constraints can be added,
more columns can be added, and existing columns’ properties can be changed. We
did not define any foreign key constraints with the L O CA TI ON table, because the
table referenced by the foreign key must already exist!

STORAGE Clause in CREATE TABLE

A C R E A TE TA BL E statement may have an optional STOR A G E clause. This


clause is used to allocate initial disk space for the table at the time of creation with
the I NI TI A L parameter and also to allocate additional space with the NE X T pa-
rameter in case the table runs out of allocated initial space. For example,

CREATE TABLEsample (Id NUMBER(3), Name VARCHAR2(25)) TABLESPACE CIS_DATA


STORAGE (INITIAL 1M NEXT 100K) PCTFREE 20;
Displaying Table Information 79

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:

The AV G_ROW_LEN is a column in U SE R_ TA BL E S D ata Dictionary table. The


0.15 (or 15% ) is recommended for overhead.

DISPLAYING TABLE INFORMATION

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.

Viewing a User’s Table Names

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:

SELECT TABLE_NAME FROM USER_TABLES;

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:

SELECT * FROM USER_TABLES;

(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:

SELECT Segment_Name, Bytes, Blocks, Initial_Extent, Next_Extent FROM USER_SEGMENTS;


80 Chap. 4 Oracle Tables: Data Definition Language (DDL)

Viewi ng a Table’s Structure

You can display the structure entered by you in a C R E A TE TA B L E statement. If


you have made any changes to the table’s structure, the changes will also show in the
structure’s display. Figure 4-6 shows the SQL * Plus command to view a table’s struc-
ture. The command is D E SC R I B E (or DE SC), which does not need a semicolon at
the end because it is not a SQL statement. Notice that the default display of column
names, the N OT N U L L constraint, and data type are in uppercase. You did not add a
NO T NU L L constraint for the primary key, but by default, Oracle adds it for all
primary key columns.

SQL> DESCRIBE student


Name Null? Type
- - -- - -- -- - -- - -- - -- -- - -- - -- - -- -- - -- - -- - -- - -- -- - -- - --
STUDENTID NOT NULL CHAR (5)
LAST NOT NULL VARCHAR2 (15)
FIRST NOT NULL VARCHAR2 (15)
STREETCITY STATEZIP VARCHAR2 (25)
STARTTERM BIRTHDATE VARCHAR2( 15)
FACULTYIDMAJORID CHAR (2)
PHONE CHAR (5)
CHAR (4) DATE
NUMBER (3)
NUMBER (3)
CHAR (10)

SQL>
Figur e 4-6 D ESCR IB E command and table structure.

Viewi ng Constraint Information

Oracle’s D ata Dictionary table U SE R_ CO NSTR A I NTS stores information about


constraints you have entered for each column. Figure 4- 7 shows the statement and
the result, which include the constraint’s name and type. W hen you type the state-
ment, the table name must be typed in uppercase, because Oracle saves table names
in uppercase. If you type the table name in lowercase, no constraint names will be
displayed.
The constraints named by the user have more meaningful names than the ones
named by Oracle. Constraints like NOT NU LL are usually not named by the user.
Oracle names them using the SYS_C format, where is any number. Constraint
type C is displayed for NO T NU L L and C H E C K constraints. Constraint type P is
for primary key and type R for foreign key constraints. Y ou will type only the first
two lines of the statement in Figure 4-7 to display all constraints in your account.
Displaying Table Information 81

SQL> SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE


2 FROM USER_CONSTRAINTS
3 WHERE TABLE_NAME = ‘STUDENT’; CONSTRAINT_NAME C
- - -- -- - -- - -- - -- -- - -- - -- - -- -- - -
STUDENT_FIRST_NN C
STUDENT_STUDENTID_PK P
STUDENT_FACULTYID_FK R
STUDENT_MAJORID_FK R
STUDENT_STARTTERM_FK R
STUDENT_LAST_NN C
6 rows selected SQL>

Figure 4-7 Constraint information.

The O R D E R BY clause is added to sort the constraint display by table name. For
example,

SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAMEFROM


USER_CONSTRAINTS
ORDER BY TABLE_NAME;

A nother D ata Dictionary table, USER_CONS_COLU MNS, stores column-


related information about constraints. You can use the statement shown in Figure 4-8
to see the constraint names and associated column names. I n this statement, only
the table name within single quotes needs to be in uppercase, because Oracle stores
table names in that case.

SQL> COLUMN COLUMN_NAME FORMAT A15


SQL> SELECT CONSTRAINT_NAME, COLUMN_NAME
2 FROM USER_CONS_COLUMNS
3 WHERE TABLE_NAME = ‘STUDENT’;
CONSTRAINT_NAME COLUMN_NAME
- - -- -- - -- - -- - -- -- - -- - -- - -- -- - -- - -- - -
STUDENT_FACULTYID_FK FACULTYID
STUDENT_FIRST_NN FIRST
STIDENT_LAST_NN LAST
STUDENT_MAJORID_FK MAJORID
STUDENT_STARTTERM_FK STARTTERM
STUDENT_STUDENTID_PK STUDENTID
6 rows selected.SQL>

Figur e 4-8 Constraint column information.


82 Chap. 4 Oracle Tables: Data Definition Language (DDL)

Viewing Tablespace Information

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;

Similarly, another D ata D ictionary view, U SE R _U SE R S, gives user informa-


tion about his or her account as well as permanent and temporary tablespaces. For
example,
SELECT * FROM USER_USERS;

COMMENT on Tables and Columns

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.

ALTERING A N EXISTING TABLE

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:

● A dding a new column to the table.


● D eleting a foreign key constraint from a table.
● D eleting a primary key constraint from a table, which also removes any ref-
erences to it from other tables in the database with C A SCA D E clause.
● I ncreasing the size of a column. For example, V ARCHAR2(15) can be
changed to V A R CHA R 2(20).
● Renaming columns (Oracle9i onward).
● Renaming constraints (Oracle9i onward).
Altering an Existing Table 83

Modifications allowed with 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.

Modifications not allowed include:


● Changing a column’s name (Oracle8i and earlier).
● Changing a constraint’s name (Oracle8i and earlier).
● Removing a column (Oracle8 and earlier).
In Oracle8i onward, you are allowed to remove/drop a column from a table or
set it as unused. If you already have created a table and need to make a change that is
not allowed, you may D R O P the table and recreate it. Y ou will also learn in a later
chapter that a table can be created using another table with the use of a nested query.

Add ing a New Column to an Existing Table

The general syntax to add a column to an existing table is

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.

SQL> ALTER TABLE student


2 ADD SocialSecurity CHAR(9);

Table altered.SQL>

Figur e 4-9 ALTER TABLE— adding a column.


84 Chap. 4 Oracle Tables: Data Definition Language (DDL)

Mod ifyi ng an Existing Column

The general syntax to modify an existing column is

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).

SQL> ALTER TABLE student


2 MODIFY SocialSecurity VARCHAR2(11);

Table altered.SQL>

Figur e 4-10 ALTER TABLE— modifying a column.

Add ing a Constraint

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);

Figure 4- 11a shows the A L TE R TA B L E statement that adds a new constraint

SQL> ALTER TABLE course


2 ADD CONSTRAINT COURSE_PREREQ_FK FOREIGN KEY(PREREQ)
3 REFERENCES COURSE(COURSE_ID);

Table altered.

SQL>

Figur e 4-11a ALTER TABLE— adding a constraint.


Altering an Existing Table 85

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.

SQL> ALTER TABLE term


2 ADD CONSTRAINT term_startdate_ck
3 CHECK(StartDate < EndDate);
Table altered. SQL>

Figur e 4-11b ALTER TABLE— adding a CHECK constraint.

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

SQL> ALTER TABLE student


2 ADD CONSTRAINT student_facultyid_fk
3 FOREIGN KEY (FacultyId) REFERENCES faculty(FacultyId); REFERENCES
faculty(FacultyId)
*

ERROR at one 3:
ORA-00942: table or view does not exist SQL>

Figure 4-12a ALTER TABLE— unsuccessful.

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> ALTER TABLE faculty


2 ADD CONSTRAINT faculty_facultyid_fk FOREIGN KEY(FacultyId)
3REFERENCES student(FacultyId); REFERENCES student(FacultyId)
*
ERROR at line 3:
ORA-00270; no matching unique or key for this column-list

SQL>

Figur e 4-12b ALTER TABLE— unsuccessful.

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).

SQL> ALTER TABLE student


2 ADD CONSTRAINT student_facultyid_fk FOREIGN KEY(FacultyId)
3 REFERENCES Faculty(FacultyID);
Table altered.
SQL>

Figur e 4-12c ALTER TABLE— successful.

Now, let us add a NOT NU L L constraint and a D E FA U L T value to the Start-


Term and State columns, respectively, in the STU D E NT table. If a student does not
have a start term, it is difficult for an academic department to track the student’s class
and projected date of graduation. If the college is located in the New Jersey area and
most of the students are from in- state, it is a good idea to add a default value to min-
imize having to enter data. A user can always overwrite the default value, but if it is
left blank or null, the default value is used by Oracle. To add such constraints, a
MO D I FY clause is used with an A L TE R TA B LE statement. For example,

ALTER TABLE student MODIFY StartTerm CHAR(4) CONSTRAINT


student_startterm_nn NOT NULL; ALTER TABLE student MODIFY State CHAR(2)
DEFAULT ‘NJ’;

Dropping a Column (Oracle8i Onward)

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

Oracle9i also allows a user to mark columns as unused by using

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.

SQL> ALTER TABLE student


2 SET UNUSED(SocialSecurity); Table
altered.
SQL> ALTER TABLE student
2 DROP UNUSED COLUMNS; Table
altered.
SQL>

Figure 4-13 ALTER TABLE— dropping unused columns.

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:

There is no C A SCA D E clause with E NA B L E. The D I SA B L E and E NA BL E


clauses can also be used in a C RE A TE TA BL E statement.

Renaming a Column (Oracle9i Version 9.2 Onward)

You can rename a column with the following statement:

Renaming a Constraint (Oracle9i Version 9.2 Onward)

You can rename a constraint with the following statement:

Mod ifyi ng Storage o f a Table

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;

Oracle displays a “Table dropped” message when a table is successfully dropped. If


you add the optional C A SC A D E C ONSTR A I N TS clause, it removes foreign key
references to the table as well.

RENA MING A TABLE

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,

TRUNCATE TABLE employee;

Oracle displays a “Table truncated” message on this statement’s execution. The


E MPL OY E E table is an integral part of the N2 Corporation’s database, and you do
not want to truncate it unless you would like to enter all the employees’ data again!
The truncate operation releases all table storage except for the initially allo-
cated extent. You can “k eep” all storage used by table with the R E U SE STOR A G E
clause. For example,

TRUNCATETABLE REUSE STORAGE;

ORACLE’S VARIOUS TABLE TYPES

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

Figure 4-14 Spool menu.

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)

Figur e 4-15a Online help— step 1.

Figur e 4-15b Online help— step 2.


In a Nutshell .. . 93

Figur e 4-15c Online help— step 3.

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)

V A R C HA R 2 (variable- length character data), N U M B E R (integer, fixed-


point decimal, and floating-point decimal values), and D A TE (date and time
values). The data-type column also includes the size.
● A dditional data types include L ONG, NC H A R , CLOB, BLOB, NCLOB,
B FI L E , and RA W.
● Constraints enforce rules for tables. Two types of constraints are integrity
constraint (primary key and foreign key) and value constraint (check, not
null, and unique). The constraints are named either by the user or by Oracle
using a standard convention. A constraint is defined at the column or table
level using slightly different syntax.
● A D D L statement, C R E A TE TA BLE, is used for table creation. The cre-
ation of a table includes column names, data types, sizes of the columns, and
constraint definitions.
● Oracle provides the user with SQL statements and SQL * Plus commands to
view the user’s tables, table structure, and constraint information.
● O racle also provides the user with D ata D ictionary tables and views for
information about user account, tables, tablespaces, constraints, and objects.
● The A L TE R TA BL E statement is used to modify an existing table’s struc-
ture. The modifications may include adding a new column, modifying an exist-
ing column, adding a constraint, or removing a constraint. Oracle8i and
Oracle9i do allow a user to drop a column from a table. In Oracle9i, a column
or constraint can also be renamed. There are restrictions imposed for certain
modifications.
● A table can be dropped from the database or renamed. A table can be trun-
cated to remove all its rows/records.
● Oracle error messages are displayed with error codes. A user can get more
information about the causes of an error and the action necessary to correct it
by using Oracle9i error messages from the Microsoft W indows environ-
ment or from Oracle’s online help.
● The spooling method is used to spool all queries, statements, and commands
along with their results to a text file.

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.

F ind the Valid/I nvalid Table/Column Names:


1. CRS-SECTION.
2. SAL ARY _L EVEL.
3. Employee’sId.
4. Employee Id.
5. $SALARY.
6. Proj2000.
7. Qualification_Code_For_Employees.

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.

W r ite answers for the following:


1. W hat is the use of data types? Name four basic data types, and state their use.
2. W hat are two types of constraints? Give two examples of each.
3. How are the constraints named?
4. Does Oracle allow a composite key? If so, how is it defined?
96 Chap. 4 Oracle Tables: Data Definition Language (DDL)

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

1. a. Use SQL statements to create STU DENT, FACUL TY , CO U R SE, CRSSECTION,


REG ISTR ATI ON, RO OM, TER M, LOCATION, M AJOR , and D EPARTM EN T
tables in the IU College database tables as given in Chapter 3. U se SQL * Plus com-
mands or Notepad to debug your statements’ errors, if any.
● Define a primary key constraint for each table. (D o not specify foreign keys yet.)
● Define NO T NUL L, DEFAUL T, U NI QU E, and CH ECK constraints wherever
appropriate.

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.

DATA MANIPULATION LANGUAGE (DML)

SQL’s D ata Manipulation Language (D ML ) consists of three statements— INSERT,


UPD ATE, and D E L E TE . D ata retrieval language, also known as a subset of DML,
consists of the SE LECT statement and its clauses. Some authors consider all four as
D M L statements. A new row is added to a table with the INSERT statement. D ata in
existing rows are changed with the U PD A TE statement. The D E L E TE statement re-
moves rows from a table. The SELECT statement retrieves data from tables, but it
does not affect the data in any way. In other words, the SELECT statement does not
98 Chap. 5 Working with Tables: Data Management and Retrieval

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 D ata Manipulation Language (D ML ) statement I NSERT is used to insert a


new row/record into a table. A user can insert values for all columns or a selected list
of columns in a record. The general syntax for the INSERT statement is

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,

TO_DATE(‘02/12/1980’, ‘MM/DD/YYYY’) TO_DATE(‘FEB 12, 1980’, ‘MON DD, YYYY’)

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

TO_DATE(’01:15 P.M.’, ‘HH:MI P.M.’)

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):

TO_CHAR(HireDate, ‘DD-MM-YYYY HH:MI:SS P.M.’)

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:

INSERT INTO dept


VALUES(10, ‘Finance’, ‘Charlotte’, 123);

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

Entering Null Values

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 the implicit method, the column’s name is omitted


from the column list in an INSERT statement. For example,

INSERT INTO dept(DeptId, DeptName) VALUES(50, ‘Production’);

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,

INSERT INTO dept(DeptId, DeptName, Location, EmployeeId) VALUES(60, ‘Personnel’,


‘Chicago’, NULL);

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.

Entering Default Values

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> INSERT INTO dept(DeptId, DeptName, Location, EmployeeId)


2 VALUES(&dept_id, ’&dept_name’, ’&location’, &emp_id); Enter value for
dept_id: 70
Enter value for dept_name: Testing Enter value for location: Miami Enter value
for emp_id: NULL
old 2: VALUES(&dept_id, ’&dept_name’, ’&location’, &emp_id) new 2:
VALUES(70, ’Testing’, ’Miami’, NULL)
1 row created.

SQL>

Figur e 5-1 Substitution variables.

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

SQL> INSERT INTO dept


2 VALUES (99,’R&D’, ’Windsor’, 111); Enter
value for d:

Figur e 5-2 Value with & .

Conversely, you can turn it on with the SE T D E FI N E O N command. Y ou can


also change the prefix with same command. For example, if you want to change the
prefix for substitution variable to ! , you will use the following command:
SETDEFINE !
102 Chap. 5 Working with Tables: Data Management and Retrieval

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

For an example, see Figure 5-3.

SQL> ACCEPT dept_id PROMPT ’Please enter department number(10 to 99): ’


Please enter department number(10 to 99): 80
SQL> ACCEPT dept_name PROMPT ’Please enter department name(no nulls): ’Please enter
department name(no nulls): Accounting
SQL> ACCEPT location PROMPT ’Please enter locationcity: ’Please enter location city:
Monroe
SQL> ACCEPT manager PROMPT ’Please enter EmployeeId of Manager: ’Please enter
EmployeeId of Manager: NULL
SQL> INSERT INTO dept
2 VALUES(&dept_id, ’&dept_name’, ’&location’, &manager); old 2: VALUES(&dept_id, ’
&dept_name’, ’&location’,&manager) new 2: VALUES(80, ’Accounting’, ’Monroe’, NULL)

1 row created.

SQL>

Figur e 5-3 Custom prompt with ACCEPT.

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.

UPDATING EXISTING ROWS/RECORDS

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.

Relational Operator Meaning


= Equal to Not equal to
<> or ! = Greater than
> Greater than or equal to
> = Less than
< Less than or equal to
< =

Figur e 5-4 Relational operators.

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

SQL> UPDATE student


2 SET MajorId = 700
3 WHERE StudentId = ’00103’; UPDATE student
*
ERROR at line 1:
ORA-02291: integrityconstraint (SYSTEM.STUDENT_MAJORID_FK) violated- parent key not found
SQL> 2
2*SET MajorId = 700SQL> c/700/600
2*SET MajorId = 600SQL> 1
1 UPDATE student
2 SET MajorId = 600
3* WHERE StudentId = ’00103’SQL> /

1 row updated.

SQL> 2
2* SET MajorId = 600SQL> c/600/500
2* SET MajorId = 500SQL> /

1 row updated.

SQL>

Figur e 5-5 Unsuccessful and successful UPDATE statements.

DELETING EXISTING ROWS/RECORDS

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

The keyword F R OM is optional. The W H E R E clause adds a condition to the


D E L E TE statement. Once again, the condition is optional, but it is necessary. Y ou
normally would delete only those records that meet a criterion. The D E L E TE state-
ment without a condition will result in a table with no rows. A D E L E T E statement
without a W H E R E clause has same effect as a TR U N CA TE statement. The only
difference is that the D E L E TE operation can be undone with R OL L BA C K state-
ment (see Chapter 9), but the TR U NC A TE operation makes the change permanent.
Retrieving Data from a Table 105

SQL> DELETE FROM dept


2 WHERE DeptId = 70;

1 row deleted. SQL>

Figur e 5-6 Successful DE LET E statement.

Figure 5-6 shows successful execution of a D E L E TE statement. If a row with de-


partment number 70 exists, it is deleted.
If you try to delete a record from a table whose primary key value is used in
another table’s foreign key column, Oracle will display an “Integrity constraint Á
violated - child record found” error message. The parent record that is referenced by
a child record cannot be removed. See Figure 5- 7 for such an unsuccessful D E LE TE

SQL> DELETE FROM dept


2 WHERE DeptId = 20;DELETE FROM dept
*
ERROR at line 1:
ORA-02292: integrityconstraint (SYSTEM.EMPLOYEE_DEPTID_FK) violated - childrecordfound

SQL>

Figure 5-7 Unsuccessful D ELE TE statement.

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.

RETRIEVING DATA FROM A TABLE

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

SQL> SELECT Last, First


2 FROM student;
LAST FIRST
- --- -- -- --- -- -- - -- --- -- --- -- --
Diaz Jose
Tyler Mickey
Patel Rajesh
Rickles Deborah
Lee Brian
Khan Amir
6 rows selected.SQL>

Figur e 5-8 Output from a SELECT query.

given by the D E SC R I B E command. For example, Figure 5- 8 shows output from a


SE L E CT query. This query displays the last name and first name of all students
from the STU D EN T table. The Last and First columns are vertical slices of the
STU D E NT table, a projection operation.
A s you see, the column names are displayed in uppercase. I n the STU D E NT
table, the column Last comes before the column First, but the output displays them
in the order given in the SE L E C T query. By default, character data is displayed with
left justification and numeric data with right justification.

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;

COURSE TITLE CREDITS PREREQ


-- -- -- -- --- --- --- -- --- --- - - -- --- --- - - --- --
EN100 Basic English 0
LA123 English Literature 3 EN100
CIS253 Database Systems 3
CIS265 Systems Analysis 3 CIS253
MA150 College Algebra 3
AC101 Accounting 3

6 rows selected.

SQL>

Figur e 5-9 SELECT *.


Retrieving Data from a Table 107

I n output from a SE L E C T statement, left justification is used for C HA R- ,


VA RCHAR2-, and D ATE -type columns, and right justification is used for NUM-
B ER - type columns. The default column width for displaying a N U M B E R column is
9. The display width for character columns is based on column’s width.
Two problems with displaying all rows and all columns are the screen’s default
line size and page size. A f ter 80 columns, the row display wraps to the next line.
A fter displaying 11 rows under column headings, column headings are repeated for
more rows. You can change these values from the Options menu in the SQL * Plus
envi ronment.
The environment variables can be changed by clicking on the menu in
SQL * Plus, then by selecting from it. Soon, an E nvironment window will
pop up, and you can select from the list of environment variables. Then, change
the value from D efault to Current, and type in the new value. The default value for line
size is 80. Similarly, and other variables can be set (see Fig. 5-10). A lternately,
you can type SET commands at the SQ L 7 prompt. For example,
SETLINESIZE150

Figur e 5-10 Setting environment variable line size.

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

SQL> SELECT * FROM student;


STUDE LAST FIRST STREET CITY
-- --- --- --- -- -- --- --- -- --- --- -- -- -- --- --- -- --- --- - - -- --- --
ST ZIP STAR BIRTHDATE FACULTYID MAJORID PHONE
-- - -- -- -- -- -- -- --- -- -- -- -- --- -- -- -- -- - -- -- -- --- -- -
00100 Diaz Jose 1 Ford Avenue #7 Hill
NJ 08863 WN03 12-FEB-83 123 100 9735551111

00101 Tyler Mickey 12 Morris Avenue Bronx


NY 10468 SP03 18-MAR-84 555 500 7185552222

00102 Patel Rajesh 25 River Road #3 Edison


NJ 08837 WN03 12-DEC-85 111 400 7325553333

STUDE LAST FIRST STREET CITY


-- --- --- --- -- -- --- --- -- --- --- -- -- -- --- --- -- --- --- - - -- --- --
ST ZIP STAR BIRTHDATE FACULTYID MAJORID PHONE
-- - -- -- -- -- -- -- --- -- -- -- -- --- -- -- -- -- - -- -- -- --- -- -
00103 Rickles Deborah 100 Main Street Iselin
NJ 08838 FL02 20-OCT-70 555 500 7325554444

00104 Lee Brian 2845First Lane Hope


NY 11373 WN03 28-NOV-85 345 600 2125555555

00105 Khan Amir 213 Broadway Clifton


NJ 07222 WN03 07-JUL-84 222 200 2015556666

6 rows selected.
SQL>

Figur e 5-11a Output before setting LINESIZE.

SQL> SETLINESIZE 150


SQL> SELECT * FROM student;
STUDE LAST FIRST STREET CITY ST ZIP STAR BIRTHDATE FACULTYID MAJORI
-- --- -- --- - -- -- -- - -- --- -- -- -- - --- -- -- - - --- -- --- - -- --- --- - -- --- -- - --- --
00100 Diaz Jose 1 FordAvenue #7 Hill NJ 08863 WN03 12-FEB-83 123 10
00101 Tyler Mickey 12 Morris Avenue Bronx NY 10468 SP03 18-MAR-84 555 50
00102 Patel Rajesh 25River Road #3 Edison NJ 08837 WN03 12-DEC-85 111 40
00103 Rickles Deborah 100 Main Street Iselin NJ 08838 FL02 20-OCT-70 555 50
00104 Lee Brian 2845First Lane Hope NY 11373 WN03 28-NOV-85 345 60
00105 Khan Amir 213Broadway Clifton NJ 07222 WN03 07-JUL-84 222 20

6 rows selected.

SQL>

Figur e 5-11b Output after setting LINESIZE.


Retrieving Data from a Table 109

Conversely, you can suppress feedback by using the following command:


SET FEEDBACK OFF

DISTINCT Function

The D ISTINCT function is used to suppress duplicate values. The word


is used right after the keyword SE L E CT and before the column name.
L et us see the difference in result from two SE L EC T queries, with and without
the D ISTINCT function. Figure 5- 12a shows the SE L E C T statement without D IS-
TINCT, which outputs 11 rows with some duplicate values. Figure 5- 12b shows the
SE L E CT statement with DI STI NCT, which eliminates duplicate values and returns
three unique values only.

SQL> SELECT Building


2 FROM location;

BUILDIN
- --- ---
Gandhi Gandhi Kennedy
KennedyNehruNehru
Gandhi Kennedy Kennedy
Gandhi Gandhi
11 rows selected.SQL>

Figur e 5-12a SELECT without DISTINCT.

SQL> SELECT DISTINCT Building


2 FROM location;

BUILDIN
- --- ---
Gandhi Kennedy Nehru

SQL>

Figur e 5-12b SELECT with DISTINCT.


110 Chap. 5 Working with Tables: Data Management and Retrieval

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.

SQL> SELECT CourseId AS “COURSE”, Title “Course Name”,


2 PREREQ Requirement
3 From course;

COURSE Course Name REQUIR


--- -- - - -- --- --- --- -- - -- --- -
EN100 Basic English
LA123 English Literature EN100
CIS253 Database Systems
CIS265 Systems Analysis CIS253
MA150 College Algebra
AC101 Accounting
6 rows selected.
SQL>

Figur e 5-13 Column aliases.

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

columns. The general syntax of the C O L U M N command is

For example,

COLUMN State FORMAT A5COLUMN Salary FORMAT $999,999

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

SQL> SELECT CourseId, Credits, PreReq


2 Fromcourse;

COURSE CREDITS PREREQ


--- -- - - -- -- -- -- -- -- --
EN100 0
LA123 3 EN100
CIS253 3
CIS265 3 CIS253
MA150 3
AC101 3

6 rows selected.
SQL> COLUMN CourseId FORMAT A8
SQL> COLUMN Credits FORMAT 9.99
SQL> /

COURSEID CREDITS PREREQ


--- --- -- --------- -- -- --
EN100 .00
LA123 3.00 EN100
CIS253 3.00
CIS265 3.00 CIS253
MA150 3.00
AC101 3.00
6 rows selected.
SQL>

Figure 5-14 COLU MN command.


112 Chap. 5 Working with Tables: Data Management and Retrieval

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

The word is a common word in computer jargon, but in daily life, it is


seldom used. Concatenation means joining or linking. I n SQL, concatenation joins a
column or a character string to another column. The result is a column that is a
string or a sequence of characters. Two vertical bars or pipe symbols 1 2 are used as
the concatenation operator. The symbol appears on your keyboard with the back-
slash (\) character. Y ou will need to depress the SHI FT key to enter the character.
Figure 5- 15 shows the result of concatenating two columns in the E M PL OY E E
table. The two columns’ values are joined without any space separating them.

SQL> SELECT Lname || Fname


2 FROM employee;

LNAME | | FNAME
- --- -- --- --- --- -- --- --- -- --- -
SmithJohn HoustonLarry RobertsSandi
McCallAlex DevDerek ShawJinku
GarnerStanleyChenSunny ZEESONIA
9 rows selected.SQL>

Figur e 5-15 Concatenation.

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:

SELECT First |‘ ‘||Last |‘was bornon ‘||Birthdate FROM student;


Arithmetic Operations 113

SQL> SELECT Lname | | ’,’ | | Fname | | ’ makes $’ | |


2 Salary “Employee Salary Info”
3 FROM employee;
Employee Salary Info
- --- --- -- --- --- -- --- --- -- --- --- -- --- --- --- --
Smith, Johnmakes $265000 Houston, Larry makes $150000Roberts,
Sandi makes $75000 McCall, Alex makes $66500Dev, Derek makes
$80000 Shaw, Jinkumakes $24500 Garner, Stanley makes $45000
Chen, Sunny makes $35000

8 rows selected.SQL>

Figur e 5-16 Concatenation with character strings and columns.

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

Figur e 5-17 Arithmetic operators.

Order of Operation

The order of operation is as follows:

● Whatever is in parentheses is done first.


● Multiplication and division have higher precedence than addition and sub-
traction.
● If more than one operator of the same precedence is present, the operators
are performed from left to right.
114 Chap. 5 Working with Tables: Data Management and Retrieval

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.

SQL> SELECT Lname, Fname, Salary+Commission


2 FROM employee;

LNAME FNAME SALARY+COMMISSION


-- -- --- --- -- --- - --- -- --- --- -- - -- - -- - - -- - -- - -- - -
Smith John 300000
Houston Larry 160000
Roberts Sandi
McCall Alex
Dev Derek 100000
Shaw Jinku 27500
Garner Stanley 50000
Chen Sunny

8 rows selected.

SQL>

Figur e 5-18 Arithmetic operation with null values.

RESTRICTING DATA WITH A WHERE CLAUSE

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.

Logical Operator Meaning


A ND Returns TR U E only if both conditions are true.
OR Returns TR U E if one or both conditions are true.
NOT Returns TR U E if the condition is false.

Figur e 5-19 Logical 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

Figur e 5-20 AN D and OR.

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.

Figur e 5-21 Other comparison operators.

Other special comparison operators are given in Figure 5-21. The I S N U LL


operator checks for a null value. I t returns T R U E for a null value and FA L SE for a
not null value. The B E TW E E N Á A N D oper ator checks for a range of values
using lower and upper limits. The I N operator is an alternate and shorter way of
writing O R conditions. The L I K E operator is used with wild cards for pattern
matching.
I n this section, we will give many examples of restricted data retrieval. First,
the I U College database has a few thousand students. The administration wants to
identify students who started in the Winter 2003 term. W e have used a few sample
116 Chap. 5 Working with Tables: Data Management and Retrieval

records in each table for simplicity. Based on the rows entered, we will get output as
given in Figure 5- 22.

SQL> SELECT StudentId, Last, First


2 FROM student
3 WHERE StartTerm = ’WN03’;
STUDE LAST FIRST
-- -- - -- --- -- -- --- -- - - --- --- -- --- ---
00100 Diaz Jose RajeshBrianAmir
00102 Patel
00104 Lee
00105 Khan

SQL>

Figur e 5-22 Data retrieval with the W HE R E clause.

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>

Figur e 5-23 Case sensitivity.

L et us try another relational operator in the condition. The president of the N2


Corporation wants to find out the name and department number of all employees
who make $50, 000 or more in salary only. The president will be surprised if he does
not see his name in the list in Figure 5-24!
Let us say it is time to schedule courses for the next term. The A ccounting de-
partment wants to schedule a course in a classroom that accommodates 40 to 45 stu-
dents. We can perform this query by using two conditions with the A N D operator or by
using the B E TW E E N Á A N D operator. Figure 5-25 uses a BE TW E E N Á A N D op-
erator with 40 as the lower limit and 45 as the upper limit. The same condition can be
written as a compound condition with the logical operator A N D as given in Fig. 5-26.
Restricting Data with a WHERE Clause 117

SQL> SELECT Lname, Fname, Salary, DeptId


2 FROM employee
3 WHERE Salary >= 50000;
LNAME FNAME SALARY DEPTID
--- -- --- -- -- --- -- --- -- --- -- -- - -- --- -- -- - -- -- --- ---
Smith John 265000 10
Houston Larry 150000 40
Roberts Sandi 75000 10
McCall Alex 66500 20
Dev Derek 80000 20

5 rows selected.

SQL>

Figur e 5-24 Relational operator 7= .

SQL> COL RoomNo FORMAT A6SQL> COL RoomType


FORMAT A8
SQL> SELECT Building, RoomNo, Capacity, RoomType
2 FROM location
3 WHERE Capacity BETWEEN 40 AND 45;

BUILDIN ROOMNO CAPACITY ROOMTYPE


------- - --- -- -- -- -- --- - -- -- --- -
Nehru 309 45 C
Kennedy 206 40 L
SQL>

Figur e 5-25 BE TW EEN Á AN D operator.

SQL> SELECT Building, RoomNo, Capacity, RoomType


2 FROM location
3 WHERECapacity >= 40 AND Capacity <= 45;

BUILDIN ROOMNO CAPACITY ROOMTYPE


------- - --- -- -- -- -- --- - -- -- --- -
Nehru 309 45 C
Kennedy 206 40 L
SQL>

Figur e 5-26 Compound condition with the AN D operator.

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

● The NO T operator is performed third.


● The A N D operator is performed fourth.
● The O R operator is performed last.
We can write compound conditions with multiple operators and columns. Say
we are looking for employees with a salary in the range of $50, 001 to $100,000 and
belonging to department 10. W e can further restrict data by adding another condi-
tion to check for the D epar t I d (see Fig. 5-27).

SQL> SELECT Lname, Fname, Salary, DeptId


2 FROM employee
3 WHERE Salary BETWEEN 50001AND 100000
4 AND DeptId = 10;

LNAME FNAME SALARY DEPTID


--- -- --- --- --- - -- --- -- --- --- -- - --- --- -- - - --- --- -- -
Roberts Sandi 88275 10

SQL>

Figure 5-27 Compound condition using two columns.

The B E TW E E N Á A N D operator can also be applied to character values to


find names starting with a range of characters. W ith character values, the operator
checks for the first character of column values (see Fig. 5- 28).

SQL> SELECT Lname, Fname


2 FROM employee
3 WHERE Lname BETWEEN ’M’ AND ’Z’;
LNAME FNAME
- --- -- -- --- -- -- - -- --- -- --- -- --
Smith John
Roberts Sandi
McCall Alex
Shaw Jinku

SQL>

Figure 5-28 B ETW EE N Á AN D operator with character values.

The N2 Corporation is conducting a study regarding their employees’ qualifi-


cations. The company wants to identify all employees with bachelors, masters, and
doctorate degrees. The corresponding qualification codes are 3, 2, and 1. The most
appropriate operator is O R , because the employee has to have one of the three
codes (see Fig. 5- 29). The same result can be obtained by using the I N operator in
place of three conditions and two O R conjunctions. For example,
WHERE QualId IN(3, 2,1);
Restricting Data with a WHERE Clause 119

SQL> SELECT Lname, Fname, Salary, DeptId, QualId


2 FROM employee
2 WHERE QualId=1 OR QualId=2 OR QualId=3;
LNAME FNAME SALARY DEPTID QUALID
-- -- --- --- -- --- -- --- -- --- --- -- --- --- -- -- - --- --- -- - - --- --- -- -
Smith John 265000 10 1
Houston Larry 150000 40 2
Roberts Sandi 75000 10 2
Dev Derek 80000 20 1
Chen Sunny 35000 10 3

5 rows selected.

SQL>

Figur e 5-29 O R operator.

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> SELECT Name, Phone, DeptId


2 FROM faculty
2 WHERE DeptId IN(1,2, 3);
NAME PHO DEPTID
-- -- --- --- -- --- -- - - --- --- -- -
Jones 525 1
Williams 533 2
Mobley 529 1
Vajpayee 577 2
Sen 579 3
Collins 599 3

SQL>

Figur e 5-30 IN operator.

Suppose we change the condition of Figure 5-30 to W H E R E D eptI d NOT IN


(1, 2, 3). W hat will be the outcome? The N OT operator, when used with other oper-
ators, negates the result.
In the E M PL OY E E table, there is information about the employee’s immediate
supervisor to whom he or she reports. I s there any employee who does not have a
supervisor? If so, then either the information is missing or the employee has the
highest position in the company. L et us search for such employees in Figure 5-31.
120 Chap. 5 Working with Tables: Data Management and Retrieval

SQL> SELECT Lname, Fname, Supervisor


2 FROM employee
3 WHERE Supervisor = NULL;
no rows selected

SQL> SELECT Lname, Fname, Supervisor


2 FROM employee
3 WHERE Supervisor = ”;
no rows selected

SQL> SELECT Lname, Fname, Supervisor


2 FROM employee
3 WHERE Supervisor IS NULL;
LNAME FNAME SUPERVISOR
- -- --- -- -- --- -- -- -- --- -- -- --- - -- -- -- --- -
Smith John

SQL>

Figur e 5-31 IS NULL operator.

Fortunately, only one employee is without supervisor information, and this


employee happens to hold the president’s position. If more such records were
found, data- entry personnel would have to U PD A TE that information. H av e an-
other look at the figure. The first two times, no rows are selected with conditions
Supervisor = N U L L and Supervisor = ‘’. The ony way to check for null values is
with the IS NU L L operator.
Similarly, we can check for rows with no null value in a column. I n other words,
we would like to see rows with values in a column. For example, the E M PL OY E E
table in the N2 Corporation database has rows with commission and also has rows
with a null value for the commission. John Smith is the only employee in depart-
ment 10 with a NO T NU L L value in the commission column (see Fig. 5-32).

SQL> SELECT Lname, Fname, Salary, Commission


2 FROM employee
2 WHERE Commission IS NOT NULL
2 AND DeptId = 10;
LNAME FNAME SALARY COMMISSION
- --- --- -- --- --- --- -- --- --- -- -- --- --- -- -- ---- ------
Smith John 265000 35000

SQL>

Figur e 5-32 IS NOT NULL operator.


Restricting Data with a WHERE Clause 121

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.

Wild Card Use

% Represents zero or more characters.


_(Under score) Represents any one character.

Figure 5-33 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.

SQL> SELECT Name, Phone


2 FROM faculty
3 WHERE Name LIKE ’C%’;
NAME PHO
- --- -- -- --- -- -- - --
Chang 587
Collins 599

2 rows selected.SQL>

Figur e 5-34 Wild-card %.

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

SQL> SELECT Lname, Fname, HireDate


2 FROM employee
2 WHEREHireDate LIKE ’%6_’;

LNAME FNAME HIREDATE


-- -- --- --- --- -- - -- --- --- -- --- - - --- --- --
Smith John 15-APR-60
Houston Larry 19-MAY-67

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.

Type of Value Ascending Sort Order

Numeric Lowest to highest value


Character Alphabetical order
Date Earliest to latest date

Figur e 5-36 Ascending sort 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> SELECT Last, First


2 FROM student
3 ORDER BY Last;
LAST FIRST
- --- -- -- --- -- -- - -- --- -- --- -- --
Diaz Jose
Khan Amir
Lee Brian
Patel Rajesh
Rickles Deborah
Tyler Mickey
6 rows selected.SQL>

Figur e 5-37 Single-column sort.


124 Chap. 5 Working with Tables: Data Management and Retrieval

SQL> SELECT Lname, Fname, Salary


2 FROM employee
2 WHERE DeptId = 30
2 ORDER BY Salary Desc;

LNAME FNAME SALARY


- --- --- --- -- --- --- --- -- --- --- - - --- --- ---
Garner Stanley 45000
Shaw Jinku 24500

SQL>

Figur e 5-38 Descending order sort.

SQL> SELECT Lname |’, ’||Fname AS fullname,


2 Salary / 12AS monthlysalary
3 FROM employee
4 WHERE DeptId = 10
5ORDER BY monthlysalary 6 /

FULLNAME MONTHLYSALARY
- --- -- -- --- -- -- --- -- --- -- -- --- -- - - - - - - - - - - - - -
Chen, Sunny 2916.66667
Roberts, Sandi 6250
Smith, John 22083.3333
3 rows selected.SQL>

Figur e 5-39 Sort by an alias.

SQL> SELECT Lname, Fname, Salary, DeptId


2 FROM employee
2 ORDER BY DeptId, Salary Desc;
LNAME FNAME SALARY DEPTID
- --- --- --- -- --- --- -- --- -- --- -- - --- -- -- -- --------- -
Smith John 265000 10
Roberts Sandi 75000 10
Chen Sunny 35000 10
Dev Derek 80000 20
McCall Alex 66500 20
Garner Stanley 45000 30
Shaw Jinku 24500 30
Houston Larry 150000 40

8 rows selected.

SQL>

Figur e 5-40 Multiple-column sort.


Revisiting Substitution Variables 125

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).

REVISITING SUBSTITUTION VARIABLES

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:

● I n the SE L E CT statement in place of a column name.


● I n the FR O M clause in place of a table name.
● I n the W H E R E clause as a column expression or text.
● A s an entire SEL E C T statement.

If a variable is to be r eused within a query without getting a prompt again


for the same variable, the doubl e- ampersand (& & ) substitution variable is used.
The user gets only one prompt for the variable with & & , and the value of the
variable is then used more than one time. I n Fig. 5- 41, the variable is
used twice, once in the SE L E CT statement in the column list and then again as
the sort column in the O R D E R BY clause. The user, however, gets only one
prompt for the variable.
126 Chap. 5 Working with Tables: Data Management and Retrieval

SQL> SELECT Last, First, &&columnname


2 FROM student
2 ORDER BY &columnname;
Enter value for columnname: MajorId
old 1: SELECT Last, First, &&columnname new 1:
SELECT Last, First, MajorId
old 3: ORDER BY &columnname new 3: ORDER BY MajorId

LAST FIRST MAJORID


-- -- --- --- -- --- --- --- -- --- --- - -- --- --- --
Diaz Jose 100
Khan Amir 200
Patel Rajesh 400
Tyler Mickey 500
Rickles Deborah 500
Lee Brian 600
6 rows selected.
SQL>

Figure 5-41 The & & substitution variable.

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,

SELECT * FROM employee WHERE Lname = ‘&Last’;

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

SQL> DEFINETemp = 999SQL> DEFINE


DEFINE _CONNECT_IDENTIFIER = “oracle” (CHAR) DEFINE _SQLPLUS_RELEASE =
“902000100” (CHAR) DEFINE _EDITOR = “Notepad”(CHAR)
DEFINE _O_VERSION = “Oracle9i Enterprise Edition Release
9.2.0 .1 .0 - Production
With the Partitioning, OLAP and Oracle Data Mining options JServer Release
9 .2.0.1.0 - Production” (CHAR)
DEFINE _O_RELEASE = “902000100”(CHAR) DEFINE DEPT_ID
= “80”(CHAR)
DEFINE LOCATION = “Monroe”(CHAR) DEFINE DEPT_NAME
= “Accounting”(CHAR) DEFINE MANAGER
= “NULL”(CHAR) DEFINE COLUMNNAME
= “MajorId” (CHAR) DEFINE TEMP
= “999”(CHAR)
SQL>

Figure 5-42 The DEFIN E command.

Figure 5- 42 shows use of D E FI NE command to define variable Temp with a


value of 999.The D E F I NE command then displays all defined variables for the session,
including the just- defined variable Temp. The variables are stored with data-type
CH A R .

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

I n Figure 5- 43, CA SE structure is illustrated with an U PD A TE statement. The


Salary column is updated with different increments based on employees’ depart-
ment Id. Employees in D epartment 10 get a 10% raise, employees in D epartment 20
get a 5% raise, and others do not get any raise!
128 Chap. 5 Working with Tables: Data Management and Retrieval

SQL> UPDATE employee


2 SET Salary = CASE WHEN DeptId = 10 THEN
3 Salary * 1.10
4 WHEN DeptId = 20THEN
5 Salary * 1.05
6 ELSE Salary
7 END
8 /
8rows updated.SQL>

Figur e 5-43 UPDATE with CASE structure.

IN A NUTSHELL . . .

● The D ata Manipulation Language ( D M L) statements INSE RT, U PD A TE,


and D E L E TE are used for data maintenance.
● D ate and character values are enclosed in single quotation marks. Oracle is
case sensitive about character values and format sensitive about date values.
The default date format is D D- MO N- YY . Number values are not enclosed in
quotation marks.
● To use a character value with a single quotation mark, use the single quota-
tion mark twice in succession.
● Null values can be entered implicitly or explicitly. A null value is an unknown
and undefined value.
● A foreign key value in a child table is allowed only if the value exists in the
par ent table’s primary key.
● A user can create interactive scripts by using substitution variables and the
A C CE PT command.
● The U PD A TE statement is used to change existing data.
● Conditions use column, value, relational, logical, and other special operators.
● Every INSERT, D E L E TE , and U PD A TE command is successful provided
the integrity constraints are not violated.
● A constraint can be dropped permanently or disabled temporarily using the
A L TE R TA B L E statement. The disabled constraint can be enabled later.
● The SE L E CT query is used to retrieve data from existing tables.
● The wild- card* is used to display all columns with the SE L E CT query.
● The D ISTINCT clause in front of a column name returns nonduplicate values
only.
● A column alias is used for more descriptive column headings because the
column names are abbreviated. By default, column names are displayed as
column headings in data retrieval.
Chap. 5 ExerciseQuestions 129

● 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 . . .

● D ata retrieval statements are written using single- row functions.


● Numeric, character, conversion, and miscellaneous functions are introduced
and used.
● D ata are manipulated using aggregate or group functions.
● Various clauses are used with data retrieval queries for filtering and grouping of
data.

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

where is the name of the function, is a column from a table,


is a character string or a mathematical expression, and is any
argument used by the function.
There are various types of single-row functions:

● take a character string or character-type column as an


argument and return a character or numeric value.
● take a number or number- type column as an argument and
retur n a numeric value.
● tak e a date value or date- type column as an argument and
retur n date-type data. ( The MO NTHS_ BE TW E E N function re-
turns a numeric value.)
● convert value from one data type to another.
● perform different tasks.

Character Functions. The character functions perform case conversion or


character manipulation. Figure 6-1 has a list of character functions and their use. The
case- conversion character functions change a string or character- type column data’s
case. For example,

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

Character Function Use

UPPER 1 | 2 Converts each letter to uppercase.


LO WER 1 | 2 Converts each letter to lowercase.
INITCAP1 | 2 Converts character value to the proper case
(i.e., first character of each word is converted to
uppercase and the rest to lowercase).
CONCAT 1 | | 2 Joins the first value to the second value. Similar to
the operator discussed earlier.
SUBSTR 1 | 2 Returns a substring, starting at character position
, and returns number of characters.
SUBSTR 1 | 2 Returns a substring, starting at character
position and going to the end of string.
INSTR 1 | 2 Returns the position of the supplied character.
LT RIM 1 | 2 Removes the leading supplied character.
R TR IM 1 | 2 Removes the trailing supplied character.
TR IM 1‘ ’ | 2 Removes the leading and trailing characters.
TR IM( ) Removes the leading and trailing spaces only.
LE NG TH1 | 2 Returns the number of characters.
LPAD1 | ‘ ’2 Pads the value with ‘str’ to the left to a total width
of
R PAD 1 | ‘ ’2 Pads the value with ‘str’ to the right to a total width
of
R EPLACE 1 | 2 Replaces substring , if present in the column or
expression, with string .

Figur e 6-1 Character functions.

SQL> SELECT UPPER(Lname), LOWER(Fname), ’ ’


2 INITCAP(Fname | | Lname)
3 FROM employee;

UPPER(LNAME) LOWER(FNAME) INITCAP(FNAME||”||LNAME)


---- ---- ----- -- - ---- ---- ----- - ----- ---- ---- ---- ---- ---- -----
SMITH john JohnSmith
HOUSTON larry LarryHouston
ROBERTS sandi Sandi Roberts
MCCALL alex Alex Mccall
DEV derek DerekDev
SHAW jinku JinkuShaw
GARNER stanley Stanley Garner
CHEN sunny Sunny Chen

8 rows selected.

SQL>

Figur e 6-2 Character functions in SELECT.


Built-In Functions 135

SQL> SELECT Last, First FROM student


2 WHERE State=’ny’;

no rows selected

SQL> SELECT Last, First FROM student


2 WHERE UPPER(State) = ‘NY’;

LAST FIRST
-- --- ---- --- --- -- ---- --- ---- --
Tyler Mickey
Lee Brian

SQL>

Figure 6-3 Character function in W HE RE .

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.

SQL> SELECT Last, First FROM student


2 ORDER BY LENGTH(Last);

LAST FIRST
-- --- ---- --- --- -- ---- --- ---- --
Lee Brian
Diaz Jose
Khan Amir
Tyler Mickey
Patel Rajesh
Rickles Deborah
6 rows selected.SQL>

Figur e 6-4 Character function in OR DE R BY .

I n Oracle9i, the L E N GTH function is enhanced with other functions like


L E NG THB (to get length in bytes instead of characters) and L E N GTH C (to get
length in unicode).
The character manipulation functions manipulate a character- type value to re-
turn another character- or numeric- type result. For example,
CONCA T(‘New’, ‘York’) : ‘NewY ork’
SU BSTR(‘HEA TER’, 2, 3) : ‘EAT’
136 Chap. 6 Working with Tables: Functions and Grouping

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’

I n Oracle9i, the I NSTR function is enhanced to take more arguments:

SELECT INSTR(‘CORPORATE FLOOR DOOR’, ‘OR’ 1, 2) FROM dual;

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

The TR U NC function truncates the value, expression, or column to decimal


places. I f is not supplied, zero decimal place is assumed. I f is negative, truncation
takes place to the left side of the decimal place. For example,

TRUNC(25.465,2) = 25.46
TRUNC(25.465, 0) =25
TRUNC(25.465, –1) = 20

The POW E R function finds the power of a number 1 2. For example,

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

The M OD function finds the integer remainder of divided by . I t ignores the


quotient. For example,

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

The F L O O R function is similar to the TR U N C function, and the C E I L func-


tion is similar to the R O U ND function. However, both take one argument instead
of two. For example,

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,

SELECT 25000 * 0.25 FROM DUAL;

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> SELECT ROUND(5.55, 1), TRUNC(5.5), SIGN(-5.5), MOD(5,2),


2 ABS(-5), POWER(3, 4), FLOOR(5.5), CEIL(5.5)
3 FROM DUAL;

ROUND(5.55,1) TRUNC(5.5) SIGN(-5.5) MOD(5,2) ABS(-5) POWER(3,4) FLOOR(5.5) CEIL(5.5)


--- -- --- -- - -- --- -- -- -- -- --- - - -- -- -- --- -- - -- -- --- -- - -- --- -- - - -- --- -
5.6 5 –1 1 5 81 5 6
SQL>

Figur e 6-5 Using numeric functions.

Numeric Function Use

R OUND1 | 2 Rounds the column or expression to decimal places.


TR UNC 1 | 2 Truncates the column or expression to decimal places.
POW ER( , ) Returns raised to power 1 2.
ABS( ) Returns the absolute value of .
MO D( , ) Returns the integer remainder of / .
SIGN( ) Returns 1 for positive, - 1 for negative and 0 for a zero.
FLOOR( ) Returns the largest integer less than or equal to value.
CEIL( ) Returns the smallest integer greater than or equal to value.

Figur e 6-6 Numeric functions.

SQL> DESCRIBE DUAL


Name Null? Type
-- --- --- --- --- --- -- --- --- --- -- -- --- --- -- --- --- --
DUMMY VARCHAR2(1)
SQL> SELECT * FROM dual; D
-X

SQL>

Figur e 6-7 DU AL table.

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.

Date Expression Result

Date + number Adds a number of days to a date.


Date — number Substracts a number of days from a date.
Date + number /24 Adds a number of hours to a date.
Date1 — Date2 Gives the number of days between two
dates.

Figur e 6-8 Date arithmetic.

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.

SQL> SELECT Last, First, (SYSDATE – BirthDate) / 365 AGE


2 FROM student;

LAST FIRST AGE


-- --- --- ---- --- -- --- --- ---- --- --- --- --- -
Diaz Jose 20.8289038
Tyler Mickey 19.7330134
Patel Rajesh 17.9960271
Rickles Deborah 33.1521915
Lee Brian 18.0343832
Khan Amir 19.4289038

6 rows selected.

SQL>

Figur e 6-9 Age calculation from birth date.

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

Similarly, we can find the number of months or number of weeks by dividing


days by 30 or 7, respectively.
The common date functions and their use are given in Figure 6-10. The func-
tion M ONTHS_B E TW E EN returns a number. I f is later than , the result
is positive; otherwise, the result is negative. The decimal part in the result is because
of the portion of the month or extra days of the month. I t is useful in finding the
delay between delivery date and payment date. For example,
MONTHS_BETWEEN(‘02-DEC-03’, ‘04-APR-03’) 7.93548387

Date Function Use

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.

Figure 6-10 Date functions.

The function A D D _M ON THS adds the number of months supplied as a second


argument. The number must be an integer value. I t can be positive or negative. For
example, if an item is shipped today and payment is due in three months, what is the
payment date?
ADD_MONTHS(‘10-MAY-03’, 3) ‘10-AUG-03’

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

The R O U N D function rounds a date based on the format specified. I f a for-


mat is missing, rounding is to the nearest day. For example,
ROUND(TO_DATE(‘07/20/03’, ‘MM/DD/YY’), ‘MONTH’) ‘01-AUG-03’

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:

ROUND(TO_DATE(‘07/20/03’, ‘MM/DD/YY’), ‘YEAR’) ‘01-JAN-04’

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,

TRUNC(TO_DATE(‘07/20/03’, ‘MM/DD/YY’), ‘MONTH’) ‘01-JUL-03’TRUNC(TO_DATE(


‘07/20/03’, ‘MM/DD/YY’), ‘YEAR’) ‘01-JAN-03’

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:

C U R RE N T_D A TE — returns the current date the in session’s time zone.


CU RR E NT_TI M ESTA MP— returns the current date and time in the ses-
sion’s time zone.
D B TI M E ZO NE — returns the value of the database’s time zone.
SE SSI ON TI ME ZONE — returns the current session’s time zone.
SY STI MESTA MP— returns the date and time in the time zone of the database.

Other Functions. The NV L function converts a null value to an actual


value supplied as an argument. The second argument is enclosed within the single
quotation marks for columns with DA TE, CH A R , or V A R CH A R 2 data types. The
general syntax is

If the value in a column is null, convert it to a specified value. For example,

NVL(Commission, 0) NVL(HireDate, ‘01-JAN-03’)


NVL(PreReq, ‘None’)
142 Chap. 6 Working with Tables: Functions and Grouping

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).

SQL> SELECT Lname, Fname,


2 Salary + NVL(Commission, 0) “Total Salary”
2 FROM employee;
LNAME FNAME Total Salary
-- --- --- ---- --- - ---- --- --- ---- ---- --- --- --
Smith John 300000
Houston Larry 160000
Roberts Sandi 75000
McCall Alex 66500
Dev Derek 100000
Shaw Jinku 27500
Garner Stanley 50000
Chen Sunny 35000

8 rows selected.

SQL>

Figur e 6-11 Arithmetic with the NVL function.

A n extension of the NV L function is the NVL 2 function. I t takes three param-


eters instead of the two parameters used by NV L function. The NV L2 function
checks for null as well as not null values. If the column has a not null value, the sec-
ond parameter is displayed. If the column has a null value, the third parameter is dis-
played. The general syntax is

For example,
NVL2(PreReq, ‘YES’, ‘NO’)

If prerequisite has a not null value, YE S is displayed. If prerequisite is null, NO


isdisplayed.
A nother similar function is CO A L E SC E . I t is also an extension to the NVL
function. The NV L function specifies a single alternative for a null value, whereas
the C OA L E SC E function provides multiple alternatives. The general syntax is
Built-In Functions 143

For example,

COALESCE(Commission, Salary, -1)

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.

SELECT Lname, Salary, DECODE(PositionId, 1, Salary * 1.2,


2,Salary * 1.15,
3,Salary * 1.1,
4,Salary * 1.05,
Salary) “NewSalary”
FROM employee;

The C A SE structure is an easier alternative to the D E C OD E function. I t also


uses a conditional expression, with the key words W H E N and THEN. A CA SE struc-
ture ends with the key word END. The C A SE structure can be used in the SELECT,
144 Chap. 6 Working with Tables: Functions and Grouping

FR OM , W H E R E , or OR D E R BY clause. L et us rewrite the D E C O D E function


(given above) with C A SE structure:
SELECT Lname, Salary,
CASE WHEN PositionId =1 THEN Salary*1.2
WHEN PositionId =2 THEN Salary*1.15
WHEN PositionId =3 THEN Salary*1.1
WHEN PositionId =4 THEN Salary*1.05 ELSE
Salary
END “New Salary” FROM employee;

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.

Conversion Function Use

TO _ CHAR1 | 2 Converts a number or a date to a V AR CHAR 2 value


based on the format provided.
TO_NUMBER ( [, ]) Converts a character value with valid digits to a
number using the format provided.
TO_DATE( [, ]) Converts a character value to date value based on the
format provided. Default format is DD-MON-Y Y.

Figur e 6-12 Conversion functions.

The TO_ CH A R function converts a number or date value to its character


equivalent. The format argument is enclosed in single quotation marks, and the for-
mat value is case sensitive. Figures 6- 13 to 6-16 describe common formats for number
and date with examples. I n Figure 6-16, fill mode (fm) is used to remove unnecessary
spaces or zeroes in the front or in the middle.

Number Format Meaning

9 Number of 9s to determine length (e.g., 99999). Displays


0 leading zeroes (e.g., 099999).
$ Displays floating dollar sign (e.g., $99999).
. Displays decimal point in specified location (e.g., 99999.99).
, Displays comma in specified location (e.g., 99,999).
PR Puts negative numbers in parenthesis (e.g., 99999PR).

Figur e 6-13 Number formats.


Built-In Functions 145

SQL> SELECT Lname, Fname, TO_CHAR(Salary, ’$999,999’) SALARY


2 FROM employee;

LNAME FNAME SALARY


-- ---- ---- ----- --- ----- ---- --- --- ---- --
Smith John $265,000
Houston Larry $150,000
Roberts Sandi $75,000
McCall Alex $66,500
Dev Derek $80,000
Shaw Jinku $24,500
Garner Stanley $45,000
Chen Sunny $35,000

8 rows selected.

SQL>

Figur e 6-14 T O_CHAR with number format.

Date/Time Format Meaning

Y YYY Four-digit year


Y, Y Y , or Y YY Last one, two, or three digits of the year
Y EAR Year spelled out
Q Quarter of the year
MM Two-digit month
MON First three letters of the month
MONTH Month name using nine characters; left characters padded with spaces
Month Same as MONTH, but in InitCap format
RR Two-digit year based on century (previous century for years 50 to 99 and
current century for years 00 to 49)
RM Month in Roman numerals
W W or W Week number of year or month
DD D, D D, or D Day of year, month, or week
DAY Name of day using nine characters; left characters padded with blanks
DY Three-letter abbreviated name of day
DDTH Ordinal number (e.g., seventh)
DDSP Spelled-out number
DDSPTH Spelled-out ordinal number
HH , HH 12, or HH24 Hour of day, or hour (0–12), or hour (0–23)
MI Minute (0–59)
SS Second (0–59)
SSSSS Seconds from midnight (0–86399)
“of” String in quotes displayed in the result
fm Fill mode used with other format mask (e.g., DAY ) to suppress blanks

Figur e 6-15 Date/time formats.


146 Chap. 6 Working with Tables: Functions and Grouping

SQL> SELECT Last, First,


2 TO_CHAR (BirthDate, ’fmMonth DD, YYYY’) DOB
2FROM student 4 /

LAST FIRST DOB


-- ---- ---- ----- --- ---- ---- ---- --- ----- ---- ---- --
Diaz Jose February12,1983
Tyler Mickey March 18, 1984
Patel Rajesh December 12,1985
Rickles Deborah October 20,1970
Lee Brian November 28,1985
Khan Amir July7,1984

6 rows selected.

SQL>

Figur e 6-16 TO_CHA R with date format (fill mode).

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> SELECT TO_CHAR(TO_DATE(’15-APR-60’, ’DD-MON-RR’), ’YYYY’) “19TH”,


2 TO_CHAR(TO_DATE(’15-APR-03’, ’DD-MON-RR’), ’YYYY’) “20TH”
3 FROM DUAL;
19TH 20TH
- --- - ---
1960 2003
SQL>

Figure 6-17 TO_CH AR with R R date format.

Nested Functions. Single-row functions can be nested within each other. In


nested functions, the innermost function is evaluated first, and then evaluation moves
outward. The outermost function is evaluated last. There is no limit on layers of nesting
for single- row functions. Evaluate the expression in Figure 6-18. First, the TO_D ATE
function is applied to the character date string, then the TR U N C function truncates it
Built-In Functions 147

SQL> SELECT NEXT_DAY(ADD_MONTHS(TRUNC


2 (TO_DATE(’01/13/03’, ’MM/DD/YY’), ’MONTH’), 3), ’TUESDAY’) +7
3 AS “TAX DAY OR BIRTHDAY”
4 FROM DUAL;
TAX DAY O
- --- -- ---
15-APR-03

SQL>

Figur e 6-18 Nested single-row functions.

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:

● Who makes the lowest salary?


● Who got the maximum commission?
● What is the company’s total payroll?
● How many students started in the Winter 2003 semester?
I t is easy to look through small tables and find answers. I n a real- life situation,
however, most tables have thousands or even millions of records. I t is efficient to
look through them with simple queries and group functions.
While using the functions described in Figure 6-19, the key words D ISTI NCT or
A L L can be used before listing the argument in parenthesis. The key word ALL,

Group Function Use

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.

Figur e 6-19 Group functions.


148 Chap. 6 Working with Tables: Functions and Grouping

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.

SQL> SELECT SUM(Salary), AVG(Salary), MAX(Salary), MIN(Salary)


2 FROM EMPLOYEE;

SUM(SALARY) AVG(SALARY) MAX(SALARY) MIN(SALARY)


-- ---- ----- - ----- ---- -- - ---- ----- - --- ---- ----

741000 92625 265000 24500

1 row selected.

SQL>

Figur e 6-20 Group functions.

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> SELECT MAX(BirthDate) YOUNGEST,


2 MIN(BirthDate) OLDEST
3 FROM student;
YOUNGEST OLDEST
- --- --- -- ---- -- ---
12-DEC-85 20-OCT-70

SQL>

Figur e 6-21 Group function on a date column.

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

SQL> SELECT COUNT(*)


2 FROM employee;

COUNT(*)
--- --- -- --
8

SQL>

Figure 6-22 COUNT all rows.

SQL> SELECT COUNT(EmployeeId), COUNT(Commission)


2 FROM employee;

COUNT(EMPLOYEEID) COUNT(COMMISSION)
--- --- --- -- --- --- -- --- --- -- --- --- -
8 5

SQL>

Figure 6-23 CO UN T columns with and without null values.

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?

SELECT AVG(Commission) FROM EMPLOYEE;


SELECT AVG(NVL (Commission, 0)) FROM EMPLOYEE;

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

Important points to remember include:

● W hen you include a group function and the G R O U P BY clause in your


query, the individual column(s) appearing in SE L E CT must also appear in
G R O U P BY.
● The W HE R E clause can still be used to restrict data before grouping.
● The W H E R E clause cannot be used to restrict groups.
● A column alias cannot be used in a G R O U P BY clause.
● The GR O U P BY column does not have to appear in a SE L E C T query.
● W hen a column is used in the GR O U P BY clause, the result is sorted in as-
cending or der by that column by default. I n other words, GR O U P BY hasan
implied OR D E R BY . Y ou can still use an O R D E R BY clause explicitly to
change the implied sort order.
● I n Oracle9i, the order of the W HE R E and G RO U P BY clauses in the SELECT
query does not matter, but traditionally, the W HE R E clause is written before
the G R O U P BY clause.

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.

SQL> SELECT DeptId, COUNT(*) “#of Emp”


2 FROM employee
3GROUP BY DeptId 4 /

DEPTID # of Emp
-- --- -- - --- -- -
10 3
20 2
30 2
40 1
SQL>

Figur e 6-24 COU NT rows by group.

What will happen if the query in Figure 6-24 is typed without a GR O U P BY


clause? If the SE L E CT clause contains only a group function, it does not matter.
The query in the figure, in fact, has the SE L E CT clause with a column and a group
function. W hen a column appears in the SE LE C T clause along with the group func-
tion, the column must appear in the GR O U P BY clause. Failure to do so results in
er ror ORA -00937 (see Fig. 6-25).
Grouping Data 151

SQL> SELECT DeptId, COUNT(*) “# of Emp”


2 FROM employee 3 /
SELECT DeptId, COUNT(*) “# of Emp”
*

ERROR at line 1:
ORA-00937: not a single-group group function

SQL>

Figur e 6-25 Missing G R OU P BY clause.

Can we use a condition in the W H E R E clause that contains a group function?


The W H E R E clause can be used to restrict rows, but it cannot be used to restrict
groups, as you see in Figure 6- 26. I n this figure, we are trying to see buildings that
have four or more rooms. The error ORA- 00934 states that the group function is not
allowed in the W H E R E clause. W e can fix this problem with a new, HA V I NG
clause, which is used for restricting groups, as you will see shortly.

SQL> SELECT Building, COUNT(*)


2 FROM location
3 WHERE COUNT(*) >= 4
4 GROUP BY Building; WHERE COUNT(*) >= 4
*

ERROR at line 3:
ORA-00934: group function is not allowed here
SQL>

Figur e 6-26 Invalid W H ER E clause.

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> SELECT Building, COUNT(*) ROOMS


2 FROM location
3 WHERE UPPER(Building) <> ’KENNEDY’
4 GROUP BY Building
5 HAVING COUNT(*) >= 4;
BUILDIN ROOMS
- --- --- - --- --
Gandhi 5
1 row selected.SQL>

Figur e 6-27 HAVING clause.

SQL> SELECT Building, COUNT(*)


2 FROM location
3 GROUP BY Building
4 HAVING COUNT(*) > 2;
BUILDIN COUNT(*)
- --- --- - --- -- --
Gandhi 5
Kennedy 4

SQL> i
5 ORDER BY Building DESC;
BUILDIN COUNT(*)
- --- --- - --- -- --
Kennedy 4
Gandhi 5

SQL>

Figur e 6-28 G R O UP BY sort order changed with O R D E R BY .

L et us look at another example of G R OU P BY and HA V ING. L et us find em-


ployees who have more than two dependents. We will use the D E PE N D E N T table
and G R O U P BY EmployeeId column, find C O U N T of D ependentId, and also
check for C O U N T higher than 2:

SELECT EmployeeId, COUNT(DependentId) FROM dependent


GROUP BY EmployeeId
HAVING COUNT(DependentId) > 2;
Chap. 6 ExerciseQuestions 153

Nesting Group Functions

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

3. Single-row functions can be nested to two levels only.


4. The M AX function on a date column will return the latest date.
5. The TO_ CHA R function converts date and numeric values to V ARCHAR2.
6. The A N D operator returns a T R U E result if one of the two conditions is true.
7. There is no limit in nesting group functions to multiple levels.
8. The W HE R E clause restricts individual rows, but the HA V I NG clause restricts groups.
9. The O R D E R BY clause can be used in a query with the G R OU P BY clause to override
the implied sort order.
10. Null values in a column are not counted by the COU NT function.
L ist Output from the Following Queries (U se Tables Created in the Chapter 4 L ab Activity):
1. SELECTINITCAP(First) |‘’||INITCAP(Last) “Student Name” FROM student;
2. SELECT COUNT(DISTINCT(MajorId)) FROM student;
3. SELECT Building, SUM(Capacity) TOTCAPFROM location
GROUP BY Building ORDER BY TOTCAPDESC;
4. SELECT UPPER(Lname), UPPER(Fname), (SYSDATE – HIREDATE) DAYS FROM employee
ORDER BY DAYS;
5. SELECT Building, AVG(Capacity) FROM location
GROUP BY Building
HAVING AVG(Capacity) > 25;

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

3. Count the total number of rooms in LOCATION.


4. Count the distinct building names in LOCATION.
5. Display all student names and birth dates (display birth dates with the format 20 OCTO-
B ER , 1970).
6. Find the average, highest, and lowest age for employees.
7. Display the total number of dependents for each employee for employees who have at
least two dependents.
8. Display only the year value from each employee’s hire date.
9. Find average employee commission.
(a) Ignore nulls.
(b) Do not ignore nulls.
10. Find sum of maximum count by term by course (G R OU P BY two columns).
11. Find 2 to the power of 10.
12. Display courses and prerequisites. If there is no prerequisite, display “ none” or else
display “one.”
13. Count number of faculty members by each department.
14. Display average employee salary by department, but do no include departments with an
average salary of less than $75,000.
15. Find the number of years employees have been working. Display the integer part of the
value only.
16. Find students who are born in the month of May.
17. Display employee’s last name and first name, followed by salary + commission if the
commission is not null or else display salary only.
18. Display each employee’s full name followed by a message based on salary. If the salary
is above $100,000, display “ HI GH.” If the salary is between $50,000 and $100,000, display
“ MEDI U M .” If the salary is below $50,000, display “L OW.”
IN THIS CHAPTER . . .

● Y ou will learn to design queries based on multiple tables.


● Y ou will retrieve related data from various tables in a database.
● V arious types of table joins are discussed.
● Set operations UNION, U NI ON A L L , I N TE RSE CT and MINU S are used.

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

SQL> SELECTLast, First, Name


2 FROMstudent, faculty;

LAST FIRST NAME


-- --- -- --- --- -- --- -- --- --- -- --- -- --- --- --
Diaz Tyler Patel Jose Mickey Jones Jones Jones
Rickles Lee Khan Rajesh Deborah Jones Jones Jones
Diaz Tyler BrianAmir Jose Williams Williams
... Mickey
Patel Rickles Lee
Khan
48 rows selected.
SQL>

Rajesh Collins
Deborah Collins
BrianAmir Collins
Collins

Figur e 7-1 Cartesian product.


158 Chap. 7 Multiple Tables: Joins and Set Operations

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:

SELECT FROM WHERE

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

SQL> SELECT student.Last | ’,’ | student.First STUDENT,


2 faculty.Name FACULTY, faculty.Phone TEL
2 FROM student, faculty
2WHEREstudent.FacultyId = faculty.FacultyId 5 /

STUDENT FACULTY TEL

-- -- --- --- -- --- --- --- -- - -- --- --- -- - -- -


Diaz,Jose Mobley 529
Tyler, Mickey Chang 587
Patel,Rajesh Jones 525
Rickles, Deborah Chang 587
Lee, Brian Sen 579
Khan,Amir Williams 533

6 rows selected.

SQL>

Figur e 7-2 Equijoin.


in the STU D E NT table. O n the other hand, 1FacultyId = 5552 is picked twice
because it appears twice as a value in the foreign key column of the STU D E N T table.
The Cartesian product, as mentioned earlier, is rarely useful, but equijoin is a
very important operation in database querying. A nother thing to be noted is the use
of . W hen columns are retrieved from more than one table,
the use of a table name qualifier in front of the column name tells Oracle to retrieve
that column from the specified table. Oracle is pretty smart about it. If a column
name exists in only one of the two tables involved in the query, it is not necessary to
use a table name as a qualifier. If a column exists in both tables, you must use the
table name qualifier. The join condition in an equijoin will normally have the table
name qualifier. Because the join condition usually has the same column names from
two tables, the column names become ambiguous without a qualifier. The qualifier
actually improves performance because you are telling the Oracle server where to
go to find that column. Remember that the two join columns need not have the
same name.
Sometimes, the required information is in more than two tables. I n this case,
the F RO M clause will include all needed tables, and the W H E R E clause will have
more than one join condition. I f you need to join tables, you would need - 1
join conditions. I n our NamanNavan (N2) Corporation database, an employee’s de-
mographic information is in the E M PL OY E E table. The E MPL OY E E table has
three foreign keys: PositionId, referencing the POSI TI O N table; QualId, referenc-
ing the QU A L I FI CA TI ON table; and D eptI d, referencing the D E PT table. Y ou
would need to join four tables to retrieve information from all those tables. This
means the query will have 4 - 1 = 3 join conditions.
160 Chap. 7 Multiple Tables: Joins and Set Operations

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.

SQL> SELECT employee.Lname | ’, ’ | employee.Fname EMPLOYEE,


2 dept.DeptName DEPARTMENT, position.PosDesc POSITION
3 FROM employee, dept, position
4 WHEREemployee.DeptId = dept.DeptId
5 AND employee.PositionId = position.PositionId;

EMPLOYEE DEPARTMENT POSITION


--- --- -- --- --- -- --- --- -- --- -- --- --- - -- --- -- ---
Smith, John Finance President
Houston, Larry Marketing Manager
Roberts,Sandi Finance Manager
McCall, Alex InfoSys Programmer
Dev, Derek InfoSys Manager
Shaw, Jinku Sales Manager
Garner, Stanley Sales Manager
Chen, Sunny Finance Accountant

8 rows selected.SQL>

Figur e 7-3 Multiple joins.

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

SQL> SELECT e.Lname |’,’|| e.Fname EMPLOYEE,


2 d.DeptName DEPARTMENT, q.QualDesc QUALIFICATION
3 FROM employee e,dept d, qualification q
4 WHERE e.DeptId = d.DeptId
5AND e.QualId = q.QualId 6 /

EMPLOYEE DEPARTMENT QUALIFICATI


--- --- -- --- --- -- --- -- - --- --- -- --- --- -- -- --- ---
Smith, John Finance Doctorate
Houston, Larry Marketing Masters
Roberts,Sandi Finance Masters
McCall, Alex InfoSys Associates
Dev, Derek InfoSys Doctorate
Garner, Stanley Sales High School
Chen, Sunny Finance Bachelors

7 rows selected.SQL>

Figur e 7-4 Table aliases.

E M PL O Y E E table with the Q U A L I FI C A TI O N tables instead of the PO SI TI ON


table. The result contains seven rows in Figure 7- 4 instead of eight rows, as in
Figure 7- 3, because one of the employees does not have a Q ualI d.

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

SQL> SELECT e.Lname |’, ’|| e.Fname EMPLOYEE,


2 d.DeptName DEPARTMENT, q.QualDesc QUALIFICATION,
3 p.PosDesc POSITION
4 FROM employee e, dept d, qualification q, positionp
5 WHEREe.DeptId = d.DeptId
6 AND e.QualId = q.QualId
7 AND e.PositionId = p.PositionId
8AND e.DeptId = 10 9 /

EMPLOYEE DEPARTMENT QUALIFICATI POSITION


-- --- -- --- --- -- --- --- --- -- -- -- --- -- --- - --- -- --- -- -- -- --- --
Smith, JohnRoberts,Sandi Chen, Sunny Finance Doctorate President
Finance Masters Manager
SQL>
Finance Bachelors Accountant

Figure 7-5 Additional condition with join.

SQL> SELECT e.Lname |’, ’|| e.Fname EMPLOYEE, e.Salary, l.LevelNo


2 FROM employee e, emplevel l
3WHERE e.Salary BETWEEN l.LowSalary AND l.HighSalary 4 /

EMPLOYEE SALARY LEVELNO


--- --- -- --- --- -- --- --- - - --- --- -- --- -- --- --- -- --
Shaw, Jinku 24500 1
Garner, Stanley 45000 2
Chen, Sunny 35000 2
Roberts,Sandi 75000 3
McCall, Alex 66500 3
Dev, Derek 80000 3
Smith, John 265000 4
Houston, Larry 150000 4

8 rows selected.SQL>

Figur e 7-6 Nonequijoin.

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 = (+);

Figure 7- 7 shows an outer join using the E MPLO Y E E and QU A L I FI CA TI ON


tables. The outer join operator 1 + 2 is used on the QU A L I FI C A TI O N side, because

SQL> SELECT e.Fname |’, ’|| e.Lname EMPLOYEE, q.QualDesc


2 FROM employee e, qualification q
3WHERE e.QualId = q.QualId (+) 4 /

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

Figur e 7-7 Outer join.


164 Chap. 7 Multiple Tables: Joins and Set Operations

SQL> SELECT s.First |' '|| s.Last STUDENT,


2 f.Name ADVISOR
3 FROM faculty f, student s
4WHERE s.FacultyId(+) = f.facultyId 5 /
STUDENT ADVISOR
--- -- -- --- --- -- --- -- --- -- --- - -- -- --- -- --- -- --- -- --- -
RajeshPatel Jones
Jose Diaz Mobley
Amir Khan Williams
Vajpayee Collins
BrianLee Sen
Rivera
Mickey Tyler Chang
Deborah Rickles Chang

9 rows selected.

SQL> SELECT s.First |' '|| s.Last STUDENT,


2 f.Name ADVISOR
3 FROM faculty f, student s
4WHERE s.FacultyId = f.facultyId 5 /
STUDENT ADVISOR
--- -- -- --- --- -- --- -- --- -- --- - -- -- --- -- --- -- --- -- --- -
Jose Diaz Mobley
Mickey Tyler Chang
RajeshPatel Jones
Deborah Rickles Chang
BrianLee Sen
Amir Khan Williams

6 rows selected.

SQL>

Figure 7-8 Comparing outputs from outer join and equijoin.

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.

SQL> SELECT e.Lname |’,’|| e.Fname Employee,


2 s.Lname |’, ’|| s.Fname Manager
3 FROM employee e, employee s
4 WHERE e.Supervisor = s.EmployeeId;
EMPLOYEE MANAGER
- --- -- --- -- --- -- --- -- --- - -- --- -- --- -- --- -- --- -
Houston, Larry Smith, John
Roberts, Sandi Smith, John
McCall,Alex Dev,Derek
Dev, Derek Smith, John
Shaw, Jinku Garner, Stanley
Garner,Stanley Smith, John
Chen, Sunny Roberts,Sandi
7 rows selected.SQL>

Figur e 7-9 Self-join.

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-

where is one of the four set operators described in Figure 7-10a.

Set O per ator Use

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.

Figur e 7-10a Set operators.

I n Figure 7- 10b, set operators UNION, I NTE R SE C T and MI NU S are shown


using V enn diagrams. The left circle represents the first table, and the right circle
represents the second table. The shaded area is the area selected by each operation.
The U N I O N operator selects all rows from the first table as well as the second table,
so both circles are entirely shaded. The I NTE R SE CT operator selects rows present
in both tables, so the common area is shaded. The MI NU S operator selects rows in
the first table that are not present in the second table, so the area exclusively be-
longing to the first table is shaded.
We will use the STU D E NT table from the I U College database, which has all
student records. Now, we will use another table called W O R K E R (see Fig. 7-11),
which contains staff members of the college and also student workers.

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

Figure 7-10b Set operators— illustration with Venn diagrams.

WORKER (WorkerId, Last, First)

WorkerId Last First


00110 Borges Luz
00111 Bayer Julia
00103 Rickles Deborah
00113 Marte Noemi
00105 Khan Amir
00107 Feliciano Sandi Figur e 7-11 WO R KE R table.

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

The U NI O N A L L operation is similar to the U N I O N operation. The only difference


is that U NI O N A L L operation also displays duplicate rows. If you find U NI ON A L L
of the STU D EN T and W O RK E R tables, you will get six rows from the first query
and six rows from the second query (see Fig. 7-13).
168 Chap. 7 Multiple Tables: Joins and Set Operations

SQL> SELECT StudentId ID, Last, First FROM student


2 UNION
3SELECT WorkerId, Last, First FROM worker 4 /
ID LAST
FIRST
-- -- - --- -- --- -- --- -- --- -- --- --- -- -
00100 Diaz Jose Mickey Rajesh
00101 Tyler DeborahBrian Amir
00102 Patel Sandi Luz
00103 Rickles Julia Noemi
00104 Lee
00105 Khan
00107 Feliciano
00110 Borges
00111 Bayer
00113 Marte
10 rows selected.SQL>

Figur e 7-12 U NIO N operation.

SQL> SELECT StudentId ID, Last, First FROM student


2 UNION ALL
3SELECT WorkerId, 4 / Last, First FROM worker

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>

Figur e 7-13 U NIO N ALL operation.


Set Operators 169

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> SELECT StudentId ID, Last, First FROM student


2 INTERSECT
3SELECT WorkerId, 4 / Last, First FROM worker
LAST
ID --- -- --- --- -- FIRST
-- --- Rickles Khan -- --- -- --- --- --
00103 DeborahAmir
00105

SQL>

Figur e 7-14 INTER SECT operation.

Minus

The MI NUS operation is same as the D I F FE RE N CE operation covered in Chapter 1.


When MI NU S is performed on outputs from two queries, the result is the rows in
the first query’s result that are not in the second query’s result. R emember that the
STU D E NT table minus the W O R K E R table is not the same as the W OR K E R table
minus the STU D E NT table. Figure 7- 15 is an example of a minus operation in which
the result includes students who are not workers. Figure 7-16 shows workers who
are not students.
Join operations are useful, but sometimes, they are achieved through a very
complex query. Talking about complexity, Figure 7-17 gets information from six tables

SQL> SELECT StudentId ID, Last, First FROM student


2 MINUS
3SELECT WorkerId, Last, First FROMworker 4 /

ID LAST FIRST
--- -- - --- --- -- --- - -- --- -- --- --- -
00100 Diaz Jose
00101 Tyler Mickey
00102 Patel Rajesh
00104 Lee Brian
4 rows selected.
SQL>

Figur e 7-15 Student MINUS Worker.


170 Chap. 7 Multiple Tables: Joins and Set Operations

SQL> SELECT WorkerId ID, Last, First FROM worker


2 MINUS
3SELECT StudentId, Last, First FROM student 4 /

ID LAST FIRST
--- -- - --- --- -- --- - -- --- -- --- ---
00107 Feliciano Sandi
00110 Borges Luz
00111 Bayer Julia
00113 Marte Noemi
4 rows selected.
SQL>

Figur e 7-16 Worker MINUS Student.

SQL> SELECT e.Fname |' ' | e.Lname "NAME",


2 s.Fname |' ' | s.Lname "SUPERVISOR",
3 PosDesc, DeptName, QualDesc, LevelNo
4 FROM employee e,position p, dept d,
5 qualification q, employee s, emplevel l
6 WHERE e.PositionId=p.PositionId
7 AND e.DeptId=d.DeptId
8 AND e.QualId = q.QualId (+)
9 AND e.Supervisor=s.EmployeeId (+)
10 AND e.Salary BETWEEN l.LowSalary AND l.HighSalary
11 ORDER BY e.Lname, e.Fname;
NAME
SUPERVISOR POSDESC DEPTNAME QUALDESC LEVELNO
-- --- -- --- -- -- -- --- -- --- -- --- -- --- -- -- --- -- --- - -- -- --- -- -- - --- -- --- -- -
Sunny ChenDerek Sandi Roberts Accountant Finance InfoSys Bachelors 2
Dev Stanley Garner JohnSmithJohn Manager Sales Marketing Doctorate 3
Larry HoustonAlex SmithJohnSmith Manager InfoSys Finance High School 2
McCall Sandi Derek Dev John Manager Sales Finance Masters 4
Roberts Jinku SmithStanley Programmer Associates 3
ShawJohnSmith Garner Manager Masters 3
Manager 1
8 rows selected.
President 4
Doctorate
SQL>

Figur e 7-17 Joining them all.


Chap. 7 ExerciseQuestions 171

(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

1. U se the N2 Corporation database tables to design the following queries.


(U se the spooling method to capture all queries and results in the CHAP7SP1.LST file.)

a Display all employee names and their department names.

b Find name of the supervisor for employee number 433.

c Find all employees’ full names (lastname, firstname format) with salary and their su-
pervisor’s name with salary.

d Find each employee’s salary information and level based on the salary.

e Display each employee’s name, department name, position description, and qualifica-
tion description. W hich employee is missing? Why?

f Find all employees in the sales department.

g Display employee names and dependent information using an outer join.

h Find the names of employees and number of years worked along with their depart-
ment names in descending order by number of years worked.
.i W ho works in the same department in which John Smith works?
2. Use the I U College database tables to design the following queries.
(U se the spooling method to capture all queries and results in the CHAP7SP2.L ST file)

a Display a student’s full name along with his or her major’s description.

b G et the names of students who received a final grade of F in W inter 2003.

c Display student names, their faculty advisor names, and faculty office location.

d G et Spring 2003 course sections with the faculty member assigned to teach the class.
Include course sections without any faculty assigned to them.

e Display course titles along with their prerequisite names. Display courses without
prerequisite as well.
IN THIS CHAPTER . . .

● Subqueries or nested queries are introduced for data retrieval.


● V arious operators, such as ANY, SOM E, and A L L, are introduced.
● Subqueries are used with other data management and data definition language
statements.
● Multiple INSERT statements, such as INSE RT A L L and INSERT FIRST,
are used.
● A new M E R G E statement is introduced.
● Correlated queries are introduced with EX ISTS and NOT EX ISTS operators.
I n Chapter 5, you learned data retrieval techniques to obtain data from a sin-
gle table with the SE L E CT query. Y ou also learned the use of various clauses and
functions used in SE L E CT statements in C hapter 6. I n Chapter 7, you learned to
create queries where data are retrieved from more than one table or with more than
one query. Sometimes, you can accomplish tasks by joining two or more tables, by
joining a table to itself, or by using the output from one query as data in another.
The queries can be nested to create a table based on an existing table, to populate a
table with rows from another table, or to perform updates and deletions.
174 Chap. 8 Subqueries: Nested Queries

SUBQUERY

Subqueries are also known as nested queries. A subquery is usually a SEL E CT


query within one of the clauses in another SE LE C T query. Very powerful queries
can be designed by using simple subqueries. A subquery is very useful when a query
based on a table depends on the data in that subquery itself. The subquery can be
used within a W HE RE , HA VI NG, or FR O M clause of another SE LE C T query.
Subqueries are of two types:

1. Single-r ow subquer y: a subquery that returns only one row of data; it is


also known as a scalar subquery.
2. Multiple- r ow subquer y: a subquery that returns more than one row of
data.

Single-Row Subquery

The general syntax is

There are certain rules you have to follow while creating a subquery:

● The subquery must be enclosed within a pair of parentheses.


● The subquery returns one column from one row in most cases. I f no row is
returned, the value is null. If more than one row is returned, an error occurs.
● The O R D E R BY clause cannot be used in a subquery.
● The subquery is used on the right side of the condition.
● Relational operators 1= , 6 7 1or ! =2, 7 , 7 = , 6 , and 6 = 2 are used in the
outer query’s condition.

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

SQL> SELECT Lname, Fname, Salary, DeptId


2 FROM employee
3 WHERE DeptId =
4 (SELECT DeptId
5 FROM dept
6 WHERE UPPER(DeptName) = ’FINANCE’);

LNAME FNAME SALARY DEPTID


-- --- -- --- --- -- -- --- -- --- --- -- -- -- -- --- - -- -- --- -- -
SmithRoberts Chen JohnSandi Sunny 265000 10
75000 10
SQL>
35000 10

Figure 8-1 Subquery using two tables.

= 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

SQL> SELECT Lname, Fname, Salary, DeptId


2 FROM employee
3 WHERE Salary >=
4 (SELECT Salary
5 FROM employee
6 WHERE UPPER(Lname) = ’DEV’);

LNAME FNAME SALARY DEPTID


-- --- -- --- --- -- -- --- -- --- --- -- -- -- -- --- - -- -- --- -- -
SmithHouston Dev JohnLarryDerek 265000 10
150000 40
SQL>
80000 20

Figur e 8-2 Subquery using one table.

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

SQL> SELECT Lname, Fname, Salary, DeptId


2 FROM employee
2 WHERE DeptId !=
2 (SELECT DeptId
2 FROM employee
2WHERE UPPER(Lname) = ’SMITH’) 7 /

LNAME FNAME SALARY DEPTID


- --- --- --- -- --- -- --- -- --- --- -- -- --- --- -- - --- --- -- -
Houston Larry 150000 40
McCall Alex 66500 20
Dev Derek 80000 20
Shaw Jinku 24500 30
Garner Stanley 45000 30

5 rows selected.

SQL>

Figur e 8-3 Subquery with ! = operator.

A subquery may be nested to more levels. I n a multilevel subquery, the inner-


most query executes first, and then the execution propagates outward. I n a three-
level subquery, the output from the innermost query is used by the query nesting it,
and the output of that query is used by the outmost query that encloses it.
In the Indo–US (I U ) College database, each student has an assigned faculty ad-
visor. The faculty advisor has an office in one of the college buildings. Suppose a stu-
dent wants to find out location of his or her advisor’s office. The result can be obtained
by joining the STUD ENT, FA CU LTY , and L OC A TI ON tables. Alternately, a three-
level subquery can render the same result as shown in Figure 8- 4. Student Brian Lee
wants to see his faculty advisor during office hours. First, the innermost query finds
out the FacultyId of the advisor from the STU D E NT table, which is used by enclosing
a query to find the RoomId from the FA CUL TY table, which in turn is used by the
outermost query to find the Building and RoomNo from the L OC A TI ON table.
Creating a Table Using a Subquery You can create a table by using a
nested SEL E C T query. The query will create a new table and populate it with the
rows selected from the other table. The general syntax is

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

SQL> SELECT Building, RoomNo


2 FROM location
3 WHERE RoomId =
4 (SELECT RoomId
5 FROM faculty
6 WHERE FacultyId =
7 (SELECT FacultyId
8 FROM student
9 WHERE UPPER(Last) = ’LEE’
10 AND UPPER(First) = ’BRIAN’));

BUILDIN ROO
- --- -- - -- -
Gandhi 103
1 row selected.SQL>

Figur e 8-4 Subquery to three levels.

SQL> CREATETABLE temp


2 AS
3 SELECT EmployeeId, Lname, Fname, Salary
4 FROM employee
5 WHERE DeptId = 20;
Table created.

SQL> DESCRIBE temp

Name Null? Type


- --- -- --- --- --- -- --- --- -- --- -- - --- -- -- - --- -- --- --- ---
EMPLOYEEIDLNAME FNAME SALARY NUMBER(3)
NOT NULL VARCHAR2(15)
SQL> SELECT * FROM temp; VARCHAR2(15)
NOT NULL
NUMBER(6)

EMPLOYEEID LNAME FNAME SALARY


-- --- -- --- - --- -- --- --- --- -- --- -- --- --- -- -- --- --- --
433 McCall Alex 66500
543 Dev Derek 80000

2 rows selected.
SQL>

Figure 8-5 CR EA TE using a subquery.


178 Chap. 8 Subqueries: Nested Queries

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.

INSERT Using a Subquery A n existing table can be populated with a sub-


query. The table must already exist to insert rows into it. I NSERT with a subquery
does not create a new table. The general syntax is

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.

SQL> INSERT INTO temp (EmployeeId, Lname, Fname)


2 SELECT EmployeeId, Lname, Fname
3 FROM employee
4WHERE DeptId = 105 /
3 rows created.SQL> SELECT *
2 FROM temp;

EMPLOYEEID LNAME FNAME SALARY


--- -- --- -- --- -- --- --- --- - - --- -- --- --- --- -- --- -- ---
433 McCall Alex 66500
543 Dev Derek 80000
111 Smith John
123 Roberts Sandi
222 Chen Sunny
5 rows selected.
SQL>

Figur e 8-6 INSERT using a subquery.


Subquery 179

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:

1. INSERT A L L (conditional and unconditional)


2. INSERT FIRST

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:

Conditional INSERT FIRST The conditional INSE RT FI RST statement has


the same syntax as the conditional INSE RT A L L statement except for the key word
FI R ST in place of A LL . The working of the statement, however, is different. I t tests
conditions just like the INSERT A L L statement, but if a row satisfies both
conditions Salary 7 50000 and D eptI d6 740, it will be inserted into the first table
only, because the first condition of the W HE N clause is satisfied.
180 Chap. 8 Subqueries: Nested Queries

UPDATE Using a Subquery A nother use of a subquery is in updating data.


If an employee is leaving and his or her position, supervisor, and salary infor-
mation are to be given to another existing employee, U PD A TE can be performed
with a subquery. The general syntax is

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>

Figure 8-7 UPDATE using a subquery.

A n alternate syntax is

The optional W H E R E clause is part of the outer U PD A TE statement in the given


syntax. The inner SE L E C T query may contain another W HE R E clause.
In the example of Figure 8-8, Jinku Shaw 1EmployeeI d = 2002 gets the position,
supervisor, and D eptI d of employee Stanley Garner 1EmployeeI d = 1352. The
inner query returns three values, which are assumed by three columns in the outer
query. Y ou must be careful with the order of columns in both the inner and outer
queries. The order of columns must be same in both queries.

DELETE Using a Subquery A row or rows from a table can be deleted


based on a value returned by a subquery. The general syntax is
Subquery 181

SQL> UPDATE employee


2 SET (PositionId, Supervisor, DeptId) =
3 (SELECT PositionId, Supervisor, DeptId
4 FROM employee WHERE EmployeeId = 135)
5 WHERE EmployeeId = 200;
1 row updated. SQL>

Figur e 8-8 UPDATE using a subquery.

For example, if a corporation decides to close the A ccounting D epartment in Monroe


and all employees in the department are to be removed from the database, you will
use a D E L E TE statement with a subquery. Y ou must remember that to remove a
department from the D E PT table, you must remove all employees from that de-
partment first. Failure to do so will result in constraint violation because of the exis-
tence of child rows in the E M PL O Y E E table. I n Figure 8-9, we have tried to remove
employees from the Accounting D epartment, but no rows have been deleted. There
is no constraint violation here, but the E MPL OY E E table does not contain any em-
ployees in the Accounting D epartment 1DeptId = 802.

SQL> DELETE FROM employee


2 WHERE DeptId =
3 (SELECT DeptId FROM dept
4 WHERE UPPER (DeptName) = ’ACCOUNTING’);
0 rows deleted.SQL>

Figur e 8-9 DE LET E using a subquery.

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

IN ALL Equal to any of the values in a list.


AN Y or SOME Compare the given value to every value returned by the subquery.
Compare the given value to each value returned by the subquery.

Figur e 8-10 Multiple-row subquery operators.


182 Chap. 8 Subqueries: Nested Queries

L et us look at examples of subqueries returning more than one row. Y ou are


already familiar with the I N operator, which is an alternative to multiple O R condi-
tions. The I N operator looks for at least one match from the list of values provided.
In Figure 8-11, the inner query returns two values (111, 123) for faculty members in de-
partment 1. Y ou cannot use the = operator here, but the I N operator is more appro-
priate. U se of the = operator here will result in an error. The outer query returns
students who have faculty 111 or 123 as their advisor.

SQL> SELECT StudentId, Last,First,FacultyId


2 FROM student
3 WHERE FacultyId IN
4 (SELECT FacultyId
5 FROM faculty WHERE DeptId = 1);

STUDE LAST FIRST FACULTYID


---- - ---- ----- ------ ---- ------ ----- ----- -----
00100 Diaz Patel Jose 123
00102 Rajesh 111

SQL>

Figur e 8-11 Subquery with IN operator.

The A N Y operator can be used in combination with other relational opera-


tors. I t serves like an O R operator, because it looks for a match to any one value!
For example:

● 6 A N Y means less than the maximum value in the list.


● =A N Y means equal to any value in the list (similar to IN).
● 7 A N Y means higher than the minimum value in the list.

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

SQL> SELECT EmployeeId, Lname, Fname, Salary


2 FROM employee
3 WHERE Salary >ANY
4 (SELECT Salary FROM employee WHERE PositionId = 2)
5 AND PositionId <> 2;

EMPLOYEEID LNAME FNAME SALARY


----- ----- -- ------ ------ - ------ ----- ---- ---- ------
111 Smith John 265000
433 McCall Alex 66500
SQL>

Figur e 8-12 Subquery with 7A N Y operator.


Top-N Analysis 183

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:

● 7 A L L means more than the maximum value.


● 6 A L L means less than the minimum value.
● = A L L is meaningless, because no value can be equal to all values in a list.

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.

SQL> SELECT EmployeeId, Lname, Fname, Salary


2 FROM employee
3 WHERE Salary <ALL
4 (SELECT AVG (Salary) FROM employee GROUP BY DeptId);

EMPLOYEEID LNAME FNAME SALARY


----- ----- - ------ ------ -- ---- ----- ------ ------ ----
200 Shaw Jinku 24500
SQL>

Figur e 8-13 Subquery with 6A L L operator.

Try the query in Figure 8- 12 with 6 A L L , 7A L L , 6 A N Y , and =A N Y opera-


tors, and check out the results.

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

I n Figure 8-14, Capacity is the Top-N column. The rows in the L OC A TI ON


table are sorted in descending order to get largest capacity at the top of the list. The
condition RO W N U M 6 = 4 selects row numbers 1 through 4, the top-four capaci-
ties. The inner SE L EC T statement in the FR O M clause is used as the data source
for the outer SE L E C T statement. Such a subquery is known as an inline view. The
inline view is a subquery that can be given an alias name for use in an SQL state-
ment, just like a table alias. A n inline view is not stored as an object like the other
views created with a C R E A T E V I E W statement (see Chapter 9). A subquery may
not use the O R D E R BY clause, but an inline view may.

SQL> SELECT rownum, Building, RoomNo, Capacity


2 FROM (SELECT Building, RoomNo, Capacity
2 FROM location
2 ORDER BY Capacity DESC)
2 WHERE ROWNUM <= 4;

ROWNUM BUILDIN ROO CAPACITY


-- -- --- --- - --- -- - -- - - --- --- -- -
1 Kennedy 204 50
2 Nehru 301 50
3 Nehru 309 45
4 Kennedy 206 40

SQL>

Figur e 8-14 Top-4 capacities.

In Figure 8-15, SA LA RY is the Top- N column. The rows in the EM PL OY E E


table are sorted in ascending order, bringing the lowest salaries to the top. The condi-
tion R O W N U M 6 = 3 retrieves the three lowest- salaried employees.

SQL> SELECT ROWNUM, Lname, Fname, Salary


2 FROM (SELECT Lname, Fname, Salary
3 FROM employee
4 ORDER BY Salary)
5 WHERE ROWNUM <= 3;

ROWNUM LNAME FNAME SALARY


- ------ --- ------ ------ --- ---- ------ ----- -- ------ --
1 Shaw Jinku 24500
2 Chen Sunny 35000
3 Garner Stanley 45000

SQL>

Figure 8-15 Bottom-three salaries.


Correlated Subquery 185

Important Note about Top-N Analysis

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

You can use the M E R G E statement to perform I NSERT and U PD A TE operations


together. This operation is very useful in data warehousing. I n Figure 8-16, WORK -
E R is the target table. The STU D E NT and W O RK E R tables are merged based on
WorkerId and StudentId columns. If rows from two tables match, then the L ast and
First columns are updated in the W OR K E R table (WorkerI d 00103 and 00105). If
rows from the STU D E NT table do not have a match in the W O RK E R table, those
rows are inserted in the W O RK E R table (W orkerI d 00102, 00100, 00104, and 00101).

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

SQL> SELECT * FROM worker;


WORKE LAST FIRST
-- --- ------ ------ --- ---- ------ -----
00110
00111
00103
00113
00105
00107

6 rows selected.

SQL> MERGE INTO worker w


2 USING (SELECT StudentId, Last, First
3 FROM student) s
4 ON (s.StudentId = w.WorkerId)
5 WHEN MATCHED THEN

6 UPDATESET w.Last =s.Last,


7 w.First =s.First
8 WHEN NOT MATCHED THEN
9 INSERT (w.WorkerId, w.Last,W.First)
10 VALUES (s.StudentId,s.Last, s.First) 11 /

6 rows merged.

SQL> SELECT * FROM worker;

WORKE LAST FIRST


----- ---- ------ ----- -- ------ ------ -
00110
00111
00103 Rickles Deborah
00113
00105 Khan Amir
00107
00102 Patel Rajesh
00100 Diaz Jose
00104 Lee Brian
00101 Tyler Mickey
10 rows selected.

Figure 8-16 ME R GE statement in action.

EXISTS and NOT EXISTS Operators

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

SQL> SELECT EmployeeId, Salary, DeptId


2 FROM employee outer
3 WHERE Salary =
4 (SELECT MAX(Salary)
5 FROM employee
6 WHERE DeptId = outer.DeptId
7 GROUP BY DeptId);

EMPLOYEEID SALARY DEPTID


---- ------ -- ------ -- --- ----- --
111 265000 10
246 150000 40
543 80000 20
135 45000 30
SQL>

Figur e 8-17 Correlated subquery.

TR U E or FA LSE . The column names in the inner query have no significance. Y ou


can use any single character literal, such as , and so on.
I n Figure 8- 18, the EX ISTS operator checks if a row from the FA CU LTY table
(outer query) is returned at least once by the STU D E N T table (inner query). The
result includes all faculty members who are in the STU D E NT table.

SQL> SELECT FacultyId, Name


2 FROM faculty outer
3 WHERE EXISTS
4 (SELECT ’1’
5 FROM student
6 WHERE FacultyId = outer.FacultyId);

FACULTYID NAME
-- ------ -- -- ------- ------
111 Jones
222 Williams
123 Mobley
345 Sen
555 Chang
SQL>

Figur e 8-18 EXISTS operator.

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

SQL> SELECT FacultyId, Name


2 FROM faculty outer
3 WHERE NOT EXISTS
4 (SELECT ’1’
5 FROM student
6 WHERE FacultyId = outer.FacultyId);

FACULTYID NAME
- --- --- -- - -- --- --- -- --- --
235 Vajpayee
444 Rivera
333 Collins

SQL>

Figur e 8-19 NOT EX ISTS operator.

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

1. U se the N2 Corporation database tables to design the following subqueries. (U se the


spooling method to capture all queries and results in the CHAP8SP1.LST file.)
(a) Display employee Jinku Shaw’s department name.
(b) Find the name of the supervisor for employee number 433.
190 Chap. 8 Subqueries: Nested Queries

(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 will learn about various Oracle objects.


● You will use syntax to create, use, modify, and remove views, sequences, syn-
onyms, and indexes.
● Advantages of transaction control are discussed.
● Users, roles, and privileges for data control are covered.

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.

Simple View Complex View

It is based on one table. It is based on one or more tables.


It does not contain group functions. It may contain group functions.
It does not contain grouped data. It may contain grouped data.
Data manipulation is always possible. Data manipulation is not always possible.

Figur e 9-1 Types of views.

Creating a View

The general syntax is

[column aliases]
AS SELECT-subquery
[WITH CHECK OPTION [CONSTRAINT constraintname]]

A view is created with a SE L E CT subquery. The subquery cannot use an O R D E R


BY clause, but a view can.
I n the syntax, O R R E PL A C E replaces an existing view with the same name, if
it already exists. The F OR C E option creates a view even if the underlying table does
not yet exist. The default is N OF OR C E , which does not create a view if the under-
lying table does not exist. The column aliases are used for the columns selected by
the subquery. The number of aliases must match the number of columns selected by
the subquery. The SE L E CT subquery can use all clauses except the O R D E R BY
clause. The W I TH C H E C K OPTI ON applies to the W H E R E clause condition in
the subquery. I t allows insertion and updating of rows based on the condition that
satisfies the view. The C H E C K OPTI O N can also be given an optional constraint
Views 193

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> CREATE VIEW stud500_vu


2 (StuId, LastName, FirstName, Advisor, MajNum)
3 AS SELECT StudentId, Last, First, FacultyId, MajorId
4 FROM student
5 WHERE MajorId = 500
6 WITH CHECK OPTION;
View created.

SQL>

Figur e 9-2 Creating a simple view.

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> set linesize 50


SQL> DESCRIBE stu500_vu
Name Null? Type
-- -- --- --- -- --- --- -- - --- -- -- -- --- --- -- --
STUID NOT NULL CHAR(5)
LASTNAME NOT NULL VARCHAR2(15)
FIRSTNAME NOT NULL VARCHAR2(15)
ADVISOR MAJNUM NUMBER(3) NUMBER(3)

SQL> set linesize 100SQL>


SELECT *
2 FROM stu500_vu;
STUID LASTNAME FIRSTNAME ADVISOR MAJNUM
- --- - - -- -- --- -- -- -- - -- -- --- -- -- --- - - -- -- --- -- --- -- -- ---
00101 Tyler Mickey 555 500
00103 Rickles Deborah 555 500

SQL>

Figur e 9-3 Using a view like a table.


194 Chap. 9 Advanced Features: Objects, Transactions, and Data Control

SQL> CREATE OR REPLACE FORCE VIEW dept_sal_vu


2 AS
2 SELECT d.DeptName DEPARTMENT, MIN(e.Salary) LOWEST,
2 MAX(e.Salary) HIGHEST, AVG(e.Salary) AVERAGE
2 FROM employee e, dept d
2 WHERE e.DeptId = d.DeptId
2 GROUP BY d.DeptName;
View created.

SQL> SELECT * FROM dept_sal_vu;

DEPARTMENT LOWEST HIGHEST AVERAGE


- --- --- -- --- --- --- -- - -- --- -- -- - -- --- --- -
Finance 35000 265000 125000
InfoSys 66500 80000 73250
Marketing 150000 150000 150000
Sales 24500 45000 34750

SQL>

Figur e 9-4 Creating and using a complex view.

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:

● N o data manipulation on derived columns, such as Salary/12 or Salary


+ (Commission, 0).
● N o data manipulation on the R OW NU M pseudocolumn.
● N o insertion of a new row into the table if the base table contains columns
with the NOT N U L L constraint but are not selected by the view.
● N o insertion of rows into the table if derived columns exist in the view.

Figure 9-2 has a simple view with a W I TH C HE CK O PTI ON clause. It applies to


the W H E R E condition in the subquery. The user cannot change the MajNum, because
the view accesses rows with MajorI d = 500 only. The U PD A TE of MajNum to any
other value will result in the following error message (see Fig. 9-5):

ORA-01402: view WITH CHECK OPTION where-clause violation.

Similarly, data manipulation on a view having a W I TH R E A D ONLY clause


results in an Oracle server error.
A user can list the names of views under his or her ownership by using

SELECT view_name FROM user_views;


Views 195

SQL> update stu500_vu 2 set MajNum = 600;


update stu500_vu
*
ERROR at line 1:
ORA-01402: view WITH CHECK OPTION where-clause violation

SQL>

Figur e 9-5 WITH CH ECK OPTION where-clause violation.

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> SELECT VIEW_NAME FROM USER_VIEWS;


VIEW_NAME
- --- --- -- --- --- -- --- --- -- --- --- DEPTSALVU
DEPT_SAL_VUSTU500_VU
SQL> DROP VIEW deptsalvu; View dropped.

SQL>

Figur e 9-6 Listing and dropping view.

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

With Oracle9i, the A L TE R V I E W statement lets you add constraints to a view.


You can use clauses like MO D I F Y C ONSTR A I NT and D R O P CONSTRA INT.

SEQUENCES

A sequence is an Oracle object that is used to generate a sequence of numbers. Many


times, you create a table with a surrogate key column, such as StudentId, FacultyI d, or
EmployeeId.These columns have a numeric data type. Sequencing is a perfect solution
for generating values for such numeric columns. These values can be unique or recy-
cled again, depending on the column. I f a sequence is used for a primary key column,
however, the values must be unique! A sequence is not limited to the primary key
columns but can be used on any numeric column. The general syntax is

I n this syntax, note the following:

I NC RE M E NT BY The increment value for the number generation is .


The default increment is 1.
STAR T W I TH The starting value for the sequence is . The default
start value is 1.
M A XV AL U E The maximum value for the generated number is .
NOM AX VA LU E The sequence will keep generating until the maximum
.
allowable value 11 10272 is generated in ascending
order.
NO M A X V A L U E is - 1 for a sequence in descending
order (default).
M I NVA L U E The minimum value for the generated number is .
NOM I NV AL UE The minimum value is 1 for a sequence in ascending
order and - 1026 for a sequence in descending order
(default).
C YC L E The sequence continues generating after reaching the
maximum or minimum value.
No more generation after maximum or minimum
NOC YC LE value is reached (default).
The Oracle server generates numbers in advance and
C A CH E
Sequences 197

stores them in a cache memory ar ea for improved sys-


tem performance. The default value for is 20. I f the
user provides a number, the server will store that
many numbers in the cache memory.
NOC AC HE The server does not store any sequence numbers in
memory in advance.
O R DE R The numbers are generated in chronological order.
The numbers are not generated in chronological order.
NOOR DE R

Suppose you want to create a sequence to generate EmployeeI d values in the


E MPL OY E E table. The last EmployeeI d in the table is 543. So, you want to start at
544, and the numbers will be incremented by 1 for every new employee (see Fig. 9- 7).

SQL> CREATE SEQUENCE employee_employeeid_seq


2 INCREMENT BY 1
3 START WITH 544
4 MAXVALUE 999
5 NOCACHE;
Sequence created.SQL>

Figur e 9-7 Sequence.

SQL> CREATE SEQUENCE major_majorid_seq


2 INCREMENT BY 10
3 START WITH 610
4 MAXVALUE 999
5 NOCACHE;
Sequence created.

SQL> INSERT INTO major VALUES


2 (major_majorid_seq.NEXTVAL, ’MS - Computer Science’);

1 rowcreated.
SQL>

Figur e 9-8 Sequence— creation and use with NEXTVAL.

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

There are pseudocolumns named CU RR V A L and NEX TVA L to reference se-


quence values. The NEXTVA L column returns the next available number in the se-
quence. The C U R RV A L column gives the current sequence value. The NEXTV AL
column is used with the sequence name (e.g. ) to generate
the next sequence number. When the new sequence number is generated, the current
number is stored in the CU R R V A L column. NEX TVA L must be used at least once
to get the value from CU RRVAL .
Because the sequence is used for the first time in Figure 9-8,
the first value generated is the starting value defined for the sequence. The new major
will get value 610. Y ou can check it with the pseudocolumn CU R RV A L with Oracle’s
dummy table D UA L. For example,

SELECT major_majorid_seq.CURRVAL FROM dual;

The number returned by CU R R V A L is 610, which is the last value generated by


NEX TVA L.
The sequence is created in Figure 9-7, but it is not
used yet. I f you try to find the current value, you will get an error message. Create a
new sequence named , and then use the following state-
ment to see the error message:

SELECT employee_EmployeeId_seq.CURRVAL FROM dual;

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

SQL> CREATE SEQUENCE dept_deptid_seq


2 START WITH 90
3 INCREMENT BY 1;
Sequence created.

SQL> INSERT INTO DEPT VALUES


2 (dept_deptid_seq.NEXTVAL, ’IT’, ’BRONX’, 111);

1 row created.

SQL> INSERT INTO employee (EmployeeId,Lname,Fname,DeptId)


2 VALUES (employee_employeeid_seq.NEXTVAL,
3 ’Viquez’, ’Heillyn’, dept_deptid_seq.CURRVAL);
1 row created.

SQL>

Figur e 9-9 Sequence— NEXTVAL and CURRVAL.


Sequences 199

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> SELECT sequence_name, last_number,


2 max_value, min_value, increment_by
2 FROM user_sequences;
SEQUENCE_NAME LAST_NUMBER MAX_VALUE MIN_VALUE INCREMENT_BY
-- -- --- --- --- -- --- --- -- --- --- -- --- - --- -- --- -- --- --- --- - --- --- -- --- -
DEPT_DEPTID_SEQ 110 1.0000E+27 1 1
EMPLOYEE_EMPLOYEEID_SEQ 545 999 1 1
MAJOR_MAJORID_SEQ 620 999 1 10

SQL>

Figure 9-10 USER_SEQUENCES.

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

SQL> ALTER SEQUENCE major_majorid_seq


2 INCREMENT BY 50
3 MAXVALUE 999;
Sequence altered. SQL>

Figur e 9-11 Alter Sequence.

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

You can drop a sequence with the D R OP SE QU E NC E statement. A removed se-


quence cannot be used anymore. For example,

DROP SEQUENCE major_MajorId_seq;

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

SQL> CREATE SYNONYM esq


2 FOR employee_employeeid_seq;

Synonym created.

SQL> CREATE SYNONYM emp


2 FOR employee;
Synonym created.SQL>

Figur e 9-12 Creating synonym.


Synonyms 201

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,

CREATE PUBLICSYNONYM reg


FOR nshah.registration;

A short synonym is used for table R E GI STRA TI ON owned by user


With availability of a public synonym, the students do not have to qualify my table
name with my user name. They can use

SELECT * FROM reg;

instead of

SELECT * FROM nshah.registration;

A synonym can be removed by using the D R O P SY NONY M statement. Only


the D B A privilege allows you to remove a public synonym. For example,

DROP SYNONYM esq;

SQL> SELECT SYNONYM_NAME, TABLE_NAME, TABLE_OWNER


2 FROM USER_SYNONYMS;

SYNONYM_NAME TABLE_NAME TABLE_OWNER


--- ---- ---- ---- ----- ---- --EMP --- ---- ---- ---- ----- ---- ---- --EMPLOYEE --- ---- ---- ---- ----- NSHAH
ESQ EMPLOYEE_EMPLOYEEID_SEQ NSHAH
SQL>

Figur e 9-13 User_Synonyms.

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

The TA BLESPA CE and STOR A GE clauses can be used with the CR E A TE


I N D E X statement. Indexes are stored in a different tablespace and, preferably, on a
different physical device from the table data to optimize the index’s performance.
For example, Figure 9- 14 creates an index based on student’s last and first names to

SQL> CREATE INDEX stu_idx


2 ON student(Last, First);

Index created.

SQL> SELECT index_name, table_name FROM user_indexes


2 WHERE table_name = ’STUDENT’;

INDEX_NAME TABLE_NAME
-- ---- ---- ---- ---- ----- ---- --- ----- ---- ---- ---- ---- ---
STUDENT_STUDENTID_PK STUDENT
STU_IDX STUDENT

SQL>

Figur e 9-14 Index.

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

updates the index, which is added overhead on the system.


Oracle also supports indexes, which are used in data warehousing but
are not suitable for tables with a large number of updates. Each data manipulation
statement updates the index file, thus slowing down the data manipulation operation.

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,

ALTER INDEX stu_idx REBUILD;

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> SELECT ROWID, EmployeeId, Lname, Fname


2 FROM employee
3 WHERE EmployeeId = 200;

ROWID EMPLOYEEID LNAME FNAME


--- -- --- --- -- --- -- ------ ---- -- --- --- -- -- --- --- -- --
AAAHaCAABAAAMbaAAF 200 Shaw Jinku
SQL> SELECT EmployeeId, Lname, Fname
2 FROM employee
3 WHERE ROWID = ’AAAHaCAABAAAMbaAAF’;

EMPLOYEEID LNAME FNAME


--- -- --- -- -- -- --- -- --- -- - - --- -- --- --- ---
200 Shaw Jinku

SQL>

Figur e 9-15 RO W ID Pseudocolumn.


204 Chap. 9 Advanced Features: Objects, Transactions, and Data Control

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:

● A C OM MI T or RO LL B A C K transaction control statement is used.


● A D D L (CR E A TE , A LTE R , DROP, RE N A M E , or TRU NC A TE ) state-
ment is executed (automatic commit).
● A D C L ( G RA N T or R E V OK E ) statement is executed (automatic commit).
● A user properly exits (commit).
● The system crashes (rollback).

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

W hen A U TO CO M MI T is set to ON or I M M ED I A TE , every D M L statement is


written to the disk as soon as it is executed, every D M L statement is committed
implicitly, and no rollback occurs with A U TO COM MI T. A U TOC OM MI T can be
toggled back to O FF for an explicit COMMIT. If the system crashes, any statements
after the last C OM MI T are rolled back, so partial changes to tables are not perma-
nently written.
W hen a user is in the middle of a transaction, he or she can review the resultsof
all D ML statements by using SE L E C T queries. A fter reviewing the results, the user
can decide to roll back or commit. The user is getting results from the data- base’s
temporary storage area. The other users with privileges on the same table cannot
view the results of the D ML queries until the user commits the changes. Until the
user commits all the changes, the rows with D M L statements are locked. Other users
cannot change the data in the locked rows. By committing, the user changes
become permanent, all users can view the changes, locks are released, save points are
removed, and other users can manipulate affected rows.
I n Figure 9-16, you see actions performed by three transaction control state-
ments; COMMI T, SA VEPOI NT, and ROL LBACK . I n Figure 9-17, you see illustration
Transactions 205

Transaction Control Statement Action

COMMIT Ends the current transaction, and writes all


changes permanently to the disk.
SAVEPOINT Marks a point in the current transaction.
R OLLBACK [TO SAVEPOINT ] Ends the current transaction by undoing all
changes to the last commit if a TO SAVEPOINT
clause is not used. It rolls back to the save point if
the clause is used, removing the save point and
any changes after the save point, but it does not
end the transaction.

Figur e 9-16 Transaction control statements.

SQL> INSERT INTO course VALUES(’CIS395’, ’ADV DATABASE’, 3, ’CIS253’);


1 row created.

SQL> INSERT INTOcourse VALUES(’CIS340’, ’OBJ ANALYSIS’, 3, ’CIS265’);

1 row created.

SQL> SAVEPOINT X;

Savepoint created.
SQL> UPDATE course SET credits=4 WHERE CourseId=’CIS340’; 1 row updated.

SQL> DELETE FROM course WHERE CourseId=’CIS395’;


1 row deleted. SQL> SAVEPOINT Y;

Savepoint created.

SQL> INSERT INTO course VALUES(’BL101’, ’BUSINESS LAW’, 3, ”);

1 row created.

SQL> ROLLBACK TO SAVEPOINT Y;

Rollback complete.
SQL> ROLLBACK TO SAVEPOINT X;

Rollback complete.

SQL> ROLLBACK;

Rollback complete.

Figur e 9-17 SAVEPOINT and ROLLBACK.


206 Chap. 9 Advanced Features: Objects, Transactions, and Data Control

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!

● Q uestion: If you typed a D ML statement that failed during execution, is it


still part of your transaction? I s it committed? I s it rolled back?
● A nswer: The statement is rolled back, and it is no longer part of your trans-
action.

Read Consistency and Locking

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.

LOCKING ROWSFOR UPDATE

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

The use of in F OR U PD A TE O F does not mean that the locking


is at the column level. The entire row is locked. The column names are used just for
information. The NOWA IT clause, which tells the user instantaneously if another
user has already locked the row, is optional. I f you do not use NOWA IT in the state-
ment, you will have to wait for any rows that have been locked by other applications
to be released. Y ou will not be able to do any processing on those rows until then.
Figure 9- 18 shows the display of a row in the E MPLO Y E E table and its locking.
Once the row is locked, you can change the employee’s salary and commission. Y ou
can actually change any column’s value in this row. I f another user tries to update this
row, he or she will have to wait for you to release the lock by either committing or
rolling back the transaction. I t is a good practice to run C OM MI T as soon as changes
are done so that other users can access data.

SQL> SELECT Lname, Fname, Salary, Commission


2 FROM employee
3 WHERE EmployeeId = 544
4 FOR UPDATE OF Salary, Commission
5 NOWAIT;
LNAME FNAME SALARY COMMISSION
- -- --- -- -- -- --- - -- -- --- -- -- -- - -- -- --- - - - - -- - - -- -
Viquez Heillyn

SQL>

Figur e 9-18 Locking a row with FO R UPDATE OF.

CONTROLLING ACCESS

A user’s access needs to be contr oll ed in a shared, multiuser Oracle environ-


ment. A user’s access to the database can be restricted, and a user may or may
not be allowed to use cer tai n objects in the database. Security is classified into
two types:

defines access to the database at the system level. It is imple-


mented by assigning a username and password, allocating disk space, and
providing a user with the ability to perform system operations.
defines a user’s access to various objects and the tasks a
user can perform on them.
208 Chap. 9 Advanced Features: Objects, Transactions, and Data Control

The D atabase A dministrator (D BA ) is the most trusted user, and a D B A has


all the privileges. A D B A can create users, assign them privileges, and even drop
users.

Users and Roles

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

The statement in Figure 9-19 creates a user X MA N, assigns a password as well


as temporary and default tablespaces, and grants roles. A user needs, at minimum,
two roles; CO NN E CT and RE SO U R C E .

SQL> CREATE USER “XMAN” PROFILE “DEFAULT”


2 IDENTIFIED BY “CRICKET”
3 DEFAULT TABLESPACE “CIS_DATA”
4 TEMPORARY TABLESPACE “TEMP_DATA”
5 ACCOUNT UNLOCK;
User created.

SQL> GRANT UNLIMITED TABLESPACE TO “XMAN”;

Grant succeeded.

SQL> GRANT “CONNECT” TO “XMAN”;


Grant succeeded.

SQL> GRANT “RESOURCE” TO “XMAN”;


Grant succeeded. SQL>

Figur e 9-19 Creating a new user.

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)

U ND E R is a new object privilege introduced with Oracle9i. I t lets you create a


subview under the current view. Y ou can grant this object privilege only if you
have the U ND E R A NY V I E W privilege W I TH G R A N T OPTI ON on the immediate
superview of this subview.
A user has his or her objects in his or her own schema. A n owner has all possible
privileges on the owner’s objects. A user can grant privileges on objects from his or
her own schema to other users or roles. The grantee can also be given further rights
to grant the same privileges to other users on an object. The general syntax is
210 Chap. 9 Advanced Features: Objects, Transactions, and Data Control

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).

SQL> GRANT SELECT


2 ON dept
3 TO XMAN;
Grant succeeded.

SQL> GRANT SELECT, INSERT, UPDATE


2 ON employee
3 TO STUDENT, XMAN
4 WITH GRANT OPTION;
Grant succeeded. SQL>

Figur e 9-20 Granting object privileges.

The user X MA N can use table E M PL O Y E E with the following query:


SELECT * FROM nshah.employee;

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

The user with the R E F E R E NC E S privilege in the G R A NT statement can refer-


ence the table. C A SC A D E CO NSTRA I NTS removes any foreign key or referential
integrity constraints on the object.
I n Figure 9-21, user X M A N loses A L L granted privileges on granted the EM-
PL OY E E table from user NSH A H . If user X M A N has passed privileges on the
E M PL OY E E table to any other users, their privileges are also revoked.

SQL> REVOKE ALL


2 ON employee
3 FROM XMAN;
Revoke succeeded.SQL>

Figur e 9-21 Revoking object privileges.

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

5. W hen a system crashes, it results in an automatic COMMIT.


6. D ML statements cannot be rolled back once committed.
7. Any user can create another user with the same privileges.
8. A user cannot pass on privileges to other users on objects from his or her own schema
unless the W I TH G R A NT O PTI ON is used in a GR A N T statement.
9. The SEL ECT statement generates an automatic lock on rows.
10. W hen DM L statements are not committed, other users cannot modify the rows involved.
11. A sequence can be used only on the one table for which its created.
12. If a user owns a table named EMP, the user cannot have a synonym named EMP.
13. A view is created with W I TH CH ECK OPTI ON to prevent modifications to all columns
used in the view.
14. CU R RV AL returns the START W I TH value of a sequence for a sequence that is created
but is never used to generate a value.
15. W hen a view is dropped, the underlying table is also dropped.
16. W hen a table is dropped, the sequence used on that table also is dropped.

Answer the Following Questions:


1. Name any five Oracle objects.
2. W hat are the differences between simple and complex views?
3. W hen does an automatic commit occur?
4. W hat is the advantage of creating the following objects?

a Index.

b Sequence.

c View.

d Synonym.
5. How is transaction control important in a shared environment?
6. Name Oracle9i’s object privileges. W hat is used to grant all object privileges? What is
used to grant privileges to everybody?
7. W hen does an automatic rollback occur?
8. For what are the pseudocolumns ROWID, ROW NU M, NEX TV AL , and CU RRV AL used?
9. How can you lock rows in a table with the SEL ECT query? If another user has already
locked those rows, what will happen if you try to lock them as well? Is there any way to
avoid the situation?
10. W hen a table is dropped, what happens to its indexes, sy nonyms, views, and sequences?

LAB ACTIVITY

U se the Case-Study Databases for the Following Queries:


1. Create a view to include all employee information, but hide salary and commission.
2. Create a view to include department name and average salary by department.
214 Chap. 9 Advanced Features: Objects, Transactions, and Data Control

3. Create an index to search students faster based on their major ID.


4. Create a sequence to add room IDs, and then insert a new room into the L OCATI ON
table using the newly created sequence. What is the CU R RV AL after the new row is
inserted?
5. G R A NT only the SEL ECT privilege to another user on your TER M table.
6. INSERT a new Winter 2004 term in the TER M table. U se a SEL ECT query to see the
result. Ask the user with the SEL ECT privilege (from activity 5) to view your TER M
table. CO MMI T your transaction, and ask the same user to view the table again.
7. L ock student ID 00101 for an update of major to 600. U pdate the row, and COMMIT.
8. Create a view that will display name, department number, and total income
1 salary + commission2 of each employee in Department 10. Prevent a change of
department through the view.
9. Create a view that will display department names and the sum of all employee income
by department.
10. Create a sequence deptid_seq to generate department Id (in the D EPT table) and another
sequence empid_seq to generate employee Id (in the EM PL OY EE table). U se deptid_seq
to add a new department in the D EPT table. Now, add yourself as a new employee with
empid_seq in the department you just added.
I n this section, a new database is introduced with four tables. This review section is
added at this point in the text to review all the statements covered in Chapters 3
through 9. The scripts for creating all four tables and inserting rows into them are
also provided after the illustrations of the tables. E ach script is followed by various
problems and their solutions. The four sample tables are:

A table with customer demographic information.


A table with information about the items offered by the company.
A table with individual invoices produced for customers.
A composite entity with invoices and items ordered.

CUSTOMER (CustNo, CustName, State, Phone)

CustNo CustName State Phone


211 Garcia NJ 732-555-1000
212 Parikh NY 212-555-2000
225 Elsenhauer NJ 973-555-3333
239 Bayer FL 407-555-7777

ITEM (ItemNo, ItemName, ItemPrice, QtyOnHand)

ItemNo ItemName ItemPrice QtyOnHand


1 Screw 2.25 50
2 Nut 5.00 110
3 Bolt 3.99 75
4 Hammer 9.99 125
5 Washer 1.99 100
6 Nail 0.99 300
216 SQL Review: Supplementary Examples

INVOICE (InvNo, InvDate, CustNo)

InvNo InvDate CustNo


1001 05-SEP-03 212
1002 17-SEP-03 225
1003 17-SEP-03 239
1004 18-SEP-03 211
1005 21-SEP-03 212

INVITEM (InvNo, ItemNo, Qty)

InvNo ItemNo Qty


1001 1 5
1001 3 5
1001 5 9
1002 1 2
1002 2 3
1003 1 7
1003 2 1
1004 4 5
1005 4 10

SCRIPTFOR CREATION OF TABLES

CREATE TABLE customer(CustNo NUMBER (3),


CustName VARCHAR2(10) CONSTRAINT customer_custname_nn NOT NULL, State
CHAR(2) DEFAULT‘NJ’,
Phone CHAR(12),
CONSTRAINT customer_custno_pk PRIMARY KEY (CustNo)); CREATE TABLE
item(ItemNo NUMBER (2),
ItemName VARCHAR2(6), ItemPrice NUMBER(3,2), QtyOnHand NUMBER(3),
CONSTRAINT item_itemno_pk PRIMARY KEY(ItemNo), CONSTRAINT
item_qtyonhand_ck CHECK (QtyOnHand >= 0));
CREATETABLEinvoice(InvNoNUMBER(4),
InvDate DATE,
CustNo NUMBER(3) CONSTRAINT invoice_custno_nn NOT NULL, CONSTRAINT
invoice_invoiceno_pk PRIMARY KEY(InvNo), CONSTRAINT invoice_custno_fk FOREIGN
KEY(CustNo)
REFERENCES customer(CustNo)); CREATETABLEinvitem(InvNo NUMBER(4),
ItemNo NUMBER(2),
SQL Review: Supplementary Examples 217

Qty NUMBER(2) NOT NULL,


CONSTRAINT invitem_invno_itemno_pk PRIMARY KEY(InvNo, ItemNo),
CONSTRAINT invitem_invno_fk FOREIGN KEY(InvNo)
REFERENCES invoice(InvNo),
CONSTRAINT invitem_itemno_fk FOREIGN KEY(ItemNo) REFERENCES
item(ItemNo));

SCRIPTFOR INSERTION OF ROWSINTO TABLES

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);

INSERT INTO invoice VALUES(1001, TO_DATE(‘05-09-2003’, ‘dd-mm-yyyy’), 212); INSERT INTO


invoice VALUES(1002, TO_DATE(‘17- 09-2003’, ‘dd- mm-yyyy’), 225); INSERT INTO invoice
VALUES(1003, TO_DATE(‘17-09-2003’, ‘dd-mm-yyyy’), 239); INSERT INTO invoice VALUES(1004,
TO_DATE(‘18-09-2003’, ‘dd- mm-yyyy’), 211); INSERT INTO invoice VALUES(1005, TO_DATE(
‘21-09-2003’, ‘dd-mm-yyyy’), 212);

INSERT INTO invitem VALUES(1001, 1, 5);


INSERT INTO invitem VALUES(1001, 3, 5);
INSERT INTO invitem VALUES(1001, 5, 9);
INSERT INTO invitem VALUES(1002, 1, 2);
INSERT INTO invitem VALUES(1002, 2, 3);
INSERT INTO invitem VALUES(1003, 1, 7);
INSERT INTO invitem VALUES(1003, 2, 1);
INSERT INTO invitem VALUES(1004, 4, 5);
INSERT INTO invitem VALUES(1005, 4, 10);

INSERTION OF ROWSWITH SUBSTITUTION VARIABLES

Alternate Method

INSERT INTO customer


VALUES(&customer_no, ‘&customer_name’, ‘&state’, ‘&phone’); INSERT INTO
item
VALUES(&item_no, ‘&item_name’, &price, &qty_on_hand);
218 SQL Review: Supplementary Examples

INSERT INTO invoice


VALUES(&inv_no, TO_DATE (‘&inv_date’, ‘dd-mm-yyyy’), &cust_no); INSERT INTO
invitem
VALUES(&invoice_no, &item_no, &qty);

Display all Customer Information

SELECT *
FROM customer;

Display all Item Names and their Respective Unit Price

SELECTItemName,ItemPrice FROM item;

Display Unique Invoice Numbers from the INVITEM Table

SELECT DISTINCT InvNo


FROM invitem;

Display Item Information with Appropriate Column Aliases

SELECT ItemNo “Item Number”, ItemName “Name of Item”,ItemPrice “Unit


Price”
FROM item;

Display Item Name and Price Using Concatenation

SELECT ItemName |‘has aunit price of $’||ItemPrice FROM item;

Find the Total Value of Each Item Based on Quantity on Hand

SELECT ItemName, ItemPrice * QtyOnHand “Total Value”FROM item;

Find Customers from Florida

SELECT *
FROM customer
WHERE UPPER(State) = ‘FL’;

Display Items with a Unit Price of at Least $5

SELECT UPPER (ItemName), ItemPrice FROM item


WHERE ItemPrice >= 5;
SQL Review: Supplementary Examples 219

Find Items with a Unit Price Between $2 and $5

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’);

Find all Customers Whose Names Start with the Letter

SELECT *
FROM customer
WHERE UPPER(CustName) LIKE ‘E%’;

Find Items with the Letter in their Name

SELECT *
FROM item
WHERE ItemName LIKE‘ %w%’ ;

Sort all Customers Alphabetically

SELECT *
FROM customer ORDER BY CustName;

Sort all Items in Descending Order by their Price

SELECT *
FROM item
ORDER BY ItemPrice DESC;

Sort all Customers by their State and also Alphabetically

SELECT *
FROM customer
ORDER BY State, CustName;
220 SQL Review: Supplementary Examples

Display all Customers from New Jersey Alphabetically

SELECT *
FROM customer
WHERE UPPER(State) = ’NJ’
ORDER BY CustName;

Display all Item Prices Rounded to the Nearest Dollar

SELECTItemName, ROUND(ItemPrice,0) FROM item;

Find the Payment Due Date if the Payment is Due in Two Months from
the Invoice Date

SELECT InvNo, CustNo, InvDate, ADD_MONTHS(InvDate, 2) “Payment Due”FROM


invoice;
or
SELECT InvNo, CustNo, InvDate, InvDate + 60 “Payment Due”FROM invoice;

Display Invoice Dates in “September 05, 2003” Format

SELECT InvNo, TO_CHAR (InvDate, ‘fmMonth DD, YYYY’) “Invoice Date” FROM
invoice;

Find the Total, Average, Highest, and Lowest Unit Prices

SELECT SUM (ItemPrice), AVG (ItemPrice), MAX (ItemPrice), MIN (ItemPrice) FROM
item;

Display How Many Different Items Are Available for Customers

SELECT COUNT (*)


FROM item;

Count the Number of Items Ordered in Each Invoice

SELECT InvNo, COUNT(ItemNo) “Items Ordered” FROM invitem


GROUP BY InvNo;

Find Invoices in which Three or More ItemsAre Ordered

SELECT InvNo, COUNT(ItemNo) “Items Ordered” FROM invitem


GROUP BY InvNo
HAVING COUNT(ItemNo) >= 3;
SQL Review: Supplementary Examples 221

Find all Possible Combinations of Customers and Items(Cartesian Product)

SELECT c.*, t.*


FROM customer c,item t;

Display all Item Quantities and Item Prices for Invoices

SELECTa.InvNo, a.ItemNo, b.ItemName, a.Qty, b.ItemPrice,a.Qty * b.ItemPrice “qty*price”FROM invitem a,


item b
WHERE a.ItemNo =b.ItemNo;

Find the Total Price for Each Invoice

SELECT a.InvNo, SUM(a.Qty * b.ItemPrice) “Total Amount”FROM invitem a, item b


WHERE a.ItemNo = b.ItemNo GROUP BY a.InvNo;

Use an Outer Join to Display Items Ordered and Not Or- dered

SELECT x.ItemNo, y.InvNo FROM item x,invitem y


WHERE x.ItemNo = y.ItemNo(+);

Display Invoices, Customer Names, and Item Names To- gether (Multiple Joins)

SELECT a.InvNo, b.CustName, c.ItemName, d.Qty FROM invoice a, customer b, itemc,


invitem d
WHERE a.CustNo = b.CustNo AND a.InvNo = d.InvNo AND c.ItemNo = d.ItemNo;

Find Invoices with as an Item

SELECT v.InvNo, t.ItemName, v.Qty FROM invitem v,item t


WHERE v.ItemNo =t.ItemNo AND UPPER(ItemName) = ‘HAMMER’;

Find Invoices with as an Item by Using a Sub- query

SELECT InvNo, Qty “Hammers ordered” FROM invitem


WHERE ItemNo =
(SELECT ItemNo FROM item WHERE Upper(t.ItemName) = ‘HAMMER’);
222 SQL Review: Supplementary Examples

Display the Items Ordered in Invoice Number 1001 (Sub- query)

SELECT ItemName FROM item WHERE ItemNo IN


(SELECT ItemNo FROM invitem WHERE InvNo = 1001);

Find Items That Are Chapter than

SELECT ItemName, ItemPrice FROM item


WHERE ItemPrice <
(SELECT ItemPrice FROM item WHERE UPPER(ItemName) = ‘NUT’);

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’;

Copy all New York Customers to the Newly Created NJ_CUSTOMER


Table

INSERT INTO nj_customer


SELECTCustNo, CustName, Phone FROM customer
WHERE UPPER(State) = ‘NY’;

Rename NJ_CUSTOMER Table to NYNJ_CUSTOMER

RENAME nj_customer TO nynj_customer;

Find Customers Who Are Not from New York or New Jersey (Set
Operator)

SELECTCustName, State FROM customer


MINUS
SELECTCustName, State FROM nynj_customer;
SQL Review: Supplementary Examples 223

Delete Rows from the CUSTOMER Table that Are also in the NYNJ_CUSTOMER Table

DELETE FROM customer WHERE CustNo IN


(SELECT CustNo FROM nynj_customer);

Find the Items with the Top-Three Prices

SELECT ROWNUM, ItemName, ItemPrice


FROM (SELECT ItemName, ItemPrice FROM item ORDER BY ItemPrice DESC) WHERE ROWNUM
<=3;

Find the Two Items with the Lowest Quantity on Hand

SELECT ROWNUM, ItemName, ItemPrice, QtyOnHand


FROM (SELECT ItemName, ItemPrice, QtyOnHand FROM item ORDER BY QtyOnHand) WHERE
ROWNUM <=2;

Create a Simple View with Item Names and Item PricesOnly

CREATE OR REPLACE VIEW item_vu(Name, Price) AS


SELECT ItemName, ItemPrice FROM item;

Create a View that Displays Invoice Number and Cus- tomer Names for New
Jersey Customers

CREATE OR REPLACE VIEW nj_cust_vuAS


SELECT InvNo, CustName FROM invoice, customer
WHERE invoice.CustNo = customer.CustNo AND UPPER(State) = ‘NJ’
WITH CHECK OPTION;

Create a Sequence that Can Be Used to Enter New Itemsinto the ITEM Table

CREATE SEQUENCE itemnum_seq INCREMENT BY 1


START WITH 7
MAXVALUE 99
224 SQL Review: Supplementary Examples

NOCYCLENOCACHE ORDER;

Add a New Item into the ITEM Table with the ITEMNUM_SEQ
Sequence

INSERT INTO item


VALUES (itemnum_seq.NEXTVAL, ‘Scissors’, 7.95, 100);

Create a Synonym for the INVITEM Table

CREATESYNONYM ii
FORinvitem;

Create an Index File Based on Customer Name

CREATE INDEX customer_name_idx ON


customer(CustName);

Lock Customer Bayer’sRecord to Update State and Phone Number

SELECT *
FROM customer
WHERE UPPER(CustName) = ‘BAYER’
FOR UPDATE OFState,Phone NOWAIT;

Give Everybody SELECT and INSERTRights on Your ITEM Table

GRANT select, insert ON item


TO public;

Revoke the INSERT Option on the ITEM Table from User BOND

REVOKE insert ON item FROM bond;


PART 3
PL/SQL

INTHISCHAPTER . . .

● Y ou will learn the basics of the PL/SQL programming language.


● The PL/SQL anonymous block is introduced.
● V ariables, constants, data types, and declarations are discussed.
● The assignment statement and use of arithmetic operators are covered.
● The scope and use of various types of variables are shown in sample programs.
● Y ou will be prepared to write simple PL/SQL blocks.
I n Part 2, you learned Oracle’s nonprocedural language SQL and its various state-
ments to interface with the Oracle database. SQL is a great query language, but it
has its limitations. So, Oracle Corporation has added a procedural language exten-
sion to SQL known as Programming Language E xtensions to Structured Query
Language (PL/SQL). I t is Oracle’s proprietary language for access of relational
table data. PL/SQL is like any other high- level compiler language. If you are already
familiar with another programming language, you will find PL/SQL constructs to be
similar to those of Pascal, C, or V isual Basic. PL/SQL also possesses features of object-
oriented languages, such as:

● D ata encapsulation.
● E rr or handling.
226 Chap. 10 PL/SQL: A Programming Language

● I nformation hiding.
● Object-oriented programming (OOP).

PL/SQL also allows embedding of SQL statements and data manipulation in


its blocks. SQL statements are used to retrieve data, and PL/SQL control statements
are used to process data in a PL/SQL program. The data can be inserted, deleted, or
updated through a PL/SQL block, which makes it an efficient transaction- processing
language.
The Oracle Server has an engine to execute SQL statements. The server also
has a separate engine for PL/SQL. Oracle D eveloper tools have a separate engine to
execute PL/SQL as well. The SQL statements are sent one at a time to the server for
execution, which results in individual calls to the server for each SQL statement. I t
may also result in heavy network traffic. On the other hand, all SQL statements
within a single PL/SQL block are sent in a single call to the server, which reduces
overhead and improves performance.

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:

● The transaction control statements SA V EPOINT, ROL LBACK , and COMMIT.


● The D ML statements INSE RT, D E L E TE , and U PD A TE .
● The extended data types Boolean, BI N A R Y _ I NTE GE R , PL/SQL records,
and PL/SQL tables.
● Built-in functions— character, numeric, conversion, and date functions.
● Built-in packages.
● The control structures sequence, selection, and looping.
● D atabase access through work areas called cursors.
● E rror handling.
● Modular programming with procedures and functions.
● Stored procedures, functions, and packages.
● Programmer-defined subtypes.
● D D L support through the D BMS_SQL package.
● The PL/SQL wrapper.
● The DBMS_JOB job scheduler.
● File I /O with the U TF_ FI L E package.
Fundamentals of PL/SQL 227

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

A PL/SQL program consists of statements. Y ou may use upper- or lowercase letters in


your program. In other words, PL /SQL is not case sensitive except for character string
values enclosed in single quotes. Like any other programming language, PL/SQL
statements consist of reserved words, identifiers, delimiters, literals, and comments.

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

User-defined identifiers are used to name variables, constants, procedures, func-


tions, cursors, tables, records, and exceptions. A user must obey the following rules in
naming these identifiers:

● The name can be from 1 to 30 characters in length.


● The name must start with a letter.
● L etters (A –Z, a–z), numbers, the dollar sign ($), the number sign (#) and the
underscore (_) are allowed.
● Spaces are not allowed.
● O ther special characters are not allowed.
● K ey words cannot be used as user-defined identifiers.
● Names must be unique within a block.
● A name should not be the same as the name of a column used in the block.

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#

Figur e 10-1 Valid user-defined identifiers.

Invalid User-Defined Identifiers Reason

2Number Starts with a number


Employee-name Special character hyphen
E ND Reserved word
Depar tment number Spaces
Lar gest_year ly_salar y_paid_to_employees Too long
Taxrate% Special character %

Figur e 10-2 Invalid user-defined identifiers.

Literals

Literals are values that are not represented by user- defined identifiers. Literals are
of three types: numeric, character, and boolean. For example:

Numeric 100, 3.14, —55, 5.25E7, or NU LL


Character ‘A ’, ‘this isa string’, ‘0001’, ‘25- MAY-00’, ‘ ’, or NUL L
Boolean TR UE , FAL SE , or NUL L

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

PL/SQL is a block-structured language. A program can be divided into logical


blocks. The block structure gives modularity to a PL/SQL program, and each object
within a block has “scope.” Blocks are of two types:

1. A n is a block of code without a name. It can be used any-


where in a program and is sent to the server engine for execution at runtime.
PL/SQL Block Structure 229

2. A is a block of code that is named. A is a named


block that can be called and can take arguments. A is a subpro-
gram that can perform an action, whereas a is a subprogram that
returns a value. A is formed from a group of procedures and func-
tions. A is a block that is called implicitly by a D ML statement.

A PL /SQL block consists of three sections:

1. A declar ation section.


2. A n executable section.
3. A n exception-handling section.

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

Declaration An optional section to declare variables, constants, cursors, PL/SQL


composite data types, and user-defined exceptions, which are referenced
in executable and exception-handling sections.
Executable A mandatory section that contains PL/SQL statements to manipulate data
in the block and SQL statements to manipulate the database.
Exception handling Specifies action statements to perform when an error condition exists in
the executable section. It is also an optional section.

Figure 10-3 Sections in a PL/SQL block.

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

Anonymous block An unnamed block, that is independent or embedded within an


application.
Procedure/function A named block that is stored on the Oracle server, can be called by its
name, and can take arguments.
Package A named PL/SQL module that is a group of functions, procedures, and
identifiers.
Trigger A block that is associated with a database table or a view. It is executed
when automatically fired by a DML statement.

Figur e 10-4 Programming constructs.

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:

1. To write a single-line comment, two dashes (- -) are entered at the begin-


ning of a new line. For example,
- -This is asingle-line comment.

2. To write a multiline comment, comment text is placed between /* and * /.


A multiline comment can be written on a separate line by itself, or it can
be used on a line of code as well. For example,

/* This is a
multiline comment that ends here. */

A programmer can use a comment anywhere in the program.

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.

Other scalar data types include raw, rowid, and trusted.

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:

B INA R Y _ I NTE G ER (approximatel y - 231 + 1 to 231 - 1, or - 2 billion to + 2


billion)
I NTE G E R I NT SMALLI NT
PO SI TI V E (a subtype of BI NA R Y _ I NTE GE R — range, 0 to 231) NA TU R A L
(a subtype of B I NA RY _I N TE G E R— range, 1 to 231)

Similarly, there are various data types for decimal numbers: NU M B E R


D E C (fixed-point number) D E C I MA L (fixed-point number) N U M E R I C
(fixed-point number) FLOA T (floating-point number) R E A L (floating-point
number)
D O U B L E PR E C I SI ON (floating- point number)

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( , )

where is precision and is scale.


I f scale has a value that is negative, positive, or zero, it specifies rounding of the
number to the left of the decimal place, to the right of the decimal place, or to the
nearest whole number, respectively. I f a scale value is not used, no rounding occurs.
Other Data Types 233

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.

OTHER DATA TYPESNLS

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

● The type contains a pointer to a large block of multibyte character


data of fixed width.
● The type contains a pointer to large binary objects in an external op-
erating system file. I t would contain the directory name and the filename.

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

where is the name of a variable or constant. A CO NSTA N T is an


identifier that must be initialized and the value of which cannot be changed in the
program body. A N OT NU L L constraint can be used for variables, and such vari-
ables must be initialized. The D E FA U LT clause, or : =, can be used to initialize a
constant or a variable to a value. A n expression can be a literal, another variable, or an
expression.
The identifiers are named based on rules given previously in this chapter. Dif-
ferent naming conventions can be used. You should declare one variable per line for
good readability. For example,

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

PL/SQL uses % TY PE attribute to anchor a variable’s data type. A nother variable


or a column in a table can be used for anchoring. I n anchoring, you tell PL/SQL to
Anchored Declaration 235

use a variable or a column’s data type as the data type for another variable in the
program. The general syntax is

where is another variable’s name or table’s column with a table qualifi-


er (e.g., ). I t is very useful while retrieving a value of a col-
umn into a variable with a SE L E C T query in PL/SQL. For example,
DECLARE
v_num1 NUMBER(3);
v_num2 v_num1%TYPE;

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

The % TY PE attribute’s use can be nested. For example,


DECLARE
–– source variable v_commission v_commission NUMBER(7, 2);
–– anchoredvariable v_total_commission v_total_commission
v_commission%TYPE;
–– nested anchoring variable v_net_commissionv_net_commission
v_total_commission%TYPE;
236 Chap. 10 PL/SQL: A Programming Language

I n this example, the original variable anchors ,


which in turn is used to anchor There is no limit on the number
of layers of nesting in anchored declarations.
The source variable for a % TY PE declaration does not have to be in the same
block. The variable could be a global variable declared at the SQL * Plus environ-
ment, or it could be declared in a block that contains the current block.

NOT NULL Constraint for %TYPE Declarations

If a source variable is declared with a NO T N U L L constraint, the % TY PE declara-


tion inherits the N OT N U L L constraint from the source, its anchor. The anchored
variable must be initialized with a value in the % T Y PE declaration.
If the source for a % TY PE declaration is a table’s column, the N OT NU L L
constraint is not inherited by the anchored variable. There is no need to initialize the
anchored variable, and it can be assigned a N U L L value.

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:

v_count =10; /* Wrong assignment operator, = sign */


v_count * 2 := v_double; v_num1:= /* Expression cannot be on the left. */
v_num2:=v_num3; /* Cannot use two assignments in one statement. */
Bind Variables 237

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> VARIABLE double NUMBER

W hen a numeric variable is declared with VA R I A B L E command, precision


and scale values are not used. I f a VA R C HA R2- type variable is decl ared, length is
not used. A host variable’s value can be pri nted in the SQL * Plus env ironment by
using the PR I NT command.
L et us put everything together in a program. The program contains a script
that includes SQL * Plus statements and a PL/SQL block.
I n Fi gure 10-5, two types of variables are used, a local variable and a
host variabl e The host variable is declared in SQL * Plus with a
VA R I A B L E statement, and the program block references it with a colon prefix (:).
The local variable is declared in the declaration secti on of a program block;
there is no need to use the colon prefix with it. The program assigns the value 5 to

SQL> VARIABLE g_double NUMBER SQL>


DECLARE
2 v_num NUMBER(2);
3 BEGIN
4 v_num := 5;
5 :g_double := v_num* 2;
6 END;
7 /

PL/SQLprocedure successfullycompleted. SQL>


PRINT g_double
G_DOUBLE
-- --- --- -- -
10

SQL>

Figur e 10-5 Using a host variable in a PL/SQL block.


238 Chap. 10 PL/SQL: A Programming Language

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.

Question: How does a PL /SQL block end?


Answer : I t ends with an E N D and a semicolon on the same line a slash
(/) on the next line.

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.

SUBSTITUTION VARIABLESIN PL/SQL

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

SQL> VARIABLE g_double NUMBER SQL>


DECLARE
2 v_num NUMBER(2);
3 BEGIN
4 v_num := &p_num;
5 :g_double := v_num * 2;
6 END;
7 /
Enter value for p_num: 10

PL/SQLprocedure successfully completed. SQL>

PRINT g_double
G_DOUBLE
-- --- --- -- -
20

SQL>

Figur e 10-6 Local, host, and substitution variables.


Printing in PL/SQL 239

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

SQL> VARIABLE NUM NUMBER SQL> SET SERVEROUTPUT ON SQL> DECLARE


2 DOUBLE NUMBER;
3 BEGIN

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>

Figure 10-7 DBMS_OUTPUT.PUT_LINE.


240 Chap. 10 PL/SQL: A Programming Language

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:

● E xponentiation is performed first, multiplication and division are performed


next, and addition and subtraction are performed last.
● I f more than one operator of the same priority is present, they are performed
from left to right.
● W hatever is in parentheses is performed first.

Figure 10-8 shows arithmetic operators and their use.

Arithmetic Operator Use

+ Addition
— Subtraction and negation
* Multiplication
/ Division Exponentiation
**

Figur e 10-8 Arithmetic operators.

Question: W hat is the answer from the following expression?

–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 . . .

● PL/SQL (Programming Language extension to Structured Query Language) is


Oracle’s proprietary language.
● PL/SQL contains features of modern languages, such as data encapsulation,
error handling, information hiding, and object-oriented programming (OOP).
● PL/SQL is a block-structured language. A block is of two types: anonymous
block and subprogram (procedures and functions).
● A program code contains reserved words, user- defined identifiers, delimiters,
comments, and literals.
● A program block consists of three sections: declaration, executable, and excep-
tion handling.
● A program uses variables and constants to hold values. A variable’s value can
be changed, but a constant’s value remains the same throughout the execu-
tion of the program.
● A variable is declared in the declarative section with a scalar data type. The
standard data types are number, character, Boolean, and date. PL/SQL also
supports other L O B (Large Object) data types.
● A declaration attribute % TY PE is used to anchor a variable with another
variable’s data type or with a table column’s data type.
● A bind variable, or host variable, is global to a PL/SQL block. A n anonymous
block refers to it with a colon prefix (:). A bind variable is declared with the
V A R I A B L E statement and is printed with the PRI NT statement in the
SQL * Plus environment.
● A n assignment statement is used in the executable section to assign a literal, a
variable’s value, or the result of an expression to a variable. A n assignment uses
the : = operator.
● PL/SQL does not have an input statement, but substitution variables are al-
lowed in a block to assign a value to a variable.
● A built- in Oracle package and its procedure D BMS_OUTPU T.PU T_LI NE are
used to output information. A n environment variable SE R V ER OU TPU T must
be set to ON before using it.
● A rithmeti c operator s ( +, - , * , /, and ** ) are used in mathematical expres-
sions. The operations follow rules of precedence for evaluati ng expressions
with more than one operator.
242 Chap. 10 PL/SQL: A Programming Language

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.

Answer the Following Questions:


1. State differences between Oracle’s SQL and PL/SQL languages.
2. W hat are the two types of blocks in PL /SQL ? W hat are the differences between them?
3. Name four standard scalar data types used in PL/SQL. W hen is each type used for vari-
ables?
4. Name three types of variables used in PL/SQL. Where are they declared? Give a sample
declaration of each.
5. Give any differences and similarities between := and DEFAU LT.
6. W hat are advantages of the % TY PE attribute in a variable declaration?
7. State the rules of precedence used in arithmetic operations.
8. How will you declare a bind variable named , use it in a PL/SQL block, and print
its value?
9. Declare a variable , which may not have a null value. Assign a value to with a
substitution variable, and print that value.
10. How do you run a PL/SQL block?
Lab Activity 243

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

AREA = PI * RADIUS * RADIUS

Then, print the result in SQL * Plus.


2. W rite a PL/SQL block to find the square, cube, and double of a number inputted with a
substitution variable, and print the results using the built-in package DBMS_OU TPU T.
3. W rite a PL/SQL block to swap the values of two variables. Print the variables before and
after swapping.
4. W rite a PL/SQL program to input hours and rate. Find gross pay and net pay with a tax
rate is 28% . Print your results. (No need to perform overtime calculations.)
5. W rite a PL/SQL program with two variables, for the first name and the last name. Print
the full name with the last name and first name separated by comma and a space.
IN THISCHAPTER . . .

● Y ou will learn about various programming control structures in PL/SQL.


● D ifferent decision- making statements based on various options are covered.
● L ooping statements are introduced to perform a set of statements repetitively.
● SQL statements are embedded within a PL/SQL block to interact with the
Oracle server.

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:

1. I n a , a series of instructions are performed from the


beginning to the end in a linear order. N one of the instructions is skipped,
and none of the instructions is repeated.
2. The is also known as a or an
. I t involves conditions with a TR U E or FALSE outcome. Based
on the outcome, one of the options is performed, and the other option is
skipped. Selection statements are also available for multiple options.
3. I n a , a series of instructions is performed repeatedly.
There are different looping statements appropriate for a variety of situa-
tions. A programmer has to write a loop correctly to make it perform a
specific number of times.

We have already covered sequential statements in the previous chapter. I n this


chapter, we will talk about the selection and the looping structures. I n actuality, a
program may utilize one or a combination of all control structures.

Selection Structure

There are three selection or conditional statements in PL/SQL. Relational opera-


tors, logical operators, and other special operators are used to create Boolean ex-
pressions or conditions. The tables in Figures 11-1, 11-2, and 11-3 are repeated from
Chapter 5 for reading convenience. Figure 11-1 shows the use of relational opera-
tors, which constitute simple conditions. Figure 11- 2 explains the use of logical oper-
ators in compound conditions. Figure 11-3 shows a truth table for the A ND , OR , and
NO T operators. The A N D and O R operators are binary operators, because they
work on two conditions. The N OT operator is a unary operator, because it works on
a single condition.

Relational Operator Meaning


= Equal to Not equal to
< > or != Greater than
> Greater than or equal to
> = Less than
< Less than or equal to
< =

Figur e 11-1 R elational operators.


246 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL

Logical Operator Meaning

AND Returns TR U E only if both conditions are true.


OR Returns TR U E if one or both conditions are true.
NOT Returns TR U E if the condition is false.

Figur e 11-2 Logical operators.

AN D OR NOT

T R UE AN D TR U E = TRU E TR U E O R TR U E = TR UE NOT T R UE = FALSE


T R UE A N D FALSE = FALSE TR U E O R FALSE = TR UE NOT FALSE = TRU E
FALSE A N D TR U E = FALSE FALSE OR T R UE = T RU E NOT NULL = NULL
FALSE A ND FALSE = FALSE FALSE O R FALSE = FAL SE
NULL A N D TR U E = NULL NULL OR TR U E = TR U E
NULL AN D FALSE = FALSE NULL O R FALSE = NULL
NULL AN D NULL = NULL NULL O R NULL = NULL

Figur e 11-3 Truth tables for AND, OR , and NOT operators.

Other special operators (IS NULL, IN, L I K E , and BE TW E E N Á A N D ) dis-


cussed in the SQL section are also available in PL/SQL. PL /SQL has five condition-
al or selection statements available for decision making:

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.

IF . . . THEN . . . END IF. The I F . . . THE N . . . E ND I F statement is also known


as a simple I F statement. A simple I F statement performs action statements if the
result of the condition is TR U E . If the condition is FA LSE , no action is per- formed,
and the program continues with the next statement in the block. The gener- al syntax
is

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

PL/SQL procedure successfully completed.SQL> /


Enter value for day: MONDAY

PL/SQL procedure successfully completed.SQL>

Figure 11-4 Simple IF statement.

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.

IF Á THEN Á ELSE Á END IF. The I F Á TH E N Á E L SE Á E ND


IF statement is an extension of the simple IF statement. I t provides action statements
for the TR U E outcome as well as for the FALSE outcome. The general syntax is

If the condition’s outcome is TR U E , are performed. If the out-


come is FA LSE, are performed. One set of statements is skipped
in any case.
For an example, see Figure 11-5. I f the entered age is 18 or older, age is dis-
played with string A DU LT; otherwise, age is displayed with string MI NOR .
248 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL

SQL> SET SERVEROUTPUT ON SQL> DECLARE


2 V_AGE NUMBER(2) := ’&AGE’;
3 BEGIN
4 IF (V_AGE >=18) THEN
5 DBMS_OUTPUT.PUT_LINE(’AGE: ’||V_AGE |’- ADULT’);
6 ELSE
7 DBMS_OUTPUT.PUT_LINE(’AGE: ’||V_AGE |’- MINOR’);
8 END IF;
9 END;
10 /
Enter value for age: 21 AGE: 21- ADULT
PL/SQLprocedure successfully completed.

SQL> /
Enter value for age: 12 AGE: 12- MINOR
PL/SQLprocedure successfully completed.SQL>

Figur e 11-5 IF. . .ELSE . . .E ND IF statement.

IF . . . THEN . . . ELSIF . . . END IF. The I F . . . THE N . . . EL SIF . . . E ND


I F statement is an extension to the previous statement. W hen you have many alter-
natives/options, you can use previously explained statements, but the ELSI F alter-
native is more efficient than the other two. The D E C O D E function in SQL is not
allowed in PL/SQL , and the I F . . . THE N . . . E L S . . . E N D I F statement is not al-
lowed in SQL. The general syntax is

...

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> SELECT LName, FName,


2 DECODE(PositionId, 1, Salary*1.2, 3
2, Salary*1.15,
4 3, Salary*1.1,
5 4, Salary*1.05,
6 Salary) “New Salary”
7 FROM employee;

LNAME FNAME New Salary


- --- --- -- --- --- -- -- --- --- -- --- -- --- --- --
Smith John 318000
Houston Larry 172500
Roberts Sandi 86250
McCall Alex 73150
Dev Derek 92000
Shaw Jinku 24500
Garner Stanley 51750
Chen Sunny 36750
Viquez Heillyn
9 rows selected.
SQL>

Figur e 11-6 D E COD E function.

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>

Figur e 11-7 ELSIF statement.


250 Chap. 11 More on PL/SQL: Control Structures and Embedded 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>

Figur e 11-8 Simple IF with multiple conditions.


Control Structures 251

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>

Figur e 11-9 ELSIF statement.

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.

CASE. The C A SE statement is an alternative to the I F . . . T HE N . . . ELSIF


. . . E N D IF statement. The C A SE statement beginswith key word CA SE and ends with
the key words E N D CA SE . The body of the CA SE statement containsW H E N clauses,
with values or conditions, and action statements.W hen a W HE N clause’s value/condition
evaluates to TRU E , itsaction statements are executed. The general syntax is
252 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL

Searched CASE. A statement with a value is known as a , and


a statement with conditions is known as a statement. A CA SE
statement uses as a selector, but a searched CA SE does not use
as a selector. Figure 11-10 is an example of a C A SE statement that
evaluates if a number is odd or even. Figure 11-11 rewrites the same solution for a
searched CA SE statement.

SQL> DECLARE /* Example of Case */


2 V_NUM NUMBER := &ANY_NUM;
3 V_RES NUMBER;
4 BEGIN
5 V_RES := MOD(V_NUM, 2);
6 CASE V_RES
7 WHEN 0 THEN DBMS_OUTPUT.PUT_LINE(V_NUM | ’ IS EVEN’);
8 ELSE DBMS_OUTPUT.PUT_LINE(V_NUM | ’ IS ODD’);
9 END CASE;
10 END;
11 /
Enter value for any_num: 5 5 IS ODD
PL/SQL procedure successfully completed.SQL>

Figur e 11-10 CASE statement.

SQL> DECLARE /* Example of Searched Case */


2 V_NUM NUMBER := &ANY_NUM;
3 BEGIN
4 CASE
5 WHEN MOD(V_NUM, 2)=0 THEN
6 DBMS_OUTPUT.PUT_LINE(V_NUM | ’ IS EVEN’);
7 ELSE
8 DBMS_OUTPUT.PUT_LINE(V_NUM | ’ IS ODD’);
9 END CASE;
10 END;
11 /
Enter value for any_num: 5 5 IS ODD
PL/SQL procedure successfully completed.SQL>

Figur e 11-11 Searched CASE statement.


Control Structures 253

Nested IF. The nested I F statement contains an I F statement within another I F


statement. I f the condition in the outer I F statement is TR U E , the inner I F state-
ment is performed. Any I F statement with a compound condition can be written as
a nested I F statement. For example, the program segment in Figure 11- 12 assigns an
insurance surcharge based on an individual’s gender and age. There are four cate-
gories:

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>

Figur e 11-12 Simple IF with multiple conditions.


254 Chap. 11 More on PL/SQL: Control Structures and Embedded 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

Looping means iterations. A loop repeats a statement or a series of statements a spe-


cific number of times, as defined by the programmer. You would use a loop to repeat
a series of statements many times r ather than typing the same statements many

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’) THEN /* MALE */
7 IF (V_AGE >= 25) THEN
8 V_CHARGE := 0.05;
9 ELSE
10 V_CHARGE := 0.10;
11 END IF;
12 ELSE /* FEMALE */
13 IF (V_AGE >= 25) THEN
14 V_CHARGE := 0.03;
15 ELSE
16 V_CHARGE := 0.06;
17 END IF;

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

PL/SQL procedure successfully completed. SQL>

Figur e 11-13 Nested IF statement.


Control Structures 255

times. Three types of looping statements are available in PL/SQL:

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.

Basic loop. A basic loop is a loop that is performed repeatedly. Once a


loop is entered, all statements in the loop are performed. When the bottom of the
loop is reached, control shifts back to the top of the loop. The loop will continue in-
finitely. A n infinite loop, or a “never- ending loop,” is a logical err or in programming.
The only way to terminate a basic loop is by adding an E X I T statement inside the
loop. The general syntax is

...

The E X I T statement in a loop could be an independent statement, or it could


be part of an I F statement. For example,

IFv_count > 10 THEN EXIT;


END IF;

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,

EXIT WHEN v_count > 10;

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

SQL> SET SERVEROUTPUT ON


SQL> DECLARE
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 */
7LOOP8
9 V_SUM := V_SUM + V_COUNT;
10 V_COUNT := V_COUNT + 1; /* COUNTER INCREMENTED */
11 EXIT WHEN V_COUNT > 10; /* CONDITION */
12 END LOOP;
13 V_AVG :=V_SUM / (V_COUNT -1);DBMS_OUTPUT.PUT_LINE(’AVERAGE OF 1
14 TO 10 IS ’
|TO_CHAR(V_AVG));
15 END;
16 /
AVERAGE OF 1 TO 10 IS 5.5

PL/SQLprocedure successfullycompleted. SQL>

Figure 11-14 Counter-controlled basic loop.

Q uestion: I n a basic loop, if the counter is initialized to one and is incre-


mented within the loop by two, and if the condition at the bottom of the
loop body is E X I T W HE N the counter is less than 10, how many times the
loop is performed?

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?

Q uestion: I n a basic loop, the counter is initialized to zero and is incre-


mented within the loop by one. How many times will the loop be performed
if the condition at the bottom of the loop body is E X I T W HE N the count-
er equals five?

A nswer : Five times (for counter values equal to 0, 1, 2, 3, and 4).

Q uestion: I n a basic loop, the counter is initialized to 10 and is incremented


within the loop by one. How many times will the loop be performed if the
condition at the bottom of the loop body is E X I T W H E N the counter
equals 10?

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.

SQL> SET SERVEROUTPUT ON SQL> DECLARE

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>

Figur e 11-15 Counter-controlled W H ILE loop.

Basic Loop W HIL E Loop

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.

Figur e 11-16 Differences between a basic loop and a W HIL E loop.


258 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL

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

FOR v_count IN REVERSE 1..10LOOP

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

PL/SQL procedure successfully completed. SQL>

Figur e 11-17 FOR loop.


Nested Blocks 259

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
...

EXIT out_loop WHEN condition; EXIT /* exits out_loop */


WHEN condition; /*exits in_loops */
...
END LOOP in_loop; /* label optional here */
...
END LOOP out_loop; /*label optional here */

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,

DECLARE /* Outer block starts here.*/


Var1 NUMBER; BEGIN /* known to outer and inner*/
...DECLARE
Var2NUMBER; /* can use Var1 here */
BEGIN /*Inner block starts here.*/
...END; /* known to inner block */
...END;
/* can use Var1and Var2here */
/* Inner block ends here.*/
/* can use Var1 here */
/* Outer block ends here.*/
260 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL

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.

SELECT Statement 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>

Figur e 11-18 SELECT-INTO in PL/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>

Figur e 11-19 SELECT Á INTO with Error.


262 Chap. 11 More on PL/SQL: Control Structures and Embedded SQL

shows another example that results in exceptions because the SE L E C TÁ I N TO


statement returns either too many rows or no data.

DATA MANIPULATION IN PL/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:

1. The I NSE R T statement to add a new row in a table.


2. The DE L E TE statement to remove a row or rows.
3. The UPD A TE statement to change values in a row or rows.

INSERTStatement

We will use an INSERT statement to add a new employee in the E M PL OY E E


table. The statement will use sequences created earlier. For simplicity, only a few
columns are used in the statement in Figure 11- 20. N EX TV A L uses the next value
from the sequence as the new EmployeeId, and CU RR V A L uses the current value
of the department from that sequence. If you also decide to insert today’s date as the
hire date, you could use the SYSDA TE function for the value.

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>

Figure 11-20 INSER T in PL/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

PL/SQLprocedure successfullycompleted. SQL>

Figur e 11-21 DE LE TE in PL/SQL.

from the E M PL O Y E E table. Figure 11- 21 shows the D E L E TE statement in


PL/SQL.

UPDATE Statement

The U PD A TE statement can be used in a PL/SQL block for modification of data.


The company decides to give a bonus commission to all the employees who are en-
titled to commission. The bonus is 10% of the commission received. Figure 11- 22
shows an example of an U PD A TE statement in PL/SQL block to modify commission.

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>

Figur e 11-22 UPDATE in PL/SQL.


264 Chap. 11 More on PL/SQL: Control Structures and Embedded 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:

● The C OM MI T statement to commit the current transaction.


● The SAV EPOI NT statement to mark a point in your transaction.
● The R OL L BA CK [ TO SAV EPOINT ] statement to discard all or part of
the transaction.

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

3. W hat is the difference between CASE and searched CASE statements?


4. Give four differences between the basic loop and the W HI L E loop.
5. L ist the SQL statements allowed and not allowed in a PL/SQL block.
6. W hat is the purpose of a SEL ECT statement in the PL /SQL block? Explain it with an
example.

Complete the Table for a Counter-Controlled W HI L E Loop

Initial Value of Counter Condition Increment/Decrement Number of Loop Executions

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

The cursor in PL /SQL is of two types:

1. I n a , the contents are known at compile time. The cursor ob-


ject for such an SQL statement is always based on one SQL statement.
2. I n a , a cursor variable that can change its value is used.
The variable can refer to different SQL statements at different times.

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:

1. You do not declare an . PL/SQL declares, manages, and


closes it for every D ata Manipulation Language (D ML ) statement, such
as I NSERT, U PD A TE , or D E L E TE .
2. You declare an explicit cursor when you have an SQL statement in a
PL/SQL block that returns more than one row from an underlying table.
The rows retrieved by such a statement into an explicit cursor make up the
active set. W hen opened, the cursor points to the first row in the active set.
You can retrieve and work with one row at a time from the active set. With
every fetch of a row, the pointer moves to the next row. The cursor returns
the current row to which it is pointing.

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

implicit cursor automatically. A programmer cannot perform on an implicit cursor all


the operations that are possible on explicit cursor statements. PL/SQL creates an im-
plicit cursor for each D M L statement in PL/SQL code. Y ou cannot use an explicit cur-
sor for D M L statements. Y ou can choose to declare an explicit cursor for a SELECT
statement that returns only one row of data, but if you don’t declare an explicit cursor
for a SELECT statement returning one row of data, an implicit cursor is created for it.
Y ou have no control over an implicit cursor. The implied queries perform op-
erations on implicit cursors. PL/SQL actually tries to fetch twice to make sure that a
TO O_MA NY _R OW S exception does not exist. The explicit cursor is more effi-
cient, because it does not try that extra fetch. I t is possible to use an explicit cursor
for a SE L E CT statement that returns just one row, because you have control over it.
For example,

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

A n explicit cursor is declared as a SE L EC T statement in the PL/SQL block. I t is


given a name, and you can use explicit statements to work with it. You have total
control of when to open the cursor, when to fetch a row from it, and when to close it.
There are cursor attributes in PL/SQL to get the status information on explicit cur-
sors. Remember, you can declare an explicit cursor for a SE L EC T statement that re-
turns one or more rows, but you cannot use an explicit cursor for a D M L statement.
Four actions can be performed on an explicit cursor:

1. Declare it.
2. Open it.
3. Fetch row(s) from it.
4. Close it.

Declaring an Explicit Cursor

A cursor is declared as a SE L E C T statement. The SE L E C T statement must not


have an I N TO clause in a cursor’s declaration. I f you want to retrieve rows in a spe-
cific order into a cursor, an O R D E R BY clause can be used in the SE L E C T state-
ment. The general syntax is
270 Chap. 12 PL/SQL Cursors and Exceptions

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;

Figure 12-1 Explicit cursor.

SQL> DECLARE
2 CURSOR EMPLOYEE_CUR IS
3 SELECT EMPLOYEEID, SALARY
4 FROM EMPLOYEE
5 WHERE DEPTID = 20;
6
7 BEGIN 8 ...
9 END;

Figure 12-2 Explicit cursor.

A cursor is based on a SEL E C T statement, so it is linked to at least one table


from the database. The list that follows can contain the names of columns, local vari-
ables, constants, functions, and bind variables. I t is possible for a variable to have the
same name as a column in a table. If you try to use both of them together in a SE-
L E C T statement, the column gets higher precedence. Though permitted, it is not
advisable to use the same name for a variable that exists in a column retrieved by
the SEL E C T statement.
In the next section, we will talk about the actions performed on an explicit cursor.

Actions on Explicit Cursors

Actions are performed on cursors declared in the D E C L A R E section of the block.


Before rows can be retrieved from a cursor, you must open the cursor.
Explicit Cursors 271

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

where may include a local variable, a table, or a bind variable and


is the name of a record structure. For example,
FETCH employee_cur INTO v_empnum, v_sal;
or
FETCH employee_cur INTO emp_rec;
where is declared with % R OW TY PE declaration attribute:
emp_rec employee_cur%ROWTYPE;
I n the first example, two columns, EmployeeI D and Salary, are retrieved into
and , respectively. The number of items matches the number of
variables in the SE L E C T statement. The order of items and variables must also
match. The variables should be declared with a % T Y PE declaration variable to en-
sure the correct data type. I f the number of items in SE L E C T does not match the
number of variables, it results in the following compiler error:
PLS-00394:wrongnumber of values in the INTO list of a FETCH statement
272 Chap. 12 PL/SQL Cursors and Exceptions

The second example of F E TC H uses a record. A composite data type can be


used for the record instead of the CursorN ame% R OW TY PE declaration. Y ou will
learn about the record data type in the next chapter.
Suppose you opened a cursor in a PL/SQL block to retrieve data from a table,
and then inserts, deletes, and updates are performed on that table after the OPE N
statement is executed. Oracle enforces r ead consistency, and the data manipulation
statements are ignored. You will have the same data from the point of execution of
OPE N to the point of execution of C L OSE statements. Changing data in the under-
lying table does not change data in the work area.
Closing a cursor. When you are done with a cursor, you should close it. A
closed cursor can be reopened again. If you terminate your PL/SQL program with-
out closing an open cursor, it will not result in an exception. I n fact, the local cursor
declared in a PL/SQL block is closed automatically when the block terminates. I t is
a good habit, however, to close an open cursor before terminating the block. There
is a limit to the number of cursors a user may open simultaneously. The default value
is in a parameter called OPE N_ CU R SOR S, which has default value of 50. A user re-
leases memory by closing a cursor. PL/SQL uses the C LO SE statement to close a
cursor. The general 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:

% I SO PE N I t returns T R U E if the cursor is open; otherwise, it


returns FA LSE.
% FO U N D I t returns T RU E if the last fetch returned a row; other-
wise, it returns FA LSE.
% N OT FOU N D I t returns TR U E if the last fetch did not return a row;
otherwise, it returns FA L SE . I t complements the
% FO U N D attribute.
I t returns total number of rows returned.
% R O WCO UNT

%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.

SQL> SET SERVEROUTPUT ON SQL> DECLARE


2 V_LAST EMPLOYEE.LNAME%TYPE;
3 V_FIRST EMPLOYEE.FNAME%TYPE;
4 V_SALEMPLOYEE.SALARY%TYPE;
5 CURSOR EMPLOYEE_CUR IS
6 SELECT LNAME, FNAME, SALARY
7 FROM EMPLOYEE
8 WHERE DEPTID = 20;
9 BEGIN
10 IF NOT EMPLOYEE_CUR%ISOPEN THEN
11 OPEN EMPLOYEE_CUR;
12 END IF;
13 LOOP
14 FETCH EMPLOYEE_CUR
15 INTO V_LAST, V_FIRST,V_SAL;
16 EXIT WHEN NOT EMPLOYEE_CUR%FOUND;
17 DBMS_OUTPUT.PUT_LINE
18 (V_FIRST||’’||V_LAST |’’||V_SAL);
19 END LOOP;
20 DBMS_OUTPUT.PUT_LINE
21 (EMPLOYEE_CUR%ROWCOUNT |’ EMPLOYEE(S) FOUND’);
22 END;
23 /
Alex McCall 66500
Derek Dev 80000
2 EMPLOYEE(S) FOUND
PL/SQLprocedure successfullycompleted.SQL>

Figur e 12-3 Cursor attributes.

%FOUND

The % FO U N D attribute returns a TR U E if the last FE TC H returned a row; other-


wise, it returns a FALSE. For example, Figure 12-3 shows a block segment that exits
the loop if a row is not found. The loop continues as long as a row is fetched.
%NOTFOUND

The % N O TFO U ND attribute returns a TR U E if the last FE T CH did not return a


row; otherwise, it returns a FA LSE. I t is the opposite of the % FO U N D attribute.
274 Chap. 12 PL/SQL Cursors and Exceptions

The statement
EXIT WHEN NOT employee_cur%FOUND;

can be written as
EXIT WHEN employee_cur%NOTFOUND;

%ROWCOUNT

When a cursor is opened and no fetch is done from it, % R O W C O U NT is equal to


zero. W ith every fetch, % R O W C O U N T is incremented by one. The cursor must be
open before using % R O W C O U NT on it. For example, the code in Figure 12- 3 goes
through the loop as long as a row is fetched. A count of the number of rows fetched
is kept by the PL /SQL engine. I n the code, we are printing the total number of rows
fetched by the cursor at the end.

IMPLICITCURSOR ATTRIBUTES

A n implicit cursor cannot be opened, fetched from, or closed with a statement. Y ou


do not name implicit cursors. The cursor attributes are available for an implicit cur-
sor with the name SQL as a prefix. The four attributes for a implicit cursor are:

1. SQL % I SOPE N.
2. SQL % RO W CO U NT.
3. SQL % NOTFO U ND .
4. SQL % FOU N D .

If an implicit cursor is not open, SQ L % R OW C OU NT will return NU LL. Sim-


ilarly, the other three attributes will return FAL SE. Y ou will never get an IN-
V A LI D _C U R SOR error for an implicit cursor. The % I SOPE N attribute will always
return FALSE, because it is open only during the statement’s execution. I t is opened
and closed implicitly. W hen a SEL E C T statement returns either no or more than
one row, the NO _D A TA _FOU ND or TOO _MA NY _R OW S exception, respective-
ly, is raised. The cursor attribute SQL applies to the last SQL statement executed in
the block.

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

FO R loop automates all the cursor actions. The general syntax is

...

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.

SQL> SET SERVEROUTPUT ON SQL> DECLARE


2 CURSOR EMPLOYEE_CUR IS
3 SELECT LNAME, FNAME, SALARY
4 FROM EMPLOYEE;
5 BEGIN
6 FOR EMP_REC IN EMPLOYEE_CUR LOOP
7 IFEMP_REC.SALARY > 75000THEN
8 DBMS_OUTPUT.PUT(EMP_REC.FNAME |’’);
9 DBMS_OUTPUT.PUT(EMP_REC.LNAME | ’’);
10 DBMS_OUTPUT.PUT_LINE(EMP_REC.SALARY |’’);
11 END IF;
12 END LOOP;
13 END;
14 /
John Smith265000
Larry Houston 150000
Derek Dev 80000

PL/SQLprocedure successfullycompleted.SQL>

Figur e 12-4 Cursor FO R Loop.


276 Chap. 12 PL/SQL Cursors and Exceptions

Cursor FOR Loop Using a Subquery

Use of a subquery in the cursor FO R loop eliminates declaration of an explicit cursor.


The cursor is created by a subquery in the FO R loop statement itself. I n Figure 12-5,
an explicit cursor is used with implicit actions. O ne thing that is missing is the cursor
name. The cursor declaration is not necessary, because it is created through the sub-
query. This subquery is similar to the inline view covered in the SQL section of this
text.

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>

Figur e 12-5 Cursor FO R loop with a subquery.

SELECT. . . FOR UPDATE CURSOR

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

The optional part of a F OR U PD A TE clause is , which en-


ables you to specify columns to be updated. You can actually update any column in
a locked row. The optional word tells you right away if another user has
already locked the table and lets you continue with other tasks. If you do not use
NOW AI T and one or more rows are already locked by another user, you will have
to wait until the lock is released. If you have granted U PD A TE privilege to another
user on your table, that user can prevent you from performing D M L operations on
your own table by locking them indefinitely!

WHERE CURRENTOF CLAUSE

I n a cursor, data manipulation in the form of U PD A TE or D E L E TE is performed


on rows fetched. The W H E R E CU R R E N T O F clause allows you to perform data
manipulation only on a recently fetched row. The general syntax is

You do not have to use a separate W H E R E condition. The W HE R E C U R R E NT


OF clause references the cursor, and changes apply to only the last fetched row.

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

where , and so on are formal parameters passed to the cursor


and is any scalar data type assigned to the parameter. The parameters are
assigned only data types; they are not assigned size.
When a cursor is opened, values are passed to the cursor. E ach value must
match the positional order of the parameters in a cursor’s declaration. The values
278 Chap. 12 PL/SQL Cursors and Exceptions

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.

SQL> SET SERVEROUTPUT ON


SQL> DECLARE
2 V_FIRST EMPLOYEE.FNAME%TYPE; V_LAST EMPLOYEE.LNAME%TYPE;
3 D_ID NUMBER(2) := &DEPARTMENT_ID;
4 CURSOR EMPLOYEE_CUR (DEPT_NUM EMPLOYEE.DEPTID%TYPE) IS
5 SELECT LNAME, FNAME
6 FROM EMPLOYEE
7 WHERE DEPTID = DEPT_NUM;
8
10
9 BEGIN
11 OPEN EMPLOYEE_CUR(D_ID);
12 DBMS_OUTPUT.PUT_LINE
13 (’EMPLOYEES IN DEPARTMENT ’||TO_CHAR(D_ID));
14 LOOP
15 FETCH EMPLOYEE_CUR INTO V_LAST, V_FIRST;
16 EXIT WHEN EMPLOYEE_CUR%NOTFOUND;
17 DBMS_OUTPUT.PUT_LINE(V_LAST |’, ’||V_FIRST);
18 END LOOP;
19 CLOSE EMPLOYEE_CUR;

20 END;21 /
Enter value for department_id: 10 EMPLOYEES IN DEPARTMENT
10
Smith, JohnRoberts,Sandi Chen, Sunny

PL/SQL procedure successfully completed. SQL>

Figure 12-6 Cursor with Parameter.


Cursor Variables: An Introduction 279

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

CURSOR VARIABLES: AN INTRODUCTION

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

where is the name of the type of cursor. The R E TU R N clause is op-


tional. The is the R E T U R N data type and can be any valid data structure,
such as a record or structure defined with % RO W TY PE . For example,

TYPE any_cursor_type IS REFCURSOR; any_cursor_var


any_cursor_type; TYPE employee_cursor_type IS REF
CURSOR
RETURN employee%ROWTYPE; employee_cursor_var
employee_cursor_type;

I n this example, the first cursor type, , is called the type,


because its R E TU RN clause is missing. This type of cursor type can be used with
any query. The cursor type declared with the R E TU R N clause is called the
type, because it links a row type to the cursor type at the declaration time.
280 Chap. 12 PL/SQL Cursors and Exceptions

Opening a Cursor Variable

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;

The structure returned by the SE L E C T query matches the R E T U R N type employ-


ee% R OW TY PE .
The other cursor type, , is declared without the R E TU R N
clause. I t can be opened without any worry about matching the query’s result to
anything. The weak type is more flexible than the strong type, but there is no error
checking. L et us look at some OPE N statements for the weak cursor variable:
OPEN any_cursor_var FOR SELECT * FROM dept; OPEN any_cursor_var FOR SELECT *
FROM employee; OPEN any_cursor_var FOR SELECT DeptId FROM dept;

I t is possible to have all three statements in one program block. The cursor variable
assumes different structures with each OPEN.

Fetching from a Cursor Variable

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

( A t the end of this chapter, under , are three more


coding examples on cursors.)

EXCEPTIONS

I n PL/SQL, errors are known as exceptions. A n exception occurs when an unwanted


situation arises during the execution of a program. Exceptions can result from a sys-
tem error, a user error, or an application error. W hen an exception occurs, control of
the current program block shifts to another section of the program, known as the
exception section, to handle exceptions. If the exception handler exists, it is per-
formed. I f the exception handler does not exist in the current block, control propa-
gates to the outer blocks. If the handler is not in any of the blocks, PL/SQL returns
an error, and the script stops.
A programmer writes a program to perform certain tasks, keeping only the pos-
itive things in mind. Programming is more than just writing statements to perform a
Types of Exceptions 281

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,

The general syntax of an exception section is:

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 three types of exceptions in PL/SQL:

1. are exceptions that are named by


PL/SQL and are raised implicitly when a PL /SQL or D BMS error occurs.
282 Chap. 12 PL/SQL Cursors and 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.

Predefined Oracle Server Exceptions

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.

Exception Name Error Number B rief Description

NO_DATA_FO UND ORA-01403 Single-row SELECT returned no data.


TOO_MANY_R OW S ORA-01422 Single-row SELECT returned more than one row.
ZER O_DIVIDE ORA-01476 Attempted to divide by zero.
VALUE_ER ROR ORA-06502 Arithmetic, conversion, truncation, or size constraint
error occurred.
STOR AGE_ERR OR ORA-06500 PL/SQL ran out of memory, or memory is corrupted.
LOGIN_DENIED ORA-01017 Logging on to Oracle with an invalid username or
password.
NOT_LOGG ED_ON ORA-01012 PL/SQL program issues a database call without
being connected to Oracle.
PROGR AM_ERR OR ORA-06501 PL/SQL has an internal problem.
ACCESS_INTO_NULL ORA-06530 Attempted to assign values to the attributes of an
uninitialized object.
CUR SOR_ALR EADY_OPEN ORA-06511 Attempted to open an already-open cursor.
DUP_VAL_ON_INDEX ORA-00001 Attempted to insert a duplicate value.
INVALID_CURSOR ORA-01001 Illegal cursor operation occurred.
INVALID_NUMBER ORA-01722 Conversion of a character string to number failed.
R OWTY PE_MISMATCH ORA-06504 Host cursor variable and PL/SQL cursor variable
involved in an assignment have incompatible return
types.
TIMEOUT_ON_RESOUR CE ORA-00051 Time-out occurred while Oracle is waiting
for a resource.

Figur e 12-7 Predefined/named system exceptions.


Types of Exceptions 283

Suppose a program block generates an error message for exception error


number ORA -01403 that is not handled by the exception section. The err or has oc-
curred because of a SE L EC T statement that did not return any data. Y ou can write
an exception handler as shown in Figure 12-8.

SQL> SET SERVEROUTPUT ON SQL> DECLARE


2 V_FIRST EMPLOYEE.FNAME%TYPE;
3 V_LAST EMPLOYEE.LNAME%TYPE;
4 D_ID NUMBER(2) :=&DEPARTMENT_ID;
5 BEGIN
6 SELECT LNAME, FNAME
7 INTO V_LAST, V_FIRST
8 FROM EMPLOYEE
9 WHERE DEPTID = D_ID;
10 DBMS_OUTPUT.PUT_LINE(’ ’);
11 DBMS_OUTPUT.PUT_LINE(V_LAST |’, ’||V_FIRST);
12 EXCEPTION
13 WHEN NO_DATA_FOUND THEN
14 DBMS_OUTPUT.PUT_LINE
15 (’NO SUCH DEPARTMENT WITH EMPLOYEES’);
16 WHEN TOO_MANY_ROWS THEN
17 DBMS_OUTPUT.PUT_LINE
18 (’MORE THAN ONE EMPLOYEE IN DEPT ’||D_ID);
19 END;
20 /

Figure 12-8 Handling named exceptions (source).

I n Figure 12-8, two named exceptions, N O_ D A TA _ FO U N D and


TOO_ MA NY _R OW S, are handled. The NO _D A TA _FOU ND exception occurs
when a SE L E C T . . . I NTO statement does not retrieve a row. The TOO_M A NY _
ROW S exception occurs when a SE L E C T . . . I N TO statement retrieves more than
one row. Figure 12- 9 shows execution of the code in Figure 12-8 to demonstrate han-
dling of both exceptions. I nput value 10 returned more than one row, resulting in the
TOO_M A NY _ ROW S exception, which is raised implicitly and handled. Input
value 50 returned 0 rows, resulting in the NO_ D A TA _ FOU N D exception, which is
also raised implicitly and handled by the block. I nput value 40 returned one em-
ployee, so no exception was thrown.

Nonpredefined Oracle Server Exceptions

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

Enter value for department_id: 10 MORE THAN


ONE EMPLOYEE IN DEPT 10

PL/SQLprocedure successfully completed.SQL> /


Enter value for department_id: 50
NO SUCH DEPARTMENT WITH EMPLOYEES

PL/SQLprocedure successfully completed.SQL> /


Enter value for department_id: 40Houston, Larry
PL/SQLprocedure successfully completed.SQL>

Figure 12-9 Handling named exceptions (output).

is raised implicitly by Oracle, or you can raise it explicitly. Y ou can write exception-
handler code for it.

Pragma Exception_Init. PR A G M A is a compiler directive that associates an


exception name with an internal Oracle error code. The PR A GM A directive isnot
processed with the execution of a PL/SQL block, but it directs the PL/SQL com- piler
to associate a name with the error code. You can use more than one PRA GM A
E X C EPTI O N_I N I T directive in your D E C L A R E section to assign names to differ-
ent error codes. Y ou may even assign more than one name to the same error number.
Naming an internal error code makes your program more readable.
Naming and associating are two separate statements in the declaration sec-
tion. First, an exception name is declared as an EX CE PTI O N. Second, the declared
name is associated with an internal error code returned by SQL C O D E with the
PR A GM A directive. The general syntax is

where is user supplied and er rornumber is Oracle’s internal error


code. The error code is a numeric literal with a negative sign 1 - 2.
Suppose you tried to remove a department from the D E PT table but the child
rows still exist in the E M PL O Y E E table, because there are employees with that
D eptI d. You will get Oracle error ORA- 02292. You can declare an exception and as-
sociate it with the server error code number - 2292. Figure 12-10 shows a PL/SQL
block with a declaration and exception trapping of a nonpredefined Oracle excep-
tion. There is no explicit RA I SE statement.
Types of Exceptions 285

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>

Figur e 12-10 Nonpredefined Oracle exception.

E xception-Tr apping functions. When an exception occurs in your program,


you don’t know the error code for the err or and its associated message unless you
take specific action to identify them. Once you know the error code and the mes-
sage, you can modify your program to take action based on the error. The two func-
tions to identify the err or code and error message are:

1. SQ L CO DE . The SQ L C OD E function returns a negative error code num-


ber. The number can be assigned to a variable of NU M BE R type.
2. SQ L ER R M. The SQ L E R RM function returns the error message associat-
ed with the err or code. The maximum length of error message is 512 bytes.
I t can be assigned to a V ARCHAR2-type variable.

Figure 12-11 shows the use of SQ L C OD E and SQ L E RR M to identify the


er ror code and message for further modifications of the exception section of a pro-
gram based on information displayed.
286 Chap. 12 PL/SQL Cursors and Exceptions

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

PL/SQLprocedure successfully completed.SQL>

Figure 12-11 SQ LCOD E and SQLERRM.

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:

1. You must declar e the exception in the D E C L A R E section. There is no


need to use a PR A G M A directive, because there is no standard error
number to associate.
2. You must r aise the exception in the execution section of the program with
an explicit R A I SE statement.
3. You must wr ite the handler for the exception.
Types of Exceptions 287

Figures 12- 12 and 12- 13 are examples of the user-defined exceptions


and The exception is
raised when the commission value is negative. The exception is
raised when the commission value is NU LL. Figure 12-12 shows the source code,
and Figure 12-13 shows exception handling based on the EmployeeId entered by
the user.

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 /

Figure 12-12 User-defined exception (source).

RAISE_APPLICATION_ERROR Procedure

The R A I SE _A PPL I C A TI ON _E R RO R procedure allows you to display nonstan-


dard error codes and user-defined error messages from a stored subprogram. The
general syntax is

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

Enter value for emp_id: 111 35000

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>

Figure 12-13 User-defined exception (output).

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’);

You can use a R A I SE _A PPL I C A TI O N_ E RR OR procedure in the execution


and exception sections of the program. I t is very useful in communicating errors be-
tween the client and the server.
I n a PL/SQL program with an anonymous block that has nested blocks as well
as procedures and functions, the outermost block nests other blocks and calls the
procedures and functions. Each block can have its own exception-handling section,
and some blocks may not have an exception-handling section. A n exception de-
clared in the inner block cannot be raised in the enclosing outer block. If an excep-
tion is declared in the outer block, it can be raised in the block itself or in its inner
subblock. When the exception is raised implicitly or explicitly in an inner block with-
out the exception- handling section, control shifts to the adjacent outer block and
then propagates outward until its handler is found or it ends up being an unhandled
exception.
In a Nutshell .. . 289

The RA I SE statement is very much like the G O TO statement. They both


branch to another part of the program. The difference is that the R A I SE statement
branches to the exception section, whereas the G OT O statement branches to an-
other statement in an executable block.

MORE SAMPLE PROGRAMS

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

SQL> SET SERVEROUTPUT ON


SQL> /* program uses a cursor to get employee information.
DOC>Then prints total wages for eachemployee.
DOC>Program also prints total company wages. */ SQL> DECLARE

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>

Figur e 12-14 Sample program— explicit cursor.


In a Nutshell .. . 291

SQL> SET SERVEROUTPUT ON


SQL> /* Program uses acursor with a date parameter. DOC>User inputs
a value for the parameter.
DOC>Program displays employees hired after inputted date */SQL>
DECLARE
2 CURSOR EMP_CUR(START_DATE DATE) IS
3 SELECT LNAME, FNAME, HIREDATE, DEPTNAME FROM EMPLOYEE
4 E, DEPT D
5 WHERE HIREDATE > START_DATE AND D.DEPTID=E.DEPTID;
6 V_FIRST EMPLOYEE.FNAME%TYPE;
7 V_LAST EMPLOYEE.LNAME%TYPE; V_HIRE
8 EMPLOYEE.HIREDATE%TYPE; V_DEPT DEPT.DEPTNAME%TYPE;
9 V_DATE EMPLOYEE.HIREDATE%TYPE := ’&P_DATE’;
10
11 BEGIN
12 OPEN EMP_CUR(V_DATE);
13 FETCH EMP_CUR INTO V_LAST, V_FIRST, V_HIRE, V_DEPT; WHILE
14 EMP_CUR%FOUND LOOP
15 DBMS_OUTPUT.PUT(V_LAST |’, ’||V_FIRST);
16 DBMS_OUTPUT.PUT
17 (’was hired on ’||TO_CHAR(V_HIRE, ’MM/DD/YYYY’));
18 DBMS_OUTPUT.PUT_LINE(’ in ’||V_DEPT |’ department’); FETCH
19 EMP_CUR INTO V_LAST, V_FIRST, V_HIRE, V_DEPT;
20 END LOOP; DBMS_OUTPUT.PUT_LINE
21 (’TOTALEMPLOYEES: ’||EMP_CUR%ROWCOUNT); CLOSE EMP_CUR;
22
23

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>

Figur e 12-15 Sample program— cursor with parameter.


292 Chap. 12 PL/SQL Cursors and Exceptions

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>

Figur e 12-16 Sample program— cursor FO R loop and W H ER E CU R R EN T OF.

● Four actions are performed on explicit cursors: D E CL A R E , OPEN, FE TC H,


and CLOSE.
● The cursor attributes % I SOPE N, % FO U N D , % NOTF OU ND , and % R OW -
C OU NT give the status of the cursor.
● The cursor attributes that are used with an implicit cursor have as a
qualifier or a prefix (e.g., SQL % I SOPE N).
● A cursor F O R loop implicitly opens, fetches, and closes a cursor.
● A n explicit cursor does not need to be declared if the cursor F O R loop uses
a subquery to create a cursor.
● The SE L E CT . . . FO R U PD A TE statement is used with a cursor to lock
rows for future updates. These rows are released with a CO MM I T or
RO L LB A C K statement.
● The W H E R E C U R R E NT O F clause allows you to perform data manipula-
tion on a recently fetched row.
● A cursor with parameters enables you to pass values to the cursor.
In a Nutshell .. . 293

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>

Figur e 12-17 Sample program— exception handling.

● 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

● Nonpredefined Oracle server exceptions are declared with a PRA GM A


E X C E PTI ON _I N I T directive to associate an exception name with a stan-
dard error code.
● U ser- defined exceptions are declared, raised, and handled explicitly.
● The exception-trapping functions SQ L C OD E and SQ L E R RM retur n an
error code and the associated error message, respectively.

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.

State Differences Between the Following Terms:


1. Static cursor and dynamic cursor.
2. Implicit cursor and explicit cursor.
3. Predefined Oracle server exception and user-defined exception.
4. Nonpredefined Oracle server exception and user-defined exception.

Answer the Following Questions:


1. W hat actions can be performed on an explicit cursor? Give an example of each state-
ment’s use.
2. W hat are four cursor attributes? State their use.
3. Can you use cursor attributes with implicit cursors? If yes, how?
4. W hat is a cursor FO R loop? What are its benefits?
5. W hat are exceptions? W here are they handled?
6. Name the error-trapping functions. How are they useful?
7. How are the three types of exceptions declared, raised, and handled?
Lab Activity 295

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 . . .

● You will learn about composite data types in PL/SQL.


● The basics of a PL/SQL record structure and its declaration, assignment of a
value, and use in a program are covered.
● The PL /SQL composite data type of table is discussed, together with its dec-
laration, referencing, and types of assignments.
● Built- in methods to obtain table information are outlined.
● A complex structure, a table of records, is covered.
● Variable- sized arrays, or varrays, are introduced.

COMPOSITE DATA TYPES

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.

Creating a PL/SQL Record

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;

In this declaration, is the user- defined R E C O R D type. Three


fieldsare included in its structure; , and . The record is
a record declared with the user- defined record type . Each field dec-
laration is similar to a scalar variable declaration.
298 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays

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.

Referencing Fields in a Record

A field in a record has a name that is given in the R E C OR D - type definition. Y ou


cannot reference a field by its name only; you must use the record name as a quali-
fier:

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,

employee_rec.e_sal := 100000; employee_rec.e_last := ‘Jordan’;

Working with Records

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

Here, assumes the structure of the E M PL OY E E table. The fields in


take their column names and their data types from the table. I t is advanta-
geous to use % RO W TY PE , because it does not require you to know the column
names and their data types in the underlying table. If you change the data type
and/or size of a column, the record is created at execution time and is defined with
the updated table structure. The fields in the record declared with % R OW TY PE
are referenced with the qualified name .
The program in Figure 13- 1 declares a record with a record type. The SE-
L E C T query retrieves a row into the record based on the student I D entered at
the prompt. The fields in the record ar e printed using the
notation.

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>

Figur e 13-1 PL/SQL record.

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;

I n this example, nests as a field type. If you de-


cide to use an unnested simple record, the record becomes cumbersome. There are
six fields in . Y ou will have to use six fields each for each of the three
record fields , and , which will result in a
total of 18 fields.
Nesting records makes code more readable and easier to maintain. Y ou can
nest records to multiple levels. D ot notation is also used to reference fields in the
nested situation. For example, references a field
called in the nested record , which is enclosed by the record
.

PL/SQL TABLES

A table, like a record, is a composite data structure in PL/SQL. A PL/SQL table is a


single-dimensional structure with a collection of elements that store the same type
of value. I n other words, it is like an array in other programming languages. I f you
know C OB OL , arrays are called tables in C O BO L terminology, although there are
dissimilarities between a traditional array and a PL /SQL table. A table is a dynamic
structure that is not constrained, whereas an array is not dynamic in most computer
languages.

Declaring a PL/SQL Table

A PL/SQL TA B L E declaration is done in two steps, like a record declaration:

1. Declare a PL /SQL table type with a TY PE statement. The structure could


use any of the scalar data types.
2. Declare an actual table based on the type declared in the previous step.

The general syntax is


PL/SQL Tables 301

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.

Primary Key Column Data Column


... ...
1 Sales
2 Marketing
3 Information Systems
4 Finance
5 Production
... ...

Figure 13-2 PL/SQL table structure.

Referencing Table Elements/Rows

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

The following are valid assignments for the table’s rows:

deptname_table(5) :=‘HumanResources’; major_table(100) := v_major;

You can use an expression or a value other than a B I NA R Y _I NTE GE R


value, and PL/SQL will convert it. For example,

/* 25.7 is rounded to 26.*/ deptname_table(25.7) := ‘Training’;


/* ‘5’||’00’is convertedto 500.*/
deptname_table (‘5’||‘00’) := ‘Research’;
/* v_num + 7 is evaluated. */ deptname_table(v_num + 7) := ‘Development’;

I n other programming languages, such as C or Visual Basic, you specify the


number of elements in an array when you declare the array. The memory locations
are reserved for elements in an array at the declaration time. I n a PL/SQL table, the
primary key values are not preassigned. A row is created when you assign a value to
it. If a row does not exist and you try to access it, the PL /SQL predefined server ex-
ception N O_D A TA _F OU ND is raised. Y ou can keep track of rows’ primary key
values if you use them in a sequence and keep track of the minimum and the maxi-
mum value.

Assigning Values to Rows in a PL/SQL Table

You can assign values to the rows in a table in three ways:

1. Direct assignment.
2. Assignment in a loop.
3. Aggregate assignment.

Direct Assignment. You can assign a value to a row with an assignment


statement, as you already learned in the previous topic. This is preferable if only a
few assignments are to be made. If an entire database table’s values are to be as-
signed to a table, however, a looping method is preferable.

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 /

JANUARY 04, 2004


JANUARY 11, 2004
JANUARY 18, 2004
JANUARY 25, 2004
FEBRUARY 01, 2004
FEBRUARY 08, 2004
FEBRUARY 15, 2004
FEBRUARY 22, 2004
FEBRUARY 29, 2004
...
DECEMBER
DECEMBER 19, 2004
26, 2004

PL/SQL procedure successfully completed.


SQL>

Figure 13-3 Table row assignment in a loop.

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

Built-In Table Methods

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

where is one of the methods described in Figure 13- 4. For example,

total_rows :=deptname_table.COUNT; /* counts elements */


deptname_table.DELETE(5); /* deletes element 5 */
deptname_table.DELETE(7, 10); /* deletes element 7 to 10 */
deptname_table.DELETE; /* deletes all elements */
next_row :=deptname_table.NEXT(25); /* index after 25*/
previous_row:=deptname_table.PRIOR(7); /* index before 7 */
first_row:= deptname_table.FIRST; last_row:= /* smallest index */
deptname_table.LAST; /* largest index */
IF deptname_table.EXISTS(11) THEN ... /* true,if index 11 exists */

Built-in Method Use


FIRST Returns the smallest index number in a PL/SQL table.
LAST Returns the largest index number in a PL/SQL table.
COUNT Returns the total number of elements in a PL/SQL table.
PRIOR( ) Returns the index number that is before index number .
NEXT( ) Returns the index number that is after index number .
EXISTS( ) Returns T R UE if index exists in the table.
TRIM Removes one element from end of the table.
TRIM ( ) Removes elements from end of the table.
DELETE Removes all elements from a PL/SQL table.
DELETE ( ) Removes the -th element from the table.
DELETE ( , ) Removes all elements in the range ... from a table.
EXTEND Appends a null element to a table.
EXTEND ( ) Appends null elements to a table.
EXTEND ( , ) Appends copies of the -th element to a table.

Figur e 13-4 PL/SQL built-in table methods.

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

PL/SQLprocedure successfully completed.SQL>

Figur e 13-5 PL/SQL table.

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;

CURSOR employee_cur IS SELECT * FROM employee;


TYPE employee_cur_table_type IS employee_cur%ROWTYPE INDEX BY BINARY_INTEGER;
Employee_cur_table employee_cur_table_type;

The % R OW TY PE attribute is not used when the table is based on a user-


defined record. Y ou use the % R OW TY PE attribute when the table is based on a
database table or a cursor.
The fields of a PL/SQL table based on a record are referenced with the fol-
lowing syntax:

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

A PL/SQL V ARRA Y declaration is done in two steps, like a table declaration:

1. Declare a PL/SQL VA RRAY type with a TY PE statement. The TY PE


declaration includes a size to set the upper bound of a varray. The lower
bound is alwaysone.
2. Declare an actual varray based on the type declared in the previous step.

The general syntax is

For example,

DECLARE
TYPE Lname_varray_type IS VARRAY(5) OF employee.LName%TYPE; Lname_varray
Lname_varray_type :=Lname_varray_type( );

When a varray is declared, it is NU LL. I t must be initialized before referencing


its elements. I n the second step of a varray’s declaration, the assignment par t initial-
izes it. The E X T E ND method is used before adding a new element to a varray. In
the example above, the upper bound would be five, which limits number of elements
to five.
I n Figure 13-6, C OU R SE I D _V A RR A Y _TY PE is declared with upper bound
of 10. Next, the CO U R SE I D _V A R RA Y is declared with the varray type and then
initialized. A cursor F OR loop then adds elements to the varray. Notice the use of
the E X TE ND method before assigning a value to the new element. The C OU NT
method returns the number of elements, the L I M I T method the upper bound, the
FI R ST method the first subscript, and the L A ST method the last subscript.
I n Oracle9i, it is possible to create a collection of a collection (multilevel col-
lection) like a varray of varrays. For example,

DECLARE
TYPE varray_type1 IS VARRAY(3) OF NUMBER; TYPE varray_type2 IS VARRAY(2)
of varray_type1;

I n Figure 13- 7, V 1 is a varray, and V 2 is a varray of varray V 1. V array V 1 con-


tains three elements, and varray V 2 contains six elements 12 .3 = 62. Elements of
varray V 1 are referenced with one subscript, but elements of varray V 2 are refer-
enced with two subscripts.
There is one more type of collection in PL/SQL. use a column that
has a table type as its data type and are single-dimensional, unbounded collections of
308 Chap. 13 PL/SQL Composite Data Types: Records, Tables, and Varrays

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>

Figur e 13-6 PL/SQL Varray.


In a Nutshell .. . 309

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>

Figur e 13-7 Varray of varrays.

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.

Answer the Following Questions:


1. How do you declare a PL/SQL record? Explain with an example.
2. Give examples of the assignment of values to fields in a PL/SQL record.
3. W hat is a PL/SQL table? W hat are its similarities and differences between a PL/SQL
table and an array?
4. How do you declare a PL/SQL table? Explain with an example.
5. Give three methods used in assigning values to the rows in a PL/SQL table.
6. W hat is a table of records?
7. W hat is a varray? What are the similarities and differences between a varray and a
PL/SQL table?
8. How is a varray of varrays declared? How are its elements referenced?

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 . . .

● Y ou will learn about PL/SQL modules, also known as named blocks.


● The basics of a named module called a procedure (its call, its body, and its
parameter types) are explained.
● The PL/SQL module called a function is covered, along with its call, body,
and R E TU R N types.
● Package structure, specification, body, benefits, and call to its blocks are
discussed.
● Triggers, their types, and their functioning are introduced.
I n previous chapters dealing with PL/SQL, an anonymous block was used for all
programming examples. The anonymous block does not have a name, and it cannot
be called by another block in the program. I t cannot take arguments from another
block, either. A n anonymous block can call other types of PL/SQL blocks called
pr ocedur es and functions. The procedures and functions are named block s, and
they can be called with parameters. A n anonymous block can be nested within a
procedure, function, or another anonymous block. The purpose of a procedure or
function call is to modularize a PL /SQL program. A named PL/SQL block is com-
piled when it is created or when it is altered. The compilation process consists of
three steps: syntax error checking, binding, and p- code creation. A syntactically
314 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

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;

I n these examples of procedure calls, parameters are enclosed in parentheses.


You can use a variable, constant, expression, or literal value as a parameter. If you
are not passing any parameters to a procedure, parentheses are not needed.
Procedures 315

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.

Parameter Type Use

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.

Figur e 14-1 Types of parameters.


316 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

Actual and Formal Parameters

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 Call SEAR CH _EMP (543, LAST)

-- Procedure Header
PR OC ED UR E SE AR CH_EM P (EMPNO IN N UMB E R, LAST OUT VA RCHAR 2)

Figur e 14-2 Actual and formal parameters.

Matching Actual and Formal Parameters

There are two different ways in PL/SQL to link formal and actual parameters:

1. I n , the formal parameter is linked with an actual pa-


rameter implicitly by position (see Fig. 14-2). Positional notation is more
commonly used for parameter matching.
2. In , the formal parameter is linked with an actual parameter
explicitly by name. The formal parameter and actual parameters (the values
of the parameters) are linked in the call statement with the symbol = 7 .

The general syntax is

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> CREATE OR REPLACE PROCEDURE DEPENDENT_INFO


2 IS
3 CURSOR DEP_CUR IS
4 SELECT LNAME, FNAME, COUNT(DEPENDENTID) CNT
5 FROM EMPLOYEE E, DEPENDENT D
6 WHERE E.EMPLOYEEID = D.EMPLOYEEID
7 GROUP BY LNAME, FNAME;
8 BEGIN
9 FOR DEP_RECIN DEP_CUR LOOP
10 IFDEP_REC.CNT >= 2 THEN
11 DBMS_OUTPUT.PUT_LINE(DEP_REC.LNAME||’, ’||
12 DEP_REC.FNAME||’ has ’||DEP_REC.CNT||’ dependents’);
13 END IF;
14 END LOOP;
15 END;
16 /
Procedure created.

SQL> EXECUTEDEPENDENT_INFO
Dev,Derek has 2 dependents Chen, Sunny has 3 dependents
PL/SQL procedure successfully completed. SQL>

Figure 14-3 Procedure without parameters.

If you receive an error, use the following command:


SHOW ERROR

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:

ALTER PROCEDURE COMPILE;

In Figure 14- 4, the procedure receives three parameters—


and — as IN, OU T, and O U T types, respectively. Parameter is
used for input/reading, and parameters and are used for writing. In
Figure 14-5, you will see an anonymous block that calls the procedure in Figure 14-4
with three parameters. The procedure searches for the employee’s name based on the
V_I D that is passed. I f the employee is not found, the exception is handled in the pro-
cedure. If the employee is found, the procedure sends out the last name and first name
318 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

SQL> CREATE OR REPLACE PROCEDURE SEARCH_EMP


2 (I_EMPID IN NUMBER,
3 O_LAST OUT VARCHAR2,
4 O_FIRST OUT VARCHAR2)
5 IS
6 BEGIN
7 SELECT LNAME, FNAME
8 INTO O_LAST, O_FIRST
9 FROM EMPLOYEE
10 WHERE EMPLOYEEID = I_EMPID;
11 EXCEPTION
12 WHEN OTHERS THEN
13 DBMS_OUTPUT.PUT_LINE(’EmployeeId ’||
14 TO_CHAR(I_EMPID) |’does not exist’);
15END SEARCH_EMP; 16 /

Procedure created.
SQL>

Figur e 14-4 Procedure with parameters.

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>

Figur e 14-5 Anonymous block with call to procedure in Figure 14-4.


Functions 319

of the employee to the calling anonymous block.The anonymous block then prints the
employee’s information.

FUNCTIONS

A function, like a procedure, is a named PL/SQL block. Like a procedure, it is also a


stored block. The main difference between a function and a procedure is that a
function always returns a value to the calling block. A function is characterized as
follows:

● A function can be passed zero or more parameters.


● A function must have an explicit R E TU R N statement in the executable sec-
tion to return a value.
● The data type of the r eturn value must be declared in the function’s header.

• A function cannot be executed as a stand- alone program.

A function may have parameters of the I N, OU T, and I N O U T types, but the


primary use of a function is to return a value with an explicit R E TU R N statement. The
use of O U T and I N O U T parameter types in functions is rare— and considered to be a
bad practice. The general syntax is

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.

RETURN Data Types

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

SQL> CREATE OR REPLACE FUNCTION GET_DEPTNAME


2 (I_DEPTID IN NUMBER)
3 RETURN VARCHAR2
4 IS
5 V_DEPTNAME VARCHAR2(12);
6 BEGIN
7 SELECTDEPTNAME
8 INTO V_DEPTNAME
9 FROM DEPT
10 WHERE DEPTID = I_DEPTID;
11 RETURN V_DEPTNAME;
12END GET_DEPTNAME; 13 /

Functioncreated.
SQL>

Figur e 14-6 Function with parameters.

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 /

Enter value for emp_id: 200Employee: 200


Department Name: Sales
PL/SQL procedure successfully completed. SQL>

Figure 14-7 Function call.


322 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

I n the next example, reusability of a function is explained. When a function is


compiled and stored, it can be called many times. Y ou write it once, but you can use
it many times. Figure 14-8 has a W H I L E loop in the anonymous block that calls the
function of Figure 14-9 eight times, for values of the counter (or D eptI d)

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 /

DEPTID SALARY COMMISSION


---------- ----------- -------------------
10 $375,000 $35,000
20 $146,500 $20,000
30 $69,500 $8,000
40 $150,000 $10,000
SUBTOTAL $741,000 $73,000
TOTAL OF SALARY AND COMMISSION: $814,000
PL/SQLprocedure successfullycompleted.SQL>

Figur e 14-8 Function call from a loop.


Packages 323

SQL> CREATE OR REPLACE FUNCTION DO_TOTAL


2 (I_AMOUNT IN NUMBER, I_TOTAL IN NUMBER)
3 RETURN NUMBER
4 IS
5 V_RESULT NUMBER(8) :=0;
6 BEGIN
7 V_RESULT:= I_TOTAL+I_AMOUNT;
8 RETURN V_RESULT;
9END DO_TOTAL; 10 /

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.

Calling a Function from an SQL Statement

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

A package is a collection of PL/SQL objects. The objects in a package are grouped


within B E GI N and E N D blocks. A package may contain objects from the following
list:

● 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.

SQL> CREATE OR REPLACE PACKAGE COURSE_INFO


2 AS
3 PROCEDURE FIND_TITLE
4 (I_IDIN COURSE.COURSEID%TYPE,
5 O_TITLEOUT COURSE.TITLE%TYPE);
6 FUNCTION HAS_PREREQ
7 (I_IDIN COURSE.COURSEID%TYPE)
8 RETURN BOOLEAN;
9 FUNCTION FIND_PREREQ
10 (I_IDIN COURSE.COURSEID%TYPE)
11 RETURN VARCHAR2;
12END COURSE_INFO; 13 /
Package created.SQL>

Figur e 14-10 Package specification.

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

A s a field is to a record, so an object is to a package. W hen you reference an


object in a package, you must qualify it with the name of that package using dot no-
tation. I f you do not use dot notation to reference an object, the compilation will
fail. Within the body of a package, you do not have to use dot notation for that pack-
age’s objects, but you definitely have to use dot notation to reference an object from
another package. For example,
IF bb_team.total_players < 10 THEN

For example,

EXCEPTION
WHEN bb_team.player_on_dl THEN

where and are modules/objects in the package.


There is a set of rules that you must follow in writing a package’s body:

● The variables, constants, exceptions, and so on declared in the specification


must not be declared again in the package body.
● The number of cursor and module definitions in the specification must
match the number of cursor and module headers in the body.
● A ny element declared in the specification can be referenced in the body.

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

SQL> CREATE OR REPLACE PACKAGE BODY COURSE_INFO AS


2 PROCEDURE FIND_TITLE
3 (I_ID IN COURSE.COURSEID%TYPE, O_TITLE OUT COURSE.TITLE%TYPE) IS
4 BEGIN
5 SELECT TITLE INTO O_TITLE FROM COURSE WHERE COURSEID = I_ID;
6 EXCEPTION
7 WHEN OTHERS THEN
8 DBMS_OUTPUT.PUT_LINE(I_ID||’not found.’);
9 END FIND_TITLE;
10 --------------------------------------------------------------------------------------------
11 FUNCTION HAS_PREREQ
12 (I_ID IN COURSE.COURSEID%TYPE) RETURN BOOLEAN IS
13 V_PREREQ VARCHAR2(6);
14 BEGIN
15 SELECT NVL(PREREQ, ’NONE’ ) INTO V_PREREQ
16 FROM COURSE WHERE COURSEID = I_ID;
17 IF V_PREREQ =’NONE’ THEN
18 DBMS_OUTPUT.PUT_LINE(’Noprerequisite’);
19 RETURN FALSE;
20 ELSERETURN TRUE;
21 END IF;
22 EXCEPTION
23 WHEN NO_DATA_FOUND THEN
24 DBMS_OUTPUT.PUT_LINE(’Course: ’||I_ID |’does not exist’);
25 RETURN FALSE;
26 END HAS_PREREQ;
27 --------------------------------------------------------------------------------------------
28 FUNCTION FIND_PREREQ
29 (I_ID IN COURSE.COURSEID%TYPE) RETURN VARCHAR2 IS
30 V_ID VARCHAR2(6);
31 V_TITLE VARCHAR2(25);
32 V_PRE VARCHAR2(30);
33 BEGIN
34 SELECT NVL(P.COURSEID, ’NONE’), NVL(P.TITLE, ’NONE’)
35 INTO V_ID, V_TITLE FROM COURSE C, COURSE P
36 WHERE C.PREREQ= P.COURSEIDAND C.COURSEID = I_ID;
37 V_PRE :=V_ID||’--’ |V_TITLE;
38 RETURNV_PRE;
39 EXCEPTION
40 WHEN OTHERS THEN RETURN ’NONE’;
41 END;
42END COURSE_INFO; 43 /
Package body created.

Figur e 14-11 Package body.


328 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

SQL> /* Anonymous block calls


DOC> procedure FIND_TITLE in package COURSE_INFO */ SQL> DECLARE
2 V_COURSEID COURSE.COURSEID%TYPE := ’&P_COURSEID’;
3 V_TITLECOURSE.TITLE%TYPE;
4 BEGIN
5 COURSE_INFO.FIND_TITLE(V_COURSEID, V_TITLE);
6 IFV_TITLE IS NOT NULLTHEN
7 DBMS_OUTPUT.PUT_LINE(V_COURSEID |’: ’||V_TITLE);
8 END IF;
9 END;
10 /
Enter value for p_courseid: CIS265 CIS265: Systems Analysis
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for p_courseid: CIS100 CIS100 not found.
PL/SQLprocedure successfullycompleted.SQL>

Figur e 14-12 Call to procedure in the package of Figure 14-11.

TRIGGERS

A database trigger , known simply as a tr igger, is a PL/SQL block. I t is stored in the


database and is called automatically when a triggering event occurs. A user cannot
call a trigger explicitly. The triggering event is based on a D ata Manipulation Lan-
guage (D M L ) statement, such as I NSERT, U PD A TE , or D E L E TE . A trigger can be
created to fire before or after the triggering event. For example, if you design a trig-
ger to execute after you I NSERT a new employee in the E MPL OY E E table, the
trigger executes after the INSE RT statement. The execution of a trigger is also
known as fir ing the trigger . The general syntax is
Triggers 329

SQL> /* Anonymous block calls function HAS_PREREQ


DOC> and function FIND_PREREQ in package COURSE_INFO */ SQL>
DECLARE
2 V_FLAG BOOLEAN;
3 V_COURSEID COURSE.COURSEID%TYPE := ’&P_COURSEID’;
4 V_TITLEVARCHAR2(30);
5 BEGIN
6 V_COURSEID := UPPER(V_COURSEID);
7 V_FLAG :=COURSE_INFO.HAS_PREREQ(V_COURSEID); IFV_FLAG =
8 TRUETHEN
9 V_TITLE :=COURSE_INFO.FIND_PREREQ(V_COURSEID);
10 DBMS_OUTPUT.PUT_LINE(’Course: ’||V_COURSEID);
11 DBMS_OUTPUT.PUT_LINE(’Pre-Requisite - ’||V_COURSEID); END IF;
12
13 END; 14 /
Enter value for p_courseid: CIS265 Course: CIS265
Pre-Requisite - CI5253
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for p_courseid: CIS253 No prerequisite
PL/SQLprocedure successfullycompleted.SQL> /
Enter value for p_courseid: CIS999 Course: CIS999 does not exist
PL/SQLprocedure successfullycompleted.SQL>

Figur e 14-13 Call to functions in the package of Figure 14-11.

where CR E A TE means you are creating a new trigger and R E PL A C E means


you are replacing an existing trigger. The key word R E PL A C E is optional, and
you should only use it to modify a trigger. If you use R E PL A CE and a procedure,
function, or package exists with the same name, the trigger replaces it. I f you cre-
ate a trigger for a table and then decide to modify it and associate it with another
table, you will get an error. I f a trigger already exists in one table, you cannot re-
place it and associate it with another table.
A trigger is very useful in generating values for derived columns, keeping
track of table access, preventing invalid entries, performing validity checks, or
330 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

maintaining security. There are some restrictions, however, involving creation of a


trigger:

• A trigger cannot use a Transaction Control Language statement, such as


COMMIT, ROLLBA CK, or SA VEPOI NT. A ll operations performed by a
trigger become part of the transaction. The trigger operations get committed
or rolled back with the transaction.
• A procedure or function called by a trigger cannot perform Transaction
Control L anguage statements.
• A variable in a trigger cannot be declared with L O N G or L O NG RAW data
types.

BEFORE Triggers

The B E FO R E trigger is fired before execution of a D M L statement. The BE F OR E


trigger is useful when you want to plug into some values in a new row, insert a cal-
culated column into a new row, or validate a value in the I NSERT query with a
lookup in another table.
Figure 14-14 is an example of a trigger that fires before a new row is inserted
into a table. If a new employee is being added to the E MPL OY E E table, you can use
a trigger to get the next employee number from the sequence, use SYSDA TE as the
employee’s hire date, and so on. The trigger in Figure 14- 14 fires before the I NSE RT
statement. The naming convention used in the example uses the table name the trig-
ger is for, followed by for “before insert, ” and then the word . A trigger usesa
pseudorecord called :NEW , which allows you to access the currently processed row.
The type of record :NEW is % TY PE. I n this example, the type of
:NEW is employee% TY PE. The columns in this :NEW record are referenced with
dot notation (e.g., :NEW.EmployeeI d).

SQL> CREATE OR REPLACE TRIGGER EMPLOYEE_BI_TRIGGER


2 BEFORE INSERT ON EMPLOYEE
3 FOR EACH ROW
4 DECLARE
5 V_EMPID EMPLOYEE.EMPLOYEEID%TYPE;
6 BEGIN
7 SELECTEMPLOYEE_EMPLOYEEID_SEQ.NEXTVAL
8 INTO V_EMPID FROM DUAL;
9 :NEW.EMPLOYEEID := V_EMPID;
10 :NEW.HIREDATE :=SYSDATE;
11 END;
12 /
Trigger created. SQL>

Figur e 14-14 B EFO R E trigger.


Triggers 331

The trigger provides values of E mployeeId and Hire-


Date, so you need not include those values in your INSERT statement. I f you have
many columns that can be assigned values via a trigger, your I NSERT statement will
be shortened considerably. I n Figure 14-15, a row is inserted in the E M PL OY E E
table without values for EmployeeId and H ireD ate columns. Those columns are
given value with firing of the B E FO R E trigger of Figure 14- 14.

SQL> INSERT INTO EMPLOYEE


2 (LNAME, FNAME, POSITIONID, SUPERVISOR, SALARY, DEPTID, QUALID)
3 VALUES
4 (’ZEE’, ’SONIA’, 3, 543,100000, 20,2);

1 row created.

SQL> SET LINESIZE 200


SQL> SELECT * FROM EMPLOYEE WHERE LNAME=’ZEE’;

EMPLOYEEID LNAME FNAME POSITIONID SUPERVISOR


--- -- --- --- - -- --- -- --- --- -- --- -- --- --- --- - -- --- -- --- --- -- --- --
546 ZEE SONIA 3 543

SQL>

Figur e 14-15 B EFO R E trigger— row inserted.

AFTER Triggers

A n A F TE R trigger fires after a D M L statement is executed. I t utilizes the built- in


Boolean functions I NSERTI NG, U PD ATING, and D E LE TI N G. I f the triggering
event is one of the three D M L statements, the function related to the D ML state-
ment returns TR U E and the other two return FALSE. For example, if the current
D M L statement is INSERT, then I NSE RTI N G returns TR U E , but D E L E TI N G
and U PD A TI N G return FA LSE.
The example in Figure 14- 16 uses an existing table named TRANSHISTORY,
which keeps track of transactions performed on a table. I t keeps track of updates and
deletions, the user who performs them, and the dates on which they are performed.
The trigger is named where stands for “after delete or up-
date.” The trigger uses the transaction type based on the last D M L statement. It also
plugs in the user name and today’s date. The information is then inserted in the
TRA NSHI STORY table. Figure 14-17 shows rows inserted in the TRA NSHISTORY
table on use of D E L E TE and U PD A TE statements by trigger.
For the example in Figure 14- 14, we used FO R E A C H ROW . Such a trigger is
known as a r ow tr igger . If it is based on INSERT, the trigger fires once for every
newly inserted row. If it is based on U PD A TE statement and the U PD A TE affects
five rows, the trigger is fired five times, once for each affected row. I n Figure 14- 16,
we did not use a FO R E A C H ROW , clause. Such a trigger is known as a statement
tr igger. A statement trigger is fired only once for the statement, irrespective of the
number of rows affected by the D ML statement.
332 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

SQL> CREATE OR REPLACETRIGGER EMPLOYEE_ADU_TRIGGER


2 AFTER DELETE OR UPDATE ON EMPLOYEE
3 DECLARE
4 V_TRANSTYPE VARCHAR2(6);
5 BEGIN
6 IF DELETING THEN
7 V_TRANSTYPE := ’DELETE’;
8 ELSIF UPDATING THEN
9 V_TRANSTYPE := ’UPDATE’;
10 END IF;
11 INSERT INTO TRANSHISTORY
12 VALUES (’EMPLOYEE’, V_TRANSTYPE, USER, SYSDATE);
13 END;
14 /

Trigger created.

SQL>

Figur e 14-16 AFTE R trigger.

SQL> DELETE FROM EMPLOYEE


2 WHERE UPPER(LNAME) = ’VIQUEZ’;

1 row deleted.

SQL> SELECT * FROM TRANSHISTORY;

TABLENAME TRANSTYPE USER_NAME TRAN_DATE


----------------- ----------------- ------------------ -----------------EMPLOYEE
DELETE NSHAH 05-DEC-03

SQL> UPDATE EMPLOYEE


2 SET COMMISSION = SALARY * 0.10
3 WHERE EMPLOYEEID = 547;
1 rows updated.

SQL> SELECT * FROM TRANSHISTORY;

TABLENAME TRANSTYPE USER_NAME TRAN_DATE


----------------- ----------------- ------------------ -----------------NSHAH
EMPLOYEE DELETE 05-DEC-03
EMPLOYEE UPDATE NSHAH 05-DEC-03
SQL>

Figur e 14-17 A FTE R trigger— in action.


Triggers 333

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> CREATE OR REPLACE VIEW STUDENT_FACULTY


2 AS
3 SELECT S.STUDENTID, S.LAST, S.FIRST, F.FACULTYID, F.NAME
4 FROM STUDENT S, FACULTY F
5 WHERE S.FACULTYID(+) = F.FACULTYID;
View created.

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>

Figur e 14-18 No data manipulation through complex view.

I n Figure 14-19, an I N STE A D O F D E L E TE trigger is created on the


STU D ENT_FACU LTY view. Now, when the D E L E T E statement is issued to
delete a faculty member with the complex view, the trigger is fired, and the faculty
334 Chap. 14 PL/SQL Named Blocks: Procedure, Function, Package, and Trigger

SQL> CREATE OR REPLACETRIGGER faculty_delete_iod


2 INSTEAD OF DELETE ON student_faculty
3 FOR EACH ROW
4 BEGIN
5 DELETE FROM faculty
6 WHERE FacultyId = :OLD.FacultyId;
7 END;
8 /

Trigger created.
SQL> DELETE FROM student_faculty WHERE FacultyId = 235; 1 row deleted.

SQL>

Figur e 14-19 Data manipulation and the INSTEAD O F Trigger.

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:

SELECT Object_Name, Procedure_Name FROM USER_PROCEDURES;


SELECT Trigger_Name, Trigger_Type, Triggering_Event, Table_Name, Trigger_Body FROM
USER_TRIGGERS;
SELECT Name, Type, Line, Text FROM USER_SOURCE; SELECT Object_Name, Object_Type FROM
USER_OBJECTS;
SELECT Name, Type, Sequence, Line, Position FROM USER_ERRORS;

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.

Answer the Following Questions:


1. Name three types of PL/SQL modules. Describe each module with one characteristic
specific to the module.
2. W hat are the differences between a procedure and a function?
3. Name three types of parameters. List the characteristics of each type.
4. How are actual parameters and formal parameters associated? Explain with an example.
5. W hat are the benefits of using a package? Describe two parts of a package and their
contents.
6. W hat is a trigger? Explain the working of B EF OR E and AF TE R triggers.
7. How are IN STEA D O F triggers different from B EF OR E and A F TER triggers?
8. W hat Data Dictionary tables/views are available to get information about named blocks?
Give information stored by those views/tables.

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 . . .

● A background overview of Java is given.


● Connection to the Oracle database through Java is covered.
● Steps to connect to Oracle with Sun’s JD B C driver are shown.
● Set up of OracleDriver for Java and use of Oracle’s thin client are outlined.
● Oracle’s SQLj is introduced.
● U se of SQLj iterators is shown.
● PL/SQL blocks are accessed through SQLj.
The purpose of this chapter is not to teach the Java language but to illustrate Java’s
ability to connect to the Oracle database with drivers provided by Sun and Oracle.
Java is a language for W eb- based applications, and it is an integral part of the Oracle9i
environment. With Oracle8i, the SQL statement C R E A TE JA VA was added for cre-
ating a Java source, class, or resource. Familiarity with Java is required for under-
standing terminology and code samples given here.
JDBC 339

JAVA: A PROGRAMMING LANGUAGE

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

JD B C is an Application Programming I nterface (A PI ) for database access in Java.


Using the JD B C 3.0 A PI , you can access virtually any data source, from relational
databases to spreadsheets to flat files. JD BC technology also provides a common
base on which tools and alternate interfaces can be built.
The JD B C 3.0 A PI is comprised of two packages:

1. The java.sql package.


2. The javax.sql package.

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

Sun’s sun.jdbc.odbc.JdbcOdbcD river and another with Oracle’s oracle.jdbc.driver.


OracleD river. There are five steps in creating a JD B C application:

1. I mport JD BC classes or packages with JD B C classes.


2. Load JD B C drivers.
3. Establish connection with the database.
4. Execute SQL statements/interact with the database.
5. Close connection.

Importing Package or JDBC classes

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.*;

Loading JDBC Drivers

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”);

Connecting to the Oracle Database

The class manages JD B C drivers. A fter a JD B C driver is loaded, the


classwide method of the D riverManager class is used for establish-
ing a connection to the database. The general syntax is
JDBC 341

For example, using Sun’s driver,

Connection conn =
DriverManager.getConnection(“jdbc:odbc:shah_ora”, userName, passWord);

where is the url suited for Sun’s jdbc.odbc.JdbcOdbcDriver. The url


contains data source name . D ata source is created with W indows operat- ing
system’s A dministrative Tool D ata Sources (O D B C) in the control panel. OD BC
(Open DataBase Connectivity) is a programming interface that enables applications to
access data in database-management systems that use SQL as a data access standard.
Username and password can be passed as string objects or hard-coded literals.
A nother example, using Oracle’s driver, would be

Connection conn = DriverManager.getConnection (“jdbc:oracle:thin:@nshah-monroe:1521:oracle”,”


nshah”,”india_usa”);

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.

Interacting with the Oracle Database

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:

1. Statement class for SQL statements without parameters.


2. PreparedStatement class for SQL statements with different parameters.
3. CallableStatement class for executing stored procedures.

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

a statement object is created with the Connection class’ instance method


. For example,

Statement stmt = conn.createStatement( );

Then, executeQuery( ) method is used with Statement object for a SE LE CT


query, and executeU pdate( ) method is used for an INSERT, D E L E TE , U PD A TE
or C R E A TE TA B L E statement. For example,

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 .

ResultSet Class. When is executed, the


data are retrieved into a ResultSet object. For example,

ResultSet rset =stmt.executeQuery(select_query);

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:

getString( ) Numeric position is used to get data from a column.


wasNull( ) Checks last column for a null value, and returns true or false
accordingly.
findColumn(column) R eturns the position of a column.

ResultSetMetaData Class. The ResultSetMetaD ata class is used to get


metadata information about ResultSet object . The ResultSetMetaD ata object
is created with the following statement:

ResultSetMetaData rsmeta = rset.getMetaData( );

This class provides the user with many methods to get metadata information.
For example,

getColumnCount( ) Returns the number of columns retrieved into result set.


getColumnLabel( ) R eturns the column title for dispay based on column
position parameter .
JDBC 343

getColumnName( ) R eturns the column name based on column position


parameter .
getColumnType( ) R etur ns the column’s data type based on position
parameter .
getColumnD isplaySize( ) Returns column’s size based on position parameter .
getTableName( ) Returns name of table based on column position parameter .
getPrecision( ) R eturns the number of digits to the left of decimal point.
getScale( ) R eturns the number of digits to the right of decimal point.

PreparedStatement Class. The PreparedStatement class is a derived class (or


subclass) of the Statement class. It allows execution of the same SQL statement many
times with different parameters. A n object of the PreparedStatement class iscreated
with the prepareStatement( ) method, where may contain
parameters. The statement is already compiled for faster execution. The pa- rameters
can be set with method like set ( ), where is the position of pa- rameter,
is a variable or literal, and is a data type like String, I nt, Float, and so on. For
example,

PreparedStatement pstmt = conn.prepareStatement(“INSERT INTO dept VALUES(?, ?)”);


pstmt.setInt(1, 99); // first parameter set to99
pstmt.setString(2,“Athletics”); // second parameter set to ‘Athletics’
pstmt.executeUpdate( );

A fter pstmt is built with set ( ) methods, the executeU pdate( ) method is used
to execute the SQL statement.

CallableStatement Class. The CallableStatement class is a subclass of the


PreparedStatement class. I t is used to execute PL/SQL anonymous or named
blocks. Its object is created with prepareCall( ) method. The I N parameters are set
with set ( ) method that was used earlier with the superclass PreparedState-
ment. The O U T parameters are set with registerOutParameter( , ),
where is the position and is the SQL type code defined in
java.sql.Types class. Once a callable statement is built with all parameter values or
type, it is executed. For example,

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.

SUN’S JDBC DRIVERAND THE ORACLE DATA SOURCE

Creating a Data Source in the Windows Control Panel

To make the program work with , you must have the


Oracle driver in Oracle’s home directory, such as OraHome92. The typical installation
of Oracle installs this driver.
First, from My Computer, run the W indows Control Panel. I n Control Panel,
double- click on the A dministrative Tools icon, and then on D ata Sources (O D B C)
to bring up the O D B C D ata Source A dministrator (see Fig. 15- 1). V isual FoxPro

Figur e 15-1 O DB C Data Source Administrator.


Sun’s JDBC Driver and the Oracle Data Source 345

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).

Figur e 15-2 Create New Data Source.

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.

Sample Java Code

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

Figur e 15-3 Oracle O DB C Driver Configuration.

Figur e 15-4 O DB C Data Source Administrator.


Sun’s JDBC Driver and the Oracle Data Source 347

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();
}
}

Figur e 15-5 Java source with data source.

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> SELECT * FROM phone;

LAST FIRST PHONE RELATION


-- -- -- -- -- -- -- -- - --- -- -- -- -- - -- -- -- --- -- - -- -- -- -- -- -
SHAH NAMAN 609.555.1111 SON
JOHNSON KIM 732.555.2222 FRIEND
SHAH DHIRAJ 222.386.3260 FATHER
MATTHEWS MICKEY 407.555.3333 FRIEND

SQL>

Figur e 15-6 Oracle table output.


348 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj

Figur e 15-7 Table output from Java.

ORACLEDRIVER AND ORACLE DRIVER

Setting Up oracle.jdbc.driver.OracleDriver for SDK1.4 or JBuilder8

The oracle.jdbc.driver.OracleDriver is set up as follows:

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

C: \OR A CL E \OR A 90 or C: \OR A C LE \O RA 92 for Oracle9i. For example,


it is C :\or acle\ora92 on my computer.
2. Search for the file under your Oracle home directory in
the JDBC\LI B directory. For example, the path on my computer is
c:\or acle\ora92\jdbc\lib\classes12.zip. Y ou may use the W indows file name
search for file path.
3. Now, go to the LI B directory under Java’s home directory on your com-
puter. Java’s home directory will be C:\J2SD K1.4.1_01 for Sun’s command-
line Java D evelopment K it or C:\JBU ILD ER8\JDK 1.4 for Borland’s
JBuilder I D E version 8. For example, the path to L I B folder on my com-
puter is c:\jbuilder8\j dk1.4\lib.
4. Copy the CLASSES12.ZIP file from the Oracle home to the Java home
directory. For example, for JBuilder8,

C:\> copy c:\oracle\ora92\jdbc\lib\classes12.zip c:\jbuilder8\jdk1.4\lib

For command- line Java,

C:\> copy c:\oracle\ora92\jdbc\lib\classes12.zip c:\j2sdk1.4.1_01\lib

5. If you are using command- line Java, set the following classpath to use
OracleD river from the CLA SSES12.ZIP file:

Set classpath= c:\j2sdk1.4.1_01\lib\classes12.zip;

If you are using JBuilder, follow the directions given here:

● I n JBuilder8 I D E , create your project, application, or applet.


● Before executing your program, right-click on your project name (
file) in the Project Pane on the top left.
● Select A dd files/packages Á from the pop- up menu.
● Select Or acleD r iver from the following folder path:

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.)

Sample Java Code

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.

package oracle; import java.sql.*; import java.io.*; public class Connect {


public static void main(String[] args) throws SQLException, IOException{
try {Class.forName(“oracle.jdbc.driver.OracleDriver”);
}
catch (ClassNotFoundException e) {System.out.println(“Could not load driver”);
}
String user, pass;
Connection conn = DriverManager.getConnection
(“jdbc:oracle:thin:@nshah-monroe:1521:oracle”,”nshah”,”india_usa”);
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();
}
}

Figur e 15-8 Java source with OracleDriver.


Java Applet: Putting it all Together 351

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.

JAVA APPLET: PUTTING ITALL TOGETHER*

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

Figure 15-9 JavaApplet in AppletViewer.

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

//Construct the applet public AppletData() {


}
//Initialize the applet public void init() {
try { jbInit();
}
catch(Exception e) { e.printStackTrace();
}
}
//Component initialization
private void jbInit() throws Exception {
jTextField1.setBackground(Color.white); jTextField1.setText(“”);
jTextField1.setBounds(new Rectangle(27, 42, 85, 20));
this.setLayout(null);
jTextField2.setBounds(new Rectangle(135, 41, 85, 20));
jTextField2.setText(“”);
jTextField3.setBounds(new Rectangle(28, 91, 85, 20));
jTextField3.setText(“”);
jTextField4.setBounds(new Rectangle(135, 90, 85, 20));
jTextField4.setText(“”);
jButton1.setBackground(SystemColor.activeCaption);
jButton1.setBounds(new Rectangle(238, 39, 136, 21));
jButton1.setFont(new java.awt.Font(“Dialog”, 1, 11));
jButton1.setText(“AddRow”); jButton1.addActionListener(
new AppletData_jButton1_actionAdapter(this));
jLabel1.setFont(new java.awt.Font(“Dialog”, 1, 11)); jLabel1.setText(
“Last”);
jLabel1.setBounds(newRectangle(54, 23,32, 17));
jLabel2.setBounds(newRectangle(162, 22, 33,17));
jLabel2.setFont(new java.awt.Font(“Dialog”, 1, 11)); jLabel2.setText(
“First”);
jLabel3.setBounds(newRectangle(48, 71,41, 17));
jLabel3.setFont(new java.awt.Font(“Dialog”, 1, 11)); jLabel3.setText(
“Phone”);
jLabel4.setBounds(newRectangle(157, 71, 56,17));
jLabel4.setFont(new java.awt.Font(“Dialog”, 1, 11)); jLabel4.setText(
“Relation”); jButton2.setBackground(SystemColor.activeCaption);
jButton2.setBounds(new Rectangle(238, 89, 136, 21));
jButton2.setFont(new java.awt.Font(“Dialog”, 1, 11));
jButton2.setText(“ClearTextOnly”); jButton2.addActionListener(
new AppletData_jButton2_actionAdapter(this));
354 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj

jButton3.setBackground(SystemColor.activeCaption); jButton3.setBounds(new Rectangle(28, 262, 132, 29));


jButton3.setFont(new java.awt.Font(“Dialog”, 1, 11)); jButton3.setText(“DisplayPhoneList”);
jButton3.addActionListener(
new AppletData_jButton3_actionAdapter(this)); jLabel5.setFont(new java.awt.Font(“Dialog”, 1,
24)); jLabel5.setText(“Phone List”);
jLabel5.setBounds(new Rectangle(244, 8,135, 27)); this.setBackground(Color.orange);
jTextArea1.setRequestFocusEnabled(false); jTextArea1.setColumns(50); jTextArea1.setTabSize(8);
jTextArea1.setBounds(new Rectangle(28, 117, 347, 134)); jButton5.addActionListener(
new AppletData_jButton5_actionAdapter(this)); jButton5.setText(“LastNameSearch”);
jButton5.addActionListener(
new AppletData_jButton5_actionAdapter(this)); jButton5.setFont(new java.awt.Font(“Dialog”, 1,
11));
jButton5.setBounds(new Rectangle(238, 64, 136, 21));
jButton5.setBackground(SystemColor.activeCaption); jPasswordField1.setEnabled(false); jPasswordField1.
setText(“india_usa”); jPasswordField1.setBounds(new Rectangle(291, 272, 70, 23));
jTextField5.setEnabled(false);
jTextField5.setText(“nshah”); jTextField5.setBounds(new Rectangle(207, 273, 70, 22));
jLabel6.setFont(new java.awt.Font(“Dialog”, 1, 14)); jLabel6.setText(“UserName”); jLabel6.setBounds(new
Rectangle(206, 254, 77, 18));
jLabel7.setFont(new java.awt.Font(“Dialog”, 1, 14)); jLabel7.setText(“PassWord”); jLabel7.setBounds(new
Rectangle(291, 255, 74, 15)); this.add(jTextField1, null);
this.add(jTextField2, null); this.add(jTextField3, null); this.add(jTextField4, null); this.add(jButton1, null);
this.add(jTextArea1, null); this.add(jButton2, null); this.add(jButton4, null); this.add(jButton5, null);
this.add(jLabel5, null); this.add(jLabel1, null); this.add(jLabel3, null); this.add(jLabel2, null); this.add(jLabel4,
null);
Java Applet: Putting it all Together 355

this.add(jLabel6, null); this.add(jTextField5, null); this.add(jLabel7, null); this.add(jPasswordField1, null);


this.add(jButton3, null);
}
//Get Applet information public String getAppletInfo() {
return“Applet Information”;
}
//Get parameter info
public String[][] getParameterInfo() { returnnull;
}
/* ** *** *** *** ** *** *** * ADDS a ROW **** **** ***** **** ***** / void
jButton1_actionPerformed(ActionEvent e) throws Exception{
// user canbe promptedto input username andpassword,
// but commented out here
/* String userName, passWord; userName =
JOptionPane.showInputDialog(“Oracle username: “).trim(); passWord =
JOptionPane.showInputDialog(“Oracle password: “).trim(); */ 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(),
jPasswordField1.getText());PreparedStatement pstmt =conn.prepareStatement(
“INSERT INTO phone VALUES(?,?,?,?)”); //statement with 4 parameters String one = jTextField1.getText();
String two = jTextField2.getText(); String three =jTextField3.getText(); String four = jTextField4.getText(); if
(one.equals(“”)||two.equals(“”)
|three.equals(“”)| four.equals(“”))
{
JOptionPane.showMessageDialog
(null, “One or more fields are left blank”,”Error”,JOptionPane.ERROR_MESSAGE);
}

else{ // 4 parameters set here


pstmt.setString(1, one);
pstmt.setString(2, two);
356 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj

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

FROM phone ORDER BY Last, first “); // all rows retrieved


String s=””;
while (rset.next()) {
s+=(rset.getString(1)+”\t\t”+rset.getString(2)+ “\t”
+rset.getString(3)+”\t”+rset.getString(4)+”\n”);
}
jTextArea1.setText(s); stmt. // rows displayed inJTextArea object
close();
conn.close();
}
/* *** **** *** *** SEARCHES TABLE BASED ON LAST NAME ****** ****** **/ void
jButton5_actionPerformed(ActionEvent e) throws SQLException{
jTextArea1.setText(“”); try{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch (ClassNotFoundException ex) { System.out.println(“Could not load driver”);
}
Java Applet: Putting it all Together 357

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

class AppletData_jButton3_actionAdapter implements java.awt.event.ActionListener


{
AppletData adaptee;
AppletData_jButton3_actionAdapter(AppletData adaptee) throws Exception { this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) { try{
adaptee.jButton3_actionPerformed(e);
}
catch (Exceptionex){ System.out.println(“Error”);
}
}
}

class AppletData_jButton5_actionAdapter implements java.awt.event.ActionListener


{
AppletData adaptee;
AppletData_jButton5_actionAdapter(AppletData adaptee) throws Exception{ this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) { try{
adaptee.jButton5_actionPerformed(e);
}
catch(Exceptionex){ System.out.println(“Error”);
}
}

SQLj

A n alternative to JD BC, SQL j is Oracle’s implementation of the A NSI SQL- 1999


Part- 0 “ E mbedded SQL in Java,” which specifies the integration of SQL statements
in Java programs. Oracle SQLj is more concise and easier to write than JD BC, and it
provides compile-time schema validation and syntax checking for easier debugging.
With SQLj, SQL statements can be embedded directly in a Java program. Y ou
need to configure your Java environment by adding JA Rs; ,
and . I f you remember, classes12.jar (from the CLA SSES12.ZIP file) was
used during the set up of JDBC. You also need the SQLj executable, . SQLj is
an attractive alternative, because it can perform syntax checking of SQL statements
at translation time. The SQLj translator translates a Java program ( ) with SQL
statements into Java code ( ), which can be executed through the JD B C driver.
SQLj code is more compact than its JD B C counterpart.
SQLj 359

Configuring Oracle SQLj in JBuilder8

To configure Oracle SQLj in JBuilder 8, do the following:

1. I n JBuilder8, choose Tools ƒ configure L ibraries ƒNew Á ƒ Type “ SQL j”


for ‘Name:’ field ƒ keep entry “ U ser H ome” for ‘L ocation’ field ƒA dd Á ƒ
select two files, r untime12.jar and translator.jar , from the Oracl e directory
C :\ORA C L E\ORA 92\SQ LJ\L I B.
2. I n JB uilder8, choose Tools ƒ configure L ibraries ƒNew Á ƒ Type “ Oracle
D ri ver” for ‘Name:’ field ƒ keep entry “ U ser Home” for ‘Locati on’ field ƒ
A dd Á ƒ select classes12.jar from the Oracle directory C :\O RA C L E
\ORA 92\JD BC\LIB.
3. I n JBuilder8, choose Tools ƒ Enterpri se Setup ƒ SQL j ƒ Oracle ƒ click on
the Á (ellipses) button for SQL j executable ƒ select sqlj .exe file from
C :\ORA C LE \O RA 92\BI N\.
4. I n Jbuilder8, choose Tools ƒ Enterpri se Setup ƒ SQL j ƒ Oracle ƒ A dd SQL j
library from Step 1 to the ‘L i brary’ list box, and click on OK .

Creating an SQLj Project

To create an SQL j project, do the following:

1. I n JBuilder8, File ƒ New Project ƒ name your project “sqljone” ƒ Finish.


2. Right click on the file in project pane, and select ‘Add
files/Packages’. Type “TestSQLj.sqlj” for file name, and select file type as
SQL J ( ) file. Y ou will see a dialog box with message “The selected file
does not exist. D o you wish to create it?” Click on OK to create it.
3. I n the project pane, double-click on the file to open it up in
the editor. Type the code from Figure 15-10 in the editor. Y ou can substitute
names for username, password, and so on.
4. File ƒ SaveA ll.
5. Select Project ƒ Project Properties ƒ Paths ƒ R equir ed Li braries ƒ A dd
“ SQL j” library.
6. Select Project ƒ Project Properties ƒ Paths ƒ R equir ed Li braries ƒ A dd
“ Oracl e D river” library.
7. Select Project ƒ Project Properties ƒ Build ƒ General ƒ SQL j Traslator ƒ select
“ Oracl e” from the combo box.
8. I n the project pane, right- click on , and select Make. The
process will produce a Java ( ) file and invoke the Java compiler to
produce a bytecode ( ) file.
9. Right click on the file, and select R un U sing D efaults. You
will see the output.
360 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj

import oracle.sqlj.runtime.*; import sqlj.runtime.*; import


sqlj.runtime.ref.*; import java.io.*;
import java.sql.*; public class TestSQLj2{
public static void main(String []args) { try{
Oracle.connect (“jdbc:Oracle:thin:@localhost:1521:oracle”,
“nshah”, “india_usa”, true);
String dname = “”;int num= 10;
#sql {SELECT DeptName into :dname FROM dept WHERE
DeptId = :num};
System.out.println(“Deptname is “+dname);
}
catch(SQLExceptione) {e.printStackTrace();
}
finally {
try { Oracle.close(); }
catch(SQLException e) { e.printStackTrace(); }
}
}
}

Figure 15-10 SQLj program.

The program in Fig. 15- 10 illustrates statements involved in writing an SQLj


program:

• I mport classes. The package is imported for JD B C classes,


and packages for SQLj runtime classes, and the
package for Oracle class.
• C onnect to the database. Connection to the Oracle database is achieved with
the Oracle.connect( ) method. The method takes four parameters; url, user-
name, password, and autocommit mode. The autocommit mode could be true
or false. I f false is used, the programmer has to commit SQL statements. If you
are using any database other than Oracle, you would use DriverManager.-
registerD river( ), but this is not needed for Oracle database.
• E mbed SQ L statements. The SQL statements are embedded with
# 5 _ 6, where tells the SQLj translator that the SQL
statement follows. The statements may include host variables with a colon (:)
prefix (as seen in PL/SQL section), which are declared in the Java program.
SQLj Iterators 361

For example, string variable is declared in Java and used as in


an SQL statement as a host variable, and Java variable is used as
as shown Figure 15-10.

HOSTVARIABLES

A host variable is used with a colon (:) prefix followed by I N, O U T or I N OU T de-


pending on if it is for input, output, or both, respectively. Remember them from
PL/SQL? The default is IN for host variables, except for the I N TO clause of SELECT
statement. W e can rewrite the SQL statement in Figure 15-10 as
#sql {SELECT deptName INTO :OUT dname FROM phone WHERE DeptId = :IN num};

where and are declared in the Java program.


You need to choose data types carefully while using Java variables in SQL . Or-
acle’s C H A R and V A RC H A R 2 types correspond to string in Java. Oracle’s D A TE
type corresponds to java.sql.D ate class. Oracle’s NU M BE R type corresponds to
Java’s int, long, float, and double. A C U RSOR in Oracle is ResultSet in Java. A ny
valid Java expression can be used as a host expression in an SQL statement.

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:

1. Named Iterator: D ata types and column names are specified.


2. Positional Iterator: Only data types are specified.

Named Iterator

The general syntax for declaring a named iterator is

I n Figure 15-11, a named iterator is used. The following statement declares a


named iterator
#sql iterator DeptIter(int i, String n,String l);

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

import oracle.sqlj.runtime.*; import sqlj.runtime.*; import sqlj.runtime.ref.*;


import java.io.*;
import java.sql.*; public class TestSQLj3{
public static void main(String []args) {
#sql iterator DeptIter(int i,String n, String l); try {
Oracle.connect (“jdbc:Oracle:thin:@localhost:1521:oracle”,
“nshah”, “india_usa”, true); DeptIter di =null;
#sql di =
{SELECT deptid i, deptname n, location l FROM dept}; while
(di.next( )) {
System.out.println(di.i( )+”\t”+di.n( )+”\t\t”+di.l( ));
}
di.close( );
}
catch(SQLExceptione) { System.out.println(e.getMessage( ));
}
finally {
try {Oracle.close( ); }
catch(SQLException e) { e.printStackTrace( ); }
}
}
}

Figur e 15-11 SQLj named iterator.

which is populated with a SE L E C T query. I t is important to use column aliases for


columns retrieved, and the column aliases must be same as the column names in the
iterator:
DeptIter di = null;
#sql di={SELECTdeptid i,deptname n,locationl FROM dept};

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);

import oracle.sqlj.runtime.*; import sqlj.runtime.*; import sqlj.runtime.ref.*;


import java.io.*;
import java.sql.*; public class TestSQLj4 {
public static void main(String []args) {
#sql iterator DeptIter(int,String, String); int i=0;
String n=null; String loc=null; try {
Oracle.connect (“jdbc:Oracle:thin:@localhost:1521:oracle”,
“nshah”, “india_usa”, true); DeptIter di =null;
#sql di ={SELECT deptid,deptname, locationFROM dept}; #sql {fetch:
di into :i, :n,:loc};
while (!di.endFetch()) {System.out.println(i+”\t”+n+”\t\t”+loc);#sql
{fetch:di into :i,:n, :loc};
}
di.close();
}
catch(SQLExceptione) { System.out.println(e.getMessage());
}
finally {
try { Oracle.close(); }
catch(SQLException e) { e.printStackTrace(); }
}
}
}

Figur e 15-12 SQLj positional iterator.


364 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj

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};
}

Finally, the iterator is closed when the processing is done:

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

#sql { anonymous block statements };

The general syntax of PL/SQL procedure call is

#sql {CALL procedurename [ (parameterlist) ]};

The general syntax of PL/SQL function call is

variablename = #sql { VALUES (functionname (parameterlist)) };


In a Nutshell .. . 365

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.

import oracle.sqlj.runtime.*; import sqlj.runtime.*; import sqlj.runtime.ref.*; import


java.io.*;
import java.sql.*; import javax.swing.*; public class TestSQLj4 {
public static void main(String []args) { try {
Oracle.connect (“jdbc:Oracle:thin:@localhost:1521:oracle”,
“nshah”, “india_usa”, true);
String cid=JOptionPane.showInputDialog(“Enter Course Id:”); String title;
String preReq;
#sql {CALL course_info.find_title(:in cid, :out title)};
#sql preReq = {VALUES(course_info.find_prereq(:in cid))};
System.out.println(cid+”-”+title+” — > PreReq: “+preReq);
}
catch(SQLExceptione) { System.out.println(e.getMessage());
}
finally {
try { Oracle.close(); }
catch(SQLException e) { e.printStackTrace(); }
}
}
}

Figure 15-13 SQLj calls to PL/SQL named blocks.

IN A NUTSHELL . . .

● Java is a portable programming language with a broad set of predefined classes


and methods that handle most fundamental requirements of programmer.
● JD B C is an A PI (A pplication Programming Interface) for database access
in Java.
366 Chap. 15 Oracle with Java: A Tutorial on JDBC and SQLj

● There are five steps in creating a JD B C application: I mpor t JD BC classes or


package with JD B C classes, load the JD B C drivers, establish the connection
with the database, execute SQL statements/interact with the database, and
close the connection.
● JD B C uses a variety of classes for interaction with the Oracle database: State-
ment, ResultSet, ResultSetMetaD ata, PreparedStatement, and Callable-
Statement.
● To mak e program work with , you must have
Oracle driver in OraHome92 (Oracle Home).
● A n Oracle- supplied JD B C driver is used with Oracle thin driver for con-
necting to the Oracle database with Java.
● SQLj is an alternative to JD BC. With SQLj, SQL statements can be embedded
directly in a Java program.
● SQLj translator translates a Java program ( ) with SQL statements into
Java code ( ), which can be executed through the JD B C driver.
● A n SQLj program includes importing of classes, connecting to the database,
and embedding of SQL statements.
● In an SQLj program, a host variable is used with a colon (:) prefix followed by
IN, OU T, or I N OU T depending on if it is for input, output, or both, respectively.
● When an SQL query returns more than one row in Java program, an SQLj
iterator is used. A n interator is similar to a JD B C result set, but columns are
given data types in an iterator.
● There are two types iterator declarations: named iterator, in which data
types and column names are specified; and positional iterator, in which only
data types are specified.
● SQLj can embed SQL statements with #sql. SQLj can also embed an entire
anonymous block with #sql. SQLj can call PL/SQL stored procedures and
functions as well.

EXERCISE QUESTI ONS

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

7. CallableStatement class allows a call to PL /SQL blocks.


8. SQL statements are embedded directly into the Java program with SQL j.
9. Host variables are used in an SQL j program as IN parameters only.
10. Two types of SQL j iterators are named and anonymous iterators.

Answer the Following Questions:


1. Compare the features of JDB C and SQLj.
2. State and briefly explain the steps in creating a JD BC application.
3. W hat is the difference in use of the JDB C drivers provided by Sun and Oracle?
4. W hich Oracle-provided files are necessary for creating an SQLj project with any Java en-
vironment?
5. Describe the use of iterators in SQLj projects.

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 . . .

● The functions of a D atabase Administrator (D B A ) are listed.


● D ifferent aspects of Oracle’s architecture are explained.
● Y ou will learn about Oracle database administration with Oracle Enterprise
Manager ( OEM ).
● Oracle security, users, roles, and system privileges are covered.
● Oracle D ata Dictionary views and their types are listed.

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 ADMINISTRATOR (DBA)

The D BA is responsible for installing the Oracle database, managing day-to-day


needs of the complex database, and running the system at peak performance. A
D BA performs software maintenance, resource management, data administration,
Oracle Architecture: An Overview 369

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.

ORACLE ARCHITECTURE: AN OVERVIEW

Figure 16- 1 presents an overview of Oracle architecture. Oracle architecture con-


tains three major areas:
1. System Global A r ea (SG A ) or memory structure.
2. Background processes.
3. Physical storage structure.
The System Global Ar ea (SG A ) is a memory area used, for example, to store
information that is shared by database and user processes. The SG A consists of a
database buffer cache, a shared pool, a Java pool, and redo log buffers. I n Oracle8i,
the Java pool was used only if Java was used, but it is required in Oracle9i. The data-
base buffer cache contains actual data from the database. The user transactions are
first stored in the buffer and then written to the disk. The shared pool contains the
executed SQL and PL/SQL statements for reuse of the information. The shared pool
keeps parsed statements based on a “least recently used” algorithm. The redo log
buffers store the redo entries for the online redo logs before writing them to the disk.
The back gr ound pr ocesses run simultaneously and independently of each other.
These processes work on databases, and there can be a number of such processes
370 Chap. 16 Oracle9i: Architecture and Administration

Database
Buffer Cache R edo Log Buffer Shared Pool

SGA

Database System Process Checkpoint


Server Log Writer Archiver
Writer Monitor Monitor Process
Process (LGW R ) ( AR CH )
(DB W R) (SMON) (PMON) (CKPT)

User Offline
Process Redo Log Filel Storage
Redo Log File2

Rollback
Data Segment Control
Segment Files

Figure 16-1 Oracle Architecture.

depending on the configuration of the Oracle initialization file (INIT.ORA ). Some of


the background processes are dedicated server processes, database writer (D B W R),
system monitor (SMON), process monitor (PMON ), log writer (L GW R ), archiver
(A RC H) , and checkpoint process (CKPT).
SMON process performs all housekeeping tasks. A system process is created
for each user process to handle its requests. I t performs instance recovery, rolls for-
ward or back as needed for recovery, clears temporary segments that are not
needed, coelesces free spaces into a large area of free space, and “listens” to user
processes. The user writes to the database buffer cache, and D B W R takes data from
the buffer cache in SGA and writes to the database. D B W R is the only process that
can write to the database. All updates are performed in the buffer cache, and not on
the database files. PM O N monitors all processes, checks for failed processes, and
terminates them properly. I t also releases resources used by failed processes.
L GW R writes the SGA redo log buffer’s contents to the redo log files. Each instance
contains its own LG W R . The redo log buffer holds data images before and after
changes. R edo log files contain data as well as rollback information. L G W R writes
the redo log buffer’s contents to redo log files when the COMMIT command is issued,
Oracle Architecture: An Overview 371

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

SQL> SELECT PADDR, NAME, DESCRIPTION


2 FROM V$BGPROCESS;

PADDR NAME DESCRIPTION


- --- --- - -- --- - - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
681E46BC PMON process cleanup
00 DIAG diagnosibility process
00 FMON File Mapping Monitor Process
00 LMON global enqueue service monitor
00 LMD0 global enqueue service daemon 0
00 LMS0 global cache service process 0
00 LMS1 global cache service process 1
00 LMS2 global cache service process 2
00 LMS3 global cache service process 3
00 LMS4 global cache service process 4
00 LMS5 global cache service process 5
...

00 DMON DG Broker Monitor Process


00 RSM0 DR Resource Manager Process
00 NSV0 DR Server NetSlave Process 0

69 rows selected.

SQL>

Figure 16-2 Oracle background processes.

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

A n Oracle instance is defined as O R A C L E _SI D or OR A _SI D . I n most cases, data-


base and instance have one-to-one relationship, but in Oracle9i, the database can
be mounted by one or more instances. The data are available only when the data-
base is open.
You also must select the database name and its instance name. The initialization
file has a name with I NIT as a prefix to the instance name with extension ORA . For ex-
ample, if the instance name is ORCL, then the initialization file is INITORCL.ORA.
The database name is specified in the I NI T.OR A file in the D B _N A M E parameter.
The I N I T.O RA file is in the DBS directory of the OR A CL E _H OME .
The instance contains four types of files:

1. The par ameter file I NI T.OR A is read when an instance is opened.


2. The contr ol files are read when the database is mounted.
3. The data files are read when the database is opened.
4. The changes to a database are logged in the r edo log files.

Oracle uses many different logical database structures. A tablespace is the


basic storage allocation to a database. During Oracle’s installation, many table-
spaces with minimal capacity are created. Every database has a SY STEM table-
space, and it also has other tablespaces, such as a TE M PO R A R Y tablespace. The
tablespaces are operating system files with the . OR A extension. The D B A creates
tablespaces for databases according to the need, and a user-supplied name may con-
tain other extensions, such as .D A T or .DBF.
A user account is called a schema. E ach object is stored under its owner’s
schema, which is referenced with a username. A n Oracle database is created with
two schemas: SY S to store the D ata D ictionary, and SY STEM to store more D ata
Dictionary information and tables for Oracle tools.
E ach object is stored as one or more segments. A segment resides in only one
tablespace. A tablespace may contain many segments, however, and a segment may
contain many extents. A n extent may contain many block s. The block size is defined
in the D B _BL O CK _ SI ZE parameter. W henever a user updates a table, the old
value is written to the r ollback segment for read consistency. This also allows a user
to roll back updates without committing them. Oracle uses tempor ary segments
during table creation and joins.
Other database structures are tables to store user data and the D ata D ictio-
nary and the index for fast search operation from the table.
The Oracle Relational DataBase Management System (RD BM S) is sold as a
base product in the Enterprise version. I t also comes with other options, data car-
tridges, development tools, and Enterprise applications. The available licensing op-
tions are concurrent user license, named user license, and site license.
The ver sion number normally has four numbers (e.g., 9.2.0.1). The first num-
ber is the major release number. The second number is the minor release number.
The third number is the code release number, and the fourth number is the patch
number for the code number.
Oracle Architecture: An Overview 373

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

performs name resolution without using TNSNA M E S.O RA . A n Oracle Names


server can integrate with other name- resolution services, such as the Novell Net-
ware D irectory service (NDS).
Oracle can connect to databases created under different vendors’ software,
ranging from Microsoft’s PC-database A ccess to Microsoft’s SQL- Server. Mi-
crosoft’s O pen D atabase Connectivity (O D B C) driver running on a client enables
the client to connect to a server running SQL*Net. The client need not run
SQL *Net, because the OD B C driver emulates it. Oracle also utilizes gateway prod-
ucts to connect to non-Oracle database hosts. The gateway translates Oracle SQL
queries to a non-Oracle host’s native SQL and returns data to the Oracle server. A n
Oracle gateway is available from the server with a database link, but it is not avail-
able from a client.

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:

● I nstalls Oracle software components.


● Creates a starter database.
● E xecutes operating system functions to run Oracle.

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.

CONNECTING TO THE ORACLE9i DATABASE

Oracle9i provides user with different ways to connect to the database:

● SQL* Plus (may go away in the future).


● SQL* Plus W orksheet.
● iSQL*Plus (Web-based).
● Form.
● Reports.

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

Start |Programs |Oracle – OraHome92 |Enterprise Manager Console

Then, launch it stand- alone (as seen in Figure 16- 3).

Figur e 16-3 Oracle Enterprise manager console— launching stand-alone.


376 Chap. 16 Oracle9i: Architecture and Administration

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.

Figure 16-4 Oracle Enterprise manager login screen.

On successful login to the Console, the initial O E M screen is displayed. Here,


the D B A can manage Oracle modules, such as Instance, Schema, Security, Storage,
and so on (as shown in Figure 16-5).
Instance and Database 377

Figur e 16-5 Oracle Enterprise Manager initial screen.

INSTANCE AND DATABASE

A n instance is used to access the database. Y ou can perform two operations on an


instance: STARTU P, and SHU TD OW N. When an instance starts, memory is allocat-
ed for SGA , and background processes are started. W hen an instance shuts down,
the database is closed, and memory is released. D atabase is another entity, and you
can perform three operations on it: OPEN, MOUNT, and C LO SED . A database
state is changed in one direction only, from M OU NT to OPEN, when an instance is
started. The operations can be performed with OEM’s I nstance Manager,
SQL* Plus, or SQL*Plus W orksheet. The general syntax for startup is

where FO R CE shuts down instance before starting it up, N OM OU NT starts an in-


stance without mounting a database, M OU NT mounts a database for D B A opera-
tions only, OPE N makes a database available to users, and R E STR I CT restricts
access to users with SESSI ON-related privileges. PFI L E contains parameters for
startup. If it is not specified, parameters are taken from I NI T< Oracle_sid>.ORA file.
378 Chap. 16 Oracle9i: Architecture and Administration

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.

WORKING WITH ORACLE ENTERPRISE MANAGER (OEM)

Tablespace with Storage Manager

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:

CREATE [UNDO |TEMPORARY |PERMANENT] TABLESPACE tablespacename

A temporary tablespace is for keeping temporary sort data, which is created in


the same way but with type Temporary selected (radio button shown in Fig. 16- 6).
The storage clause is similar to the one used with tables. If the storage clause is not
used with a table, then the storage clause from tablespace is used for it.
Working with Oracle Enterprise Manager (OEM) 379

Figur e 16-6 Creating a tablespace.


380 Chap. 16 Oracle9i: Architecture and Administration

Figur e 16-7 Tablespace created with information on all tablespaces.

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).

User and Role with Security Manager

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

A D B A or anyone with the C RE A TE U SE R system privilege can create a


user. I f the default tablespace is not specified, D E FA U L T TABLESPA CE is used.
Working with Oracle Enterprise Manager (OEM) 381

SQL> SELECT TABLESPACE_NAME, INITIAL_EXTENT, NEXT_EXTENT,


2 BLOCK_SIZE FROM USER_TABLESPACES;

TABLESPACE_NAME INITIAL_EXTENT NEXT_EXTENT BLOCK_SIZE


-- --- --- --- ---- --- --- --- ---- - - --- ---- --- -- -- --- --- --- --- --- --- -
SYSTEM 65536 8192
UNDOTBS1 65536 8192
TEMP 1048576 1048576 8192
CWMLITE 65536 8192
DRSYS 65536 8192
EXAMPLE 65536 8192
INDX 65536 8192
ODM 65536 8192
TOOLS 65536 8192
USERS 65536 8192
XDB 65536 8192
TABLESPACE_NAME INITIAL_EXTENT NEXT_EXTENT BLOCK_SIZE
-- --- --- --- ---- --- --- --- ---- - - --- ---- --- -- -- --- --- --- --- --- --- -
CIS_DATA 65536 8192
TEMP_DATA 1048576 8192
13 rows selected.
SQL>

Figur e 16-8 Tablespaces storage information.

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

Figur e 16-9 Creating a user.

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

Figur e 16-10 Creating a user with Create Like Á

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

Figur e 16-11 Creating a role.


386 Chap. 16 Oracle9i: Architecture and Administration

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:

System Privilege Type of Action


CREATE Create an object in a user’s own schema.
CREATEANY Create an object in another user’s schema.
CREATESESSION Connect to database.
DROP Drop an object in a user’s own schema.
DROP ANY Drop an object in another user’s schema.
ALTER SYSTEM Manipulate an instance.
ALTER DATABASE Manipulate database.
ALTER USER Change a user’s role or password.
ALTERƒCREATEƒDROPƒMANAGE TABLESPACE Manipulate a tablespace.

Figur e 16-12 System privileges and actions.

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

If W I TH A D MI N OPTI ON is used, the user can pass on that privilege to an-


other user. D ata Dictionary view DBA _SYS_PRIV S can show privileges granted to
a user/role (see Fig. 16- 13). The query in Figure 16- 13 returned 139 privileges granted
to the D B A role. Y ou can also find out the same information from O E M Security
Manager.

SQL> SELECT grantee, privilege, admin_option


2 FROM dba_sys_privs
3 WHERE grantee = ’DBA’;

GRANTEE PRIVILEGE ADM


--- --- --- -- --- --- -- --- --DBA -- -- --- -- -- --- -- --- -- --- - - - -
DBA DBA DBA DBA DBA DBA DBA AUDIT ANY YES
DBADBADBA DROP USER YES
. . . RESUMABLE YES
139 rows selected. ALTER USER YES
ANALYZE ANY YES
SQL>
BECOME USER YES
CREATEROLE YES
CREATERULE YES
CREATETYPE YES
CREATEUSER YES
CREATEVIEW YES

Figur e 16-13 DBA_SY S_PRIVS.

ORACLE DATA DICTIONARY

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:

● — These views are for information on database


objects, database data files, and database users. The views begin with
U SE R_< objects_you_own>, A LL_<objects_you_have_access_to>, DBA_
< all_objects>— for example, D BA _ CONSTR A I NTS, D BA_CONS_
C OL U M NS, D I C TI ONA RY , D B A _ I ND EX E S, U SE R_TA BL E S, A LL _
TR I GG E RS, D BA_ROL ES, D B A _PR OFI L ES, DBA _SY S_PRI VS, D BA _
U SE RS, D BA _TA BL ESPACES, DBA _V IE WS, and so on.
● — These views are for informa-
tion on instance objects, archive log files, and currently connected users— for
example, V $SESSION, V $PROCE SS, V $TABLESPA CE, V $SQL, V$SGA ,
and so on.

IN A NUTSHELL . . .

● The D B A is responsible for installing the Oracle database, managing daily


operations, and running the database at peak performance.
● The Oracle database is the data stored on disk, and the Oracle instance is
the System Global A rea (SGA ) memory and background processes.
● A n instance contains four types of files: the parameter file INST.ORA , con-
trol files, data files, and redo log files.
● A tablespace is the basic storage allocation to a database.
● A user account or username is called a schema. A n Oracle database is creat- ed
with two schemas, SYS and SY STEM.
● Oracle uses three configurations for availability to users: replication, hot
standby, and Oracle parallel server.
● Oracle provides good backup mechanisms in the forms of EXP/IMP, cold
backup, archive log files, and hot backup.
● The installation process installs Oracle components, creates a starter data-
base, and executes operating system functions to run Oracle.
● Oracle networking connects clients to a database and a database to another
database. Connections in Oracle are through services. The TNSNA MES.ORA file
contains relations between a service and an instance.
● Oracle can connect to other vendor-supplied databases by using O D B C
drivers and gateway products.
ExerciseQuestions 389

● 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.

Answer the F ollowing Questions:


1. What is the difference among users, roles, and system privileges?
2. What are the duties of a DBA?
3. How does Oracle9i make sure that the database is available to users at all times?
4. Explain the backup mechanisms used by Oracle9i.
5. Discuss three types of Oracle system privileges.
6. Describe Oracle9i architecture.
7. Describe Oracle’s Data Dictionary.
This textbook utilizes two sample databases thoughout its chapters. I n this section, the table
structures are described. The primary key columns are underlined. I t is always a good idea to
have primary key columns with the N U M B E R data type, but other data types are also used
here for primary key columns (e.g., the primary key column in the TE R M table. A ll columns,
their appropriate data types, and constraints are given. However, some of the columns,
though not used for any mathematical operations, are assigned the N U MB E R data type for
simplicity. They can also be assigned one of the character data types, C HA R or V ARCHA R2.
Students may modify the table structures as desired.

THE INDO–US (IU) COLLEGE STUDENT DATABASE

STUDENT

Column Name Data Type Constraints

StudentId CHAR(5) PRI MAR Y KEY

Last VARCHAR2(15) NOT NULL


First VARCHAR2(15) NOT NULL
Street VARCHAR2(25)
City VARCHAR2(15)
The Indo–US (IU) College Student Database 391

Column Name Data Type Constraints

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

Column Name Data Type Constraints

FacultyId NUMBER(3) PR IMAR Y KEY


Name VARCHAR2(15) NOT NULL
RoomId NUMBER(2) FO RE IG N KEY
Phone CHAR(3) U NIQ UE
DeptId NUMBER(1) FO RE IG N KEY

CRSSECTION

Column Name Data Type Constraints

CsId NUMBER(4) PRI MAR Y KEY


CourseId VARCHAR2(6) FOR E IG N KEY , NOT NULL
Section CHAR(2) NOT NULL
TermId CHAR(4) FOR E IG N KEY , NOT NULL
FacultyId NUMBER(3) FOR E IG N KEY
Day VARCHAR2(2)
StartTime VARCHAR2(5)
EndTime VARCHAR2(5)
RoomId NUMBER(2) FOR E IG N KEY
MaxCount NUMBER(2) CHECK
392 App. A Sample Databases: Table Definitions

COURSE

Column Name Data Type Constraints

CourseId VARCHAR2(6) PR IMAR Y KEY

Title VARCHAR2(20) U NIQ UE


Credits NUMBER(1) CHECK
PreReq VARCHAR2(6) FO R EIG N KEY

REGISTRATION

Column Name Data Type Constraints

StudentId CHAR(5) COMPOSITE PR IMA RY KEY , FO R EI GN KEY


CsId NUMBER(4) COMPOSITE PR IMA RY KEY , FO R EI GN KEY
Midterm CHA R CHECK
Final CHA R CHECK
RegStatus CHA R CHECK

ROOM

Column Name Data Type Constraints

R oom Type CHA R PRI MAR Y KEY

RoomDesc VARCHAR2(9)

LOCATION

Column Name Data Type Constraints

RoomId NUMBER(2) PR IMAR Y KEY


Building VARCHAR2(7) NOT NULL
RoomNo CHAR(3) NOT NULL, UN IQ UE
Capacity NUMBER(2) CHECK
RoomType CHA R FO R EIG N KEY
The Namannavan (N2) Corporation Employee Database 393

TERM

Column Name Data Type Constraints

TermId CHAR(4) PR IMAR Y KEY


TermDesc VARCHAR2(11)
StartDate DATE
EndD ate DATE

DEPARTMENT

Column Name Data Type Constraints

DeptId DeptName NUMBER(1) PR IMAR Y KEY

FacultyId VARCHAR2(20)
NUMBER(3) FO R EIG N KEY

MAJOR

Column Name Data Type Constraints

MajorId NUMBER(3) PRI MAR Y KEY

MajorDesc VARCHAR2(25)

THE N AM AN NAV AN (N2) CORPORATION EMPLOYEE DATABASE

EMPLOYEE

Column Name Data Type Constraints

EmployeeId NUMBER(3) PRI MAR Y KEY


Lname VARCHAR2(15) NOT NULL
Fname VARCHAR2(15) NOT NULL
PositionId NUMBER(1) FOR E IG N KEY
Supervisor NUMBER(3) FOR E IG N KEY
HireDate DATE
Salary NUMBER(6)
Commission NUMBER(5)
DeptId NUMBER(2) FOR E IG N KEY
QualId NUMBER(1) FOR E IG N KEY
394 App. A Sample Databases: Table Definitions

Dept

Column Name Data Type Constraints

DeptId NUMBER(2) PRI MAR Y KEY


DeptName VARCHAR2(12)
Location VARCHAR2(15)
EmployeeId NUMBER(3) FOR E IG N KEY

EMPLEVEL

Column Name Data Type Constraints

LevelNo NUMBER(1) PR IMAR Y KEY

LowSalary NUMBER(6)
HighSalary NUMBER(6)

POSITION

Column Name Data Type Constraints

PositionId PosDesc NUMBER(1) PR IM AR Y KEY

VARCHAR2(10)

DEPENDENT

Column Name Data Type Constraints

EmployeeId NUMBER(3) COMPOSITE PR IM AR Y KEY ,


FOR EI GN KEY
DependentId NUMBER(1) COMPOSITE PR IM AR Y KEY
DepDOB DATE
Relation VARCHAR2(8)

QUALIFICATION

Column Name Data Type Constraints

QualId QualDesc NUMBER(1) PR IMAR Y KEY

VARCHAR2(11)
SQL KEY WORD S

Figur e B-1 SQL keywords.


396 App. B Quick Reference to SQL and PL/SQL Syntax

PL/SQL KEY WORDS

Figur e B-2 PL/SQL keywords.

SQL AN D PL/SQL SYNTAX

I n the syntax for various SQL statements and PL/SQL blocks, the following conven-
tion is used:

• The key words are in uppercase letters.


• The user- defined names are in lowercase or mixed case.
• The optional items are enclosed in brackets ([ ]).
• The pipe symbol 1 ƒ2 is used to denote O R.
SQL and PL/SQL Syntax 397

Creating a Table

...,
...,
...
...), ...)

Column-Level Constraint

Table-Level Constraint

( column, ...),

A dding a Column to an Existing Table

Mo dif ying an Existing Column

A dding a Constraint to a Table

Dropp ing a Column (Oracle8 Onward)

Setting a Column as Unused (Oracle8 Onward)

Dropp ing an Unused Column (Oracle8 Onward)


398 App. B Quick Reference to SQL and PL/SQL Syntax

Renaming a Column (Oracle9i Onward)

Renaming a Constraint (Oracle9i Onward)

Dropping a Table

Renaming a Table

Truncating a Table

Inserting a New Row into a Table

...) ]
...);

Customized Prompts

Updating Rows

...]

Deleting Rows

Dropping a Constraint

|UNIQUE (columnname) |
SQL and PL/SQL Syntax 399

Enabling|Disabling a Constraint

Retrieving D at a from a Table

n(s)]

Define Command

Decode Function

|expr, value1, action1,


...,]

Case Structure

Joining Tables: Equijoin or Outer Join

.columnname, tablename2.columnname

.columnname [(+)] = tablename2.columnname [(+)];

Set Operation
400 App. B Quick Reference to SQL and PL/SQL Syntax

Select Subquery

Creating a Table Using a Subquery

Inserting a Row Using a Subquery

Inserting into Multiple Tables

Updating Using a Subquery

Deleting Using a Subquery

Top-N Query
SQL and PL/SQL Syntax 401

Mer ge Statement

Creating a View

Altering a View

Dropp ing a View

Creating a Sequence

|NOMAXVALUE] |
NOMINVALUE] |NOCYCLE]
|NOCACHE]
|NOORDER];

Mo dif ying a Sequence

|NOMAXVALUE] |
NOMINVALUE] |NOCYCLE]
|NOCHACHE]
|NOORDER];
402 App. B Quick Reference to SQL and PL/SQL Syntax

Creating a Synonym

Dropp ing a Synonym

Creating an Index

...);

Rebuilding an Index

Locking Rows for Update

Creating a User

C hangi ng a User’s Password

Granting System Privileges


SQL and PL/SQL Syntax 403

Granting Object Privileges

Revoking Privileges

PL/SQL A nonymous Block

PL/SQL Variable/Constant Declaration

Anchored Variable Declaration

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

Explicit Cursor Declaration

Opening an Explicit Cursor

Fetching a Ro w from an Explicit Cursor

Closing an Explicit Cursor

Cursor For Loop

...

Cursor For Loop with a Subquery

...
406 App. B Quick Reference to SQL and PL/SQL Syntax

Where Current Of Clause

Cursor with Select–For Update

Cursor with Parameters

Ref Cursor Type

Opening a Cursor Variable

Fetching from a Cursor Variable

Exception Section
SQL and PL/SQL Syntax 407

Pragma Exception_Init Directive

Raise_Application_Error Procedure

Creating a PL/SQL Record

Declaring a PL/SQL Table

Declaring a PL/SQL Varray

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 Package Specification

PL/SQL Package Body

PL/SQL Trigger
SQL and PL/SQL Syntax 409

Creating a Tablespace

Starting Up an Instance

Shutting D own an Instance

Creating a User f rom the Command Line with Various Clauses

Dropping a User

Logg ing into SQL*PLUS f rom the Command Line


Allowable command abbreviations are underlined.

ARRAYSIZE. The A R R A Y SI ZE command sets the number of rows fetched from


the database. The valid values are 1 to 5000. The general syntax is

AUTOCOMMIT. The A U TOC OM MI T command sets the automatic com- mit


of a D ML statement to On or OFF. The general syntax is

BREAK. The BR E A K command specifies action based on a change of a


value of a column or an expression, or when a row is returned. The general syntax is

The actions are SK IP lines, SK IP PAGE, NOD U PL I CA TES, or D U PLI C A TE S.


App. C Reference to SQL*Plus Commands 411

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.

CLEAR BUFFER. The C L E A R BU FF E R command clears an entire SQL


statement from the buffer. The general syntax is

CLEAR COLUMNS. The C L E A R C OL U MN S command clears all column


formatting set during the current session. The general syntax is

CLEAR SCREEN. The C L E A R SCR E E N command clears the entire screen.


The general syntax is

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

COLUMN. The CO L U M N command is used to display, suppress, reset, or set


column attributes as well as to set column headings. The general syntax/use is

(shows display attributes for all columns)


(shows display attributes for one column)
(resets display attributes of column)
(sets display attribute of column) (sets column
heading)

COMPUTE. The C OM PU TE command performs calculations using stan-


dard mathematical functions and displays the summary lines. The general syntax is

... ...
412 App. C Reference to SQL*Plus Commands

where the functions ar e SUM, A V G, C OU N T, M A X I M U M, M I NI M U M,


NU M B E R , STD , and V A RI A N C E . The O N clause must match the B R E A K
statement.

CONNECT. The CO NN EC T command connects a user to the database. The


general syntax is

COPY. The CO PY command copies a result from table to table or allows


you to append or to create rows or to create new tables. The general syntax is

where

<db> = database string (e.g., scott/tiger@d:nshah-monroe)


<opt> = key word APPEND, CREATE, INSERT or REPLACE
<table> = name of the target table
<cols> = alist of target column aliases separatedby commas
<sel> = any valid SELECT statement

DEFINE. The D E F I N E command defines a variable and stores it with C HA R


data type. If a variable name is not supplied, it shows all previously defined variables.
The general syntax is

To turn use of a substitution character on or off, use

DESCRIBE. The D E SC RI BE command describes the structure of a table or


view with column names, data types, and lengths. The general syntax is

DISCONNECT. The D I SC ON NE C T command commits the current transac- tion


and disconnects a user from the database, but it does not exit from SQL * Plus. The
general syntax is
App. C Reference to SQL*Plus Commands 413

ECHO. The E C H O command controls the display of a command as it is exe-


cuted. ON lists the display; OFF suppresses the display. The general syntax is

EXECUTE. The E X E C U T E command executes a PL/SQL block/statement.


The general syntax is

EXIT. The E X I T command commits the current D M L transaction, disconnects the


user from the database, and closes the SQL * Plus session. The general syntax is

FEEDBACK. The F EE D BA CK command displays the number of rows re-


turned by a query when the query returns at least rows. I t can also suppress the
display with the O FF switch. The default value for is 6. The general syntax is

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

HOST. The H OST command executes an operating system command from


SQL * Plus. If the command isnot specified, the system prompt is displayed. You can
return back to SQ L * Plus by typing E X I T. The general syntax is

LINESIZE. The L I NE SI ZE command is used to set the total number of


characters displayed by SQL * Plus per line before wrapping. The default line size is
80. The general syntax is

NUMWIDTH. The NU M W I D TH command sets the width for displaying


numbers. The default is nine. The general syntax is

PAGESIZE. The PA GE SI ZE command sets the number of lines per page.


The default is 24. Y ou can change it to zero to suppress all titles, headings, and page
414 App. C Reference to SQL*Plus Commands

breaks. The general syntax is

PAUSE. The PA U SE command displays a blank line followed by a line with


specified text, then waits for the user to press the E nter key. The general syntax is

REMARK. The characters followed by the R E M A R K keyword on the same


line are treated as a comment that is ignored by SQL * Plus. The general syntax is

SET. The SE T command shows and sets system and environment variables.
The general syntax is

SHOW. The SH OW command shows the values of all system variables or


the current user’s name. The general syntax is

SHOWMODE. The SH OW M OD E command controls the display of old and


new settings when a variable setting is changed with SET. The general syntax is

|OFF

SHUTDOWN. The SH U TD O W N command shuts down the Oracle data-


base instance. The general syntax is

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

SQLCASE. The SQ L CA SE command converts the case of SQL state-


ments, PL /SQL statements, and text, including text in quotation marks. The gener-
al syntax is

| |

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

...]

UNDEFINE. The U ND E F I N E command deletes a variable defined with


D E FI N E or & or & & . The general syntax is

VERIFY. The V E R I F Y command, when turned ON, shows an SQ L state-


ment before and after SQL * Plus replaces substituti on variables with values. The
general syntax is

WRAP. The W R A P command controls the truncation of a row if it is longer


than the line width. The general syntax is

|OFF
416 App. C Reference to SQL*Plus Commands

SQL*PLUSEDITING COMMANDS

Command Description

APPEND Adds text to the end of the current line.


CHANGE / Changes old text to new text in the current line.
CHANGE / Deletes text from the current line.
CLEAR BUFFER Deletes all lines from the SQL buffer.
DEL Deletes the current line.
DEL Deletes line number .
DEL Deletes lines through .
INPUT Inserts an indefinite number of lines.
INPUT Inserts a line of text.
LIST Lists all lines from the SQL buffer.
LIST Lists line number .
LIST Lists lines from through .
RUN Displays and runs an SQL statement from buffer.
Makes line current.
Replaces line with text.
0 Inserts a line before line 1.
CLEAR SCREEN Clears the screen.

SQL*PLUSFILE-RELATED COMMANDS

Command Description

GET [.ext] Writes a previously saved file to the buffer. The default exten-

sion is . Writes SQL statements, not SQL * Plus commands.


START [.ext] Runs a previously saved command from the file.
@ Same as START (default extension must be ).
EDIT Invokes the default editor (e.g., Notepad), and saves the buffer
contents in a file called .
EDIT [ [.ext]] Invokes the editor with the command from a saved file.
SAVE [.ext]REPLACE ƒ Saves the current buffer contents to a file with the option to
APPEND replace or append.
SPOOL[ [.ext] ƒ OFF ƒ OUT] Stores query results in a file. OFF closes the file, and OU T
sends file to the system printer.
EXIT Leaves the SQL * Plus environment.
The filename in the file-related commands also requires a file path.
AN OBJECT

A n object in Oracle9i is a reusable component that represents real- word things. A n


object is defined with a user- defined data type called an object type. Object types
are used as data types to define columns (known as object columns) in a table. Ob-
ject types are also used in place of a list of columns for an object table. A n object
type can be used as an element in another object type as well.
A n object contains a name, attribute(s), and methods. A n object contains data
and information about what can be done with the data. A n object may also contain
another object. The methods are procedures and functions written in an Oracle9i-
supported languages. Each method has a name as well as the name of the object that
contains that method. The method can be passed data through parameters from a
calling program.
Oracle9i is a relational database as well as an object-oriented database. I t pro-
vides several ways to connect relational tables and objects:

• — A n object view is like a relational view. I t does not contain


any data, but it is based on underlying tables. I t allows users to view a rela-
tional table with an object orientation. Y ou can modify data in the underly-
ing table with SQL statements, with object methods, or by using an object
view.
418 App. D ObjectOrientation

• — A n object table is a table that is described by object type, not


by attribute names. The elements in an object type define the data for the
object table. The object table can also contain object methods as part of a
table’s definition. These methods are used to perform data manipulation on
the object table. You can define a primary key for an object table and create
an index for it as well.
• — A relational table may contain one
or more columns with the object type as their data type. Such a table is also
known as a hybrid table, because it contains columns with scalar data types
as well as object columns.

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).

Name Item Type Attribute Name Data Type


Object type LAST_NAME VA RCHAR 2
FIRST_NAME VA RCHAR 2
Object type NA ME_REF R E F to
MID_INITIAL VA RCHAR 2
Object table Row of
Hybrid table STUDENT_ID N UMB ER
FULL_NAME
PHONE_NUM VA RCHAR 2

Figur e D-1 Object types, R E F column, object column, and hybrid table.

SQLQUERIESFOR OBJECTS

Retrieving Data from an Object Table

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

The retrieved rows are displayed with column headings as follows:


LAST_NAME FIRST_NAME MID_INITIAL
-----------------------------------------------------

You can use W H E R E , O R D E R BY , and G R OU P BY clauses with the SE LE C T


statement, just as in standard relational SQL.
Now, let us display the last name, first name, and phone number of students
from STU D ENT_TA BLE. The attributes belonging to the object type are refer-
enced using dot notation:

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

Inserting a Row into an Object Table

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,

INSERT INTO STUDENT_TABLE VALUES


(543, FULL_NAME(‘Spencer’, ‘Karen’, ‘A’), ‘732-555-6789’);

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;

Deleting Rows from an Object Table

DELETE FROM NAME_TABLE N WHERE LAST_NAME = ‘Smith’;


This appendix describes new features of SQL and PL/SQL in Oracle9i (release 1).

NEW FEATURES I N SQL

1. New or modified built-in data types:


C HA R— can take C H A R or B Y TE parameter. V A R CH A R2— can tak e
C H A R or B Y TE parameter. TI ME STA MP— for additional datetime
functionality.
I NTE RV A L Y E A R TO M ON TH— for additional datetime functionality.
I NTE RV A L D AY TO SE CO ND — for additional datetime functionality.

2. New or enhanced expressions:


C A SE expressions— enhanced with Searched Case expression.
C U RSO R expressions— enhanced to pass as R E F C U RSOR arguments
to function.
D A TE TI M E expressions— new. I NTE RV A L expressions— new. Scalar
subquery expressions— new.
New Features in SQL 421

3. New built-in functions:

ASCIISTR BIN_TO_NUM COALESCE


COMPOSE CUR REN T_D ATE CURRENT_TIMESTAMP
DB TIM EZONE DECOMPOSE EX ISTSNODE
EXTRACT( ) EX TR ACT (X ML) FIRST
FROM_TZ GR OU P_ID GR OUPING_I D
GR OU PIN G_ID LAST LOCAL_TIMESTAMP
NULLIF R OW TONH EX RO WID TONCHA R
SESSIONTIMEZONE SY S_CONNECT_BY _PATH SY STIMESTAMP
TO_CHAR( ) TO_CLOB TO_DSINTERVAL
TO_NCHAR( ) TO_NCHAR( ) TO_NCHAR( )
TO_NCLOB TO_TIMESTAMP TO_TIMESTAMP_TZ
TO_Y MINTERVAL TR EAT TZ_OFFSET
UNISTR WIDTH_BUCKET

4. E nhanced functions:
I NSTR.
L E NG TH .
SUBSTR.

5. New system and object pr ivileges:


E X E M PT A CCESS POLI CY . R E SU MA BL E .
SE L E C T A N Y D I CTI ONA RY . U N D E R A NY TY PE .
U N D E R A NY NEW.
U NDER( ).

6. New SQL statements:


C R E A TE PFILE. C R E A TE SPFILE. ME R G E .

7. SQL statements with new syntax:

A L TE R DA TA BASE— new syntax to end hot backup while database is


mounted; also for standby databases.
A L TE R I N D E X — to get statistics on index usage.
A L TE R OU TL I NE — for modifications to public and private outlines.
422 App. E What’s New in Oracle9i SQL and PL/SQL?

A L TE R RO L E — to identify role using application- specified package.


A L TE R SESSION— to specify if statements issued during a session can
be suspended.
A L TE R SY STEM— extended SE T clause.
A L TE R TA BL E— allows partitioning by specified values.
A L TE R TY PE — to change attribute or method definition of an object
type.
A L TE R V I E W — to add constraints to views.
A NA LY ZE — new O NL I N E and OF FL I N E clauses, and selection of stan-
dard or user- defined (or both) statistics.
C ON STR A I N T_C L A U SE — for index handling when dropping or dis-
abling constraints.
C RE A TE CO NTE X T— to initialize the context from the L D A P directo-
ry or an OC I interface and to make context accessible throughout an
instance.
C RE A TE CO NTRO L FI L E — for creation of Oracle-managed files.
C RE A TE DA TA BASE— to create default temporary tablespaces and to
undo tablespaces.
C RE A TE FU NC TI O N— to create pipelined and parallel table functions
and user- defined aggregate functions.
C RE A TE OU TL I NE — for creation of private and public outlines.
C RE A TE RO LE — to identify a role using an application-specified package.
C RE A TE TABLE— allows creation of external tables, creation of Oracle-
managed files, and partitioning by a list of values.
C RE A TE TABLESPA CE— for segment space management, creation of
Oracle- managed files, and creation of undo tablespaces.
C R E A TE TE M PO R A R Y TA BL E SPA CE — for creation of O racle-
managed files.
C RE A TE TY PE— allows creation of subtypes.
C RE A TE V I EW— lets you create subviews of object views and define
constraints on views.
D RO P TA BLESPA CE — lets you drop operating system files when con-
tents are dropped from a tablespace.
FI L E SPE C— for creation of Oracle-managed files. INSERT— lets you
insert default column values.
SE L E C T— lets you specify multiple grouping in G R O U P B Y clause,
assign names to subquery blocks, and support A N SI - compliant join
syntax.
SE T TRA NSA C TI O N— to specify a name for a transaction. U PD A TE — to
update default column values.
New Features in PL/SQL 423

NEW FEATURES IN PL/SQL

1. I ntegr ation of SQL and PL /SQL :


PL/SQL supports the complete range of syntax for SQL statements. No
er ror messages for valid SQL syntax as in previous versions.
Compile time error- checking.

2. CA SE expr essions:
New C A SE statements as alternatives for I F statements.

3. New date/time types:


TIMESTA MP data type that records time in fractional seconds.
TIMESTA MP W I TH TI M E ZO N E and TIMESTAMP W I TH LO CA L
TI M E ZO NE for adjusting account for time zone differences (with day-
light savings).
I NTE RV A L D AY TO SE C ON D and I N TE R V A L Y E A R TO MON TH
for representing differences between two date and time values.

4. Typeevolution:
Attributes and methods can be dropped from an object type without
recreating the type and corresponding data.

5. Native compilation of PL/SQL code:


Improved performance by compiling Oracle-supplied and user- created
stored procedures into native executables with C-language development
tools.

6. Table functionsand cursor expr essions:


You can query a set of returned rows like a table. Result sets can be
passed from one function to another.
7. Multilevel collections:
Nesting of collection types— for example, VA RRAY of VA RRAY S and
PL/SQL table of PL/SQL table.

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.

BOOKS A ND OTHER PUBLISHED MATERIAL

1. R elational database concepts:


K roenke, David, ,
Prentice-Hall, January 2002.
Rob, Peter, and Treyton Williams, ,
McGraw-Hill, Primis Custom Publishing.
2. O racle SQL :
Mishra, Sanjay, and A lan Beaulieu, , O’Reilly and
Associates, April 2002.
Rischert, Alice, , Prentice-Hall, December
2002.
3. O racle PL /SQL :
Feuerstein, Steven, , O’Reilly and Associates,
September 2002.
Rosenzweig, Benjamin and El ena Silvestrova,
, Prentice-Hall, October 2002.
U rman, Scott, , McGraw-Hill Osborne, November
2001.
4. M iscellaneous topics:
L oney, K evin, and Marlene Theriault, , McGraw-Hill
Osborne, November 2001.
Price, Jason, , McGraw-Hill Osborne, May 2002.
5. G eneral r eference:
Staron, Richard J., , Addison Wesley, April 2003.
#sql, 360 Modifying a C olumn, 84 R ENA ME Built- in Table M ethods, 304–305
% FO U N D , 273 COLU MN C lause, 88 COUNT, 304
% ISOPEN, 272–273 R ENA M E CONSTRA INT Clause, D EL ETE , 304
% NOTFOU ND, 273–274 88 EX ISTS, 304
% ROW COU NT, 274 Renaming a Column, 88 R enaming EX TEND , 304
% ROW TYPE, 271, 299 a Constr aint, 88 SET U NU SE D FIRST, 304
% TY PE, 234 Clause, 87 LA ST, 304
& Prefix, 101 A lternate Text Editor, 49–51 NEX T, 304
& & Pr efix, 125 A mpersand (& ), 101 PRIOR, 304
(+) Oper ator, 163 A nalysis, 26 TR IM, 304
:IN Parameter, 361 A nchor, 234–235 Business Rules, 23
:NEW Record, 330 A nchor Column, 234–235
:OUT Parameter, 361 A nchor V ariable, 234–235 Callable Statement Class, 343
@ C ommand, 47 A nchored D eclaration, 234–235, 271 Cardinality, 22
1:1 (One-to-One), 2 % R O W TY PE Attribute, 271 Cartesian Product, 11, 157–158
1:M (One-to-Many), 2 % T Y PE A ttribute, 235 C A SC A D E C ONSTRA INTS Clause,
1NF to 2NF, 29, 32 Nested A nchoring, 234–236 211
2NF to 3NF, 30, 32 A N D Operator, 115 CA SE Structure, 127–128, 143–144
A nomaly, 26–27 CA SE . . . EN D CA SE Statement, 251
A BS Function, 136 D eletion Anomaly, 26 CEIL F unction, 137 C entral
A CC EPT Command, 102 Insertion A nomaly, 26 Transaction L og, 41 C HA NG E
A ccess Control, 207 U pdate A nomaly, 27 Command, 48
A ctions on Explicit C ursor, 270–272 Anonymous Block, 228 CHA R, 69
A ctual Parameter , 316 A NY Operator, 181 Character data, 98
A D D _M ONTHS F unction, 140 A dding A PPEN D Command, 48 Character F unctions, 132–136
a C olumn, 83 A pplets, 351 Character L iterals, 228
A dding a C onstraint, 84–86 A dding a A pplications of Relational Algebra, CHECK C onstraint, 75
new row, 98–102 14–15 CK PT Process, 370
INSERT Statement, 98–102 A rchive L og Files, 373 A rithmetic C L E A R B U FF E R Command, 48, 411
V A LU ES Clause, 98 Advanced Data Operations, 113 C L E A R COLU MNS Command, 411
Types A rithmetic Operators, 113 C L E A R SC REEN Command, 48, 411
BF ILE, 71–72 A RRA Y SIZE Command, 410 Client Computer, 37
BL OB, 71–72 A SC K eyword, 123 A scending Client Failure, 39, 40
CL OB, 71–72 Sorting Order, 123 Client/Server D atabase, 39–41
L ONG, 71–72 A ssigning Values to PL /SQL Table, Client/Server Environment, 41
L ONG R AW , 71–72 302–303 CL OB Type, 71
NCHA R, 71–72 A ggregate A ssignment, 303 CL OSE Statement, 272
RA W , 71–72 A ssignment in a Loop, 302 Direct COA LESCE Function, 142–143
A F TE R Tr igger, 331–333 A ssignment, 302 Cold Backup, 373
A ggr egate Functions, 132 A ssignment, 12 Collections, 296
A L L Oper ator, 181 A ssignment Operation, 236 COL SEP Command, 411
A L L Privileges, 209–210 A ssignment Operator, 236 Column A lias, 110
A L TER Privilege, 209 A ssociative Entity, 23 A sterisk (* ) COL UM N C ommand, 110–112, 411
A L TER Pr ocedure Statement, 317 W ild C ard, 106 A ttributes, 2 Column Level Constraint, 73
A L TER TABL E Statement, 82–88 A UTOCOMMIT Command, 204, 410 COMMENT on Tables and Columns, 82
A D D C lause, 83 A V G Function, 147–148 Comments, 230
A D D CONSTR AI NT Clause, 84 Multi-Line Comment, 230
A dding a C onstraint, 84–86 A dding a Background Processes, 369 Single-Line Comment, 230
New Column, 83 CA SCA D E C lause, Basic L oop, 255–256 COMMI T Statement, 8, 208
88 Basic L oop V ersus W H I L E Loop, 257 Compar ison Oper ators, 115–122
Circular Reference, 85 B EF O R E Trigger, 330–331 B ETW EE N .. . A N D , 115–118 IN, 115,
D ISA BL E C ONSTRA INT C lause, 88 B ETW EEN . . . A ND Operator, 115, 119
D isabling a C onstraint, 88 D R O P 117–118 IS NU L L, 115, 120
COL U MN Clause, 87 BFIL E Type, 71 LI KE, 115, 121–122
D R OP U N U SED COL U MN Clause, Bind V ariables, 237 Complex V iew, 192
87 BL OB Type, 71 Composite A ttribute, 24
D ropping a Column, 86–87 Dr opping Blocks, 372 Composite D ata Types, 230, 296
a Constraint, 87–88 Boolean Literals, 228 Composite Entity, 23
ENAB LE CONSTRA INT Clause, 88 B OO L EA N Type, 233 Composite K ey, 7 C omposite U nique
Enabling a Constraint, 88 B R EA K Command, 410 Key, 75 C OM PU T E Command, 411
M odifications Allowed, 82 BTITLE Command, 411 CONCA T Function, 134
M odifications A llowed with Built-in Functions, 132 Concatenation, 112–113
Restriction, 83 Modifications Group or A ggregate F unctions, 132 Concatenation Character (||), 112–113
Not A llowed, 83 M ODIF Y C lause, 84 Single-Row Functions, 132 CONNECT Command, 376, 412
428 Index

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

MONTHS_ BETWEEN Function, 140 Numeric D ata, 98 Parameter Types, 315


Multiline Comment, 230 Multiple Numeric Functions, 136–137 IN, 315
Column Sort, 124 M ultiple Conditions, Numeric Literals, 228 IN OU T, 315
250 NUM W IDTH C ommand, 413 OU T, 315
Multiple-Row Subquer y, 181–183 NVL Function, 114, 141 Partial D ependency, 25, 32
Multiplicity, 22 NVL 2 Function, 142 PAU SE Command, 414
Multivalued A ttribute, 24 P-Code, 313–314
Object, 417 Percent ( % ) W ild C ard, 121
NamanNavan (N2) C orporation Object Column, 418 Performance, 373
Employee D atabase, 61–64, Object Privileges, 209, 211 Personal Database Management
393–394 A LL , 209–211 System, 37–39
D E PEN D EN T Table, 62 A LTER, 209–211 PL/SQL, 1, 42,225–229, 230, 238–240,
D E PT Table, 62 D E L ETE , 209–211 244, 253, 260–264, 306–309,
EMPL OY EE Table, 61 EXECU TE, 209–211 423–424
POSITION Table, 62 IND EX , 209–211 A Procedural L anguage, 41, 225
QUA L IFICA TION Table, 62 INSERT, 209–211 A nchored Declaration, 234–236
SA LA RY L EVEL Table, 62 REFERENC ES, 209–211 A rithmetic Operators, 240
Table D efinitions, 393–394 SEL ECT, 209–211 A ssignment Oper ation, 236
Named B lock, 229, 313 U PD ATE, 209–211 B lock Structure, 228
Named Notation, 316 Naming a Object Table, 418–419 A nonymous, 228
Constraint, 72–73 Naming Conventions, D eleting Rows, 419 Named, 228
68 Inserting Row, 419 B uilt-in Functions, 260
Naming Rules, 68 R etrieving D ata, 419 C omments, 230
Natural Join, 13 SQL Queries, 418 U pdating an Object, M ultiline, 230
NC H A R Type, 71 419 Single L ine, 230 Composite D ata
NCL OB Type, 71 Object Type, 417 Types, 296 Control Structures, 245
Nested A nchoring, 235–236 Object View, 417 L ooping, 245
Nested Blocks, 259 ODB C (Open Database Connectivity), Selection, 245
Nested Functions, 146–147 Nested IF 374 Sequence, 245
Statement, 253 Nested L oops, 259 OEM , 375 D ata M anipulation Language, 262–
Nested Query, 174 ON D E L ET E CA SC AD E, 74 263
Nested R ecords, 299–300 Online Help, 49, 91–93 D ata Types, 230–234
Nested Tables, 307 OPE N Statement, 271 Opening a B FIL E, 234
Nesting Functions, 146–147 Nesting Cursor Var iable, 280 Optimistic L ocking, B LOB, 233
Group Functions, 153 Network, 38 39 B OOL EA N, 233
NEX T Method, 304 Optional R elationship, 23 C HA R, 231
O R Operator, 115 C LOB, 233
NEX T_D A Y Function, 140
Ora.hlp File, 49 C omposite, 230, 296
NEX T_TIME Function, 140
NEX TVA L PseudoColumn, 197 Oracle D ata Source, 344 Oracle Errors, D A TE, 233
NO_ D ATA _ FOU ND Exception, 260 49 L OB, 233
Nonequijoin, 13, 161–162 Oracle Repor ts, 42 NCL OB, 234
Oracle Table, 76–90 Altering a Table, NL S, 233
Nonkey Column, 25 Nonpredefined
82–88 Cr eating a Table, 76–82 N U M B ER , 232
Oracle Server
D isplaying Structure, 80 D ropping a Scalar, 230–234
Exception, 282–284
Table, 89 Renaming a Table, 89 B OOL EA N, 233
Non-procedural Language, 15
Truncating a Table, 89–90 C HA R, 231
Normal F orm, 26–28
Oracle D river, 348 D A TE, 233
First Normal F orm (1NF), 27–28 ORA CL E_ SID , 372 N U M B ER , 232
Second Normal Form (2NF ), 28 Oracle9i, 41–42, 419–424 V A RCHA R2, 231–232
Third Normal Form (3NF), 28 What’s New, 419–424 Embedding SQL in Block, 260–264
Normalization, 26, 32–34 Or acleDriver Class, 340, 348 F undamentals, 227
NOT EX ISTS Operator, 186–187 O R D E R BY Clause, 122, 135, 151 History, 226
NOT IN Operator, 119 Order of Arithmetic Operations, 113 L iterals, 228
NOT NU LL CHECK Constr aint, 76 Order of L ogical Operations, 117–118 L ogical Operators, 246
NOT NUL L Constraint, 75 Order of Precedence, 117–118 M andatory K eywords, 229
NOT NU LL V ariables, 234 NOT OTN, 91 Printing, 239–240 Printing in
Operator, 115 OU T Parameter, 315 D BMS_ OU TPUT.PU T_ LINE,
Notepad, 49–51, 78 Outer Join, 13, 163–164 239
A lternate Editor, 78 Outer Query, 174 R ecord Type, 297
NOW A IT Clause, 207 R ecords, 297–300
NUL L FIR ST K eywords, 123 NUL L Package, 230, 323–326 R elational Operators, 245
V alue, 100, 114 Body, 325–326 R eser ved Words, 227
Explicit Null, 100 Objects, 323–324 Sections, 229
Implicit Null, 100 Specification, 324–325 D eclaration, 229
NUL L IF Function, 143 Structure, 324 Exception Handling, 229
NU M B ER Type, 70 PA GESIZE Command, 413 Executable, 229
Number Format, 144 NU M B E R Parallel Server, 373 SEL ECT. . . INTO Statement, 260
Sub-data Types, 232 Parameter File, 372 SQL in PL/SQL, 260–264
Index 431

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

SQL K eywords Reference, 395 SQL SY S U ser , 383 U nion, 9–10


Review, Supplementary SY SD ATE Function, 137 System U NI ON A L L Oper ator, 167 U nion
Examples, 215–224 SQL Global Ar ea, 369 System Privileges, 386 Compatible, 9
Statement Syntax, 397–403 SQL Types, 386 U NI ON Operator, 166
Statements, 43 System Security, 207 U NI QU E Constraint, 75
D ata Control L anguage, 43 D ata SY STEM User, 383 U niversal Installer, 374
D efinition L anguage, 43 U nnormalized Table, 27
D ata Manipulation L anguage, 43 Table, 5, 68, 372 U pdate A nomaly, 27
D ata R etrieval, 43 D isplaying Names, 79 U PD A TE Privilege, 209
Tr ansaction Control, 43 D isplaying Structure, 80 U PD A TE Statement, 103, 263
SQL Syntax, Quick Reference, 395–403 Table M odification, 82–86 U pdating Rows, 102–104 U PD A TE .. .. ..
SQL versus SQL * Plus, 47 Table Alias, 160 SET, 103
SQL* Plus, 42 Table L evel Constraint, 74 Table U pdating with Subquery, 180
SQL* Plus Commands, 46–48 L ocking, 39, 40 Table of a Table, 306 U PPE R F unction, 133
Editing Commands, 48 Table of Cursor, 306 U ser Creation, 208, 380–382
File-R elated C ommands, 47 Table of Records, 305–306 U SER_ ER RORS V iew, 334
SQL* Plus Editing Commands, 48, 416 Table Types, 90 U SER_ INDEX ES Table, 202
SQL* Plus Environment, 43 Tablename Qualifier, 159 U SER_ OB JECTS V iew, 334
SQL* Plus File-Related Command, 47, Tablespace, 67, 372, 378 U SE R_ PR O CE D U R E S View, 334
416 Tablespace Information, 82 U SER_ SOUR CE View, 334
SQL* Plus W orksheet, 51–53 Temporary Segment, 372 Theoretical U SER_ SY NONY MS Table, 201
SQLC ASE Command, 415 Relational L anguages, 8 U SE R_ TR I GGER S V iew, 334
SQL C O D E Function, 285 Relational Algebra, 8 U SER_ VI EW S Table/V iew, 194
SQL E RR M Function, 285 Relational Calculus, 8 U ser-D efined Exceptions, 286–288
SQLj, 358–365 Third Normal Form (3NF), 28 U sers, 208
Configuring Oracle SQLj, 359 Three-Tier A rchitecture, 41 U sing a Sequence, 198
Connecting to the Or acle Database, TIME Command, 415
360 Time Format, 70, 99 V $ V iews, 388
Creating a SQLj Project, 359 TIMING Command, 415
V $BGPROCESS, 371
Embedding SQL Statements, 360 TNSNA MES.ORA , 373
V alid Names, 68
Impor ting classes, 360 TO_ C HA R F unction, 99, 144
V alue Constraint, 72
SQLj Iterator, 361–364 TO_ D ATE Function, 99, 144
CHECK , 75
Named Iterator , 361–362 TO_ NUM BER F unction, 144
NOT NUL L , 75
Positional Iterator, 363–364 TOO_ MA NY _ ROW S Exception, 260,
U NI QU E , 75
SQLPROMPT Command, 415 269
V A RCHA R2 Type, 69
Stand-A lone Environment, 41 TOP- N Analysis, 183–185
V A RIA BL E Command, 237
STAR T Command, 47 TOP- N Column, 183
V ariable Declaration, 234
STAR TU P Command, 377 Total D ependency, 25, 32
Transaction Control, 43 V ariable- Length Character V alue, 69
Statement Class, 341–342
Transaction Control in PL /SQL , 264 V enn Diagram, 167
Statement Trigger, 331
Transaction Control L anguage, 43 V ERIFY Command, 415
Static Cursor , 268 V ersion, 372
Explicit, 269 Transaction log, 39
Transaction Processing, 39, 41 V iew, 191–196
Implicit, 268
Transactions, 204–206 A ltering a View, 195–196 Complex
Static D ata D ictionary V iew, 387 V iew, 192 Creating a V iew, 192–
STOR A G E Clause, 78–79 A UTOCOMMIT, 204
Storage Manager, 378 COMMIT, 204 194 Removing a V iew, 195 Simple
Subquery, 174–181 ROLL BA CK , 204 V iew, 192
SA VEPOINT, 204 V iewing Table Constraints, 80–81
Creating a Table with Subquery, 176–
Transitive Dependency, 25, 32 V iewing Table Names, 79 V iewing
178
Trigger Types, 330 Table Structur e, 80
D eleting Using a Subquer y, 180–181
INSERT U sing a Subquery, 178–179 Tr iggers, 230, 328–334 Creating a
Inserting into M ultiple Tables, 179 Tr igger, 328 Firing the Trigger, 328
Multiple-Row Subquer y, 174 Types, 330 W eak Entities, 24
Single-Row Subquery, 174 TRIM Function, 134 W H EN O THE R S C lause, 286
U pdating U sing a Subquery, 180 TRIM Method, 304 W HE R E Clause, 114, 135
Substitution V ariable, 100–101, TRU NC Function, 136 W HE R E C U R R E NT O F Clause, 277
125–126 TRU NCA TE Statement, 104 W H IL E L oop, 257
& & Pr efix, 125 TRU NCA TE TA BL E Statement, 89 W ild Cards, 121–122
A mpersand (& ), 101 Truncating a Table, 89 % (percent), 121
SU BSTR Function, 134 TTITL E Command, 415 _ (underscore), 121
SU M F unction, 147–148 Tuple, 5 W ITH AD MIN OPTION C lause,
Surrogate K ey, 7 386–387
Synonym, 200–201 Creating a U N D EF I NE Command, 102, 126, 415 W ITH C HECK Option, 192
Synonym, 200 U nderscore (_ ) W ild Card, 121 W ITH G R A N T OPTION Clause, 210
D ropping a Sequence, 201 PU BL IC W I TH R E A D ONL Y Option,
Synonym, 201 192–193
Synthesis, 26 W R A P C ommand, 415

You might also like