You are on page 1of 157

Contents

CHAPTER 1

INTRODUCTION TO RDBMS AND ORACLE


APPROACHES TO DATABASE MANAGEMENT............................................................7
DATABASE MANAGEMENT AN EVOLUTIONARY PHENOMENON................................7
INTRODUCTION TO DBMS.......................................................................................8
CONCEPT OF DBMS.................................................................................................8
DATABASE MODELS.................................................................................................9
CHARACTERISTICS OF RELATIONAL DATABASE MANAGEMENT SYSTEM..............11
THE 12 RULES FOR AN RDBMS ( CODDS RULE ).................................................11
INFORMATION REPRESENTATION............................................................................11
APPLICATION DEVELOPMENT CYCLE.....................................................................13
DATABASE DESIGNING...........................................................................................14
ER DIAGRAM.........................................................................................................15
DEGREE OF RELATIONSHIP.....................................................................................16
NORMALIZATION....................................................................................................17
NEED FOR NORMALIZATION....................................................................................17
STEPS IN NORMALIZATION......................................................................................18
INVOICE MANAGEMENT SYSTEM...........................................................................18
INVOICE TABLE......................................................................................................20
CUSTOMER TABLE..................................................................................................20
ORACLE AS AN OBJECT ORIENTED DBMS...........................................................21
FEATURES OF ORACLE ...........................................................................................22

Chapter 2

Introduction to SQL *Plus


INTRODUCTION TO SQL.........................................................................................25
ORACLE DATA TYPES.............................................................................................25
STARTING SQL* PLUS EDITOR...............................................................................29
OPERATORS AND EXPRESSIONS..............................................................................31
QUERYING DATABASE TABLES..............................................................................34
ROLLUP OPERATION GETTING SUB TOTALS........................................................39
CUBE OPERATION GETTING CROSS TABS............................................................39

Chapter 3

Querying Multiple tables


MULTIPLE TABLE QUERIES....................................................................................42
EQUI JOIN..............................................................................................................42
CARTESIAN JOIN.................................................................................................42
OUTER JOIN..........................................................................................................43
SELF JOIN..............................................................................................................44
USING SET OPERATORS..........................................................................................45
SUB QUERIES..........................................................................................................46
SINGLE-ROW SUB QUERIES...................................................................................46
MULTIPLE-ROW SUB QUERIES...............................................................................47
CORRELATED SUBQUERIES.....................................................................................47
USING SPECIAL OPERATORS IN SUBQUERY.............................................................48

Page 1

Contents
CHAPTER 4

FUNCTIONS
FUNCTIONS.............................................................................................................51
SINGLE ROW FUNCTION.........................................................................................51
GROUP FUNCTIONS.................................................................................................54

Chapter 5

Data Definition and Manipulation Language


DATA DEFINITION LANGUAGE................................................................................57
CREATING TABLES.................................................................................................57
WORKING WITH CONSTRAINTS..............................................................................58
CREATING A TABLE WITH DATA FROM ANOTHER TABLE.........................................61
MAINTAINING DATABASE OBJECTS........................................................................62
ALTER TABLE.........................................................................................................62
THE ENABLED/DISABLED CLAUSE..................................................................64
DROPPING / RENAMING TABLES............................................................................64
TRUNCATING TABLE...............................................................................................65
INSERT VALUES INTO A TABLE................................................................................66
INSERTING RESULT OF A QUERY INTO A TABLE......................................................66
INSERTING THROUGH PARAMETER SUBSTITUTION..................................................66
UPDATING COLUMNS OF A TABLE...........................................................................67
DELETING ROWS FROM A TABLE............................................................................67
INTRODUCTION TO VIEWS......................................................................................68
CREATING A VIEW..................................................................................................68
MANIPULATING DATA THROUGH VIEWS................................................................68
CREATING A JOIN VIEW..........................................................................................69
KEY-PRESERVED TABLE..........................................................................................69
RULES FOR DML STATEMENTS ON JOIN VIEW.......................................................70
DROPPING A VIEW..................................................................................................71
WORKING WITH SEQUENCES..................................................................................71

Chapter 6

Data Control Language


DATABASE SECURITY AND PRIVILEGES.................................................................75
GRANT COMMAND.................................................................................................75
REVOKE COMMAND...............................................................................................76
APPLICATION PRIVILEGE MANAGEMENT...............................................................76
ORACLE PROVIDES THREE STANDARD ROLES:.....................................................76
COMMIT AND ROLLBACK......................................................................................76
IMPLICIT COMMIT................................................................................................77
AUTO ROLLBACK...............................................................................................77
SAVEPOINT..............................................................................................................77

Chapter 7

Introduction to PL/SQL
INTRODUCTION TO PL/SQL...................................................................................80
ADVANTAGES OF PL/SQL......................................................................................80
PL/SQL ARCHITECTURE........................................................................................80
PL/SQL BLOCK STRUCTURE..................................................................................81
NAMED AND ANONYMOUS BLOCK.........................................................................81

Page 2

Contents
CONDITIONAL AND ITERATIVE CONTROL ...............................................................82
IF THEN...........................................................................................................82
IF THENELSE...............................................................................................83
IF THENELSIF.............................................................................................83
LOOPEND LOOP.............................................................................................84
WHILELOOP....................................................................................................85
FORLOOP.........................................................................................................85
SQL WITHIN PL/SQL.............................................................................................86
WRITING A PL/SQL CODE......................................................................................86
COMPOSITE DATA TYPES........................................................................................87
PL/SQL RECORDS..................................................................................................87
RECORD ASSIGNMENT............................................................................................87
PL/SQL TABLES..................................................................................................88
Chapter 8

PL/SQL - II
CURSOR MANAGEMENT IN PL/SQL......................................................................92
IMPLICIT CURSOR...................................................................................................92
EXPLICIT CURSOR..................................................................................................92
USING CURSOR.......................................................................................................92
EXPLICIT CURSOR ATTRIBUTES...............................................................................94
FOR UPDATE CLAUSE WITHIN CURSOR............................................................94
WHERE CURRENT OF CLAUSE..........................................................................95
CURSOR WITH PARAMETER..................................................................................95
CURSOR FOR LOOP...........................................................................................96
CURSOR FOR LOOP USING A QUERY................................................................96
EXCEPTION, ERRORS, AND PL/SQL.......................................................................97
EXCEPTION HANDLING IN PL/SQL........................................................................97
EXCEPTION PROPAGATION....................................................................................100

Chapter 9

Advanced Pl/SQL
SUB-PROGRAMS IN PL/SQL.................................................................................105
ADVANTAGES OF SUB-PROGRAMS.......................................................................105
PROCEDURE..........................................................................................................105
CALLING A PROCEDURE.......................................................................................106
ACTUAL VS. FORMAL PARAMETER......................................................................106
ARGUMENT MODES..............................................................................................106
FUNCTIONS...........................................................................................................108
STORED PACKAGE................................................................................................109
ADVANTAGES OF PACKAGE...................................................................................110
CREATING A PACKAGE BODY:...............................................................................110
DROPPING PROCEDURES, FUNCTION AND PACKAGE............................................111
DATABASE TRIGGER.............................................................................................112

Chapter 10

PL/SQL File Input - Output


PL/SQL FILE INPUT-OUTPUT...............................................................................118
INSTALLATION OF UTL_FILE PACKAGE..............................................................118

Page 3

Contents
FUNCTIONS AND PROCEDURES OF UTL_FILE PACKAGE.....................................118
Chapter 11

Implementing Object Technology


WHAT IS OBJECT TECHNOLOGY?.........................................................................123
WHAT IS AN OBJECT?...........................................................................................123
EXISTENCE OF AN OBJECT...................................................................................123
RETRIEVING ATTRIBUTE FROM AN OBJECT TABLE................................................124
REF AND DEREF OPERATOR...............................................................................125
OBJECT WITH METHODS.......................................................................................128
CALLING A METHOD............................................................................................129

Chapter 12

Using Lobs
LARGE OBJECTS (LOB).......................................................................................132
CREATING TABLE WITH LOBS..............................................................................132
INSERTING VALUES ON THE TABLE.......................................................................132
UPDATING LOB VALUES.......................................................................................133
DATA MANIPULATION IN LOBS...........................................................................133
WORKING WITH DBMS_LOB PACKAGE..............................................................134

Chapter 13

Collections in Oracle
COLLECTIONS.......................................................................................................139
NESTED TABLES...................................................................................................139
CREATING TABLE USING NESTED TABLE..............................................................139
DML OPERATIONS ON NESTED TABLE.................................................................140
NESTED TABLE IN PL/SQL..................................................................................140
VARRAYS............................................................................................................141
CREATING VARRAYS..........................................................................................141
DML OPERATIONS WITH VARRAYS....................................................................142
VARRAYS IN PL/SQL.........................................................................................142
SIMILARITIES AND DIFFERENCES BETWEEN NESTED TABLE AND VARRAYS.....143
Appendix A
Appendix B
Appendix C
Project

SQL Reserved Word


Table Structure
Hands On Session

Page 4

Page No : 144
Page No : 145
Page No : 146
Page No : 149

Chapter 1
Snapshots

Approaches to Database Management


Database Management An Evolutionary phenomenon
Introduction to DBMS
Concept of DBMS
Database Models
Characteristics of Relational Database Management System
The 12 rules for an RDBMS ( Codd's Rule )
Information Representation
Application Development Cycle
Database Designing
ER Diagram
Degree of relationship
Normalization
Need for normalization
Steps in normalization
Invoice Management System
Oracle as an Object Oriented DBMS
Features of Oracle

Page 5

Introduction to RDBMS and Oracle

Objectives

After studying this chapter, the student should be able to :


Understand the features of an Object Oriented Database Management System
( OODBMS )
Design Database
Draw E-R Diagrams
Normalize Data Structure
Understand Oracle as an Object Oriented Database Management System ( OODBMS )

Page 6

Introduction to RDBMS and Oracle

Approaches to Database Management


Manual methods of Data Management
Management of Data and Information
Convenient and efficient retrieval
Updating operations
Limitation of Manual Data Management
Physical volume of Data
Human processing of Data
Technological advancement in Data Management
Using computers to speed up processing of Data
Advancement of processing power
Using time-sharing for multiple users
High-speed storage device
Centralize to distributed Database
Centralize to distributed processing (Client-Server)

Database Management an Evolutionary phenomenon


The evolution of database management was accompanied and promoted by:
Advances in computing: Hardware, Operating Syatem and Networking
Drawbacks of the prevalent approach to data management
Data redundancy
Risk to data integrity
Data isolation
Difficult access to data
Unsatisfactory security measures
Poor support of parallel access of data
Data redundancy
Since the files and application programs are written over a long period of time, data in the files is
likely to get repeated. This may also lead to inconsistency that is; the various copies of the same
data may contain different information. Data redundancy could also occur due to duplication of
data at different locations the need for the same data at physically different locations.
Risk to data integrity
The data value stored must satisfy certain integrity constraints. These constraints can be enforced
in the system, by adding appropriate code in the application programs. The problem is
compounded when constraints involves several data items for different files.
Data Isolation
Since data is scattered in various files, and files may be in different formats, it is difficult to write
new application programs to retrieve the appropriate data.
Page 7

Introduction to RDBMS and Oracle

Difficult access to data


Whenever there is a new request, that was not anticipated earlier, there are two possible
solutions. Either extract the records manually by mentioning the indexes, access methods, or
have the system programmer write the necessary application again with minor changes. This
leads to the repeated task of programmer for daily requirements.
Unsatisfactory security measures
Every user of the system should be allowed to view only that part of the data that is relevant to
his department. Since application programs are added to the system in an ad-hoc manner, it is
difficult to enforce such integrity constraints.
Concurrent access
Many systems allow multiple users to update the data simultaneously to improve the overall
performance of the system and obtain a faster response. But in such an environment interaction
of concurrent updates may result in inconsistent data. Since the application programs, which
have not been previously coordinated, are used access data, supervision is very difficult to
provide.
Database management addressed all this problems, though at the price of increased overheads
and costs. However, with the advancement of technology and the all-round development made in
hardware, software, networking and OS, the drawbacks of data management have been
eliminated to a great extent.

Introduction to DBMS
A programmers productivity tool
Good User Interface
Powerful Database Structure
Advancement of Data Manipulations
Use of 4 GL Tools
A discipline towards data independence
Logical Data Independence
Physical Data Independence
Data View
External View
Conceptual View
Internal View

Concept of DBMS
A Database is a collection of interrelated data from which some information can be extracted. A
database is designed and built for a specific purpose, keeping in mind the needs of the

Page 8

Introduction to RDBMS and Oracle


applications that are going to use it and the end users of those applications. It is managed by a
software package known as a Database Management System ( DBMS ).
A DBMS is a general-purpose software system that enables users to define and manipulate
databases. It provides an environment, wherein data can be stored and retrieved from database
easily and most efficiently. The DBMS is the software used to create and maintain the database.

Database Models
Hierarchical
Network
Relational
Hierarchical Model
This model was introduced in the Information Management System ( IMS ) developed by IBM
in 1968. This model is like a hierarchical tree structure, used to construct a hierarchy of records
in the form of nodes and branches. The data elements present in the structure have a ParentChild relationship. A parent unit may have many child units, but a child is restricted to have only
one parent. This leads to the repetition of same child record for different parents.
The drawbacks of this model are:
1. The hierarchical structure is not flexible enough to represent all the relationship proportions
which occur in the real world.
2. It can not demonstrate the over all data model for the enterprise because of the nonavailability of actual data at the time of designing the data model.
3. It can not represent the Many-to-Many relationship.
4. The hierarchical model is used only when the concerned data has a clearly hierarchical
character with a single root, for example DOS directory structure.
Network Model
It is improvement on the hierarchical model. Here multiple parent-child relationships are used.
Rapid and easy access to data is possible in this model due to multiple access paths to the data
elements.
Transaction is maintained using pointers and tracing the pointers is the drawback of this design.
Relational Model
Data is organized in terms of rows and columns in a table known as relations.
The position of a row in a table is of no importance.
The intersection of a row and column must give a single value and not a set of values.
All values appearing in the columns are derived from the underlying schema.
Row must be unique.
Column name must be unique.
All column values are atomic.

Page 9

Introduction to RDBMS and Oracle


In relational database, there are no hard-coded relationships defined between tables. A
relationship can be specified at any time using any column names.
The publication of the paper A relational model of Data for large shared database by E.F. Codd
in June, 1970 in the Communication of ACM, set a trend for vigorous and extensive investigation
into a theoretical frame work to support further work in the area of data modeling. The end result
is the Relational Database Management Systems.
Supplier
Scode
S01
S02
S03
S04

Sname
Agarwal
Patni
Chandra
Keshav

Sstatus
15
20
25
15

SCity
Delhi
Pune
Mumbai
Patna

Parts
Pcode
P01
P02
P03
P04

Pname
Screw
Nut
Bolt
Nut

Weight
8
16
20
16

Pcity
Delhi
Pune
Mumbai
Patna

Shipment
Scode
S01
S01
S02
S02
S03

Pcode
P01
P02
P03
P04
P01

Qty
150
200
250
100
300

Consider the tables shown in the sample database. In table Shipment, each supplier status has a
unique supplier code which uniquely identifies the entire row of the table and exactly one name,
and city. Likewise each part has a unique Pcode and exactly one name, size and city and at any
given time on more than one shipment exists for a given supplier/part combination.
The term Relation is used to describe these tables, which is more precise way of defining than
the traditional data processing term File or Table. Rows of such table are referred to as Tuples,
again a more precise definition than rows or records and columns are referred to as Attribute. In
relational data structure is that association between tuples are represented solely by data values in
columns.
External View

Conceptual View

Internal View

User Level
Admin Level
Hardware Level
Mapping to achieve logical
Mapping to achieve physical
Page 10
data independence
data independence

Introduction to RDBMS and Oracle

Characteristics of Relational Database Management System


Relational database have the following three major characteristics that constitute a well defined
RDBMS:
Structures
These are objects that store or access data from the database. Tables, views and indexes are
examples of structures.
Operations
These are the actions used to defined the structures or manipulate data between the structures.
SELECT or CREATE statements are examples of operations.
Integrity rules
These govern the kinds of actions allowed on data and the database structure. Integrity rules
protect the data and the structure of the database. The primary keys and foreign keys are the
example of integrity rules.

The 12 rules for an RDBMS ( Codds Rule )

Information Representation
Guaranteed Access
Systematic Treatment of null values
Database Description rule
Comprehensive Data Sub-language
View Updating
High Level Insert, Update and Delete
Physical Data Independence
Logical Data Independence
The Distribution rule
Non-subversion
Integrity rule

E.F. Codd formulated 12 rules for RDBMS in 1970. In addition to the 12 rules, there exists a
rule, called rule ZERO, which states:
A relational system must be able to manage databases entirely through its relational capabilities.
Any DBMS that advices users to the some non-relational methods to achieve acceptable
performance should be interpreted as an apology by the vendor.

Information Representation
In the relational model all the information is explicitly and logically represented by the data
values in the tables. This means that even such information as table, view, column names etc.
Page 11

Introduction to RDBMS and Oracle


should be contained somewhere as a table form. This makes it necessary for the provision of an
active data dictionary that, itself, is relational in nature.

Guaranteed Access
This rule refers to the fact that the table can be taken as a storage structure and at the intersection
of each column and row there will necessarily be only one value of data (or null). Every value of
data must be logically addressable by using a combination of table name, primary key value and
column name.
Systematic Treatment of null values
In database management system null values are supported for the representation of missing and
in-applicable application. This support for null values must be consistent throughout the DBMS,
an independent of data types ( for example, a null value in Char field must mean the same as in
an Integer field ).
Database Description rule
A description of the database is stored and maintained the form of tables as is done while
defining the data. This allows the uses with appropriate authority to query such information in
same ways and using the same languages as they would any data in the database. This implies
that a data dictionary should be present within the RDBMS that is constructed of tables and / or
views that can be examined using the SQL.
Comprehensive Data Sub-language
The RDBMS must be completely manageable through its own extension of SQL, although some
systems still support SQL like language (e.g. INGRESS support QUEL). The SQL should
support data definition, views, data manipulation, integrity constraints, authorization, and
transaction boundary.
View Updating
It is a myth that all views that can be updated in theory, can also be updated by the system itself.
Though it is possible to create views with all sort of aggregate and virtual columns, it is
obviously not possible to update through some of them.
High Level Insert, Update and Delete
An RDBMS must do more than just be able to retrieve relational data sets. It has to be capable of
inserting, updating and deleting data as a relational set. A database can not be called relational, if
it uses a single record at time procedural technique when it comes to manipulating the data.
Physical Data Independence
User access to database, via monitors or application programs, must remain logically consistent
even when changes to the storage representation, or access methods to the data are changed.
Logical Data Independence
Application programs must be independent of the changes made to the base tables. This rule
allows many types of database design changes to be made dynamically, without the users being

Page 12

Introduction to RDBMS and Oracle


aware of them. A single table should be divisible into one or more other tables, provided it
preserves all the original data (non-loss), and maintains the primary key in each and every
fragment/table.
The Distribution rule
An RDBMS must have distribution independence. This use one of the most attractive aspects of
the RDBMS. Database systems built on the relational framework are well suited to todays
client-server database design.
Non-subversion
If an RDBMS supports a lower level language that permits for examples, row-at-a-time
processing, then this language must not be able to bypass any integrity rules or constraints of the
relational language. Thus, an RDBMS must be governed by relational rules as its primary laws.
Integrity rule
Integrity constraints specific to a particular relational database must be definable in the relational
data sub-languages and storable in the catalogue, not in the application programs.
An RDBMS product has to satisfy at least six of the twelve rules of Codd to be accepted as a
full fledged RDBMS.

Application Development Cycle


A well designed database makes the application programming and tuning much easier. Before
going into the details of database design and modeling, lets review the stages involved in
application development.
Analysis
This is the first stage of an application development, and it should enable you to answer the
following questions:
1. Why is the application being developed?
2. Who is going to use it?
3. How will the application benefit the users?
4. What business rules and needs should be addressed?
The complete functionalities of the system should be determined in requirement analysis.
Typically, functional-level managers take care of this phase.
Design
This is the most important phase of application development. After the application requirements
are analyzed, the design phase begins. In this phase, the database design is performed using ER
diagrams. The logical database design is converted to physical structures.
Development
In the development phase, coding is done based on the design; you use the end product of the
design phase of the life cycle as a building block for the development process. The database
Page 13

Introduction to RDBMS and Oracle


design and the designed system requirements provide the basis for the development of the
application.
Testing
The developed application is tested against its objectives to ensure that it is doing what it is
supposed to do. System/Integration testing is done on the entire system. Any errors are corrected,
and the application is tested again. Application users do the acceptance testing.
Implementation
Implementation is the final stage in the development cycle. Once the testing is complete, the
application is ready to implement. Errors reported after implementation is fixed by going back to
the appropriate stage.

Database Designing
Requirement, formulation and analysis
Collection and documentation of requirement
Analysis of requirement
Conceptual design
Data Modeling
1st Level ER (Entity-Relationship) Modeling
nd
2 Level Normalization
Physical Model
Requirement, formulation and analysis
The objective of this phase to answer the following question:
What are user views of the data (Present and Future)?
What data elements are required in these user views?
What are the entities and their primary keys?
What are the operational requirements regarding security, integrity and response time?
Conceptual Design
The major step in conceptual design is to identify the entities and relationships that reflect the
organizations data. The objective of this step is to specify the conceptual structure of the data
and is often referred to as data modeling. The ER model, with an emphasis on the top-down
approach.
Data Modeling
Data modeling is achieved in two levels; the 1 st level builds the conceptual model of the data,
using ER modeling. The 2nd level organizes this model better, by removing redundancies, through
a process called normalization. The normalized model is then converted into the physical
database.
Physical Model

Page 14

Name
Introduction to RDBMS and Oracle
You create a physical model by using the logical model to assist in creating a database and
database objects to represents to entities and relationships. In the physical model, each entity
becomes a table, and attributes of the entity become columns of the table. The relationship
between the entities is part of one or more constraints between the tables. Physical
implementation might require you to combine, separate, or create completely new entities in
order to best realize the logical model. The unique identifiers of an entity become the primary
key of the table. You may create stored procedures, functions and triggers to enforce business
rules.

ER Diagram
Entity Relationship modeling is a technique for analysis and logical modeling of the system data
requirements. It uses three basic concepts, entities, their attributes and the relationship that exists
between the entities. It uses graphical notation for representing these.
Graphical notation for ER diagram
NAME

SYMBOL

Entity
Attribute
Relationship

FUNCTION
Data object in the system
uniquely identifiable by
identifier has attributes that
describe it.
Describes an entity

Relation

Relates two entities uniquely


identified by the identifier

Entity
An entity is an object, place, person, concept, activity about which an enterprise records data. It
is an object which can have instances or occurrences. Each instance should be capable of being
uniquely identified. Each entity has certain properties or attributes associated with it and
operation applicable to it. Entity type and entity instance are two important term related to
entities. An entity type is a set of things which shares common properties. An entity type is
usually denoted in upper case. An entity instance is a specific individual thing. An entity instance
is usually denoted in lower case.
Example of entity type: STUDENT COURSE, COURSEWARE DEVELOPMENT TEAM etc.
Example of entity instance: sudipta, physics etc.
Attributes
Attributes are data element that describes an entity. If the attribute of an entity has more
attributes that describe it, then it is not an attribute of that entity, but another entity. Attributes can
either be listed next to the entities, or placed in circle and attached to the entity. Identifier is one
or more attributes of an entity or relation, whose value uniquely identifies the entities or
relationships.

Page 15

Introduction to RDBMS and Oracle


Relationship
This is an association between entities. It is represented by a diamond in the ER diagram.
Relationship can also have properties and attributes associated with it.

Page 16

Introduction to RDBMS and Oracle

Degree of relationship
ONE to ONE (1:1)
ONE to MANY(1:N)
MANY to MANY(N:N)
The degree of relationship indicates the link between two entities for a specified occurrence of
each. The degree of relationship is also called cardinality.
ONE to ONE
This relationship is one in which each occurrence of one entity is represented by single
occurrence in another entity. For example, consider an individual and that individuals social
security number: One person can have only one social security number, and a social security
number can belong to only one person.
Person

Social Security Number

ONE to MANY
This relationship is one in which an occurrence of one entity may be represented by many
occurrence in another entity. An example is department and employees: One department has one
or more employees, and an employee belongs to only one department.
Department

Employee

MANY to MANY
This relationship in which an occurrence from one entity may be represented by one or more
occurrence in another entity, and an occurrence from second entity may be represented by one or
more occurrence in the first entity. The relationship between Doctor and Patient is an example: A
patient can visit many doctors, and a doctor can have many patients.
Doctor

Patient

Note: MANY to MANY relationship should not exists in RDBMS because they can not be
properly joined to represent a single row correctly. To solve this, create another entity that has a
ONE to MANY relationship with the first entity and a ONE to MANY relationship with the
second entity.
When you have established the relationship between entities, it is time to normalize the design.

Page 17

Introduction to RDBMS and Oracle

Normalization
Refinement of the ER Model.
Segregation of data over many entities or tables.
Normalized model converted to physical database tables.
Normalization is the process of refining the data model built by the ER Diagram. The
normalization technique, logically groups the data over a number of tables, with minimum
redundancy of data.
The goal of the relational data base design is to generate a set of relation scheme that allows us to
information with minimum redundancy of data and allow us to retrieve information easily and
efficiently.
The first step towards normalization is to convert the ER model into tables or relations. The next
step is to examine the tables for redundancy and if necessary, change them to non-redundant
forms. This non-redundant model is then converted to a database definition.

Need for normalization

Improves database design.


Ensures minimum redundancy of data.
Reduces need to re-organize data when design is modified/enhanced.
Removes anomalies for database activities.

Un-Normalized Data Structure


Supplier
Code
S01
S02
S03
S04
S05
S06

Supplier
Name
Agarwal
Patni
Chandra
Keshav
Bhushan
Menon

Supplier
Status
15
20
25
15
25
15

City
Supplier
Delhi
Pune
Mumbai
Patna
Kolkata
Guahati

Part
Code
101
102
103
102
104
102

Part
Name
Screw
Nut
Bolt
Nut
Bolt
Nut

Weight Qty City Sold


8
16
20
16
20
16

500
250
250
300
50
200

Kolkata
Meerut
Ranchi
Silvasa
Pune
Patna

Above table structure presents several difficulties in operations like:


Insertion in fields If new field is introduced into the system, it can not be added to the
database, until becomes related to another existing field, e.g. if supplier name is introduced its
details can not be entered in the table unless a part name is represent for that supplier.
Updation of fields If the supplier code of a supplier is to be modified, it has to be changed
throughout the table, in all occurrence of the supplier record. Missing out even a single
correction, would result in incorrect data.

Page 18

Introduction to RDBMS and Oracle


Deletion of fields If information related to a specific column is to be deleted, the entire row
has to be deleted, which results in loss of required information. For example, if the row of the
supplier Saleh is deleted, the information about the part name is lost. Deletion of supplier detail
also deletes other details.

Steps in normalization
First Normal Form (1NF)
Identify a repeating fields
Remove repeating groups to a separate table
Identify the keys for the table
Key the parent table is brought as part of the concatenated key of the second table
Second Normal Form (2NF)
Check if all fields is dependent on the whole key
Remove fields that depend on part of the key
Group partially-dependent fields as a separate table
Name the tables
Identify key(s) to the table(s)
Third Normal Form(3NF)
Remove fields that
Depend on other non-key attribute
Can be calculated or derived from logic
Group independent fields as separate tables, identify the key and name of the table

Invoice Management System


An invoice management system accepts items and customer details from the user and prepares
invoices. The item details include item description, quantity sold, rate and discount (if
applicable). For each order the customer is given an invoice. Each invoice can have details of
more than one item.
The raw table containing invoices details: Un-normalized
Invno
112
112
113
114
114

Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97

Ordno
1
2
1
1
2

Chlno
1
1
1
1
1

Custno
C1
C1
C4
C1
C1

Custnm
Ashoke
Ashoke
Vipul
Ashoke
Ashoke

Itno
I1
I2
I3
I8
I2

Itdesc
Pepsi
Butter
Bread
Biscuit
Butter

Qty
2
1
1
2
4

Rate
8
22
12
22
22

Dis
Nil
Nil
Nil
Nil
Nil

Inval
16
22
12
44
88

First Normal Form


The attributes invno, invdate, ordno, chlno, custno and inv_val are repeating groups in the
invoice table. These attributes can be are split into a separate table called invoice table which
contains the invno, invdate, ordno, chlno, custno and inval.

Page 19

Introduction to RDBMS and Oracle


The identifier of this table is invno. The other table is called invoice items which contains invno,
into, itdesc, qty, rate and dis. The identifier of this table is invno and into which identifies a
single row.

Page 20

Introduction to RDBMS and Oracle


Invoice Table
Invno
112
112
113
114
114

Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97

Ordno
1
2
1
1
2

Chlno
1
1
1
1
1

Custno
C1
C1
C4
C1
C1

Custnm
Ashoke
Ashoke
Vipul
Ashoke
Ashoke

Inval
16
22
12
44
88

Invoice Items
Invno
112
112
113
114
114

Itno
I1
I2
I3
I8
I2

Itdesc
Pepsi
Butter
Bread
Biscuit
Butter

Qty
2
1
1
2
4

Rate
8
22
12
22
22

Dis
Nil
Nil
Nil
Nil
Nil

Second Normal Form


The invoice item table is further split, by removing itdesc and rate which are not dependent on
the full concatenated key (invno+itno). The new table is named as ITEMS table which contains
itdesc, rate and itno as its primary key. The identifier of this table is itno, which identifies a
single row.
The remaining attributes in the invoice item table consists only of, invno, itno, qty and dis. The
identifier here is invno+itno which identifies a single row. Here each elements is dependant on
full concatenated key.
Invoice Table
Invno
112
112
113
114
114

Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97

Ordno
1
2
1
1
2

Chlno
1
1
1
1
1

Custno
C1
C1
C4
C1
C1

Custnm
Ashoke
Ashoke
Vipul
Ashoke
Ashoke

Invoice Items
Invno
112
112
113
114
114

Itno
I1
I2
I3
I8
I2

Qty
2
1
1
2
4

Dis
Nil
Nil
Nil
Nil
Nil

Page 21

Inval
16
22
12
44
88

Introduction to RDBMS and Oracle


Item Table
Itno
I1
I2
I3
I8
I2

Itdesc
Pepsi
Butter
Bread
Biscuit
Butter

Rate
8
22
12
22
22

Third Normal Form


The invoice table derived from the un-normalized table is now in the second form can be further
normalized. There is still a dependency between non-key attributes: custnm depends upon
custno, a non-key attribute. custnm is removed to the CUSTOMER table, with custno as the key.
The remaining attributes remain in the INVOICE table with invno as the key.
Invoice Table
Invno
112
112
113
114
114

Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97

Ordno
1
2
1
1
2

Chlno
1
1
1
1
1

Custno
C1
C1
C4
C1
C1

In_val
16
22
12
44
88

Customer Table
Custno Custnm
C1
Ashoke
C4
Vipul
Invoice Items
Invno
112
112
113
114
114

Itno
I1
I2
I3
I8
I2

Qty
2
1
1
2
4

Dis
Nil
Nil
Nil
Nil
Nil

Page 22

Introduction to RDBMS and Oracle


Item Table
Itno
I1
I2
I3
I8
I2

Itdesc
Pepsi
Butter
Bread
Biscuit
Butter

Rate
8
22
12
22
22

Oracle as an Object Oriented DBMS


Oracle is an ORDBMS. It lets you define user defined object types in the relational database
system. Object types are structures that consists of built-in or user-defined data types. For
example, an address can be defined as an object type and can be referenced in tables:
Customer_Table
Cust_name
Cust_addr
Cust_phone
Cust_fax

Varchar2(40)
Address_Type
Varchar2(12)
Varchar2(12)

Where Address_type is an object type defined as


Address_Type
Street Street_Type
City Varchar2(30)
State Char(2)
Zip
Number(5)
Where Street_Type is defined as :
Street_Type
Street_number
Street_name1
Street_name2
Apartment_no

Number(6)
Varchar2(40)
Varchar2(40)
Varchar2(5)

Now that the Address_Type is defined, it can be used in number of tables where addresses need
to be stored. This small example shows the reusability of objects.

Page 23

Introduction to RDBMS and Oracle

Features of Oracle
High transaction processing performance All the facilities for transaction and its recovery in
case of any failure are supported in Oracle for better performance of transaction processing.
Industry accepted standards All the recent technologies like object oriented technology and
distributed data processing are supported in Oracle .
Manageable Security Very strong security provisions are there inside Oracle to guard against
malicious users.
Large database support In supporting large database, Oracle is more reliable compared to any
other database packages.
Concurrent Processing More than one user can work simultaneously on the same database
without any interference.
Client/Server environment It supports client server technology i.e. the server contains the
main database and clients ( users ) can access the database to fetch and manage only that data for
which they are given the authorization.
Distributed database system Oracle supports distributed environment i.e. applications made
on different platforms and in different environments can exchange the data with the common
interface language called Interface Definition Language ( IDL ).
Portability Runtime models made inside Oracle environment can run without any changes on
other compatible platforms easily.
Compatibility It is compatible with all sorts of front ends although, Oracle has its own front
end but still Oracle database can be used with other front ends like Visual Basic, VC++ etc.
easily.

Page 24

Chapter 2

Snapshots

Introduction to SQL
Oracle Data Types
Starting SQL* Plus editor
Operators and Expressions
Querying DataBase Tables
RollUp Operation - Getting sub totals
Cube Operation - Getting cross tabs

Page 25

Introduction to SQL

Objectives

After studying this chapter, the student should be able to :


Understand the Structured Query Language ( SQL )
Understand the Datatypes supported by Oracle
Log on to Oracle
Query database tables using SQL statement
Understand how to use Aggregate Functions
Understand Order by and Group by clause
Understand ROLLUP and CUBE operation

Page 26

Introduction to SQL

Introduction to SQL

The language used to access data within Oracle database


Developed in a prototype RDBMS, System R, by IBM in mid 1970s
Oracle Corporation introduced the first commercially available implementation of SQL
ANSI adopted SQL as a standard language for RDBMS in October 1986
Key features of SQL are:
Non-procedural language
Unified language
Common language for relational database

SQL (Structured Query Language) pronounced as see-quell is made of three sub-languages


such as:
Data Definition Language (DDL): Consists of commands Create, Alter, Drop to create or remove
objects such as Tables, Views, and Indexes etc.
Data Manipulation Language (DML): Used for query, Insertion, Deletion and Updation of
information stored in the database.
Data Control Language (DCL): Used for controlling data and access to the databases. Examples:
Commit, Rollback.
SQL *Plus is a software product from Oracle Corporation that allows users to interactively use
the SQL commands, produce formatted reports and support written command procedures to
access Oracle database.
Through SQL *Plus a user can:
Enter, edit, store, retrieve and run SQL commands
Format, perform calculation, store, print query result in the form of reports
List column definition of any table
Access and copy data between SQL databases
Send messages to and accept responses from an end user

Oracle Data Types


When you create a table to store data in the database, you need to specify a datatype for all
columns to define in the table. Oracle has different datatypes to suit your needs. The datatype
are broadly classified into Character, Number, Date, LOB and RAW datatypes. Oracle lets you
use user-defined datatypes, but they are constructed from the basic datatypes.
CHAR
VARCHAR
VARCHAR2
LONG

BLOB
CLOB
BFILE

NUMBER
DATE

Page 27

RAW
LONG RAW

Introduction to SQL

Character Datatypes
Character datatypes are used to store alphanumeric data. When you define character data in
Oracle , you specify a length for the column, which is the maximum width of the column. In
Oracle you can have different type of datatype to store alphanumeric value:
CHAR(<size>) The CHAR datatype is a fixed-length character string having a maximum
length of size. Data stored in CHAR column is space-padded to fill the maximum length. The
size can range from a minimum of 1 to maximum of 2000 characters.
When you create a column using the CHAR datatype, the database will ensure that all data
placed in this column has the defined length. If data is shorter than the defined length, it is spacepadded on right to the specified length. If the data is longer, an error is raised.
VARCHAR(<size>) A VARCHAR datatype in Oracle is synonymous with the VARCHAR2
datatype.
VARCHAR2(<size>) The VARCHAR2 datatype is a variable-length alphanumeric string
having a maximum length of size bytes. VARCHAR2 variables only require the amount of space
needed to store the data. VARCHAR2 database columns can store up to 4000 bytes and
VARCHAR2 variables up to 32676 bytes. An empty VARCHAR2(2000) column takes up as
much room in the database as an empty VARCHAR2(2) column.
The default size of the CHAR datatype is 1. In VARCHAR2, you must always specify the size.
LONG The LONG datatype is a legacy datatype that will no longer be supported in the future.
It has been deprecated in favor of large object datatype. A LONG datatype column is of variable
length and can take up to 2GB. There are many restriction on the use of LONG columns and
variables. LONG columns can not appear in Where clause, Group By clause, Order By clause or
with the Distinct operator in Select statements.
Numeric Datatype
Numeric datatype are used to store negative and positive integers: fixed-point and floating-point
numbers with a precision of up to 38 digits. Specifying a number outside this range will raise an
error.
Number(<p>,<s>) The number datatype stores numbers with a precision of p digits and a
scale of s digits. The precision and the scale value are optional. Specifying the scale and
precision does not force all inserted values to be a fixed length. If the number exceeds the
precision, however, an Oracle error is returned. If the number exceed the scale, it is rounded to
the scale. If the scale is negative, the number is rounded to the left of the decimal. Basically, a
negative scale forces s number of zeros just to the left of the decimal.

Page 28

Introduction to SQL

Precision and scale example


Actual Value
1234567.89
1234567.89
1234567.89
1234567.89
1234567.89
1234567.89
1234567.89
1234511.89
1234567.89
1234567.89

Datatype
Number
Number(8)
Number(6)
Number(9,1)
Number(9,3)
Number(7,2)
Number(5,-2)
Number(5,-2)
Number(5,-4)
Number(*,1)

Stored Value
1234567.89
1234568
Numeric Error
1234567.9
Numeric Error
Numeric Error
1234600
1234500
1230000
1234567.9

Date Datatype
The Date datatype is used to store date and time information. This datatype can be converted to
other forms for viewing, and it has number of special functions and properties that makes date
manipulation and calculation simple. The Date datatype occupies a storage space of 7 bytes. The
following information is contained within each date datatype:

Century

Year

Month

Day

Hour

Minute

Second

The default format for Oracle Date datatype is DD-Mon-YY; this is the format shown whenever
a date is selected within SQL *Plus.
LOB Datatype
Large object datatypes store blocks of unstructured data, such as a binary file, a picture, or an
external file. A LOB can store data up to 4GB. The data may be stored in the database or in an
external file. LOB data maniputaion is done using the DBMS_LOB package.
Datatype Purpose
BLOB
Binary Large Object
CLOB
Character Large Object
BFILE

Binary File

Description
Can store up to 4GB of binary data in the database.
Can store up to 4GB of character data in the database.
Oracle converts the data into Unicode format and stores it
in the database.
Stores binary data up to 4GB in operating system files
outside of the database. The size of the binary file must
conform with operating system limitations on file size. A
BFILE column stores a file locator that points to an
external file containing the data. BFILE datatypes are
read-only; You can not modify them.

Page 29

Introduction to SQL
Note : There may be more than one LOB datatype column in a table, but there can be only one
LONG datatype column.
Other Datatypes
Oracle has RAW datatypes in addition to the character, numeric and date datatypes.
RAW RAW is unstructured, binary data that is not interpreted by the database. RAW columns
can be up to 2000 bytes long.
LONGRAW Like the LONG datatype, LONGRAW is a legacy datatype that has been
deprecated in favor of the LOB datatypes BLOB or BFILE. LONGRAWs can store up to 2GB of
unstructured data. LONGRAW data cannot be indexed, but RAW data can be indexed.
Literals
Literals are values that represent a fixed value. There are three types of literals values:
Text
Integer
Number
Text literals must be enclosed in single quotes; integer and number literals need not be. You can
use literals within many of the SQL functions, expressions and conditions.
Text The text literal must be enclosed in single quotation marks. Any character between the
quotation marks is considered part of the text value. Oracle treats all text literals as though they
were CHAR datatypes. The maximum length of a text literal is 2,000 characters. Single quotation
marks can be included in the literal text value by preceeding it with another single quotation
mark.
Here are some examples:
The quick brown fox
That mans suit is black
And I quote:This will never do.
Integer Integer literals can be any number of numerals, excluding a decimal separator and up
to 38 digits long.
Examples follow:
24
-456
Number Number literals can include scientific notation, as well as digits and the decimal
separator.
Here are some example:
24
-345.65
Page 30

Introduction to SQL

23E10

Starting SQL* Plus editor


Step I : Locate the Oracle short cut in your desktop. If it is not there try to get it from
Start>Programs menu.

The SQL Plus Short Cut

Step II : Double click or press <Enter> on the short cut shown above.
Step III : Provide the User Name, Password and Connect String in the dialog shown. The
Connect String is nothing but the Database name.

Page 31

Introduction to SQL
After providing the User Name, Password and Connect String click on the OK button. If all the
information you have provided is correct then you will get the following screen.

Tables used in Examples


DEPT EMP

Contains information about the departments in the company


Contains information about the employees of that company

Structure of DEPT table

Column
names
DEPTNO
DNAME
LOC

Type(Size)
NUMBER(2)
VARCHAR2(20)
VARCHAR2(10)

Description
Department number
Department name
Location of the department

Data of DEPT Table :

Page 32

Constraints
Primary Key
NOT NULL
NOT NULL

Introduction to SQL

Structure of EMP table

Column
names
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO

Type(Size)

Description

NUMBER(4)
VARCHAR2(20)
VARCHAR2(10)
NUMBER(4)
DATE
NUMBER(9,2)
NUMBER(7,2)
NUMBER(2)

Employee number
Employee name
Designation
Respective managers EMPNO
Date of Joining
Basic Salary
Commission
Department number

Constraints
Primary Key
NOT NULL
NOT NULL
NOT NULL
NOT NULL
NOT NULL, Foreign
Key

Data of EMP Table :

Operators and Expressions


An operator is a manipulator that is applied to a data item in order to return a result. Special
characters represent different operations in Oracle. Operators may be classified into two types :
Unary Operators : A unary operator has only one operands. +2 and 5 are examples. They have
the format < operator operand >
Binary Operators : Binary operators have two operands. 5+4 and 7 x 5 are examples. They
have the format < operand1 operator operand2 >

Page 33

Introduction to SQL

Arithmetic Operators
Arithmetic operators operate on numeric datatypes.
Operator Purpose
+Unary operators: Use to represent positive or negative data item. For
positive items, the + is optional.
+
Addition: Use to add two data items or expressions.
Subtraction: Use to find the difference between two data items or
expressions.
*
Multiplication: Use to multiply two data items or expressions.
/
Division: Use to divide a data items or expression with another.

Example
-234.45
3+7
7-5
5 * 10
8/4

Concatenation Operator
This operator is used to concatenate or join two character ( text ) strings. The result of
concatenation is another character string. If one of the strings is NULL, the result is also NULL.
Concatenating a zero-length string( ) with another string results in a string, not a NULL. Two
vertical bars ( || ) are used as the concatenation operator. Here are a few examples:

Oracle || Database results in OracleDatabase


Oracle || Database results in Oracle Database

Comparison Operator
Comparison operators compare two values or expression and give a Boolean result of TRUE,
FALSE, or NULL. Comparison operators are mainly used in the WHERE clause of the SQL
statement.
Operator
=

Purpose

Example
SELECT * FROM emp WHERE
ename=SCOTT;
SELECT * FROM emp WHERE
ename!=SCOTT;

Equality test

!=
<>
^=
<

Inequality test

>

Greater than test

>=

Greater than equal to

Less than test

SELECT * FROM emp WHERE


sal<2000;
SELECT * FROM emp WHERE
sal>2000;
SELECT * FROM emp WHERE

Page 34

Introduction to SQL
sal>=2000;
SELECT * FROM emp WHERE
sal<=2000;

<=

Less than equal to

Operator
[NOT] IN

Purpose
Example
Equal to any member of test. If NOT is SELECT * FROM emp WHERE
used, evaluates to TRUE if the value is not deptno IN (10,20);
in the member list.
SELECT * FROM emp WHERE
deptno NOT IN (10,20);
Compares a value to each value in a list or SELECT * FROM emp WHERE
return by a query. Must be preceded by =, ! sal<=ANY(SELECT sal FROM
=, <, >, <=, >=. Evaluates to FALSE if the emp WHERE deptnp=10);
query returns no rows.
Compares a value to every value in a list or SELECT * FROM emp WHERE
return by a query. Must be preceded by =, ! sal<=ALL(500, 1200, 800);
=, <, >, <=, >=. Evaluates to TRUE if the
query returns no rows.
TRUE if value greater than or equal to a SELECT * FROM emp WHERE
and less than or equal to b. If NOT is used, sal BETWEEN 2000 AND 5000;
the result is the reverse.
TRUE is a sub query returns at least one SELECT * FROM emp WHERE
row.
deptno=10
AND
EXISTS(SELECT COUNT(*)
FROM emp WHERE deptno=10
GROUP BY deptno HAVING
COUNT(*) > 3);
Used for pattern matching. Wild card SELECT ename FROM emp
character % is used to match any string of WHERE ename=S%;
length zero or more characters and _ is used
to match any single character. Escape is
used to interpret % or _ literally.
The only operator used to test for NULL SELECT * FROM emp WHERE
values.
comm. IS NULL;

ANY
SOME
ALL

[NOT]
BETWEEN
a AND b
[NOT]
EXISTS

a [NOT]
LIKE b
[ESCAPE
char]
IS [NOT]
NULL

Logical Operators
Logical operators are used to combine the results of two comparison conditions to produce a
single result or to reverse the result of a single comparison.
Operator Purpose
NOT
Used to reverse the result. Evaluates to TRUE if
the operand is FALSE. Evaluates to FALSE if the
operand is TRUE. Returns NULL if the operand
is NULL.
AND
Evaluates to TRUE if both operands are TRUE.
Evaluates to FALSE if either operand is FALSE.
Otherwise returns NULL.
OR
Evaluates to TRUE if either operands are TRUE.
Page 35
Evaluates to FALSE if both operands are FALSE.
Otherwise returns NULL.

Example
SELECT * FROM emp
WHERE NOT (sal<1000);
SELECT * FROM emp
WHERE deptno=10 AND sal
>=2000;
SELECT * FROM emp
WHERE deptno=10 OR
deptno=30;

Introduction to SQL
Set Operators
Set operators are used to combine queries: Queries that combine the results of two queries. The
number of columns selected in both queries must be the same.
Operator
UNION

Purpose
Example
Returns all rows from either queries ; no SELECT job FROM emp
duplicate rows.
WHERE deptno=20 UNION
SELECT job FROM emp
WHERE deptno=30;
INTERSECT Returns distinct rows that are returned by both SELECT job FROM emp
the queries.
WHERE
deptno=20
INTERSECT SELECT job
FROM
emp
WHERE
deptno=30;
MINUS
Returns distinct rows that are returned by the 1st SELECT job FROM emp
query but not returned by the second.
WHERE deptno=20 MINUS
SELECT job FROM emp
WHERE deptno=30;
Expressions
An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value. An expression generally assumes the datatype of its components.
Expressions can appear in the following clauses:

The SELECT clause of queries


The WHERE clause
The VALUE clause of the INSERT statement
The SET clause of the UPDATE statement

Querying DataBase Tables


A query is a request for information from the database tables. Simple queries are those that
retrieve data from a single table. The basis of a query is the SELECT statement.
SELECT Statement
The SELECT statement is the most commonly used statement is SQL and is used to retrieve
information already stored in the database. The syntax for SELECT statement is:
SELECT <column list> FROM <table name>
[WHERE <condition>]
[GROUP BY <column name(s)>]
[HAVING <condition>]
[ORDER BY <expression>];

Page 36

Introduction to SQL

Example:
SELECT * FROM emp;
In the above statement the * indicates all the columns.
SELECT empno, ename FROM emp;
The above statement will display all employees code and their name.
Conditional Retrieval of Rows
The WHERE clause is used along with the SELECT statement to specify the condition. When a
WHERE clause is present, the database program goes though the entire table one row at a time
and examines each row to determine if the condition is TRUE with respect to row. It is not
necessary for the columns used in the where clause to be present among those selected for
output.
Example:
SELECT * FROM emp WHERE deptno=20;
This will display all the details of employees belonging to the department 20.
SELECT empno,ename FROM emp WHERE deptno=20 OR deptno=30;
Displays codes and names for all the employees for department 20 as well as 30.
SELECT empno,ename FROM emp WHERE deptno=20 AND job=CLERK;
Displays codes and names for all those employee of department 20 whose designation is
CLERK.
SELECT empno,ename FROM emp WHERE deptno!=20;
Displays codes and names for all the employees except department 20.
SELECT empno,ename FROM emp WHERE IN(20,30);
Displays codes and names for all the employees for department 20 as well 30.
SELECT ename,sal FROM emp WHERE sal BETWEEN 1000 AND 5000;
Displays names and salary for the employees whose salary is ranges between 1000 to 5000.
DISTINCT clause with SELECT
The DISTINCT clause is used with SELECT to suppress duplicate values if any in a column.
Example:
SELECT DISTINCT job FROM emp;
This will displays the different job category available in the emp table.

Page 37

Introduction to SQL

Working with NULL values

NULL values are not 0 or a blank


It represents an unknown or inapplicable value
It can not be compared using the relational or logical operators
The special operator IS is used with the keyword NULL to locate the NULL values

Example:
SELECT ename,comm FROM emp WHERE comm. IS NULL;
Displays names and commisions for all the employees who are not eligible for getting
commission.
SELECT ename,comm FROM emp WHERE comm. IS NOT NULL;
Displays names and commisions for all the employees who are eligible for getting commission.
Matching a pattern from a table
The LIKE operator is used only with CHAR and VARCHAR2 to match a pattern. Wild card
character % is used to match any string of length zero or more characters and _ is used to match
any single character.
Example:
SELECT ename FROM emp WHERE ename LIKE S%;
Displays names of those employees whose name starts with S ( not s )
SELECT ename FROM emp WHERE ename LIKE _____;
Displays names of those employees whose name have exactly 5 characters
Using expression with columns

Arithmetic computations can be done on numeric columns


Alias names can be given to columns and / or expressions on query outputs
Alias names are displayed in place of column names
Alias names are given to the right of a column name, enclosed within quotes

Example:
SELECT ename, sal, sal*.1 FROM emp;
Displays names, salary and PF amount of all the employees ( PF is calculated as 10% of salary).
We can provide an alias to the column sal*.1 as PF
SELECT ename, sal, sal*.1 PF FROM emp;
Page 38

Introduction to SQL

Ordering the result of a query


The SELECT statement may include the ORDER BY clause to sort the resulting rows in a
specific order based on data in the columns. Without the ORDER BY clause, there is no
guarantee that the rows will be returned in any specific order. The rows are returned by
ascending order of the columns specified; if you need to sort the rows in descending order, use
the keyword DESC nest to the column name.
Example:
SELECT ename, sal, FROM emp ORDER BY sal;
Display names and salary of all the employees in ascending order by salary.
Aggregate functions
The aggregate functions produce a single value for an entire group or table.
COUNT : Determine the number of rows of non NULL column values
SUM : Determines the sum of all selected columns
MAX : Determines the largest of all selected values of a columns
MIN : Determines the smallest of all selected values of a columns
AVG : Determines the average of all selected values of a columns
In all above functions, NULL are ignored.
COUNT : Determine the number of rows of non NULL column values. If * is passed, then the
total number of rows is returned.
Example:
SELECT COUNT( * ) FROM emp;
Display number of employees working with the company.
SELECT COUNT( distinct job ) FROM emp;
Display number of jobs available in the emp table.
SUM : Determines the sum of all selected columns.
Example:
SELECT SUM( sal ) FROM emp;
Display the total salaries payable to employees working with the company.

Page 39

Introduction to SQL

MAX : Determines the largest of all selected values of a columns. Note that DISTINCT and
ALL have no effect.
Example:
SELECT MAX( sal ) FROM emp;
Display the maximum salary payable to employee working with the company.
MIN : Determines the smallest of all selected values of a columns. Note that DISTINCT and
ALL have no effect.
Example:
SELECT MIN( sal ) FROM emp;
Display the minimum salary payable to employee working with the company.
AVG : Determines the average of all selected values of a columns.
Example:
SELECT AVG( sal ) FROM emp;
Display the average salary payable to employee working with the company.
Grouping the result of a query

The GROUP BY Clause is used to divide the rows in a table into smaller groups
The GROUP BY Clause is used with SELECT clause
SQL groups the result after it retrieves the rows from a table
Conditional retrieval of rows from a grouped result is possible with the HAVING clause

Example:
SELECT deptno,count( * ) FROM emp GROUP BY deptno;
Display the department number and number of employees in each department.

Groups within group

SELECT deptno, job, AVG(sal) FROM emp GROUP BY deptno, job;


Display the average monthly salary for each job type within department.

HAVING with GROUP BY

SELECT deptno, AVG(sal) FROM emp GROUP BY deptno HAVING COUNT(*) >3;
Display average salary for all departments employing more than five people.

Page 40

Introduction to SQL

RollUp Operation Getting sub totals


ROOLUP enables a SELECT statement to calculate multiple levels of subtotals across a
specified group of dimensions. It also calculates a grand total.
Example:
SELECT job, deptno, sum(sal) FROM emp GROUP BY ROLLUP(job, deptno);
Display the subtotal at different levels like job wise then department wise from the EMP table.

Cube Operation Getting cross tabs


The subtotals created by ROLLUP are only a fraction of possible subtotal combinations, whereas
CUBE enables a SELECT statement to calculate all possible combination of a group of
dimensions.
Example:
SELECT job, deptno, sum(sal) FROM emp GROUP BY CUBE(job, deptno);
Display the subtotal at different levels like job wise then department wise from the EMP table.

Page 41

Chapter 3

Snapshots

Multiple Table Queries


EQUI Join
CARTESIAN Join
OUTER Join
SELF Join
Using Set Operators
Sub Queries
Single-Row Sub Queries
Multiple-Row Sub Queries
Correlated Subqueries
Using special operators in subquery

Page 42

Multiple Table Queries

Objectives

After studying this chapter, the student should be able to :


Understand how to collate information using Joins
Understand the types of joining
Understand the different SET Operators
Different type of Nested Queries
Using some special Operators in Nested Queries

Page 43

Multiple Table Queries

Multiple Table Queries


In Relational Database Management Systems, data stored in different tables is related. You use
the power of SQL to relate the information and query data. A SELECT statement has a
mandatory SELECT clause and FROM clause. The SELECT clause can have a list of columns,
expressions, functions and so on. The FROM clause tells you which table(s) to look in for the
required information. So far, you have seen only one table in the FROM clause.
In order to query data from more than one table, you need to identify a common column that
relates the two tables. In the WHERE clause, you define the relationship between the tables listed
in the FORM clause using comparison operators.
A join is a query that combines rows from two or more tables or views. The types of joins are:
EQUI joins, CARTESIAN joins, OUTER joins and SELF joins.

EQUI Join
When two tables are joined together using equality of values in one or more columns, they make
an Equi join. The prefixes are utilized to prevent ambiguity and the WHERE clause specifies the
columns being joined.
Example:
SELECT empno, ename, emp.deptno, dname
FROM emp, dept WHERE emp.deptno= dept.deptno ;
Displays the employee numbers, employee names, department numbers and department names.

CARTESIAN Join
A Cartesian join occurs when data is selected from two or more tables and there is no common
relation specified in the WHERE clause. If you do not specify a join condition for the tables
listed in the FROM clause, Oracle joins each row from the first table to every row in the second
table. If the first table has three rows and the second table has four rows, the result will have
twelve rows.
Example:
Consider the following tables:
Tab1: Holds the principal amount.
Tab2: Holds year and rate of interests.
Tab1
PRINCIPAL
1000
2000
3000

Tab2
YEAR RATE
1
10
2
11
3
11.5
4
12
Finding the possible combinations of calculation of amount, a Cartesian join of the tab1 and tab2
is required. The formula for calculation of amount is Principal*(1+(rate/100))year.
Page 44

Multiple Table Queries


SELECT principal, year, rate, principal*POWER(1+(rate/100),year)
FROM tab1, tab2;
The above will produce the following output:
PRINCIPAL
1000
2000
3000
1000
2000
3000
1000
2000
3000
1000
2000
3000

YEAR
1
1
1
2
2
2
3
3
3
4
4
4

RATE
10
10
10
11
11
11
11.5
11.5
11.5
12
12
12

principal*POWER(1+(rate/100),year)
1100
2200
3300
1232.1
2464.2
3696.3
1386.1959
2772.3918
4158.5876
1573.5194
3174.0387
4720.5581

OUTER Join
Sometime you might want to see the data from one table, even if there is no corresponding row
in the joining table. Oracle provides the outer join mechanism for this. The + symbol surrounded
by parentheses denotes an Outer join in the query. Enter (+) beside the column name of a table,
where may not be corresponding row. The Outer join operator (+) can appear only in the
WHERE clause. If there are multiple join conditions between the tables, the Outer join operator
used against all of the conditions.
Example:
SELECT empno, ename, dept.deptno, dname, loc
FROM emp, dept WHERE emp.deptno (+)= dept.deptno;
Displays the list of employees working in each department. Displays the department information
even if no employee belongs to that department.
Rules to place the (+) operator

The outer join operator can not be on both the sides


We can not outer join the same to more than one other table in a single SELECT statement.
An Outer join can not be combine with another condition using the OR or IN logical
operators

Page 45

Multiple Table Queries

SELF Join
A Self join joins a table to itself. The table name appears in the FORM clause twice, with
different alias names. The aliases are treated as two different tables, and they are joined as you
would join any other tables.
Example:
EMP table:
EMPNO
7839
7566
7876
7934

ENAME
KING
JONES
ADAMS
MILLER
..

MGR
7839
7788
7782

Consider the emp table shown above. Primary key of the emp table is empno. Details of each
employees manager is another row in the emp table whose empno is stored in mgr column of
some other row. So every employee except PRESIDENT has their manager. Therefore mgr is a
foreign key that reference empno. To list out the names of the manager with the employee record
you have to join emp table with itself.
SELECT worker.ename , manager.ename Manager
FROM emp worker, emp manager WHERE worker.mgr=manager.empno;
Where worker and manager are two aliases for the emp table and acts as a pseudo table.
EMPNO
7839
7566
7876
7934

ENAME
KING
JONES
ADAMS
MILLER
..

MGR

EMPNO
7839
7788
7782
7934

7839
7788
7782

The output will be:


Page 46

ENAME
KING
SCOTT
CLARK
MILLER
..

MGR
7566
7839
7782

Multiple Table Queries

ENAME
SCOTT
FORD
ALLEN
WARD
JAMES
TURNER
MARTIN
MILLER
ADAMS
JONES
CLARK
BLAKE
SMITH

Manager
JONES
JONES
BLAKE
BLAKE
BLAKE
BLAKE
BLAKE
CLARK
SCOTT
KING
KING
KING
FORD

13 rows selected.

Using Set Operators


Set operators can be used to select data from multiple tables. Set operators basically combine the
result of two queries into one. These queries are known as compound queries. All set operators
have equal precedence; when multiple set operators are present in the same query, they are
evaluated from left to right unless specified otherwise with parentheses. The datatype of the
resulting columns should match in both queries. Oracle has four set operators:
Operator
UNION
INTERSECT
MINUS

Description
Returns all unique rows selected by either query
Returns all rows, including duplicates selected by either queries
Returns unique rows selected by the first query but not the rows selected
by the second query

Suppose we want following three details from emp table:


List of all the different designations in department 20 and 30
SELECT job FROM emp WHERE deptno = 20
UNION
SELECT job FROM emp WHERE deptno = 30;
List of the jobs common to department 20 and 30
SELECT job FROM emp WHERE deptno = 20
INTERSECT
SELECT job FROM emp WHERE deptno = 30;

List of the jobs unique to department 20


Page 47

Multiple Table Queries


SELECT job FROM emp WHERE deptno = 20
MINUS
SELECT job FROM emp WHERE deptno = 30;
Points to be kept in mind while using UNION operator:

The two select statements may not contain an ORDER by clause, however, the final result of
the entire UNION operation can be ordered.
The number of columns retrieved by first select must be equal to number of columns
retrieved by second select.
The data types of columns retrieved by the select statements should be same.
The optional ORDER BY clause differs from the usual ORDER BY clause in a SELECT
statement because the columns used for ordering must be referenced by a number rather than
name. The reason that the columns must be referenced by number is the SQL does not
require that the column name retrieved by first select be identical to the columns names
retrieved by second select.

Sub Queries
A subquery is a query within a query. Typically, subqueries appear in the WHERE clause of the
SELECT statement. Oracle supports subqueries in the FROM clause and the HAVING clause. A
subquery answers the queries that have multiple parts; the subquery answer one part of the
question and the parent query answers the other part. You can have any number of subqueries
nested; Oracle does not place a limit.

Single-Row Sub Queries


Single-Row subqueries returns only one row of result. The common operator is the equality
operator (=). The parent query of a single-row subquery can return more than one row.
Example I:
SELECT ename, sal FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp);
Example II:
SELECT ename, deptno FROM emp
WHERE deptno != (SELECT deptno FROM emp WHERE ename=SCOTT);

Page 48

Multiple Table Queries

Multiple-Row Sub Queries


Multiple-Row subqueries returns more than one row of result from the subquery.
Example:
SELECT ename, deptno FROM emp
WHERE deptno NOT IN (SELECT deptno FROM emp WHERE ename=SCOTT);

Correlated Subqueries
Oracle performs a correlated subquery when the subquery references a column from a table
referred to in the parent statement. A correlated subquery is evaluated once for each row
processed by the parent statement.
Example 1:
Considering the emp table and the incr table list the employee number and names, who have got
more than one increments.
SQL> select * from incr;
EMPNO
AMT
-------------- -----------7369
500
7499
300
7369
400
7654
600
7698
450
7499
340
6 rows selected.

Correlated,
Same column

Select empno ,ename from emp


where 1<(select count(*) from incr where empno= emp.empno );
Result:
EMPNO
ENAME
------------ ------------7369
SMITH
7499
ALLEN

Page 49

Multiple Table Queries

Using special operators in subquery


EXISTS Operator
The exists operator is frequently used with correlated subquery. It tests whether a value is there
or not. If the value exists it returns true. If it does not exists it returns false.
Example:
SELECT empno, ename, job, deptno FROM emp e
WHERE EXISTS (SELECT empno FROM emp WHERE emp.mgr=e.empno);
The above will display all employees who have at least one person reporting to them.
ANY Operator
The any operator compares the lowest value from the list.
Example:
SELECT ename FROM emp
WHERE sal>ANY(SELECT sal FROM emp WHERE deptno=20);
The above will display all employees name whose salary is greater than the lowest salary of an
employee belonging to department 20.
ALL Operator
The all operator compares the highest value from the list.
Example:
SELECT ename FROM emp
WHERE sal>ALL(SELECT sal FROM emp WHERE deptno=20);
The above will display all employees name whose salary is greater than the highest salary of all
employee belonging to department 20.

Page 50

Chapter 4

Snapshots

Functions
Single Row Function
Arithmetic Functions
Character Functions
Date Functions
General Functions
Group Functions

Page 51

Functions

Objectives

After studying this chapter, the student should be able to :


Understand what are Functions
Type of Functions
Understand the use of various column functions and group functions

Page 52

Functions

Functions
Functions are programs that take zero or more arguments and return a single value. There are two
significant classes of function:

Single Row Function


Group Function

Single Row Function


Single Row Function knows how many arguments they will have to process before data is
fetched from the tables.

Can be used to manipulate data items


Accept arguments (number of arguments varies from function to function)
Always returns a single value
Act on each row returned
Can be used to modify the data type
Can be nested in other functions

To test all the following functions you can work with the table called dual. This table has only
one column in its structure. The column name is dummy and it has only one row with a value x.
Arithmetic functions
ABS (x)

Absolute Value of x

CEIL (x)

Smallest integer greater than or equal to x.

FLOOR (x)

Largest integer less than or equal to x.

MOD (x,y)

Returns the remainder of x divided by y

POWER (x,y)

Returns x raised to the power of y. The 2nd argument must be an integer

SIGN (x)

Returns 1 if x is negative, 1 if positive and 0 if it is zero

SQRT (x)

Returns the square root value of x. If x is null or negative then null is


returned

ROUND (x,[y]) Rounds the value x, up to y decimal places. If y is omitted it is rounded to


no decimal places. If y is negative number to left the decimal are rounded
TRUNC (x, n)

Truncate x to n decimal places to the right of the decimal point.

Character functions

Page 53

Functions
CHR (x)

Character for ASCII value x.

ASCII (c)

Returns the ASCII value of c

INITCAP (s)

String s with the first letter of each word capitalized

LOWER (s)

Converts string s to all lower case letters

UPPER (s)

Converts string s to all upper case letters.

LPAD (s, x)

Pads string s with x spaces to the left.

RPAD (s, x)

Pads string s with x spaces to the right.

LTRIM (s)

Removes leading spaces from s.

RTRIM (s)

Removes trailing spaces from s.

REPLACE (s1, s2, s3)

Replace occurrences of s1 with s2 in string s.

TRANSLATE (s1, s2, s3)

Returns s1 with all occurrences of each character in s2 replaced


by the corresponding character in s3.

SUBSTR (s, x1, x2)

Return a portion of string s starting at position x1 and ending


with position x2. If x2 is omitted, it's value defaults to the end of
s.

INSTR (s1, s2, x)

Returns the position of s2 in s1 where the search starts at


position x.

LENGTH (s)

Length of s

Date Functions

SYSDATE

Returns the system date

ADD_MONTHS(d,n)

Add or subtract months to or from a date. Returns a date as the result

MONTHS_BETWEEN(d1,d2) Returns number of months between two dates


LAST_DAY(d)

Returns the date of the last day of the month specified. The result will
be a date

NEXT_DAY(d,day)

Returns the date of next specified day of the week after the date d

Conversion functions

Page 54

Functions

Converts a date column to a string of characters. format is a set of Date


formatting codes where:
YYYY is a 4 digit year.
MM is a month number.
MONTH is the full name of the month.
MON is the abbreviated month.
DDD is the day of the year.
TO_CHAR (date, format) DD is the day of the month.
D is the day of the week.
DAY is the name of the day.
HH is the hour of the day (12 hour clock)
HH24 is the hour of the day (24 hour clock)
MI is the minutes.
SS is the seconds.

TO_CHAR (number,
format)

Converts a numeric column to a string of characters. format is a set of


number formatting codes where:
9 indicates a digit position. Blank if position value is 0.
0 indicates a digit position. Shows a 0 if the position value is 0.
$ displays a leading currency indicator.
, used as a group separator

TO_DATE (s, format)

Converts a character column (string s to a date. format is a set of Date


formatting codes as above

TO_NUMBER (s, format)

Converts a character column (string s to a Number. format is a set of


Number formatting codes as above.

Other functions
DECODE (s, search1,
Compares s with search1, search2, etc. and returns the corresponding
result1, search2, result2) result when there is a match.
NVL (s, expression)

If s is NULL, return expression. If s is not null, then return s.

USER

Returns the username of the current user.

Page 55

Functions

Group Functions
Group function dont know how many arguments they will have to process until all the data
extracted and grouped into categories. To use an aggregate function, a GROUP BY clause must
be added to the SELECT statement. Group function do not process a null value and do not return
a null value.

AVG (col)

Returns the average of a group of rows for col

MAX (col)

Returns the maximum of a group of rows for col

MIN (col)

Returns the minimum of a group of rows for col

SUM (col)

Returns the sum (total) of a group of rows for col

COUNT (columns)

Returns the number of instances of a group of rows for (columns)

Page 56

Chapter 5

Snapshots

Data Definition Language


Creating Tables
Working with Constraints
Creating a table with data from another table
Maintaining Database Objects
Alter Table
The ENABLED/DISABLED Clause
Dropping / Renaming Tables
Truncating table
Insert values into a table
Inserting result of a query into a table
Inserting through parameter substitution
Updating columns of a table
Deleting rows from a table
Introduction to Views
Creating a view
Manipulating Data through Views
Creating a join view
Key-preserved table
Rules for DML statements on Join View
Dropping a view
Working with Sequences

Page 57

Data Definition & Manipulation Language

Objectives

After studying this chapter, the student should be able to :


UNDERSTAND HOW TO CREATE TABLES
Understand what are constraints
Understand how to alter a table
Understand how to insert values into a table
Understand how to update column(s) of a table
Understand how to delete row(s) from a table
Understand what are views
Understand how to manipulate base table(s) using views
Understand how to work with sequence

Page 58

Data Definition & Manipulation Language

Data Definition Language


DDL is a subset of SQL commands used to create, modify or remove Oracle database structure.
Example: Tables, Views. These command have an immediate effect affect on the database, and
also record information in the data dictionary.

Creating Tables

Tables are created using the CREATE TABLE command


Tables are owned by the user who creates them
The names of table owned by a given user must be unique
The column names in a table must be unique

Naming convention of a table

The table name must begin with a letter


It may contain letters, numerals and special character
It may be up to 30 characters long
A table name must not be a SQL reserved word
Table name is not case sensitive
Table names are stored in uppercase except those given in double quotes

Syntax:
CREATE TABLE <table_name>
(
<column_name>
<datatype(size)>,
..
);
Example:
Create a table ITEM_MAST, which has the following columns:
Column Name
ITNO
ITNM
CLASS
QOH
RATE

Type
Number
Varchar2
Char
Number
Number

Size
4
20
1
5
8,2

Description
Item Number
Item Name
Category of item
Quantity On Hand
Item Unit Price

Page 59

Data Definition & Manipulation Language


CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5),
RATE
Number(8,2)
);

Working with Constraints


Constraints are used to enforce data integrity. Constraints are rules and as such dont take up
space in a database as a table dose. Instead, constraints exist only in the data dictionary and are
applied during the execution of SQL and PL/SQL. When constraints are enabled, they are
enforced. When constraints are disabled, they are not enforced, but they still exist in the data
dictionary. There are five varieties of constraints :

Check
NOT NULL
Unique
Primary key
Foreign key
Default

Check Constraints
Check constraints require a specific Boolean condition on a column or set of columns to be true
or at least one of the column values to be NULL. Check constraints are enforce simple business
rules about the content of data in your tables. Check constraints cannot protect columns of
datatype LOB, object, nested table, VARRAY. If the check protects a single column, it can be
created inline with the column in the CREATE TABLE statement. A check constraint can also be
created or added as a table constraint. When it protects two or more columns, you must use the
table constraint syntax. The constraints name is optional and, if this name is not present, Oracle
will generate a unique name that begins with SYS_. You should not rely on system-generated
names for constraints.

Page 60

Data Definition & Manipulation Language


Example :
CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1) constraint ch_class check (CLASS IN ( A, B, C ))
QOH
Number(5),
RATE
Number(8,2),
Constraint ch_classrate CHECK (( CLASS = A AND RATE <=1000)
OR ( CLASS = B AND RATE <=4500)
OR ( CLASS = C AND RATE >4500))
);
NOT NULL Constraints
A NOT NULL constraint applies to a single column and requires data values for the column it
protects. By default Oracle allows a NULL value in any column.
Example :
CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5) NOT NULL,
RATE
Number(8,2) NOT NULL
);
Unique Constraints
A unique constraints protects one or more columns in a table, ensuring that no two row contains
duplicate data in the protected columns.
Example :
1. CREATE TABLE ITEM_MAST
(
ITNO
Number(4) UNIQUE,
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5),
RATE
Number(8,2)
);

Page 61

2.

CREATE TABLE ITEM_MAST


(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5),
RATE
Number(8,2),
UNIQUE ( ITNO,ITNM)
);

Data Definition & Manipulation Language


Primary Key Constraints
Tables can have only a single primary key constraint. A tables primary key can protect one or
more columns and incorporates NOT NULL constraints on each column in the key, as well as
unique constraints on all columns in the key.
Example:
1. CREATE TABLE ITEM_MAST
(
ITNO
Number(4) PRIMARY KEY,
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5),
RATE
Number(8,2)
);

2.

CREATE TABLE ITEM_MAST


(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5),
RATE
Number(8,2),
PRIMARY KEY ( ITNO,ITNM )
);

Foreign Key Constraints


A foreign key constraint protects one or more columns in a table by ensuring that each rows data
values contains one or more null values or that all the data values in the protected columns exists
in a primary or unique constraints. The referenced ( primary or unique ) constraints can protect
the same table or a different one. When dealing with foreign key constraints, we often use the
terms parent table and child table. The parent table is the referenced table, that is, the one with
the primary or unique key. The child table is the referencing table, that is, the one whose data
values are checked for existence elsewhere.
Example:
Master Table
CREATE TABLE ITEM_MAST
(
ITNO Number(4) PRIMARY KEY,
ITNM Varchar2(20),
CLASS Char(1),
QOH
Number(5),
RATE Number(8,2)
);

Transaction table
CREATE TABLE ITEM_TRANS
(
ITNO Number(4) REFERENCE
ITEM_MUST(ITNO),
TRTP Char(1) CHECK ( TRTP IN ( P, S ),
TRDT DATE,
QTY Number(5),
);
TRTP Transaction Type. TRDT Date.
QTY Transaction quantity.

Page 62

Data Definition & Manipulation Language

ON DELETE CASCADE OPTION


Using this option whenever a parent row
is deleted then all the corresponding
child rows are deleted from the detail
table. This option is always used with
FOREIGN KEY.

CREATE TABLE ITEM_TRANS


(
ITNO Number(4) REFERENCES
ITEM_MUST(ITNO) ON DELETE CASCADE,
TRTP Char(1) CHECK ( TRTP IN ( P, S )),
TRDT DATE,
QTY Number(5),
);

Default Constraints
While inserting a row into a table without having values for every column, SQL must insert a
default value to fill in the excluded column(s), or the command will be rejected. The most
common default value is NULL. This can be used with columns not defined with a NOT NULL.
Example:
CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5) DEFAULT 100,
RATE
Number(8,2)
);

Creating a table with data from another table


A table can be created using CREATE TABLE statement with rows, derived from another table.

The table will be created with the specified columns and the rows retrieved by the SELECT
statement inserted into it.
If column specifications are given, the number of columns must equal the number of items in
the SELCET list.
Constraints information is inherited from the selected table.
Data type for the column cannot be specified.

Example 1:
CREATE TABLE ITEM_MAST2 AS SELECT ITNO,ITNM FROM ITEM_MAST;
Example 2:
CREATE TABLE ITEM_MAST3 ( ITNO, ITNAME) AS
SELECT ITNO,ITNM FROM ITEM_MAST;

Page 63

Data Definition & Manipulation Language

Maintaining Database Objects

Maintaining of database objects involves creating, altering , deleting them from the database
Modifications are done using the ALTER statement
Deleting is done using the DROP statement

Alter Table
To change the definition of the table ALTER TABLE statement is used. The syntax for ALTER
TABLE statement is:
ALTER TABLE <table_name>
[ADD (<column_element> | <constraints>)]
[MODIFY (<column_element>)]
[DROP (<column_element> | <constraints>)]

The ADD Option

ADD keyword is used to add column or constraints to the table. Constraints can be primary key,
check, references.
Example 1:
ADD a column ROL(ReOrderLevel) to the existing table ITEM_MAST.
ALTER TABLE item_mast ADD rol Number(3);
Example 2:
Modify the ITEM_MAST table, add a primary key constraint to ITNO. Assign the constraint
name as itnopk.
ALTER TABLE item_mast ADD CONSTRAINT itnopk PRIMARY KEY(itno);
Example 3:
Add constraint references to the column ITNO of the table ITEM_TRANS referring ITNO of
ITEM_MAST table.
ALTER TABLE item_trans ADD CONSTRAINT itnofk
FOREIGN KEY(itno) REFERENCES item_mast(itno);

Page 64

Data Definition & Manipulation Language

The MODIFY Option

MODIFY option change the following of an existing column:

Data Type
Column Width
Constraints i.e. DEFAULT, NOT NULL and NULL

Restriction for Modification

The type and/or size of a column can be changed, if every row for the column is NULL
A NOT NULL column may be added only to a table with no rows
An existing column can be modified to NOT NULL only if it has a non-NULL value in every
row
Views that references a table with SELECT * FROM will not work after a column has been
added to the table
The size of a column can only be increased

Example 1:
Modify the rate column of ITEM_MAST table to NOT NULL and increase its size to 10,2.
ALTER TABLE item_mast MODIFY rate Number(10,2) NOT NULL;

The DROP Option

Dropping a column
You can drop a column that is of no use, or you can mark the column as not used and drop it
later. DROP COLUMN drops the column name specified from the table. You can provide more
than one column names separated by commas inside parenthesis. The indexes and constraints on
the column are also dropped. You must specify CASCADE CONSTRAINTS if the dropped
column is part of a multi-column constraint; the constraint will be dropped.
Example:
ALTER TABLE item_mast DROP COLUMN rol;
You usually mark a column as unused and not dropped if the table very large and takes a lot of
resource at pick hours. In such cases you would mark the column as unused and drop it later.
Once the column is marked as unused, you will not see it as part of the table definition.

Page 65

Data Definition & Manipulation Language


Example:
ALTER TABLE item_mast SET UNUSED COLUMN rate;
The statement for dropping a column already marked as unused is:
ALTER TABLE item_mast DROP UNUSED COLUMNS;

The ENABLED/DISABLED Clause


Constraints can be enabled or disabled as and when required.
Example:
ALTER TABLE item_mast DISABLE CONSTRAINT itnopk CASCADE;
The keyword CASCADE in the above example disabled the dependant constraint also.
Example:
ALTER TABLE item_mast ENABLE CONSTRAINT itnopk;

Dropping / Renaming Tables


Once you drop a table, the action can not be undone. When you drop a table, the data and
definition of the table are removed. The indexes, constraints, triggers and privileges on the table
are also dropped.
Example:
DROP TABLE item_mast;
The rename statement is used to rename a table and other database objects, such as view. Oracle
automatically transfers integrity constraints, indexes, and grants on the old table to the new table.
Oracle invalidates all objects that depends on the renamed table, such as views, stored
procedures, and functions.
Example:
RENAME item_main TO item_mast;

Page 66

Data Definition & Manipulation Language

Truncating table
The TRUNCATE statement is similar to the drop statement, but it does not remove the structure
of the table, so none of the indexes, constraints, triggers or privileges on the table are dropped.
By default, the space allocated to the table and indexes is freed. If you do not wish to free up the
space, include the REUSE STOTAGE clause. You cannot rollback a truncate operation. Also,
you cannot selectively delete rows using the TRUNCATE statement. You cannot truncate the
parent table of an enabled referential integrity constraint. You must first disable the constraint
and then truncate the table, even if the child table has no rows. The following example
demonstrates this :
STEP I
CREATE TABLE m1
(
no number CONSTRAINT nopk PRIMARY KEY
);
STEP II
CREATE TABLE m2
(
no1 number CONSTRAINT nofk REFERENCES m1(no)
);
STEP III
TRUNCATE TABLE m1;
truncate table m1
*
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
STEP IV
ALTER TABLE m2 DISABLE CONSTRAINT nofk;
STEP V
TRUNCATE TABLE m1;

Page 67

Data Definition & Manipulation Language

Insert values into a table

Insert statement is used to insert rows in the table


Values can be inserted for all the columns or for the selected columns.
In place of values, parameter substitution can also be used with INSERT

Syntax for insert statement is :


INSERT INTO < table-name > VALUES <( list-of-values )>;
Example :
INSERT INTO ITEM_MAST
VALUES ( 111,Baby Food, A, 75,125.75);
While inserting data into table, the following points should be remembered:

Character data will be enclosed within quotes


Column values for date type of column are provided within single quotes. Oracle internally
converts the character field to date type field
NULL values are given as NULL, without any quotes because null is a true value
If data is not available for all columns, then the column list must be included, following the
table name.

Example :
INSERT INTO ITEM_MAST ( itno, itnm, class)
VALUES ( 111,Baby Food, A);

Inserting result of a query into a table


In order to use query with insert, the target table must fulfill the following conditions:
The table must be an existing one
It must have the columns retuned by the query and be of the same data type
Example:
INSERT INTO itmast SELECT itno, itnm, class FROM item_mast;

Inserting through parameter substitution


The parameter substitution provides an easier way to insert data into a table. The & sign is used
as the substitution operator.

Page 68

Data Definition & Manipulation Language


Example:
INSERT INTO itmast VALUES(&itno, &itnm,&class);

Updating columns of a table

UPADTE command is used to update the column values in a table


Values of a single column or a group of columns can be updated
Updation can be carried out for all the rows in a table or selected rows

Syntax:
UPDATE <table_name> SET <column_name>=value
[,<column_name>=value,] [WHERE <condition>];
Example:
UPDATE itmast SET qty=100 WHERE into=111;

Deleting rows from a table

DELETE statement is used to delete rows from a table


The entire row is deleted from the table
Specific column value can not be deleted from a table
CASCADE DELETE rule instructs DBMS to automatically set the foreign values to NULL
in the child rows, if the parent row is deleted

Syntax:
DELETE FROM <table_name> [WHERE <conditional>];
Example:
DELETE FROM emp;
DELETE emp;
Both the statements are same and will delete all the rows from the emp table.

Page 69

Data Definition & Manipulation Language

Introduction to Views
A view is a customized representation of data from one or more tables. The view takes the result
of a query and stores it in the database. A view can be considered to be as a stored query or a
virtual table. Only the query is stored in the Oracle data dictionary; the actual data is not copied
anywhere. So, creating views does not take any storage place, other than the space in the data
dictionary. The views can have different column names than the base table. You may create a
view to limit the data accessible to the other user.

Creating a view
A view can be created using the following syntax:
CREATE VIEW <view_name>[<column_names>] AS <select_statement>;
Example:
CREATE VIEW empview AS SELECT empno,ename,deptno FROM emp WHERE deptno=20;
Now to select the rows from the view you can use the following statement:
SELECT * FROM empview;

Manipulating Data through Views

The INSERT, UPDATE and DELETE statements can also be used with views
Using these commands with views is an indirect way of manipulating tables
WITH CHECK OPTION clause allows integrity constraints and data validation to be
enforced on data being inserted or updated
Join view can also be modified
Key-preserved table is used to understand the restriction on modifying join views

The WITH CHECK OPTION clause


This clause specifies that inserts and updates performed through the view are not allowed to
create rows which the view can not select. Let us consider the above view:
Suppose we insert the following:
INSERT INTO empview VALUES(1234,PAUL,30);
The row will be inserted without any error. But if we create that view with the following
statement the above insert statement will generates an error:

Page 70

Data Definition & Manipulation Language


CREATE VIEW empview AS SELECT empno,ename,deptno
FROM emp WHERE deptno=20 WITH CHECK OPTION;
Constraint name can also be assigned to the WITH CHECK OPTION:
CREATE VIEW empview AS SELECT empno,ename,deptno
FROM emp WHERE deptno=20 WITH CHECK OPTION CONSTRAINT mycons;

Creating a join view


CREATE VIEW myview AS SELECT empno, ename, dname
FROM emp, dept WHERE emp.deptno=dept.deptno;

Key-preserved table
A table is key-preserved if every key of the table can also be a key of the result of the join, so, a
key-preserved table has its keys preserved through a join.
Criteria to be a key-preserved table

View should be based on more than one table and should be a join view
To satisfy key-preserved table at least one column should be a PRIMARY KEY in the join
statement

Example:
CREATE VIEW myview AS SELECT empno, ename, dname, dept.deptno
FROM emp, dept WHERE emp.deptno=dept.deptno;
In the above example, table emp is a key-preserved table and table dept is a non-key-preserved
table.
Following will the output when you will select from the view called myview:

Page 71

Data Definition & Manipulation Language

Rules for DML statements on Join View


Any INSERT, UPDATE or DELETE statement a join view can modify only one underlying base
table i.e., the emp table.
Examples:
INSERT INTO myview(empno, ename) VALUES(5678,JOHN);
UPDATE myview SET ename = McGILL WHERE empno=5678;
DELETE FROM myview WHERE ename=McGILL;
If we try to insert a row into the non-key-preserved table dept with the following statement:
INSERT INTO myview(deptno, dname) VALUES(50,PRODUCTION);
The statement would failed with an ORA-01776 error (can not modify more than one base table
through a view)
UPDATE myview SET dname=ADMIN WHERE deptno=10;
This statement fails with an ORA-01779 error (can not modify a column which maps to a nonkey-preserved table)

Page 72

Data Definition & Manipulation Language

Dropping a view
The DROP VIEW command is used to remove a view from the database.
Example:
DROP VIEW myview;

Working with Sequences


An Oracle SEQUENCE is a named sequential number generator. SEQUENCE are often used for
artificial keys or to order rows that otherwise have no order. A SEQUENCE can be configured to
increase or decrease.
A SEQUENCE can have the following parameters:
KEYWORD
START WITH
INCREAMENT BY
MINVALUE

MAXVALUE

CYCLE

DESCRIPTION
Defines the 1st number that the sequence will generate. The default is
1.
Defines the increase or decrease for subsequently generated number.
The lowest number the sequence will generate. This is the bounding
value in the decreasing sequence. The default MINVALUE is the
keyword NOMINVALUE, which translates 1 for an increasing
sequence and to minus -1026 for a decreasing sequence.
The largest number the sequence will generate. This is the bounding
value by default for the increasing sequence. The default
MAXVALUE is the keyword NOMAXVALUE, which translates to
1027 for an increasing sequence and to minus -1 for a decreasing
sequence.
Configures the sequence to repeat numbers after reaching the
bounding values.

When you create the sequence the START WITH value must be equal to or greater than
MINVALUE. To access the next number in the SEQUENCE, you simply select from it, using the
pseudo-column NEXTVAL. To get the last SEQUENCE number that your session has generated,
you select from it using the pseudo-column CURRVAL. If your session has not yet generated a
new sequence number, CURRVAL will be un-defined.
To Create a SEQUENCE:
CREATE SEQUENCE sq START WITH 1 INCREAMENT BY 5 MAXVALUE 50;
To fetch the NEXTVAL from a SEQUENCE:
SELECT sq.NEXTVAL FROM dual;

Page 73

Data Definition & Manipulation Language


To fetch the CURRVAL from a SEQUENCE:
SELECT sq.CURRVAL FROM dual;
To alter a SEQUENCE:
ALTER SEQUENCE sq INCREAMENT BY 2;
To drop a SEQUENCE:
DROP SEQUENCE sq;

Page 74

Chapter 6

Snapshots

DataBase Security and Privileges


Grant Command
Revoke Command
Application Privilege Management
Oracle provides three standard ROLEs:
Commit and RollBack
Implicit COMMIT
Auto ROLLBACK
Savepoint

Page 75

Data Control Language

Objectives

After studying this chapter, the student should be able to :


Understand how to use GRANT command
Understand how to use REVOKE command
Assign and grant privileges to other users on database objects
Understand how to maintain database objects
Understand different transaction processing options

Page 76

Data Control Language

DataBase Security and Privileges

SQL is mostly executed in environments that require to recognize to differentiate between the
various users of the system.
Each user in an Oracle database has a specific authorization.
Commands are interpreted and permitted (or prohibited) on the basis of information
associated with the authorization associated with the ID of the user issuing the command.
The database administrator creates the users and assigns the privileges.
Privileges determine whether or not a user can execute a given command or a command
when acting on specific groups of data.

Grant Command

The GRANT command is used to grant access to the database.


A user can GRANT access to his/her database objects to another objects.

The syntax for GRANT command:


GRANT <database_privilage(s)> TO <user_name>;
GRANT <object_privilege(s) | ALL>
ON <object_name> TO <user(s) | PUBLIC> [WITH GRANT OPTION];
All tables, views, sequences that a user creates are owned by the user itself. Only the creator or
DBA can access it.
The <database_privilage> specifies the system level privileges to be granted to the users or roles
(discussed later). This includes CREATE/ALTER/DROP any object of the system.
The <object_privilege> specifies the actions such as SELECT, INSERT, DELETE, UPDATE,
ALTER for tables.
<ALL> indicates all the privileges. The privileges can be granted to the different users by
specifying their names or to all users by using the PUBLIC option.
The WITH GRANT OPTION clause allows the recipient user to give further grant on the
objects.
Examples:
GRANT ALL ON emp TO PUBLIC;
GRANT SELECT ON emp TO user1;
GRANT SELECT, INSERT ON emp TO user1, user2;

Page 77

Data Control Language

Revoke Command
Using REVOKE command a user can withdraw the privileges which has been granted earlier.
Syntax:
REVOKE <database_privilege(s)> FROM <user(s)>
REVOKE <object_privilege(s)|ALL> ON <object_name> FROM <user(s)|PUBLIC>
Examples:
REVOKE ALL ON emp FROM PUBLIC;
REVOKE SELECT ON emp FROM user1;
REVOKE SELECT,INSERT ON emp FROM user1, user2;

Application Privilege Management


Roles are used to simplify the administrative tusks involved in the management of privileges.
Role is a collection of system privileges.
The syntax for creating ROLE is:
CREATE ROLE <role_name>;
Example:
CREATE ROLE myroll;
GRANT SELECT, INSERT ON emp TO myroll;
GRANT myroll TO user3;

Oracle provides three standard ROLEs:


CONNECT This ROLE only allows to use Oracle.
RESOURCE This ROLE only allows to create Oracle objects.
DBA
This ROLE has the system privileges; such as Creating user, database.
When you are creating a new user, you must grant CONNECT and RESOURCE role to the
newly created user.

Commit and RollBack

Page 78

Data Control Language

The COMMIT command is used to make changes to the data, permanently.


The ROLLBACK command is used to discard parts of all work the user has done in the
current transaction.
SAVEPOINT statement are used to discard or commit all the changes up to a point.

SQL *Plus has the facility to automatically commit all the transactions without explicitly issuing
the COMMIT command.
SET AUTOCOMMIT ON
SET AUTOCOMMIT OFF

Enables autocommit feature.


Is the default and disables the autocommit feature.

Implicit COMMIT
The actions that will force a commit to occur, even without issuing the COMMIT command are:

Exiting SQL *Plus


Creating any objects
Granting or Revoking resources
Altering objects
Connecting or disconnecting from Oracle

Auto ROLLBACK
After completion of any DML statement, if the user experiences serious difficulty such as:
Hardware failure and no explicit COMMIT is made, Oracle will automatically rollback all uncommitted work.
If there is no explicit COMMIT made and if the AUTOCOMMIT mode set to OFF then after the
normal shut-down the server will commit all the un-committed transaction.

Savepoint
SAVEPOINT identifies a point in a transaction to which one can later rollback with the
ROLLBACK statement. It is helpful when a transaction contain a large number of SQL
statement and the user wants to commit only once when all are done.
If required one can rollback to a particular transaction. It works in a Last In Fast Out basis.
Example:
INSERT INTO dept VALUES(60,PURCHASE,DELHI);
SAVEPOINT sp1;
UPDATE emp SET deptno=60 WHERE ename=SMITH;
ROLLBACK TO SAVEPOINT sp1;

Page 79

Data Control Language


The ROLLBACK statement will undo the updation only. All transaction before the savepoint sp1
will remain unchanged, but not yet committed.

Page 80

Data Control Language

Snapshots

Introduction to PL/SQL
Advantages of PL/SQL
PL/SQL Architecture
PL/SQL Block Structure
Named and Anonymous block
Conditional and Iterative Control
IF THEN
IF THENELSE
IF THENELSIF
LOOPEND LOOP
WHILELOOP
FORLOOP
SQL within PL/SQL
Writing a PL/SQL code
Composite Data Types
PL/SQL Records
Record Assignment
PL/SQL TABLES

Page 81

Introduction to PL/SQL

Objectives

After studying this chapter, the student should be able to :


Understand PL/SQL block structure and architecture
Understand the Conditional and iterative control

IF THEN
IF THENELSE
IF THENELSIF
LOOPEND LOOP
WHILELOOP
FORLOOP

Understand how to use SQL within PL/SQL


Understand How to write PL/SQL code
Understand Composite Datatype

Introduction to PL/SQL

Introduction to PL/SQL

PL/SQL is the procedural extension to the non-procedural SQL


Combines data manipulation power of SQL and procedural power of standard procedural
language
Provides performance improvements through blocking of RDBMS calls
Integrates well with SQL *Plus and other Application Development products of Oracle
Supports sub-programming features such as Procedures and Functions

PL/SQL is an extension to non-procedural SQL. It includes many features and designs of


programming language. It combines the data manipulating power of SQL with the data
processing power of procedural language. The PL/SQL engine resides within Oracle server so it
is available from any application development tool that supports PL/SQL.

Advantages of PL/SQL

PL/SQL is a high performance transaction processing language. It is portable to any Oracle


environment and supports all SQL data manipulation commands.
PL/SQL supports all SQL data types and all SQL functions. It also lets you use all Oracle
object types.
PL/SQL block can be named and stored in a Oracle server and reused as required in other
PL/SQL program or from the SQL command line.
Security on PL/SQL structures stored in the server can be managed using the Oracle database
objects syntax. You can grant and revoke privileges on these stored PL/SQL program to and
from other user in the database.
PL/SQL code can be written using any ASCII text editor. So, it is portable to operating
environment in which Oracle runs.

PL/SQL Architecture
Application
Anonymous
Block
OR
Stored
Program
call

Oracle Server
SGA

Anonymous
Block
OR
Stored
Procedure
OR

PL/SQL Engine
PL/SQL
block

PL/SQL
block

Procedural

SQL

SQL statements
SQL
SQL statement executer

Procedural
statement
executor

Introduction to PL/SQL

PL/SQL Block Structure


PL/SQL block structured language. The units that constitute a PL/SQL program are logical
blocks. A PL/SQL may contain one or more blocks. Each block may be divided into three
sections as follows:
Declaration Section This section contains the data type and initial value of all variables and
constant used in the executable section of the block. This section begins with the keyword
DECLARE. This is an optional section. This section also declares CURSORs and used define
EXCEPTIONs.
Executable Section This section is mandatory section in the PL/SQL block. This section
begins with the keyword BEGIN. All the executable statements are given in this section. This
section can also have other PL/SQL blocks inside.
Exception Section This section is an optional section, which has executable statement to
handle an exception or error.
Here is the structure of a complete PL/SQL block:
[DECLARE]
-- Declaration Statements
BEGIN
-- Executable Statements
[EXCEPTION]
-- Exception Statements
END;
Each statement or declaration in a PL/SQL block is terminated with a semicolon. A statement
may be broken down into multiple lines for readability, and the semicolon marks the end of the
statement. More than one statement can appear in one line, separated by a semicolon. A single
line of comment is preceded by two hyphens(--). A set of comments can be enclosed in /* and */.

Named and Anonymous block


A Pl/SQL block can be a Named block or an Anonymous block. Anonymous blocks can be used
in the server side or in the client side. A Named block may appear in the declaration part of
another block.

Introduction to PL/SQL

Conditional and Iterative Control


Control structures are lines of code that control the flow of the PL/SQL program. PL/SQL
supports both conditional and iterative control structures.
Conditional and decision-control structures are used to perform an operation or statement based
on the outcome of another statement or expression.
IFTHENELSEEND IF statement let you say, If this is true then do this; otherwise do
that. Iterative control structure perform one or more statements repeatedly, either a certain
number of times or until a condition is met. There are three forms of iterative structure.

LOOP
WHILELOOP
FORLOOP

Syntax and Usage

IF THEN
The IF statement evaluates a condition, and if the condition is satisfied, a set of statement are
executed.
IF <condition> THEN
Statement 1;
Statement 2;
END IF;
The statements are executed only if the result of the condition is TRUE. The condition always
evaluates to a Boolean result of TRUE/FALSE.
Example :
DECLARE
no NUMBER;
BEGIN
no := &no;
IF no>100 THEN
DBMS_OUTPUT.PUT_LINE ( You got 100 points!!!!!!!!);
END IF;
DBMS_OUTPUT.PUT_LINE ( TRY AGAIN!!!!!!!);
END;

Introduction to PL/SQL

IF THENELSE
This is similar to IFTHEN statement but a set of statements can be executed if the condition
evaluates to FALSE or NULL.
IF <condition> THEN
Statement 1;
ELSE
Statement 2;
END IF;
The statement between THEN and ELSE are executed only if the result of the condition is
TRUE, and the statement between ELSE and END IF are executed only if the result of the
condition is FALSE.
Example :
DECLARE
no NUMBER;
BEGIN
no := &no;
IF no>100 THEN
DBMS_OUTPUT.PUT_LINE ( You got 100 points!!!!!!!!);
ELSE
DBMS_OUTPUT.PUT_LINE ( TRY AGAIN!!!!!!!);
END IF;
END;

IF THENELSIF
Use this structure if you need to select an action from several mutually exclusive conditions.
IF <condition1> THEN
Statement 1;
ELSIF<condition2> THEN
Statement 2;
ELSE
Statement 3;
END IF;
If conditon1 is TRUE then statement1 will executes otherwise it will check condition2. If
condition2 is TRUE then statement2 executes otherwise statement3 will executes.

Introduction to PL/SQL

Example :
DECLARE
age NUMBER;
BEGIN
age:=&age;
IF (age>=60) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 60 !!!');
ELSIF(age>=40 and age<60) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 40 !!!');
ELSIF(age>=30 and age<40) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 30 !!!');
ELSE
DBMS_OUTPUT.PUT_LINE('You are still young !!!');
END IF;
END;

LOOPEND LOOP
The basic form of iterative control is the LOOP statement. The statements between LOOP and
END LOOP will executed infinitely. You must use an EXIT statement to force a loop to
terminate un-conditionally and pass the control to the statement following the END LOOP. The
EXIT WHEN statement completes an infinitely loop conditionally.
LOOP
Statements;
END LOOP;
Example :
DECLARE
no NUMBER :=10;
BEGIN
LOOP
no := no + 10;
DBMS_OUTPUT.PUT_LINE ( Value of the variable is : || no);
IF (no>100) THEN
EXIT;
END IF;
END LOOP;
END;

Introduction to PL/SQL

WHILELOOP
This loop has a condition associated with it. The condition is evaluate, and, if the result is TRUE,
the statements inside the loop are executed. If the condition is FALSE, execution continues from
the next statement to END LOOP.
WHILE <condition>
LOOP
Statements;
END LOOP;
Example :
DECLARE
no NUMBER :=10;
BEGIN
WHILE ( no <100)
LOOP
no := no + 10;
DBMS_OUTPUT.PUT_LINE ( Value of the variable is : || no);
END LOOP;
END;

FORLOOP
Use the FORLOOP if you need the iterations to occur a fixed number of times. In the basic
LOOP and in WHILELOOP, the number of iteration is unknown. The FORLOOP is
executed for a range of values.
FOR <counter> IN [REVERSE] <start_range> .. <end_range>
LOOP
Statements;
END LOOP;
Here, counter is a variable known as the Index Variable (This need not be declared in the
DECLARE section; it is implicitly declared as Integer), which will have the value of start_range
for the first iteration and it will continue till the end_range. The two dots(..) serve as a Range
Operator. If the REVERSE keyword is used, the range is decremented. The range can be
expression or variable.

Introduction to PL/SQL
Example :
BEGIN
FOR cn IN REVERSE 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(cn);
END LOOP;
END;

SQL within PL/SQL


Points to be remember while using SQL command within PL/SQL

DDL statements are illegal in PL/SQL.


SELECT statement which do not return a single row will cause exception to be raised
DML commands can process multiple rows

DML in PL/SQL
The allowable DML statements are SELECT, INSERT, UPDATE and DELETE. When SELECT
statements are used queries must return one and only one row.
The INTO Clause
The INTO clause is used with SELECT, to store values from the table into variables. The INTO
clause occurs between the SELECT and FROM clauses. This clause specifies the names of
variables that will be populated by the items being selected in the SELECT clause. For each item
selected a separate variable must be used, and their order corresponds to the item selected.

Writing a PL/SQL code


PL/SQL code is written using text editor. The PL/SQL program is compiled and executed using
the command @<file_name>. The extension for the file should be sql.
To generate output on the screen, the procedure dbms_output.put_line() is used. It accepts only
one argument. Hence, the different variables are concatenated with double pipe(||) sign. To
enable the server output, the SET SERVEROUTPUT ON command must be given at the SQL
*Plus prompt.

Introduction to PL/SQL

Composite Data Types


PL/SQL Records

PL/SQL records provides a way to deal with separate but related variables as a unit
PL/SQL record is a variable that may contain a collection of separate values, each
individually addressable
The record type has to be defined before its record can be declared
In case one of the record component is a record, then it is called a nested record

The records have uniquely named fields. The fields within the record will obtain their names and
datatypes from the columns of the table of view referenced in the record declaration.
The syntax for creating a record is :
TYPE <type_name> IS RECORD
(
<field_name1> { field_type|variable%TYPE|table.column%TYPE|table%ROWTYPE },
<field_name2> { field_type|variable%TYPE|table.column%TYPE|table%ROWTYPE },
..
);
Where as
<type_name>
<field_type>

: is the record name


: is any datatype including RECORD datatype

Example:
DECLARE
TYPE employee IS RECORD
(
ecode
emp.empno.%type,
ename
emp.ename%type,
esalary
emp.sal.%type
);
emprec employee;

Record Assignment
In order to assign one record to another, both records must be of the same type. Even if the fields
of the records of different types match exactly, they cannot be assigned to each other. Also a list
of values cannot be assigned to a record using assignment operator and cannot be tested for
equality or inequality.

Introduction to PL/SQL
Example :

Declare a user-defined record to hold department information :

TYPE deprectype IS RECORD


(
deptno
dept.deptno%TYPE,
dname
dept.dname%TYPE,
loc
dept.loc%TYPE
);
Declare two variables, where one of deprectype and the other is of %rowtype, as follows :
DEPREC1
DEPREC2

deprectype;
dept.%ROWTYPE;

Then, the following statements are illegal :


deprec1 := deprec2;
IF deprec1 = deprec2 THEN
Statements
END IF;
Example :
DECLARE
TYPE employee IS RECORD
(
ecode
emp.empno.%type,
ename
emp.ename%type,
esalary
emp.sal.%type
);
emprec employee;
BEGIN
SELECT empno, ename, sal into emprec FROM emp WHERE deptno = 7369;
dbms_output.put_line ( emprec.empno || emprec.ename || emprec.sal );
END;

PL/SQL TABLES

Pl/SQL tables are modeled as database tables, but are actually not
Primary keys can be associated with them to have array-like access to row
The size can be dynamically increased by adding more rows when required. However no row
can be deleted
Column can belong to any scalar type, but the primary key must belong to
BINARY_INTEGER. This give you array-like access to rows

Introduction to PL/SQL
The syntax for creating a table type is :
TYPE <type_name> IS TABLE OF
<column_type | variable%TYPE | table.column%TYPE > [ NOT NULL ]
INDEX BY BINARY_INTEGER;
Where as
<type_name>
<column_type>

: is a specifier used in subsequent declarations of PL/SQL tables.


: is any scalar ( not composite ) datatype such as CHAR, DATE,
NUMBER, %TYPE attribute can be used to specify a column datatype.

Example :
DECLARE
TYPE enm IS TABLE OF emp.ename%type
INDEX BY BINARY_INTEGER;
x binary_integer :=1;
ename enm;
BEGIN
FOR i IN(SELECT ename FROM emp)
LOOP
ename(x) :=i.ename;
x:=x+1;
END LOOP;
FOR j IN 1..x-1
LOOP
DBMS_OUTPUT.PUT_LINE(ename(j));
END LOOP;
END;

Chapter 8

Snapshots

Cursor Management in PL/SQL


Implicit Cursor
Explicit Cursor
Using Cursor
Explicit cursor attributes
FOR UPDATE clause within CURSOR
WHERE CURRENT OF clause
CURSOR with parameter
CURSOR FOR LOOP
CURSOR FOR LOOP Using a Query
Exception, Errors, and PL/SQL
Exception handling in PL/SQL
Exception Propagation

PL/SQL - II

Objectives

After studying this chapter, the student should be able to :


Manipulate cursors within PL/SQL block
Understand the various types of cursors
Understand what is exception Handling in PL/SQL
Understand predefined Exceptions and User Defined Exceptions

PL/SQL - II

Cursor Management in PL/SQL


Oracle uses work areas called Private SQL Areas to execute SQL statements and stored
information. A cursor is a PL/SQL construct that allows you to name this work areas, and to
access their stored information. There are two types of cursors, Implicit cursor and, Explicit
cursor.

Implicit Cursor
Implicit cursors are declared by PL/SQL implicitly for all DML statements and for single row
queries. For example, SELECT statement issued directly within the BEGIN END part of a
block opens up an Implicit cursor.

Explicit Cursor
When the query returns more than one row, you need to define an Explicit cursor; you can not
use SELECT INTO statement. An Explicit cursor is defined in the declared section and is open,
fetched and closed in the executable or in the Exception section. An Explicit cursor can be
deemed an array with upper limit. It can have any number of rows.
Difference between Implicit and Explicit cursor
IMPLICIT CURSOR
Maintained internally by PL/SQL. Opened and
closed automatically when the query is
executed.
The cursor attributes are prefixed with SQL
(For example, SQL%FOUND).
The cursor attribute %ISOPEN is always
FALSE, because the implicit cursor is closed
immediately when the query completes.
Only one row can be processed; the SELECT
statement with the INTO clause is used.

EXPLICIT CURSOR
Defined, opened and closed explicitly in the
program. The cursor has a name.
The cursor attributes are prefixed with cursor
name (For example, C1%FOUND).
The %ISOPEN attribute will have a valid value
depending upon the status of the cursor.
Any number of rows can be processed.
Iterative routines should be set up in the
program, and each row should be fetched
explicitly (except for a Cursor-For Loop)

Using Cursor
The term cursor usually refers to an explicit cursor. The cursor to be used in the program defined
in the declare section. The cursor has a name and a SELECT statement. WHERE, ORDER BY,
GROUP BY, Sub-queries are all permitted in a cursor definition.

PL/SQL - II

Declaring a cursor
A cursor declaration defines the SELECT statements for the query you need to process in the
body of the block.
Syntax:
CURSOR <cursor_name> IS <select_statement>;
The cursor_name is an un-declared PL/SQL variable. You can not assign values to a cursor name
or use it in an expression.
Opening a cursor
The cursor should be opened before its row values can be used. Opening the cursor initiates the
query processing.
Syntax:
OPEN <cursor_name>;
Where cursor_name is the name of the cursor defined in the DECLARE section.
Fetching rows from a cursor
A cursor is fetched to retrieve a row at a time; use the FETCH command for this. After each
fetch, the cursor advances to the next row in the result set.
Syntax:
FETCH <cursor_name> INTO <variable> [, variable ];
For each column in the cursor definition SELECT, there should be a corresponding variable in
the fetch variable list. The variables should be declared with the appropriate data type in the
declaration section.
Closing a cursor
Explicitly opened cursors should be closed explicitly.
Syntax:
CLOSE <cursor_name>;

PL/SQL - II

Explicit cursor attributes


Each cursor that the user defines has four attributes. For obtaining status information about a
cursor.
%NOTFOUND Evaluates to TRUE, if the last FETCH failed, i.e, no more rows are left.
%FOUND Evaluates to TRUE, if the last FETCH succeded.
%ROWCOUNT Returns the number of rows fetched.
%ISOPEN Evaluates to TRUE, if the cursor is opened, otherwise evaluates to FALSE.
Example Code related to cursor manipulation
DECLARE
Eno emp.empno%type;
Enm emp.ename%type;
Esal emp.sal%type;
Dnm dept.dname%type;
CURSOR C1 IS SELECT empno, ename,sal,dname
FROM emp, dept
WHERE emp.deptno=dept.deptno;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO Eno, Enm, Esal, Dnm;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(Eno|| ||Enm|| ||Esal|| ||Dnm);
END LOOP;
DBMS_OUTPUT.PUT_LINE(Total number rows = ||C1%ROWCOUNT);
CLOSE C1;
END;

FOR UPDATE clause within CURSOR


FOR UPDATE clause can be used within the cursor query. This means that rows returned by the
query are locked exclusively when the OPEN statement is processed. Since locks are released at
the end of the transaction, COMMIT command should not be given across fetches from an
explicit cursor if FOR UPDATE is used.

PL/SQL - II

WHERE CURRENT OF clause


When referencing the current row from explicit cursor, SQL command may used the WHERE
CURRENT OF clause, with the name of cursor. This allows updates or deletes to be applied on
the single row, which is currently being addressed. However FOR UPDATE in the cursor query
must be used so that the rows are locked on open.
Example:
DECLARE
Ejb
emp.job%type;
Esal emp.sal%type;
Dno emp.deptno%type;
CURSOR C1 IS SELECT sal, job, deptno
FROM emp FOR UPDATE OF sal;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO Esal, Ejb, Dno;
EXIT WHEN C1%NOTFOUND;
IF Dno=10 THEN
UPDATE emp SET sal=sal+200 WHERE CURRENT OF C1;
ELSIF Dno=20 THEN
UPDATE emp SET sal=sal+300 WHERE CURRENT OF C1;
ELSE
UPDATE emp SET sal=sal+400 WHERE CURRENT OF C1;
END IF;
END LOOP;
CLOSE C1;
END;

CURSOR with parameter


Parameters allows value to be passed to a cursor when it is opened, and used within the query
when it executes. Using parameters explicit cursor may be opened more than once in a block,
returning a different working set each time. The data type of the parameters are the same as those
for scalar variables, but are not given size/scales.

PL/SQL - II
Example:
DECLARE
Eno emp.empno%type;
Enm emp.ename%type;
Esal emp.sal%type;
CURSOR C1(p number) IS SELECT empno, ename, sal
FROM emp WHERE deptno=p;
BEGIN
OPEN C1(10);
LOOP
FETCH C1 INTO Eno, Enm, Esal;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(Eno|| ||Enm|| ||Esal);
END LOOP;
CLOSE C1;
END;

CURSOR FOR LOOP


The cursor for loop implicitly declares its loop index as a record of type %ROWTYPE. Opens a
cursor, repeatedly fetch rows of the values from the active set into fields in the record then closes
the cursor when all rows have been processed or when the EXIT command is encountered.
Example:
DECLARE
Eno emp.empno%type;
Enm emp.ename%type;
Esal emp.sal%type;
CURSOR empcur IS SELECT empno, ename, sal
FROM emp;
BEGIN
FOR i IN empcur
LOOP
DBMS_OUTPUT.PUT_LINE(i.Eno|| ||i.Enm|| ||i.Esal);
END LOOP;
END;

CURSOR FOR LOOP Using a Query


A query can be defined in the cursor FOR loop. The cursor does not have a name because it is
not declared explicitly. The record name is defined with the cursor query.

PL/SQL - II
Example:
DECLARE
BEGIN
FOR i IN ( SELECT empno,ename,sal from emp )
LOOP
DBMS_OUTPUT.PUT_LINE(i.Eno|| ||i.Enm|| ||i.Esal);
END LOOP;
END;

Exception, Errors, and PL/SQL


Other languages have errors; PL/SQL has exceptions. This may seem like a simple semantic
difference, but Pl/SQL deals with exceptions differently from the way that most other languages
manage errors. Some languages, like C, require error-checking for practically every function
call. PL/SQL, on the other hand has an all-inclusive method of dealing with errors. When any
error occurs, program control branches unconditionally to the exception section of the current
Pl/SQL block. This makes the code much cleaner and separates error handling from normal
processing. Oracle has made this error/exception handling extensible by allowing the
programmer to declare other types of exception conditions. This extensibility makes PL/SQLs
exception handling robust.

Exception handling in PL/SQL

In PL/SQL, a warning or error condition is called an Exception.


When an error occurs, an exception is raised, i.e. the normal execution stops and the control
transfers to the exception handling part of the PL/SQL block
Exceptions can be of two types:
o Predefined Exception (Is one which will raised implicitly)
o Used Defined Exception(Is one which you have to raise explicitly)

Advantages of Exception

Without exception handling, every time a command is issued a check must be made for
execution errors. With exceptions, errors are handled conveniently without the need to code
multiple checks.
Exceptions improve readability by isolating error handling routines.
Exception improve readability. One need not worry about checking for an error at every point
it might occur. If PL/SQL block contains an exception handler, and if an exception is ever
raised in that block, the exception handler will handle the exception.
Helps successful execution of a block called from another PL/SQL block.

PL/SQL - II
Raising Exceptions
There are three ways that an exception can be raised:

By the Pl/SQL runtime engine


By a RAISE satatement
By a call to the RAISE_APPLICATION_ERROR procedure

When a database or PL/SQL language error occurs at runtime, an exception is raised


automatically by the OL/SQL runtime engine. Exception can also be raised explicitly with the
RAISE statement:
RAISE <exception_name>;
Explicitly raising an exception is how a programmer makes use of any custom exceptions ha has
declared. But the RAISE statement is not limited to just programmer-declared exceptions; you
can raise any exception with the RAISE statement. For example, if you want to test your new
exception-handler routines for a TOO_MANY_ROWS error, you dont have to construct a test
case that includes contention. In the other hand user defined exceptions are where the RAISE
statement really shines.
Exception Handlers
If any type of exception is raised, control is passed to the EXCEPTION section of the block in
which the exception occurred. If the exception is not handled there, or if there is no
EXCEPTION section at all then the block terminates with an un-handled exception, which may
effect the enclosing environment. The same exception can not be declared more than once in the
same PL/SQL block. To prevent exception from being propagated to the enclosing environment
or block, you may define exception handlers in the EXCEPTION section.
The syntax of defining exception handler is:
WHEN <exception_name> THEN <action>;
Where actions may be one or more PL/SQL or SQL statements, each terminated by semicolons. The actions of one exception handler are delimited by either the end of the block (END),
or by the strat of another exception handler (WHEN).
Some predefined exceptions are :
Exception Name
NO_DATA-FOUND
TOO_MANY_ROWS
CURSOR_ALREADY_OPEN
INVALID_COURSOR
INVALID_NUMBER
ZERO_DIVIDE

Oracle Error
ORA-01403
ORA-01422
ORA-06511
ORA-01001
ORA-01722
ORA-01476

PL/SQL - II
The WHEN OTHERS Exception Handler
Rather than defining a separate handler for every exception type, WHEN OTHERS exception
handler is defined, which handlers all errors not already handled in the block. WHEN OTHERS
exception handler should always be the last exception handler in the block. When an exception
has occurred, one wants to evaluate the associated error. This is more relevant when WHEN
OTHERS exception is handled as it helps to know what error has exactly occurred.
PL/SQL provides two functions for this purpose:
SQLCODE

It returns the error number associated with the exception that has occurred. If used
outside an EXCEPTION handler, the function will return zero. The error number
returned may be assigned to a NUMBER variable with default precision.

SQLERRM

It returns character data. It returns the complete error message associated with the
exception including the error number.

User Defined Exceptions


User defined exceptions are declared and defined by the user
User-defined exceptions must be raised explicitly by RAISE statement
PL/SQL allows you to define user defined exception. Unlike predefined exceptions, user defined
exceptions must be declared and must be raised explicitly by RAISE statement.
To declare an exception the syntax is :
<exception_name> EXCEPTION;
To raise an exception the syntax is :
RAISE <exception_name>;
Scope Rules

Exception can not be declared twice in the same block. However, same exception can be
declared in two different block.
Exception declared in a block are considered local to that block and global to all its subblocks. Because a block can reference only local or global exceptions, enclosing blocks
cannot reference exceptions declared in a sub block

PL/SQL - II

Exception Propagation
When an exception is raised in the executable section of a block, the exception is handled in the
following manner:
The current block has the exception handler, then it executes it and completes the block
successfully. The control then passes to the enclosing block.
DECLARE
my_exception EXCEPTION;
BEGIN
Statements;
BEGIN
RAISE my_exception;
EXCEPTION
WHEN my_exception THEN
Statements;
END;
Control passes here
Statements;
END;

EXCEPTION my_exception is
raised in the inner block
EXCEPTION handled in the
inner block

If there is no exception handler in the current block for a raised exception, the execution
propagates according to the following rules :
If there is an enclosing block for the current block, the exception is passed on to that block. The
enclosing block then becomes the current block. If a handler for the raised exception is not
found, the process is repeated.
DECLARE
my_exception1 EXCEPTION;
my_exception2 EXCEPTION;
BEGIN
EXCEPTION my_exception2 is
Statements;
raised in the inner block
BEGIN
IF < condition1 > THEN
RAISE my_exception2;
EXCEPTION my_exception2 not
EXCEPTION
handled here
WHEN my_exception1 THEN
Statements;
END;
EXCEPTION my_exception2 is propagated
EXCEPTION
to enclosing block and is handled there
WHEN my_exception2 THEN
Statements;
Control passes to enclosing block
END;
Statements;

PL/SQL - II
If there is no enclosing block for the current block, the exception si passed back to the
environment that invoked the PL/SQL program.
DECLARE
my_exception1 EXCEPTION;
my_exception2 EXCEPTION;
my_exception3 EXCEPTION;
BEGIN
Statements;
EXCEPTION my_exception3 is raised
BEGIN
in the inner block
IF < condition1 > THEN
RAISE my_exception3;
EXCEPTION my_exception3 not
EXCEPTION
handled in inner block
WHEN my_exception1 THEN
Statements;
END;
EXCEPTION my_exception3 is propagated
EXCEPTION
to enclosing block but is not handled there
WHEN my_exception2 THEN
Statements;
my_exception3 is propagated out of the calling environment
END;
Only one exception at a time can be active in the exception handling part of a block. Therefore, if
an exception is raised inside a handler, the block that encloses the current block is the first block
searched to find a handler for the newly raised exception.
Example 1 :
DECLARE
Eno emp.empno%type;
Enm emp.ename%type;
Esal emp.sal%type;
Hsal EXCEPTION;
Lsal EXCEPTION;
BEGIN
Eno := &Eno;
SELECT ename, sal into Enm, Esal FROM emp WHERE Eno = empno;
IF ( Esal <2000 ) THEN
RAISE Lsal;
ELSEIF ( Esal >4000 ) THEN
RAISE Has;
END IF;
DBMS_OUTPUT.PUT_LINE(Enm|| ||Esal);
EXCEPTION
WHEN Lsal THEN
DBMS_OUTPUT.PUT_LINE(The salary is too Low!);

PL/SQL - II

WHEN Hsal THEN


DBMS_OUTPUT.PUT_LINE(The salary is Standard);
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(Invalid Employee Code!!!);
END;
Example 2 :
DECLARE
BEGIN
FOR i IN ( SELECT empno, ename, sal FROM emp)
LOOP
DECLARE
Lsal EXCEPTION;
BEGIN
IF ( i.sal <2000 ) THEN
RAISE Lsal;
END IF;
EXCEPTION
WHEN Lsal THEN
DBMS_OUTPUT.PUT_LINE( rpad( i.ename,10,' ' )
||' --- SLARY IS TOO LOW!!!' );
END;
END LOOP;
DBMS_OUTPUT.PUT_LINE( '----- REPORT COMPLETE -----' );
END;

Chapter 9

Snapshots

Sub-Programs in PL/SQL
Advantages of Sub-Programs
Procedure
Calling a Procedure
Actual Vs. Formal parameter
Argument Modes
Functions
Stored Package
Advantages of package
Creating a package body:
Dropping Procedures, Function and Package
DataBase Trigger

Advanced PL/SQL

Objective

After studying this chapter, the student should be able to :


Understand what are subprograms in PL/SQL
Create and execute Procedures
Create and execute Functions
Understand how to use stored Functions in SQL statements
Understand how to use Actual and Formal Parameters
Understand Various Argument Modes
Create and execute stored Packages
Understand hoe to drop Procedure, Function and packages
Create and Drop database trigger

Advanced PL/SQL

Sub-Programs in PL/SQL
Subprograms are named PL/SQL programs that are stored in a compiled form in the database.
These programs can be invoked whenever required.

Advantages of Sub-Programs
Modularity
Subprograms allow you to break a program down into manageable, well-defined logic modules.
This supports top down design and the stepwise refinement approach to problem solving.
Reusability and Maintainability
Subprograms once validated, can be used with confidence in any number of applications.
Furthermore, only the subprogram is affected if its definition changes. This simplifies
maintenance and enhancement.

Procedure
A procedure is a subprogram that performs a specific action. A procedure can be called from any
PL/SQL program and also be invoked from the SQL prompt. A procedure has two parts: the
specification and body.
The procedure specification begins with the keyword PROCEDURE followed by the procedure
name and an optional list of arguments, enclosed within parenthesis. Procedures that take no
parameters are written without parentheses. The procedure body begins with the keyword IS or
AS and ends with an END followed by an optional procedure name. The procedure body has
three parts: a declarative part, an executable part, and an optional exception handling part. The
declarative part contains local declarations. The keyword DECLARE is NOT used to declare
variables and expressions. All the declarations are placed in between the IS and BEGIN
keywords. The executable part contains statements, which are placed between the keywords
BEGIN and EXCEPTION ( or END ). At least one statement must appear in the executable part
of a procedure. The exception-handling part contains exceptions handlers, which are placed
between the keywords EXCEPTION and END. This part is optional.
The syntax for writing procedure is :
CREATE [ OR REPLACE ] PROCEDURE < PROCEDURE_NAME >
(<arg1> [ mode ] <datatype>, . )
IS | AS
[ local declaration ]
BEGIN
Executable statements
[ EXCEPTION
exception handlers ]
END [ PROCEDURE_NAME ];

Advanced PL/SQL

Calling a Procedure
To call the procedure from a block, the command is
PROCEDURE_NAME ( <arguments>);
To invoked from the SQL prompt using the EXECUTE command
EXECUTE

PROCEDURE_NAME( <arguments> );

Example :
CREATE OR REPLACE PROCEDUR PR1 ( Eno NUMBER )
IS
Enm emp.ename%TYPE;
Esal emp.sal%TYPE;
BEGIN
SELECT ename,sal into Enm, Esal FROM emp WHERE Eno := emp.empno;
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (Invalid Employee Number !!!);
END;

Actual Vs. Formal parameter

The variable or expressions referenced in the parameter list of a subprogram all are actual
parameters
The variables declared in a subprogram specification and referenced in the subprogram body
are formal parameters
The actual parameter and its corresponding formal parameter must to compatible datatype

Argument Modes
Argument modes are used to define the behavior of formal parameters. There are three argument
modes to be used with any subprograms.
IN

The IN parameter lets the user pass values to the called subprogram. Inside the
subprogram, the IN parameter acts like a constant; therefore, it cannot be
modified.

OUT

The OUT parameter lets the user return values to the called subprogram. Inside
the subprogram, the OUT parameter acts like a un-initialized variable. Therefore,
it cannot be assigned to another variable or to itself.
The IN OUT parameter lets the user pass initial values to the called subprogram
and returns updated values to the calling block.

IN OUT

Advanced PL/SQL
Example 1:

Creating the Procedure :

CREATE OR REPLACE
PROCEDUR PR1 ( eno IN NUMBER, enm OUT VARCHAR2, esal OUT NUMBER )
IS
BEGIN
SELECT ename,sal into enm, esal FROM emp WHERE eno := emp.empno;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (Invalid Employee Number !!!);
END;

Calling a Procedure :

DECLARE
Eno emp.empno%TYPE;
Enm emp.ename%TYPE;
Esal emp.sal%TYPE;
BEGIN
Eno := &Eno;
PR1 ( Eno, Enm, Esal );
DBMS_OUTPUT.PUT_LINE ( Eno||
END;

||Enm||

||esal);

Example 2 :

Creating a Procedure

CREATE OR REPLACE PROCEDURE ad(aa IN OUT NUMBER)


IS
bb NUMBER;
cc NUMBER;
BEGIN
cc:=aa;
bb:=10;
DBMS_OUTPUT.PUT_LINE(The value from the calling program : ||cc);
aa:=bb;
END;

Advanced PL/SQL

Calling a procedure

DECLARE
bb NUMBER;
BEGIN
bb:=5;
ad(bb);
DBMS_OUTPUT.PUT_LINE(The changed value : ||bb);
END;

Functions
A Function is a sub-program that returns a value. A function must have return clause. The syntax
for the function is:
CREATE [ OR REPLACE ] FUNCTION < function_name >
(<arg1><datatype>, . ) RETURN <data_type>
IS
[ local declaration ]
BEGIN
Executable statements;
[ EXCEPTION
exception handlers ]
END [ function_name ];
Like a procedure, a function has two parts; the specification and the body. The function
specification begins with the keyword FUNCTION and ends with the RETURN clause, which
specifies the datatype of the result value. The function is exactly same as procedure body. The
RETURN statement immediately returns control to the caller environment. Execution then
resumes with the statement following the sub-program call.
Example 1:

Specifying a function

CREATE OR REPLACE
FUNCTION fn1 ( esal NUMBER, rate NUMBER) RETURN NUMBER
IS
da NUMBER(8,2);
BEGIN
da:= esal*(rate/100);
RETURN da;
END;

Advanced PL/SQL

Calling a function from SQL prompt

SELECT empno, ename, sal, fn1(sal,20) as DA FROM emp;

Calling function from PL/SQL block

DECLARE
eno
emp.empno%TYPE;
enm emp.ename%TYPE;
esal emp.sal%TYPE;
rt
NUMBER(2);
da
NUMBER(8,2);
BEGIN
rt:=&rt;
eno := &eno;
SELECT empno, ename, esal INTO eno, enm, esal
FROM emp WHERE empno=eno;
da:=fn1(esal, rt);
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal||
END;

||da);

Stored Package
A Package is a database object that groups logically related PL/SQL objects. Package
encapsulates related procedures, functions together as a logical unit in the database. Packages are
made of two components; the specification and the body. A specification is the interface to
applications and has declarative statements. The body of the package contains different
procedures and functions.
Package Specification
The specification is the interface to the application, it declares the procedures and functions. The
package specification holds the public declarations, which are visible to the application.
Package Body
The body holds implementation details and private declaration, which are hidden from the
application. The scope of these declarations is local to the package body. Unlike a package
specification, the declarative part of a package body can contain sub-program bodies. Package
can overload procedures and functions, declaring multiple programs with the same name. The
correct program to be called is decided at runtime, based on the number or datatypes of the
parameters. To create a package, you must first create the package specification. You cannot
GRANT privileges on only one procedure or function within a package.

Advanced PL/SQL

Advantages of package
Modularity
Packages encapsulates related procedures and functions together in a named PL/SQL module.
Easier application design
It is not important to compile the package body completely until the application is complete.
When designing an application initially the information in the specification is required. A
specification can be coded and compiled without its body. Once the specification has been
compiled, stored sub-programs that reference the package can be compiled as well.
Information Hiding
The packages can be specified in which all sub-programs are public that is, visible and accessible
or private that is hidden and in-accessible. By hiding implements details from users, integrity of
package is protected.
Better Performance
The entire package is loaded into the memory when a procedure, within the package, is called for
the first time. This reduce the un-necessary disk I/O and network traffic.
Specifying a package:
CREATE [OR REPLACE] PACKAGE <package_name> AS
/* Procedures and function declarations */
END [ <package_name> ];

Creating a package body:


CREATE [OR REPLACE] PACKAGE BODY <package_name> AS
/* Private variable declarations
Sub-program bodies */
END [<package_name>];

Advanced PL/SQL
Example:
CREATE OR REPLACE PACKAGE pkg AS
PROCEDURE addition(a NUMBER, b NUMBER);
FUNCTION higher(a NUMBER, b NUMBER) RETURN NUMBER;
END pkg;
CREATE OR REPLACE PACKAGE BODY pkg AS
PROCEDURE addition(a NUMBER, b NUMBER)
IS
c NUMBER;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE(The resultant value is : || c);
END addition;
FUNCTION hiegher(a NUMBER, b NUMBER)
IS
c NUMBER;
BEGIN
IF (a>b) THEN
c:=a;
ELSE
c:=b;
END IF
RETURN c;
END higher;
END pkg;

Dropping Procedures, Function and Package


To drop a procedure the syntax is : DROP PROCEDURE <procedure_name>;
To drop a function the syntax is : DROP FUNCTION <function_name>;
To drop a package the syntax is : DROP PACKAGE <package_name>;

Advanced PL/SQL

DataBase Trigger
Triggers are programs that are executed automatically in response to a change in the database.
Triggers can be configured to fire, or execute, either before or after the triggering event. The
events that can be hooked with triggers include the following.

DML events
DDL events
Database events

DML event triggers can be statement or row triggers. The DML statement trigger fires before or
after the triggering statement. The DML row trigger fires before or after each row affected by the
statement is changed. You can define multiple triggers for a single event and type, but there is no
way to enforce the order in which these multiple triggers will fire.
Trigger Events
Event
INSERT
UPDATE
DELETE
CREATE
ALTER
DROP

Trigger Description
Fires whenever a row is inserted into the table or view.
Fires whenever a row is updated in the table or view.
Fires whenever a row is deleted from a table or view.
Fires whenever a CREATE statement adds a new object to the database.
Fires whenever a ALTER statement changes an object in the database.
Fires whenever a DROP statement removes an object from the database.

The syntax for creating a trigger :


CREATE [ OR REPLACE ] TRIGGER <trigger_name>
{ BEFORE | AFTER | INSTEAD OF } <event>
ON { table_name | view name }
[ FOR EACH ROW [ WHEN <condition> ]]
trigger body
In case of tables BEFORE and AFTER are used. In case of views INSTEAD OF is used.
Example :
CREATE OR REPLACE TRIGGER t1
BEFORE INSERT OR UPDATE OF empno ON emp FOR EACH ROW
BEGIN
:new.ename := UPPER(:new.ename);
END;

Advanced PL/SQL
The :new in this example refers to a record containing the new, post-change data. Another is
there, i.e. :old; it would refer to a record containing the old, pre-change data. The trigger can
have visibility to both old and new values. However, the :old on an insert and :new on a delete
have no meaning; they contain all NULLs. Like constraints triggers may be disabled or enabled
to turn off or turn on their execution. To enable or disable a single trigger, use the ALTER
TRIGGER statement :
ALTER TRIGGER <trigger_name> ENABLE;
ALTER TRIGGER <trigger_name> DISABLE;
To enable or disable all triggers on a table, use the following statement:
ALTER TABLE < table_name> ENABLE ALL TRIGGER;
ALTER TABLE < table_name> DISABLE ALL TRIGGER;
To drop trigger, use the following statement :
DROP TRIGGER <trigger_name>;

Example 1
STEP 1: Create the following table.
CREATE TABLE stock
(
itno number(5),
qty number(5,2),
rate number(2),
total number(10,2)
);
STEP 2: Create the following Trigger on that table.
CREATE or REPLACE TRIGGER stock_total_updat
BEFORE INSERT or UPDATE ON stock FOR EACH ROW
BEGIN
:new.total:=:new.qty*:new.rate;
END;
STEP 3: Insert a row on stock table and see the effect.
INSERT INTO stock (into , qty , rate) VALUES(1,120,25.75);
It will update the total column of the table automatically.

Advanced PL/SQL
Example 2
Create a time restriction trigger on the above table.
CREATE or REPLACE TRIGGER restriction_on_time
BEFORE INSERT or UPDATE or DELETE on stock
BEGIN
IF (to_char(sysdate,'hh24'))<9 or (to_char(sysdate,'hh24'))>=18 THEN
RAISE_APPLICATION_ERROR(-20002,'Only Query is possible');
END IF;
end;
When you want to give an error message through trigger you should explicitly raise the error
through the following statement:
RAISE_APPLICATION_ERROR(err_code, err_message);
Err_code
: This will be the error code. The code will be onwards 20000.
Err_message : This will be error message which you want to show. The message will be within
single quotation.
Example 3
Master table updation using trigger.
STEP 1: Create the following tables.
1. CREATE TABLE ITEM_MAST
(
ITNO Number(4) PRIMARY KEY,
ITNM Varchar2(20),
QOH Number(5),
RATE Number(8,2)
);
2. CREATE TABLE ITEM_TRANS
(
ITNO Number(4) REFERENCE ITEM_MUST(ITNO),
TRTP Char(1) CHECK ( TRTP IN ( P, S ),
TRDT DATE,
QTY Number(5),
);

Advanced PL/SQL
STEP 2: Create the following trigger on the transaction table.
CREATE or REPLACE TRIGGER master_qoh_update
AFTER INSERT or UPDATE ON item_trans FOR EACH ROW
DECLARE
a NUMBER;
BEGIN
SELECT qoh INTO a FROM item_mast WHERE itno=:new.itno;
IF INSERTING THEN
IF UPPER(:new.trtp)='S' THEN
IF :new.qty>a THEN
RAISE_APPLICATION_ERROR(-20050,'Out of stock');
END IF;
END IF;
IF UPPER(:new.trtp)='S' THEN
UPDATE item_mast SET qoh= qoh-:new.qty WHERE itno=:new.itno;
ELSE
UPDATE item_mast SET qoh= qoh+:new.qty WHERE itno=:new.itno;
END IF;
END IF;
IF UPDATING THEN
IF UPPER(:new.trtp)<>UPPER(:old.trtp) THEN
IF UPPER(:new.trantype)='S' THEN
UPDATE item_mast SET qoh = qoh-(:old.qty*2)
WHERE itno=:old.itno;
ELSE
UPDATE item_mast set qoh= qoh+(:old.qty*2)
WHERE itno=:old.itno;
END IF;
END IF;
END IF;
IF DELETING THEN
IF UPPER(:old.trtp)='S' THEN
UPDATE item_mast SET qoh = qoh+:old.qty WHERE itno=:old.itno;
ELSE
UPDATE item_mast SET qoh= qoh-:old.qty WHERE itno=:old.itno;
END IF;
END IF;
END;

Advanced PL/SQL

Snapshots

PL/SQL File Input-Output


Installation of UTL_FILE package
Functions and Procedures of UTL_FILE package
Function FOPEN
Function IS_OPEN
Procedure FCLOSE
Procedure GET_LINE
Procedure PUT_LINE
Procedure FFLUSH

Pl SQL File Input - Output

Objectives

After studying this chapter, the student should be able to :


Work with Flat Files
Use the UTL_FILE package procedure and functions
Transfer the table data to a simple text file.
Transfer the text file data to a table

Pl SQL File Input - Output

PL/SQL File Input-Output


The Oracle Server adds file Input/Output capabilities to PL/SQL. This is through the supplied
package called UTL_FILE. This package has some procedures and functions which add power to
interact with a text file. The file I/O capabilities are similar to those of the standard operating
system stream file I/O.

Installation of UTL_FILE package


When you install the Oracle server software in the machine the UTL_FILE package is loaded
automatically. To work with this you have to set the active directory in the file called init.ora.
You have to set the active directory name in the environment variable called UTL_FILE_DIR in
the following way:
UTL_FILE_DIR=<directory_name>
If you are providing a specific directory name then you will be able to work with that only. To
get access to any directory you have to specify a * in place of a directory name.
Program unit
FOPEN

Type
Function

IS_OPEN
FCLOSE
GET_LINE
PUT_LINE
FFLASH

Function
Procedure
Procedure
Procedure
Procedure

Purpose
Open a text file for Input or Output. Create an Output file if it
does not exists.
Determine if a file handle refers to an open file.
Used to close a file.
Read a line of text from an opened file.
Write a line to a file. Append an OS specific line terminator.
Physically write all pending output to a file.

Functions and Procedures of UTL_FILE package


FOPEN
file_handle:= UTL_FILE.FOPEN(<location>,<file_name>,<open_mode>);
<location>
Is the OS specific string that specifies the directory in which to open the file.
<file_name> Is the name of the file including extension without any directory information.
<open_mode> Is the string that specifies how the file is to be opened.
R for read, W for write and A for append.
Function FOPEN returns a file_handle that is used in subsequent file operations.
GET_LINE
UTL_FILE.GET_LINE(<file_handle>,<buffer>);

Pl SQL File Input - Output


Procedure GET_LINE reads a line of text from the open file identified by <file_handle> and
place the text in the output <buffer>. <buffer> is a Pl/SQL variable of type VARCHAR2.
PUT_LINE
UTL_FILE.PUT_LINE(<file_handle>,<buffer>);
Procedure PUT_LINE writes a line of text contained in the <buffer> to the open file identified by
<file_handle>.
Code for writing to text file taking data from a table
DECLARE
file_handle
UTL_FILE.FILE_TYPE;
buf
varchar2(200);
BEGIN
file_handle:= UTL_FILE.FOPEN(c:\,data.txt,A);
FOR i IN ( SELECT empno, ename, sal from emp )
LOOP
Buf := i.empno||,||i.ename||,||i.sal;
UTL_FILE.PUT_LINE ( file_handle, buf );
END LOOP;
UTL_FILE.FCLOSE( file_handle );
END;
Code for writing to text file taking data from a table
DECLARE
file_handle
UTL_FILE.FILE_TYPE;
buf
varchar2(200);
eno
emp.empno%TYPE;
enm emp.ename%TYPE;
esal emp.sal%TYPE;
x
NUMBER;
y
NUMBER;
BEGIN
file_handle:= UTL_FILE.FOPEN(c:\,data.txt,R);
LOOP
BEGIN
UTL_FILE.GET_LINE ( file_handle, buf );
x := INSTR ( buf , , , 1, 1 );
y := INSTR ( buf , , , 1, 2 );
eno := SUBSTR ( buf, 1, x-1 );
enm := SUBSTR ( buf, x+1, (y-x)-1 );
esal := SUBSTR ( buf, y+1 );
INSERT INTO myemp values ( eno, enm, esal );

Pl SQL File Input - Output


EXCEPTION
WHEN NO_DATA_FOUND THEN
EXIT;
END;
END LOOP;
UTL_FILE.FCLOSE( file_handle );
COMMIT;
END;
Note : Before use this code create the table; myemp with the same datatype and size.

Chapter 11

Snapshots

What is Object Technology?


What is an object?
Existence of an Object
Persistent Objects
Transient Objects
Retrieving attribute from an object table
Column Objects
Row Objects
REF and DEREF operator
Object with Methods
Calling a Method

Implementing Object Technology

Objectives

After studying this chapter, the student should be able to :


Understanding Object Technology and its benefits
Create Objects
Use Objects in Database Tables and PL/SQL Blocks
Use DML on Tables Containing Objects
Use method in Objects

Implementing Object Technology

What is Object Technology?


Object technology is a method of managing complexity so that we can develop solutions that can
simulate real world problems.
Key Benefits of Object technology

Easy maintenance of application


Faster product development
Higher quality of code at a lower cost
Re-usability of codes

What is an object?
Object in a unit or instance of a class that contains a collection of related procedures and data, to
produce specific result. Procedures could be in the form of methods or functions. Data could be
the form of variable or attributes or data members.

Existence of an Object
In Oracle object can be of two type.
Transient Object
Persistent Object

It is an object that is local to a PL/SQL block.


It is an object that is stored in the database. It is available until it is
explicitly deleted. This can be divided again into two; Row object and
Column object.

Row Object
Column Object

Row object takes up an entire database row.


A column object is only a column of a table or an object.

Syntax for creating objects


CREATE [OR REPLACE] TYPE <type_name> AS OBJECT
(
attribute1
<data_type and size>,
attribute1
<data_type and size>,
method1,
method2
);

Implementing Object Technology


Example:
STEP1: Creating an object called address_type.
CREATE OR REPLACE TYPE address_type AS OBJECT
(
street VARCHAR2(20),
city
VARCHAR2(20),
state VARCHAR2(20),
zip
NUMBER(6)
);
STEP2: Creating another object called emp_type.
CREATE OR REPLACE TYPE emp_type AS OBJECT
(
empno NUMBER(4),
ename VARCHAR2(20),
doj
DATE,
sal
NUMBER(8,2),
This is a column object.
adr
ADDRESS_TYPE
);
STEP3: Creating an object table.
CREATE TABLE empobj OF emp_type;

This is a row object.

Constructing Object Values


Oracle provides built-in constructors for values of a declared type, and these constructors bear
the name of the type. Thus, a value of type emp_type is formed by the word emp_type and a
parenthesized list of appropriate values.
Inserting values into an object table
INSERT INTO empobj VALUES( emp_type(1111,STEAVE,01-MAR-1998,8000,
address_type(Royed Street,Kolkata,Kolkata,700031)));

Retrieving attribute from an object table


SELECT e.adr.street FROM empobj e;

Implementing Object Technology


Updating the attributes value of an object table
UPDATE empobj e SET e.adr.street=Al Fahidi WHERE empno=1111;
Note: Always remember to use table alias while retrieving or updating data.

REF and DEREF operator


Oracle will automatically generate an Object ID, whenever you entered a row into an object
table. You can store the ID into a normal table. And later on you can use the ID to refer to the
original row object.
REF
DEREF

To know the Object ID.


To refer to the original row.

Do the following steps to understand the REF and DEREF operator:


STEP 1: Create the table newemp from the existing table emp:
CREATE TABLE newemp AS SELECT * FROM emp;
STEP 2 : Create the object d_type with two attributes; deptno and dname:
CREATE TYPE d_type AS OBJECT
(
deptno NUMBER(2),
dname VARCHAR2(20)
);
STEP 3 : Create a table based upon d_type object:
CREATE TABLE newdept OF d_type;
STEP 4 : Insert data into newdept table.
INSERT INTO newdept VALUES(d_type(10,'PRODUCTION'));
INSERT INTO newdept VALUES(d_type(20,'SALES'))
INSERT INTO newdept VALUES(d_type(30,'ADMIN'))

Implementing Object Technology


STEP 5 : Check for the reference number that has been generated.
SELECT deptno, ref(e) FROM newdept e
DEPTNO
REF(E)
---------------------------------------------------------------------------------------------------10
000028020917E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03004082120000
20
000028020917E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03004082120001
30
000028020917E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03004082120002
STEP 6 : Check for the current description of newemp table.
DESC newemp;
Name
------------------------------EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO

Null?
Type
---------------- ---------------------------NOT NULL NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(2)

STEP 7 : Add a new column ref2newdept to hold the reference numbers.


ALTER TABLE newemp ADD ref2newdept REF d_type SCOPE IS newdept;
STEP 8 : Display the changed description of the newemp table.
DESC newemp;
Name
------------------------------EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
REF2NEWDEPT

Null?
-------NOT NULL

Type
---------------NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(2)
REF OF D_TYPE

Implementing Object Technology

STEP 9 : Update the ref2newdept column of newemp table with the reference number taking
from newdept table.
UPDATE newemp SET ref2newdept = (SELECT REF(d) FROM newdept d WHERE
d.deptno=newemp.deptno);
STEP 10 : Display the contents of ref2newdept with corresponding deptno.
SELECT deptno,ref2newdept FROM newemp e
DEPTNO REF2NEWDEPT
------------- --------------------------------------------------------------------------------------------------20
30
30
20
30
30
10
20
10
30
20
30
20
10

000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03

STEP 11: Select empno,ename and their corresponding department details using DEREF.
select empno,ename,deref(ref2newdept) from newemp;
EMPNO
----------------7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934

ENAME
--------------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

DEREF(REF2NEWDEPT)(DEPTNO, DNAME)
----------------------------------------------------------------D_TYPE(20, 'SALES')
D_TYPE(30, 'ADMIN')
D_TYPE(30, 'ADMIN')
D_TYPE(20, 'SALES')
D_TYPE(30, 'ADMIN')
D_TYPE(30, 'ADMIN')
D_TYPE(10, 'PRODUCTION')
D_TYPE(20, 'SALES')
D_TYPE(10, 'PRODUCTION')
D_TYPE(30, 'ADMIN')
D_TYPE(20, 'SALES')
D_TYPE(30, 'ADMIN')
D_TYPE(20, 'SALES')
D_TYPE(10, 'PRODUCTION')

Implementing Object Technology

Object with Methods


The operations that can be performed on object attributes are called methods. Methods are
declared after attributes in object type specifications and implemented in the type body.
Example :
STEP1: Creating an object called address_type.
CREATE OR REPLACE TYPE address_type AS OBJECT
(
street VARCHAR2(20),
city
VARCHAR2(20),
state VARCHAR2(20),
zip
NUMBER(6)
);
STEP2: Creating another object called emp_type.
CREATE OR REPLACE TYPE emp_type AS OBJECT
(
empno NUMBER(4),
ename VARCHAR2(20),
doj
DATE,
sal
NUMBER(8,2),
adr
ADDRESS_TYPE ,
MEMBER FUNCTION los(doj DATE) RETURN NUMBER,
MEMBER FUNCTION totsal( sal NUMBER) RETURN NUMBER
);
STEP3: Creating the type body of emp_type object.
CREATE OR REPLACE TYPE BODY emp_type
AS
MEMBER FUNCTION los(doj in DATE)
RETURN NUMBER
IS
BEGIN
RETURN ROUND (sysdate-doj);
END;
MEMBER FUNCTION totsal( sal NUMBER) RETURN NUMBER
IS
BEGIN
RETURN ROUND(.1*sal);
END;
END;

Implementing Object Technology


STEP4: Creating an object table.
CREATE TABLE empobj OF emp_type;

Calling a Method
The referencing of methods or member functions is the same as referencing attributes of abstract
or user defined object data type. To call a method for a particular instance, use the dot (.)
notation. The syntax is :
OBJECT_NAME.METHOD_NAME
Eg: SELECT empno,ename,e.adr.state,e.adr.city from empobj e;
MAP Method
A MAP method is a function that returns a scalar data type. When the object is to be stored, the
MAP method can be called to convert the object to a scalar type that can be stored. A MAP
method will be automatically invoked in the following cases:

An =, > and < operator in WHERE clause


BETWEEN or IN clause in a WHERE condition
ORDER BY, GROUP BY clause in a SELECT statement

Include the following statement on the emp_type declaration, after member function declaration.
MAP MEMBER FUNCTION NAMED RETURN NUMBER
Include the following code on the emp_type body code :
MAP MEMBER FUNCTION zip
RETURN NUMBER IS
BEGIN
RETURN adr.zip;
END;
Using the map method within select statement :
SELECT empno, ename, e.adr.zip FROM empobj e ORDER BY e.zip();

Chapter 12

Snapshots

Large Objects (LOB)


Creating table with LOBs
Inserting values on the table
Updating LOB values
Data Manipulation in LOBs
Working with DBMS_LOB package

Using LOBs

Objectives

After studying this chapter, the student should be able to :


Use Large Objects in Tables
Perform Data Manipulation in LOBs
Use the DBMS_LOB package

Using LOBs

Large Objects (LOB)


In Oracle , the new datatypes which were introduced in Oracle 8 have also been added to store
long data which are knows as Large Objects ( LOBs ). These datatypes are :
BLOB
CLOB
NCLOB
BFILE

Binary Large Object


Character Large Object
Fixed width multi byte character large object
Binary File

The BLOB, CLOB and NCLOB datatypes are stored in the database and are known as Internal
LOBs. Oracle supports data integrity and concurrency for Internal LOBs. The BFILE is not
stored in the database and Oracle does not validate whether the file exists or not when a record is
inserted using the BFILE type. The data for LOB columns is not stored in the table, if the size is
more than 4000 bytes. Oracle stores a Locator as column values for internal LOBs having more
than 4000 bytes and for BFILE types. The Locator points to the location of the actual data stored
inside or outside or inside the database. For BFILE you have to create a directory.

Creating table with LOBs


Example
STEP 1: Create the table.
CREATE TABLE personnel_details
(
man_id
NUMBER(4) PRIMARY KEY,
name
VARCHAR2(25),
responsibility CLOB,
photo
BLOB,
profile
BFILE
)
STEP 2 : Creating the directory for BFILE.
CREATE DIRECTORY per_details AS c:\personnel ;

Inserting values on the table


INSERT INTO personnel_details
VALUES ( 1001, Scott, Take Oracle Classes,
EMPTY_BLOB(),
BFILENAME ( per_details, Scott_profile.doc));

Using LOBs
To set an internally stored column to an empty locator value, we have to use the following
functions :
For BLOB columns EMPTY_BLOB()
For CLOB columns EMPTY_CLOB()
For NCLOB columns EMPTY_CLOB()

Updating LOB values


STEP 1 : To modify LOB values, the row that has to be updated, has to be exclusively locked.
SELECT responsibility FROM personnel_details WHERE man_id=1001 FOR UPDATE;
STEP 2 : This locks the row for man_id =1001. Then to update do the following:
UPDATE personnel_details SET responsibility =Take Oracle DBA classes
WHERE man_id=1001;
STEP 3 : Now to release lock and commit the change use the following command:
COMMIT;
To update the cover_letter column, to put a new cover letter you do the following:
UPDATE personnel_details SET profile=BFILENAME(per_details_dir,scottnew_profile.doc)
WHERE man_id=2;
To UPDATE a BLOB column, first set the value to EMPTY_BLOB() using the update statement
and the update expenses column value.

Data Manipulation in LOBs


DBMS_LOB package

WRITE
APPEND
COMPARE
COPY
ERASE
GETLENGTH
SUBSTR

Using LOBs
To modify the values of LOBs, the following steps have to be taken:

Declare an LOB location in a DECLARE statement of the PL/SQL block


Initialize the locator
Lock the row containing the LOB using the SELECT FOR UPADTE statement
Use the DBMS_LOB package procedure
Commit

Working with DBMS_LOB package


WRITE

The PL/SQL package procedure DBMS_LOB.WRITE writes a specified


number of bytes/character from the buffer into the LOB value at a specified
location in eth LOB.

SYNTAX :

DBMS_LOB.WRITE ( LOCATION, AMOUNT, OFFSET, BUFFERS );

Where :
LOCATION
AMOUNT
OFFSET
BUFFERS
APPEND

LOB locator stored in the tables column.


Number of bytes/characters to write.
Character position from the beginning of LOB, from where the
information has to be written for BLOB, BFILE specified in bytes
for CLOB, NCLOB in char.
Variable containing the information to be written.

Adds data from one LOB to another LOB.

SYNTAX : DBMS_LOB.APPEND ( DEST_LOB, SOURCE_LOB);


Where :
DEST_LOB
SOURCE_LOB

Is the locator of the target Lob of type BLOB/CLOB.


Is the locator of the source Lob.

COMPARE Compares the whole or parts of two LOBs. It returns 0 for a successful match.
SYNTAX : DBMS_LOB.APPEND ( FIRST_LOC, SECOND_LOC, AMOUNT,
FIRST_OFFSET, SECOND_OFFSET);
Where :
FIRST_LOC
SECOND_LOC
AMOUNT
FIRST_OFFSET
SECOND_OFFSET

Lob locator of the first LOB of type BLOB/CLOB


Lob locator of the second LOB of type BLOB/CLOB
Number of bytes/characters to be compared
Character/byte position from beginning of the first LOB value.
Character/byte position from beginning of the second LOB value.

Using LOBs
COPY

Copies the whole or a part of the source LOB into the destination LOB.

SYNTAX : DBMS_LOB.COPY ( DEST_LOC, SOURCE_LOC, AMOUNT,


DEST_OFFSET, SOURCE_OFFSET);
Where :
DEST_LOC
SOURCE_LOC
AMOUNT
DEST_OFFSET
SOURCE_OFFSET
ERASE

Lob locator of the target LOB of type BLOB/CLOB


Lob locator of the source LOB of type BLOB/CLOB
Number of bytes/characters to be compared
Character/byte position from beginning of the first LOB value.
Character/byte position from beginning of the second LOB value.

Erase the whole, or a part of the LOB value.

SYNTAX : DBMS_LOB.ERASE ( DEST_LOC, SOURCE_LOC, AMOUNT,


DEST_OFFSET, SOURCE_OFFSET);
Where :
DEST_LOC
SOURCE_LOC
AMOUNT
SUBSTR

Lob locator of the target LOB of type BLOB/CLOB


Lob locator of the source LOB of type BLOB/CLOB
Number of bytes/characters to be compared

Returns a part of the LOB value as VARCHAR2 for CLOB.

SYNTAX : DBMS_LOB.SUBSTR (LOCATOR, AMOUNT, OFFSET );


Where :
LOCATOR
AMOUNT
OFFSET

Lob locator of the source LOB of type BLOB/CLOB


Number of bytes/characters to be compared
Character/byte position in the LOB from where to start extracting

Example 1 : Read the value of CLOB column using PL/SQL block


DECLARE
A
CLOB,
N
NUMBER,
B
VARCHAR2(100),
BEGIN
SELECT responsibility INTO A FROM personnel_details WHERE man_id=1001;
N := DBMS_LOB.GETLENGTH(A);
B:= DBMS_LOB.SUBSTR(A,N,1);
DBMS_OUTPUT.PUT_LINE( Responsibility is : || b );
END;

Using LOBs
Example 2 : Writing a new value to the CLOB column using PL/SQL block
DECLARE
A
CLOB,
M
NUMBER,
N
NUMBER,
B
VARCHAR2(100),
BEGIN
SELECT responsibility INTO A FROM personnel_details
WHERE man_id=1001 FOR UPDATE;
M := DBMS_LOB.GETLENGTH(A);
DBMS_LOB.ERASE ( A, M,1 );
B:=&responsibility;
N := LENGTH(B);
DBMS_LOB.WRITE ( A, N, 1, B );
COMMIT;
END;
Example 3 : Copying One LOB to another using PL/SQL
DECLARE
A
CLOB,
N
NUMBER,
B
CLOB,
BEGIN
SELECT responsibility INTO A FROM personnel_details WHERE man_id=1001;
SELECT responsibility INTO B FROM personnel_details
WHERE man_id=1002 FOR UPDATE;
N := DBMS_LOB.GETLENGTH(A);
DBMS_LOB.COPY( B, A, N,1,1 );
END;

Chapter 13

Snapshots

Collections
Nested Tables
Creating table using Nested Table
DML operations on Nested Table
Nested Table in PL/SQL
VARRAYs
Creating VARRAYs
DML operations with VARRAYs
VARRAYs in PL/SQL
Similarities and differences between Nested Table and VARRAYs

Collections in Oracle

Objectives

After studying this chapter, the student should be able to :


Understand Collections
Work with Nested Tables and VARRAYING arrays
Use DML statements in Nested table
Use DML statements in VARRAY
Use Collection in PL/SQL
Understand Similarities and differences between Nested Table and VAARAY

Collections in Oracle

Collections
Collections are similar to arrays in other languages. In oracle release 7.3 and earlier, there was
only one kind of collection, called a PL/SQL table. This type of collection is still supported but is
now known as an index-by table. A collection is an ordered group of elements. Like records,
collections must be defined with the TYPE statement, then variables of that type can be created
and used. Oracle provides two new Collection types: Nested Table and VARRAYS.

Nested Tables
A Nested table is useful for data models requiring referential integrity and is suitable for master
detail and one to many relationships. A Nested table is a database table which stores data in it,
that cannot be accessed directly. A Nested table can be included in a table definition as one of the
columns. That is why, they are known as Nested tables. Nested table can be manipulated directly
using SQL.

Creating table using Nested Table


To create a table, using Nested table as one of the columns in that table, the syntax is :
CREATE TABLE < table_name >
(
<column_name >
datatype,

..,

..,
<column_name >
< table_type >
)
NESTED TABLE < column of table_type > STORE AS < store_table >;
Example :
Step 1 : Creating An object
CREATE TYPE book_type AS OBJECT
(
book_no
NUMBER(4),
book_name VARCHAR2(20),
author
VARCHAR2(20)
);
Step 2 : Creating a table type
CREATE TYPE bk_type AS TABLE OF book_type;

Collections in Oracle
Step 3 : Creating the nested table
CREATE TABLE studlab_rec
(
stno
NUMBER(4) NOT NULL,
stnm
VARCHAR2(20),
book_issu
bk_type
)
NESTED TABLE book_issu STORE AS booknest;

DML operations on Nested Table


1.

Insert statement
INSERT INTO studlab_rec VALUES
(1001, 'Amit Kumar', bk_type(book_type(2001,'Oracle ','loney'),
book_type(2002,'Oracle bible','kevin')));

2.

Update statement
UPDATE THE ( SELECT book_issu FROM studlab_rec WHERE stno=1001)
SET book_name ='Oracle Unleashed' WHERE book_no=2001;

3.

Insert another row in the Nested table


INSERT INTO THE (SELECT book_issu FROM studlab_rec WHERE stno=1001)
VALUES (book_type(2003,'Visual Basic','ken pol'));

4.

Delete statement
DELETE FROM THE (SELECT book_issu FROM studlab_rec WHERE stno=1001)
WHERE book_no=2003

Nested Table in PL/SQL


When a Nested table is fetched into a PL/SQL variable, it is assigned keys starting at 1 and
ranging to the number of elements in the table. The number of elements can be determined using
the COUNT method.

Collections in Oracle
Example :
DECLARE
mbk studlab_rec.book_issu%TYPE;
mnm studlab_rec.stnm%TYPE;
CURSOR ntc IS SELECT stnm,book_issu FROM studlab_rec;
BEGIN
OPEN ntc;
LOOP
FETCH ntc INTO mnm,mbk;
EXIT WHEN ntc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Book issued to : '||mnm);
FOR i IN 1..mbk.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE ('Book Title ---> '||mbk(i).book_name);
END LOOP;
END LOOP;
CLOSE ntc;
END;

VARRAYs
VARRAY is a datatype similar to an array in C or Pascal. Elements are inserted into a VARRAY,
starting at index 1 upto the maximum length declared in the VARRAY type. Each element of the
array has the position indicated by an index which can range from one to the COUNT value. A
VARRAY can be stored in a database column. A VARRAY can only be manipulated as a whole.
Individual elements of stored VARRAYS cannot be modified.

Creating VARRAYs
The syntax of creating a VARRAY is as follows :
CREATE OR REPLACE TYPE < type_name >
IS VARRAY<(maximum_size)> OF < element_type >;
Example :
STEP 1 : Creating an Object.
CREATE TYPE book_type AS OBJECT
(
book_no
number(4),
book_name varchar2(20),
author
varchar2(20)
);

Collections in Oracle
STEP 2 : Creating VARRAY.
CREATE OR REPLACE TYPE book_arr AS VARRAY(10) OF book_type;
STEP 3 : Creating the table.
CREATE TABLE stud_rec
(
stno
number(4) NOT NULL,
book_issu
book_arr
);

DML operations with VARRAYs


1.

Insert Statement
INSERT INTO stud_rec VALUES(1002, book_arr (
book_type(1001,'Java 1.2.1','Sun MicroS'),
book_type(1002,'Java Servlets','Sun MicroS'),
book_type(1003,'Java beans','Sun MicroS'),
book_type(1009,'Java 1.2.1','Sun MicroS')));

2.

Update Statement
UPDATE stud_rec SET book_issu=book_arr(book_type(1006,'Corba','Sun MicroS'),
book_type(1007,'Java beans','Sun MicroS'),
book_type(1008,'Java servlates','Sun MicroS'))
WHERE stno = 1002;

VARRAYs in PL/SQL
To modify a stored VARRAY, it has to be selected into a PL/SQL variable and then inserted back
into the table. This technique is illustrated below :

Collections in Oracle
Example 1 : Update a particular column in the VARRAY.
DECLARE
bk_arr
book_arr;
BEGIN
SELECT book_issu INTO bk_arr FROM stud_rec WHERE stno=1002;
FOR i IN 1..bk_arr.COUNT
LOOP
IF bk_arr(i).book_no=1006 THEN
bk_arr(i).book_name :='VC++';
END IF;
END LOOP;
UPDATE stud_rec SET book_issu = bk_arr WHERE stno=1002;
END;
Example 2 : Insert a new row in the VARRAY.
DECLARE
bk_arr
book_arr;
BEGIN
SELECT book_issu INTO bk_arr FROM stud_rec WHERE stno=1002;
bk_arr.EXTEND;
bk_arr(bk_arr.COUNT):=book_type(1011,'Web tool','BPB');
UPDATE stud_rec SET book_issu = bk_arr WHERE stno=1002;
END;

Similarities and differences between Nested Table and VARRAYs


Similarities :

Both types allow access to individual elements using subscript notation


Both types can be stored in database tables

Differences :

VARRAYs have a maximum size, as specified at the time of creation, while Nested Table do
not
VARRAYs stored inline with the containing table, while Nested Tables are stored in a
separate table which can have different storage characteristics
Rows in the Nested Table can be accessed individually by using the THE clause, where as
in the VARRAYs all the rows should be accessed as one object and is to be manipulated
using PL/SQL blocks

Collections in Oracle

PL/SQL RESERVED WORDS

A
ABORT
ACCEPT
ACCESS
ADD
ALL
ALTER
AND
ANY
ARRAY
AS
ASC
ASSIGN
AT
AUTHORIZATION
AVG
B
BASE_TABLE
BEGIN
BETWEEN
BINARY_INTEGER
BODY
BOLEAN
BY
C
CASE
CHAR
CHAR_BASE
CHECK
CLOSE
CLUSTER
COLAUTH
COLUMNS
COMMIT
COMPRESS
CONNECT
CONSTANT
COUNT

CRASH
CREATE
CURRENT
CURSOR
CURRVAL
D
DATABASE
DATA_BASE
DATE
DBA
DEBUGOFF
DEBOGON
DECLARE
DECIMAL
DEFAULT
DEFINITION
DELAY
DELETE
DESC
DIGITS
DISTINCT
DO
DROP
E
ELSE
ELSIF
END
ENTRY
EXCEPTION
EXISTS
EXIT
F
FALSE
FETCH
FLOAT
FOR
FORM
FROM

FUNCTION
G
GENERIC
GOTO

O
OF
ON
OPEN
OPTION
GRANT
OR
GROUP
ORDER
H
OTHERS
HAVING
P
I
PUT
IDENTIFIED
PACKAGE
IF
PARTITION
IN
PRAGMA
INDEX
PRIOR
INDICATOR
PRIVATE
INSERT
PROCEDURE
INTEGER
PUBLIC
INTERSECT
R
INTO
RAISE
IS
RANGE
L
REAL
LEVEL
RECORD
LIKE
RELEASE
LEMETED
REM
LOOP
RENAME
M
RESOURSE
MAX
RETURN
MIN
REVERSE
MINUS
REVOKE
MOD
ROLLBACK
N
ROWID
NATURAL
ROWLABEL
NEW
ROWNUM
NEXTVAL
ROWTYPE
NOT
RUN
NULL
S
NUMBER
SAVEPOINT
NUMBER_BAS SCHEMA

SELECT
SET
SIZE
SMALLINT
SPACE
SQL
SQLCODE
SQLERR
START
STATEMENT
SUM
T
TABAUTH
TABLE
TABLES
TASK
TERMINATE
THETON
TRUE
TYPE
U
UNION
UNIQUE
UPDATE
USE
V
VALUES
VARCHAR
VARCHAR2
VIEW
VIEWS
W
WHEN
WHERE
WHILE
WITH
WORK

Collections in Oracle

Table Structure
EMP table :
Column name
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO

Type
NUMBER(4)
VARCHAR2(20)
CHAR(10)
NUMBER(4)
DATE
NUMBER(9,2)
NUMBER(7,2)
NUMBER(2)

Description
Employee number
Employee name
Designation
Respective managers EMPNO
Date of joining
Basic salary
Commission
Department number

DEPT table :
Column name
DEPTNO
DNAME
LOC

Type
NUMBER(2)
VARCHAR2(20)
VARCHAR2(10)

Description
Department number
Name of the department
Location of the department

INCR table :
Column name
EMPNO
AMT
DATEINCR

Type
NUMBER(4)
VARCHAR2(20)
DATE

Description
Employee number
Incremented amount
Date of increment

ITEMMAST table :
Column name
ITNO
NAME
QOH
CLASS
ROL
RATE

Type
NUMBER(4)
VARCHAR2(20)
NUMBER(5)
CHAR(1)
NUMBER(5)
NUMBER(8,2)

Description
Item number
Item description
Quantity on hand
Category of item
Reorder quantity
Unit price of sale

ITTRAN table :
Column name
ITNO
UPD_FLAG
TRANTYPE
TRANDATE
QTY

Type
NUMBER(4)
CHAR(1)
CHAR(1)
DATE
NUMBER(5)

Description
Item number
Master updated ( Y/N )
Transaction type
Transaction date
Transaction quantity

Collections in Oracle

Hands on Session
Session 1
Write an appropriate SQL statement for the following : 01. List all details of those employees who are getting salary more than 1500.
02. List all the employees who are working on department 20 & 30.
03. List all the clerk details who are working on department 10 & 30.
04. List all the employees details who are getting commission.
05. List all the employees details who are getting no commission but the salary must be
greater than 2000.
06. List all the employees details who does not reported anybody.
07. List all the jobs available in the emp table.
08. List all the location available in the dept table.
09. List all the employees details according to their salary priority.
10. List the number of jobs available in the emp table.
11. List the maximum salary of employee working as a salesman.
12. List the average salary of employee working as a salesman.
13. List the jobs and the number of employees in each job. The result should be in
descending order of the number of employees.
14. List the total salary job wise.
15. List the average salary for each job excluding managers.
16. List the average salary for each job type within department.
17. List average salary for all departments employing more than five people.
18. List the employee details and the department name.
19. List the employee details and the department name even if no employee belongs to
that department.
20. List all the employee name along with their manager. Also show the employee name
who is not reporting to anyone.
21. List all the employees of department 30 who joined the company before their manager.
22. Display the different designations in the department 20 and 30.
23. List the jobs common to department 20 and 30.
24. List the jobs unique to the department 20.
25. List the names of the employee drawing the highest salary.
26. List the job with highest average salary.
27. List the names of the employees, who earn lowest salary in each department.
28. List employee details who earn salary greater than the average salary for their department.
29. List all employees who have at least one person reporting to them.
30. List all employees whose salary is greater than any of the manager.
31. List all employees who do not manages any one.
32. List the details of the employee earning more than the highest paid manager.
33. List the employee details who earn highest salary for their job.
34. List the details of those employees who are among the five highest earners of the company.

Collections in Oracle

Session 2
Create the following tables :
BANK_MAIN
Field Name
ACC_NO
NAME
ADDRESS
ACC_TYPE
OPEN_BAL
CURR_BAL

Description
Account number
Account holder
Address of account holder
Type of account
Opening balance
Current balance

Type & Width


Number ( 4)
Varchar2 (20)
Varchar2 (30)
Char(1)
Number (8,2)
Number (8,2)

Constraints
Primary Key
NOT NULL
NOT NULL
NOT NULL

Give a check constraints on ACC_TYPE column with the following pattern.


ACC_TYPE: Saving ( S ) , Current ( C ) , Recurring deposit ( R )
BANK_TRANS
Field Name
ACC_NO
TR_DATE
TR_TYPE
TR_AMT
UPD_FLAG

Description
Account number
Transaction date
Type of Transaction
Transaction amount
Master update ( Y/N)

Type & Width


Number ( 4)
Date
Char(1)
Number (8,2)
Char(1)

Constraints
FK to bank_main
NOT NULL
NOT NULL
NOT NULL

Give a check constraints on TR_TYPE column with the following pattern.


TR_TYPE:
INTEREST
Field Name
ACC_NO
INT_AMT

Deposit ( D ) , Withdrawal ( W )
Description
Account number
Interest amount

Type & Width


Number ( 4)
Number(6,2)

Constraints
FK to bank_main
NOT NULL

Write PL/SQL code to :


1. List out all account holders of saving account type.
2. Update the master tables ( i.e., bank_main ) CURR_BAL field with transaction details from
the transaction file ( i.e., bank_trans ) and also change the status of the UPD_FLAG field of
the transaction table to Y once the updation is complete.
Note : Use Cursor for the above Pl/SQL code.

Appendix C
Session 3
Create two tables with the following fields :
STUDMAST
Field Name
Stno
Stnm
Btcd
Btrlno
Crnm
Rgdt
Stdt
Pat
Totfee
Duefee

Description
Student ID
Student name
Batch Code
Batch Roll NO.
Course Name
Registration Date
Starting Date
Pattern
Total Fees
Due Fees

Type & Width


Number ( 4)
Varchar2 (20)
Varchar2 (15)
Number (3)
Varchar2 (20)
Date
Date
Varchar2 (4)
Number ( 7)
Number ( 7)

Constraints
Primary Key
NOT NULL

NOT NULL

Give a check constraints on Pat column with the following pattern.


Pat
:
a) Full Time. [ FT ]
b) Semi Full Time. [ SFT ]
c) Part Time
[ PT ]
FEES
Field Name
Stno
Pddate
Pdfee

Description
Student ID
Paid Date
Fees Paid

Type & Width


Number ( 4)
Date
Number (7,2)

Constraints
FK to STUDMUST
NOT NULL

Create a package with the following modules :


1. Create a Procedure to show the batch wise report by taking the user entry of batch
code.
2. Create a procedure to show the Student name, Batch code, Batch Roll no and due fees
of the students.
3. Create a procedure to show the monthly student report based on registration date with
the given fields. ( Stno, Stnm, Brlno, Pddate, Pdfee )
Create a Trigger to update the Duefee column depending upon the Pdfee column of Fees
table.

Project

Goods Inwards System (GIS)


Introduction
The project forms part of a very critical component of an over all MRP II system. This module
(GIS) covers the part of activities of the stores, purchase and goods inward departments of a
typical manufacturing organization. A planned overlap of the function of the various departments
is introduced to familiarize the students with the application as well as to enable use of various
integrity constraints. Further the projects has been defined in such a way that all the major tools
of Oracle like, PL/SQL, Database Triggers, Oracle Forms, Menus and Reports can be effectively
used.
Project Definition
A company called Efficient Manufacturing LLC., specialists in production and sale of pneumatic
components. The company has a list of suppliers who supply the raw material as well the various
components required for the production of the finished goods. Purchase orders are issued on the
basis of purchase requirement of the store department. Goods Inward Note (GIN) is prepared for
all goods received from the supplier(s). The GIN is used to updates the stock position
simultaneously.
The information model provided here is a reflection of the business data model of Efficient
Manufacturing LLC. The entities and their association are provided by the user to analyze and
design the required database tables with appropriate foreign keys and primary key.
In addition to the database structures, the user are also required to write/modify the suggested
procedures and / or Database Triggers. In the following section the required business rules to
perform the operation are provided. Suggested denormalizations to certain tables are also
provided to improve performances. The user is free to modify the database design according to
his/her design strategies.
The Data Model
ENTITIES
1. Item
2. Stock
3. Supplier
4. Purchase Order (PO)
5. Purchase Order Detail (POD)
6. Goods Inward Header (GIN)
7. Goods Inward Detail (GIND)
RELATIONSHIP BETWEEN ENTITIES
Item

must be having one and only one stock


may be present in one or more Purchase Order Details
may be present in one or more Goods Inward Details

Project
Stock
must be for one and only one item
Purchase Order
must be having one or more Purchase Order Details
may be having in one or more Goods Inward Headers
must be raised to one and only one suppliers
Supplier
may be raised one or more Purchase Order
Goods Inward Detail
must be for one and only one Goods Inward Header
must be for one and only one item
Purchase Order Detail
must be for one and only one Purchase Order
must be containing one and only one item
ATTRIBUTES
ITEM

Item Number
Item Description
Quantity on hand
Item classification
Unit of measurement
Reorder level
Reorder quantity
Item rate

STOCK

Item code
Opening balance
Opening balance date
Item classification
Year to date receipts
Year to date issues

SUPPLIER

Supplier code
Supplier name
Street
City
State
ZIP
Phone

PURCHASE ORDER DETAIL

GOODS INWARD HEADER

GOODS INWARD DETAIL

PURCHASE ORDER

Quantity ordered
Rate

Quantity received
Quantity accepted
Rate

Goods inward number


Goods inward date

Purchase order number


Purchase order date
Proposed delivery date
Purchase order value

Project
Tables and Keys
ITEMMAST
Attributes
Item Number
Item Description
Quantity on Hand
Item Classification
Unit of Measurement
Reorder Level
Reorder Quantity
Item Rate

Columns
ITNO
NAME
QOH
CLASS
UOM
ROL
ROQ
RATE

Datatype/size
NUMBER(4)
VARCHAR2(20)
NUMBER(5)
VARCHAR2(1)
VARCHAR2(4)
NUMBER(5)
NUMBER(5)
NUMBER(8,2)

Constraints
Primary Key
NOT NULL
Default 100
NOT NULL
NOT NULL

CHECK Constraint is added to this table as :


( (class = A AND RATE<1000)
OR (class = B AND (RATE BETWEEN 1000 AND 4500)
OR (class = C AND RATE>4500)
) AND (ROL>0 AND ROQ>0)
STOCK
Attributes
Item Code
Opening Balance
Opening Balance
Date
Year-to-Date receipts
Year-to-Date Issues

Columns
ITNO
OPBAL
OPBALDATE

Datatype/size
NUMBER(4)
NUMBER(8,2)
DATE

YTDRCV
YTDISS

NUMBER(8,2)
NUMBER(8,2)

SUPPLIER
Attributes
Supplier Code
Supplier Name
Street
City
State
ZIP
Phone

Columns
SUPCODE
SUPNAME
STREET
CITY
STATE
ZIP
PHONE

GINHEAD
Attributes
Goods inward number
Goods inward date
Supplier Code
Purchase order number

Columns
GINNO
GINDATE
SUPCODE
PONO

Datatype/size
NUMBER(4)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
Datatype/size
NUMBER(4)
DATE
NUMBER(4)
NUMBER(4)

Constraints
Primary Key
NOT NULL
NOT NULL

Constraints
Primary Key
NOT NULL
NOT NULL

Constraints
Primary Key
NOT NULL
FK to SUPPLIER
FK to POHEAD

Project
GIN value
GINDETAIL
Attributes
Goods inward number
Item code
Quantity received
Quantity accepted
Rate
Purchase order number

GINVAL

NUMBER(8,2)

Columns
GINNO
GINITEM
GINQTY
GINACCEPT
GINRATE
PONO

Datatype/size
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(8,2)
NUMBER(4)

Default 0
Constraints
FK to GINHEAD
FK to ITEMMAST
NOT NULL
NOT NULL
NOT NULL

Create a combined foreign key on PONO and GINITNO referencing


to PONO and POITNO of PODETAIL table.
POHEAD
Attributes
Purchase order number
Purchase order date
Proposed delivery date
Purchase order value
Supplier number
Status

Columns
PONO
PODATE
DELIDATE
PURVALUE
SUPCODE
POSTAT

PODETAIL
Attributes
Quantity ordered
Rate
Item number
Purchase order number
Quantity received

Columns
POQTY
PORATE
POITNO
PONO
PORECV

Datatype/size
NUMBER(4)
DATE
DATE
NUMBER(8,2)
NUMBER(4)
VARCHAR2(1)

Datatype/size
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(4)

Constraints
Primary Key
NOT NULL
NOT NULL
Default 0
FK to SUPPLIER
Check I,N,C or F
Default N
Constraints
NOT NULL
NOT NULL
FK to ITEMMAST
FK to POHEAD

Primary key will be on PONO and POITNO.


Validation and De-Normalizations
To facilitate quick data retrieval and improve performance of data access, the following denormalize columns are added to the tables. These de-normalized columns will be validated using
suitable constraints and / or triggers at appropriate levels.
Goods Inward Header (GINHEAD)
1. The supplier code can be added to the GINHEAD. This column must be validated against
PO raised.
2. Items specified in a PO can be received in full or in parts. For each batch of receipt, a
fresh GIN must be generated. Under no circumstances, a GIN should be modified.

Project

3. When all the items in required quantities for a particular purchase order has been
accepted, disallow further generation of GINs.
4. The GIN value will be automatically calculated from the quantity accepted and rate.
Goods Inward Detail (GINDETAIL)
1. The items for GINDETAIL must be the same as present in the PODETAIL. To perform
this operation, retrieve all the PO details and prepare the GIN details for those items only.
2. The PO number can be maintained in the GINDETAIL table, through which the item and
the quantity ordered in a particular PO can be easily retrieved. The value for this column
will be automatically derived from the GINHEAD.
3. The GIN quantity received must be less than or equal to the quantity ordered for that
item. In case a PO is received in parts, the further GINs must be generated for the
remaining items and / or quantities only.
4. When the quantity accepted is entered, the quantity on hand of ITEMMAST table must
be updated. This can be done using DB Trigger on GINDETAIL table.
Purchase Order ( PO )
1. A PO can have four state, viz. New, Incomplete, Fully received or Canceled. An
additional column must be added to the PO which will indicate the state so that a GIN
can be generated for the POs which are New or Incomplete only. The proposed Datatype
and length of this column is VARCHAR2(1) and the allowable values are :
N : New
C : Canceled

I : Incomplete
F : Fully received or complete.

2. The PO value will be calculated automatically by multiplying the quantity ordered and
the rate from the PODETAIL table.
Purchase Order Detail ( PODETAIL )
1. A column can be added to PODETAIL, which will contain the quantity accepted by a
GIN. Each time a GIN is accepted, the quantity received ( in PODETAIL ) against a
particular item can be updated. This helps us in retrieving the remaining quantities of a
particular item to be received more efficiently.
2. Create a unique index on PONP + POITNO, which will help in retrieving a particular
item in a PO from the PODETAIL.

Project
Development Methodology
The following Database Triggers, Procedure, Reports, Entry Screens suggested.
Reports/Queries and Entry screens
1.
2.
3.
4.
5.
6.

List all the pending Purchase Orders.


Generate GIN details for a given PO.
List item wise receipts over a period.
GIN wise item value report.
Entry screen for Purchase Order and GIN.
Item master, supplier and stock entry screens

Database Triggers
GINDETAIL
This trigger will fire after insertions of each row into GINDETAIL. The following functions
will be performed after execution of this trigger :
1. QOH column of the ITEMMUST table will be updated by adding the quantity accepted.
2. QTYRECV column in PODETAIL will be updated by adding the quantity accepted.
Procedures and Functions
1.
2.
3.
4.
5.
6.
7.

Calculate PO value.
Get pending Pos from the POHEAD.
Get pending items, qty ordered and qty received from the PODETAIL.
Update QOH in ITEMMUST.
Update the quantity accepted ( PORECV ) in PODETAIL.
Update the POSTAT in PO.
Get GIN numbers for a PO.

The Proposed Menu Design


Main Menu
Master

Item
Master

Transaction

Supplier
Master

Stock
Master

Purchase
Order

Note : You might not work with the stock table.

Query

GoodsInward Note

The reports and


Query Screens

You might also like