You are on page 1of 273

RDBMS

RDBMS is the acronym for Relational


Database Management System. The Concept of
relational database is known since 1980’s but the
idea of Database Management System is definitely
quite old. The most famous RDBMS packages are
Oracle,Sysbase and informix.
What is Database Management System?
A DBMS is essentially a collection of
interrelated data and a set of programs to access
this data. This collection of data is called the
Database.A Database System consists of two parts
namely, Database Management System and
Database Application.
Database Management System is the program
that organizes and maintains the information
whereas the Database Application is the
program that lets us view,retrieve and updates
information stored in the DBMS
DBMS has to protect database against
unintentional changes that could be caused by
users and applications In case of multi-user
system, it must be capable of notifying any
database change to the other user.
Codd’s Rules
A database management system
should obey the following twelve rules of Dr.
E.F.Codd for it to be relational.
1. The Information Rule:
Each and every piece of data should be
represented as datavalue of a table.
2. The Guaranteed Access Rule:
Every piece of data must be accessible
by specifying the name of the table,column
of the data and the primary key value of the
row
3. The Systematic Treatment Of Null Values:
Database System must support Null
value to represent unknown or inapplicable
information. It must be different from zero
and spaces. NULL value must be
independent of datatype.
4. The Database Description Rule:
The description of database objects
stored in the database must also be stored
logically as the data and should be
accessible to the users with appropriate
privileges. It is usually called as System
catalog or data dictionary.
5. Comprehensive Data Sub Language Rule:
The database system must have a language
that supports the following
 Data Definition
 View Definition
 Data Manipulation
 Integrity Constraints
 Authorization
 Transaction Management Operations
6. View Updating Rule :
All kinds of views that are theoretically
updateable must also be updateable by the
system.

7. The Insert and Update Rule:


The database language must have a
manipulation
commands(insertion,updation,deletion) those will
act on sets of rows instead of a single row.
8. Physical Data Independence Rule:
Application programs must remain
unimpaired when any changes are made in
storage representation or access methods.
9. Logical Data Independence Rule:
The changes / additions that are made with
the database objects should not affect the
programs that manipulates them.
10. Integrity Independence Rule:
Database system must have a capability to
maintain the integrity constraints in the database
and not in the application programs.
11. The Distribution Rule :
The system must be able to access or
manipulate the data that is distributed in
other systems.

12. The Non - Subversion Rule:

The Non -subversion rule states the


different levels of the language cannot subvert
or bypass the integrity rules and constraints.
To put it in simple words, if an RDBMS
supports a lower level language then it should
not bypass any integrity constraints defined
in the higher level.
Data Definition Language (DDL) Commands:
Create,Alter & Drop Commands
Syntax for Creating a Table:
Create table <tablename>(co11 definition, co12
definition, co13 definition, co1n definition);
Criteria In Creation of Table
 Table name should not exceed 30 characters in length
and no spaces are allowed between table name. Inspite
of spaces underscores can be used.
Example :-
SQL>Create table emp(eno number(4),ename
varchar2(30),designation varchar2(30),salary
number(8,2));
After creating the table to view the structure of the table
syntax is
SQL>Desc <tablename>
Which displays the structure of the table.
Syntax To Modify a Table:-
To add a column to the table following is the syntax
Alter table <tablename> add(col1 definition,col2
definition,coln definition);
If the user want to add more than one column than it has to
be given within parentheses. Just to add one column
parentheses is not a must.
Example:
SQL>Alter table emp add(dob date,doj date);
The columns added to the table with the help of alter table
command will be added to the end of the table, and the user
cannot insert a column between existing columns. But at
time of viewing the user can select the columns according
the user wish.
If the user want to modify the existing column like
 Changing the Datatype of the column
 Increasing the column width or decreasing the column
width.
Criteria to be followed when modifying the column in a
table.
 To change the Datatype of a column and to decrease the
width of a column the table should be empty.
Example:
SQL>Alter table emp modify(salary number(10,2));
Deleting a Column from a table:
In oracle 8i we can delete a column and the syntax to
delete a column is
SQL> Alter table <table name> drop column <column
name>
Dropping a Table: -
To dropping a table is very simple and the syntax to
drop the table is :
Drop table <tablename>;
Example:
SQL>Drop Table Emp;
The Structure of the table is removed from the database
after performing the above command.
Before dropping the table the user should be careful because
table once dropped it cannot be retrieved.

Data Manipulation Language Commands:-


Since table is dropped user has to create the table again
SQL>Create table emp(eno number(4),ename
varchar2(30),designation varchar2(30),salary
number(8,2),dob data,doj date);
Select Command : -
This command is used the view the rows in a table.
SQL> Select * from emp;
The above statement displays the value for all the columns
in the table
* is a wild card character which displays the values of all
column. By default the values are displayed in the order in
which the table is created.
SQL> Select eno,ename from emp;
The above command displays the details of only two
columns from the table. The user can have an alias name to
the column also.
SQL>Select eno Employee Id,ename Employee Name from
emp;
Employee Id and Employee Name is the alias name given for
the column eno,ename.
Insert Command : -
Insert command helps to insert rows or records into the
table. Syntax to insert rows into the table
Insert into <tablename> values(a list of data values);
Example:
SQL> Insert into emp
values(101,’Aswin’,’Programmer’,12000,’02-Aug-78’,’02-
nov-98’);
If the user want to insert a set of records then the user
should use the & symbol.
Example to insert more than one record : -
SQL> Insert into emp
values(&eno,’&ename’,’&desig’,’&sal’,’&dob’,’&doj’);
By prefixing the & symbol before the column name oracle
will prompt the user to enter the value. After inserting the
records the user can commit the transaction. Apart from
number datatype column rest of the column value has to be
given within quotes.
For number datatype giving the value within quotes is an
optional part.
By default in oracle for all the columns the user has to
insert records even to insert NULL value user has to
specify explicitly it contains NULL value .

If the user want to insert rows for few columns and not to
all the columns in the table means the syntax is

SQL>Insert into <tablename> (col1,col3,col5) values (list


of data values);

Example to Insert Records For Few Columns


SQL>Insert into emp(eno,ename,salary)
values(&e1,’&e2’,&e3);
In the above example the user can insert multiple records.
Update Command: -
Syntax to update a record in a table.
SQL>update <tablename> set =col1 where <condition>;

Example for Updating Records in a Table:

SQL> update emp set designation=‘Manager’


where eno=101;

In the update statement if the user is ignoring the where


clause then all the records in the table will be updated.
More than one column can also be updated in a table.
Example for updating more than one column in a Table:

SQL> update emp set designation=‘Manager’ ,


Doj=‘15-Sep-78’
where eno=101;

Delete Command : -

Syntax to delete all records in a table

SQL> Delete from <tablename>;

If the user want to delete a set of records then the syntax is

SQL> Delete from <tablename> where condition;


Example to delete set of records : -

SQL> Delete from emp where eno = 105;

All DML Commands are not fixedly stored in the


database if the user want to store the transaction
preformed into Database then the user has to commit the
transaction.

Transaction Control Language (TCL) Commands : -

Commit Command : -
After performing any DML Commands user has to
give the commit statement.

SQL> Commit;
Rollback Command:

To retrieve the transactions from the database user can go


for Rollback command.

SQL>Rollback;

Savepoint command:

If the user want to commit or rollback up to certain


transaction than savepoint can be used it acts like a
bookmark.

SQL> Savepoint S1;

After creating savepoint user can commit or rollback to


savepoint.
Truncate Command: -

Truncate command leaves the structure of the table


and removes all the rows in a table. And the rows cannot
be retrieved after truncating the table.

Example for Truncating the Table:

SQL>Truncate table emp;

The above command removes the rows from the table emp
and the structure is left. This we can check it by place the
select command on the table.
Select Command to Create a Table
The user can also create a table and copy the
records into it with a single statement, by
including a ‘select’ clause in a create table
command. The syntax is given below
create table <tablename> as select
column_name from <existing_table_name>;
Example :
SQL> Create table employee_details as select *
from emp;
SQL> select * from employee_details;
The above command displays all the details of
the table employee_details which is a copy of
the table emp.
If the user want to copy the structure of the
table then
SQL> Create table emp_details
(employee_id,employee_name) as select
(eno,ename) from employee_details
where 1 = 2;
Select Command to Insert Records:
Syntax to insert records to a table with the help of
Select command is
Insert into <table_name> (Column_Name) (select
column_names from <existing_table_name>);
Example
SQL> insert into
emp_details(employee_id,employee_name) (select
eno,ename from emp where salary>15000);
Operators in SQL
The following are the operators supported by
SQL
 Arithmetic Operators
 Comparison Operators
 Logical Operators
Arithmetic Operators :
All arithmetic operators (Addition,
Subtraction,Multiplication,Division) can be
performed on SQL Statements.
For Example:
SQL> Select eno,ename,salary+1500 salary
from emp where salary>8000;
Comparison Operators
Comparison Operators are used in conditions
to compare one expression with another. The
comparison operators are
=, !=,<, >, <=, >=, Between, In,Not In
Not Between, like, Not Like, is Null, is Not Null.
Example for Comparison Operator
SQL>Select eno,ename from emp where
ename like ‘R%’;
The above command displays the records of the
employees those name starts with R and
followed by any number of characters.
SQL> Select eno,ename from emp where
ename like ‘R__’;
Logical Operators : -
A logical operator is used to combine the results of
two conditions to produce a single result the logical
operators are
 And Operator
OR Operator
 Not Operator

If the user want to view the details of the employee


whose designation is ‘Programmer’ and his/her
salary should be greater than 10000. Then
SQL> Select * from emp
where designation=‘Programmer’ And
Salary>10000;
If the user want to view the details of the employees
whose designation is either ‘Programmer’,’Systems
Analyst’ or Salary <10000;
SQL> Select * from emp
where designation in(‘Programmer’,’Systems
Analyst’) Or Salary<10000;
Not Operator
If the user want to view the details of
employee who salary is not 10000 then the following
query can be issued
SQL> Select * from emp
where salary !=10000;
The above query can be issued in different ways
they are
SQL> Select * from emp
where salary not in 10000;
SQL> Select * from emp
where salary <> 10000;

Operator Precedence: -
Arithmetic Operators highest
Comparison Operators
Not Logical Operator
And Logical Operator
Or Logical Operator Lowest
Note :
The order of precedence can be altered by
using parenthesis.
Order By Clause: -
Order by Clause is used to sort the records.
Column can be sorted in either by ascending or
descending, By default oracle sorts the column in
ascending order if the user want to sort the column
in descending order then
SQL>Select * from emp order by ename desc;
Restrictions in Order by Clause : -
Order by Clause cannot have any conditions
and it can be last statement in SQL.
Group by Clause : -
Group by Clause eliminates the duplicate
records and unique records are displayed, In Group
by clause the user can place the conditions.
Conditions in a group by clause is specified with the
having Clause.
If the user want to view the employee’s details who
draw the same salary then
SQL>Select * from emp
where salary in(select salary from emp group by
salary having count(salary)>1);
Functions
Single Row Functions
Group Functions

Single Row Functions : -


Single Row Function returns only one value
for every row queried in the table. Single row
functions can appear in a select command and can
be included in a ‘where’ clause. The single row
functions can be broadly classified as :
 Date Functions
 Numeric Functions
Character Functions
 Conversion Functions
 Miscellaneous Functions

Date Functions : -
They operate on date values producing output
which also belongs to date datatype, except for
months_between date function which returns a
number.
Add_Months
The add_months function returns a date after
adding a specified date with the specified number of
months. The format is add_months(d,n). Where d
is the date and n represents the number of months
Example for Add_months
SQL> Select sysdate ,add_months(Sysdate,2) from
dual;
Last_Day
The format of is last_day(d), which returns the
date corresponding to the last day of the month.
Example for Last_day Function: -
SQL>Select Sysdate,last_day(sysdate) from dual;
The above query displays the last day the current
month.
Months_Between : -
This function results the number of months
between the given dates the format is
months_between(date1,date2)
Example
SQL> Select months_between(sysdate,’06-Dec-96’)
from dual;
Next_Day:-
The format for this function is
next_day(date,day)
Example
SQL>Select next_day(sysdate,’Friday’) from dual;
The above query will the date of next Friday.
New_Time:-
The new_time function displays the time and date
of a date column or literal date in other time zones
The format is
new_time(date,’this’,’other’);
‘this’ is replaced by a 3 letter abbreviation of
the current time zone while ‘other’ is replaced
by a three letter abbreviation of the zone in
which the date is wanted.
SQL> select new_time(‘13-Feb-99’,’est’,’yst’)
from dual;
It returns 12-Feb-99 which is the date in the
time zone ‘yst’
Numeric Functions : -
 ABS (value) -------------->ABSolute Value
 CIEL (value) ------------>Smallest integer larger
than or equal to value
 COS (value) ------------> COSine Value
 COSH (value) --------->Hypeblic COSine of value
 EXP (value) ------------>Value Raised to the
EXPonent

 FLOOR (value) --------> Larger integer smaller


than or equal to value
 LN (value) ---------> Natural Logarithm of Value
 LOG (value) ------->Base 10 LOGarithm of value
 MOD (value,divisor) ---------> MODulus
 POWER (value,exponent) ------> value raised to
an exponent
POWER
 ROUND(value,precision) ----->Rounding the
value to precision
 SIGN (value) ---------> 1 if value is positive,-1 if
value is negative, 0 if
value is zero.
 SIN (value) -------------> SINe value
 SINH (value) ------------> Hyperblic SINe of value
 SQRT( value) ----------> SQuare RooT of value
 TAN (value) ------------> TANgent of value
 TANH (value) -----------> Hyperblic TANgent of
value
 TRUNC (value,precision) -----> Value
TRUNCated to
precision
Character Functions : -
LENGTH:
LENGTH tells the user how long a string is
how many characters it has in it, including
letters,spaces.
Example:-
SQL>Select length(‘LSIL’) from dual;
Initcap:-
Initcap converts the first letter of the word given
into capital letter.
Example : -
SQL> select Initcap(‘lsil’) from dual;
LOWER : -
Converts the word into lowercase.
Example : -
SQL> select lower(‘LSIL’) from dual;
UPPER: -
Converts the word into uppercase.
Example : -
SQL> select upper(‘lsil’) from dual;
LTRIM:-
LTRIM (char,set)
SQL>Select ltrim(‘xyzadams’,’xyz’) from dual;
RTRIM:-
RTRIM(char,set)
SQL>Select rtrim(‘xyzadams’,’ams’) from dual;
Translate: -
Translate(char,from,to)
Example:-
Translates a single character
SQL>Select translate (‘jack’,’j’,’b’) from dual;
Output of the above command is back.
REPLACE:-
SQL>Select replace (‘jack and jue’,’j’,’bl’) from
dual;
output of the above command is
Black and Blue.
SUBSTR : -
Format of SUBSTR
Substr(char,m,n)
EXAMPLE:-
SQL>Select Substr(‘Aswin Kumar’,7,11) from dual;
LPAD : -
LPAD takes 3 arguments.
 The first argument is the character string, which
has to be displayed with the left padding.
 The second is the number, which indicates the total
length of the return value.
The third is the string , with which the left padding
has to be done when required.
Example:-
SQL> Select lpad(‘LSIL’,10,’*’) from dual;
The output gives the sign * before the word ‘LSIL’.
LPAD(‘LSIL’)
-------------------
******LSIL
The entire string is 10 in length after padding is
done.
RPAD
The Function RPAD does the exact opposite of the
LPAD function. The number of arguments it takes
is the same as the lpad function.
Example:-
SQL> Select rpad(‘LSIL’,10,’*’) from dual;
The output gives the sign * before the word ‘LSIL’.
RPAD(‘LSIL’)
-------------------
LSIL******
DECODE : -
Unlike the translate function which performs a
character by character replacement the DECODE
function does a value by value replacement.
Syntax Of DECODE : -
SQL> Select decode ( <value, if1,then1, if2, then2,--->)
from <tablename>;
Example : -
SQL> Select ename,designation,salary,
decode(ename,’Maya’, ’Meera’) from emp
where salary>12000;
CONCAT : -
Concat Function is used to combine the strings in
the database.
Example : -
SQL > Select Concat(first_name,Last_name) Name
from emp;
Concatenation Operator : -
Another method to Combine the String is using the
Concatenation Operator
SQL>Select first_name || last_name from emp;
SQL>Select (‘The designation of ‘ || ename || ‘ is ’||
designation || ‘and ’ || ename ||’ draws ’ || salary || ‘
per month’) from emp where ename = ‘Maya’;
CHR : -
The above function returns the character value of
the given number.
Example : -
SQL> Select chr(67) from dual;
The above statement returns ‘C’ has the output.
Conversion Function : -
Conversion functions convert a value from one
data type to another. The conversion functions are
broadly classified into the following.
 To_char()
 To_date()
 To_number()

To_char() : -
Format of this function is To_char(d[,fmt])
where d is the date,fmt is the format model which
specifies the format of date. To_char conversion
function converts date to a value of varchar2
datatype in a form specified by date format fmt. If
fmt is neglected then it converts date to varchar2
in the default date format. Consider the following
example.
SQL> select to_char (sysdate,’ddth “of” fmmonth
yyyy’) from dual;
The above statement displays the date according to
the format specified in the format model. The date
will be displayed as
28th of February 2000 if the sysdate is
‘28-Feb-00’;
In the above example fill mode (fm) format mask
is used to avoid blank padding of characters and
zero padding to numeric.
To_date ()
The format is to_date(char [,fmt]). This converts
char or varchar2 datatype to date datatype.
Format model, fmt specifies the form of character.
Consider the following example which returns date
for the string ‘January 23 2000’.
SQL> select to_date(‘January 23 2000’,’month-
dd-yyyy’) from dual;
‘23-jan-00’ will be the output.
To_number() : -
The to_number function allows the conversion of
string containing numbers into the number
datatype on which arithmetic operations can be
performed. This is largely unnecessary as oracle
does an implicit conversion of numbers contained
in a string.
SQL>Select to_number(‘100’) from dual;
Miscellaneous Functions : -
The following are some of the miscellaneous
functions supported by Oracle.
 Uid
 User
 Nvl
 Vsize

Uid:-
This function returns the integer value
corresponding to the user currently logged in.
Example :-
SQL> Select Uid from dual;
The result could be a number.
User:-
This function returns the login’s user name,
which is in varchar2 datatype.
Example : -
SQL> Select user from dual;
The result will be the name of the current user.
Null value (Nvl) : -
The Null value function is used in cases
where we want to consider Null values as zero or
the value which is specified by the user. The syntax
is given as nvl (exp1,exp2).
 If exp1 is null, nvl will return exp2.
 If exp1 is not null, nvl will return exp1
 If exp1 and 2 are of different datatypes, then
oracle converts exp2 to the datatype of exp1 and
then compares it.
Example : -
SQL> Select ename,salary,nvl(salary,2500) from
emp;
Vsize :-
SQL> Select Vsize(‘LSIL’) from dual;
Th output of the above query is ‘4’.
So far we have discussed functions classified as
single row functions. These provided the result
based on individual rows.
Group Functions : -
A group function returns a result based on a
group of rows. Some of these are just purely
mathematical functions. The group functions
supported by Oracle are summarized below.
 Avg Function
 Min Function
 Max Function
 Sum Function
 Count Function
Avg Function
The Avg function return the average of
values of the column specified in the argument of
the column
Example : -
SQL> Select avg(salary) from emp where dno=10;
Min Function : -
This function will give the least of all values of the
column present in the argument.
Example : -
SQL> Select min(salary) from emp where dno=10;
Max Function : -
This function will give the highest of all values of
the column present in the argument.
Example : -
SQL> Select max(salary) from emp where dno=10;
Sum Function : -
Th above function can be used to obtain the
sum of a range of values of a record set.
Example :-
SQL>Select sum(salary) from emp where dno=10;
Count Function :-
In order to count the number of rows, count
function is used. It can take 3 different arguments .
Count (*) :-
It counts all rows, inclusive of duplicates and
Nulls.
SQL>Select count(*) from emp;
The above query returns the number of records in
the table emp inclusive of null values.
Count(Col_name):-
It counts the number of values present in the
column excluding Null values.
SQL>Select count (dob) from emp;
Count(distinct col_name) : -
It is similar to count(col_name) but eliminates
duplicate values while counting.
SQL>Select distinct(count( dob )) from emp;
The above query returns the number of records in
dob column eliminating the duplicated records.
Set Operators & Joins
Set Operators : -
1. Union 2. Union All
3. Intersect 4. Minus
Conditions to be followed in set operators
 The queries, which are related by a set operator
should have the same number of columns and the
corresponding columns must be of same data type.
 Such a Query should not contain any column of
type long.
The label under which the rows are displayed are
those from the first select statement.
Union : -
The union operator returns all distinct rows
selected by both queries. The following example
combines the result of two queries with the union
operator , which eliminates duplicate rows.
SQL> Select dno from emp UNION Select dno from
dept ;
The union operator returns all distinct column values
from the emp and dept table respectively.
Union All : -
The ‘Union All’ operator returns all rows select
by either query including duplicates.
SQL> Select dno from emp UNION ALL select dno
from dept;
Intersect : -
Intersect returns only the rows that are common
to both the queries.
SQL> Select dno from emp INTERSECT Select dno
from dept;
Minus : -
Minus operator returns all distinct rows selected
only by the first query and not by the second.
SQL> Select dno from dept MINUS Select dno from
emp;
Joins
The purpose of a join is to combine the data
spread across tables. A join is actually performed by
the ‘where’ clause which combines the specified rows
of tables.
There are Three types of Joins: -
 Simple Join
 Self Join
 Outer Join
Simple Join : -
It is the most common type of join. It retrieves
rows from two tables having a common column and is
further classified into Equi - Join and Non Equi - Join.
Equi - Join : -
A join, which is based on equalities, which is
called an equi - join. The equi join combines rows that
have equivalent values for the specified columns.
SQL > select * from emp,dept
where emp.dno=dept.dno;
The above query fetches the rows from the table emp
and dept where the dno of emp table matches the dno of
the table dept.
Non Equi-Join : -
A Non Equi - Join specifies the relationship
between columns belonging to different tables by
making use of the relational operators(>.<,<=,>=,<>)
other than =. The following example is illustrative of
this
Example : -
SQL>Select itemdesc,max_level,qty_ord,qty_deld
from itemfile,order_detail where
(itemfile.max_level<order_detail.qty_ord) and
(Itemfile.itemcode=orderdetail.itemcode);
Table Aliases :-
To prevent ambiguity in a query we include table
names in the select statements. Table aliases are used to
make multiple table queries shorter and more readable.
SQL > Select e.eno,e.ename,e.dno,d.dno,d.dname from
emp e,dept d where e.dno = d.dno;
Self Join : -
Joining the tables to itself is known as self join,
i.e., it joins one row in a table to another. The join is
performed by mirroring the table using the ‘where’
clause it can compare each row of the table to itself and
also with other rows of the same table.
SQL>Select e1.ename || ‘works for’ || e2.ename
“Employees and their Managers” from emp e1,emp e2
where e1.mgr=e2.eno;
Outer Join :-
The outer join extends the result of a simple join.
An outer join returns all the rows returned by simple
join as well as those rows from one table that do not
match any row from the other table. This cannot be
done with simple join alone. The symbol, (+)
represents outer join
SQL>Select e.eno,e.ename,e.salary,d.dno,d.dname
from emp e,dept d
where d.dno=e.dno(+);
The above example will also retrieve rows from dept
table which do not have any matching records in the
emp table. Such a retrieval is due to the presence of an
outer join(+). The rows are retrieved in addition to
those records which have a simple join.
Subqueries
Nesting of queries one within the other, is termed as a
subquery. A statement containing a subquery is called a
parent statement. Subqueries are used to retrieve data
from tables that depend on the values in the table itself.
Example:-

The user want to view the details of the employees


who’s salary is equivalent to
‘Aswin Kumar’ salary. Without the help of subquery
the user has to perform 2 queries one is to identify the
salary of ‘Aswin Kumar’ and the second one is to list
the details
Of the employee who’s salary is equivalent to ‘Aswin
Kumar’ salary. If the user uses the subquery then
complication of the query is reduced.
SQL> select * from emp
where salary in(select salary from emp
where ename = ‘Aswin Kumar’);
Different types of subqueries are :
 Nested Subquery
 Correlated Subquery
 Multiple Subquery
Let us consider the following tables for examples :-
TABLE NAME
(a) DEVELOPER
(b) CAREERS
(c)
PRODUCT
Developer Table Structure

NAME Varchar2(30) Not Null


DOB Date
DOJ Date
SEX Char(1)
SKILL1 Varchar2(20)
SKILL2 Varchar2(20)
SALARY Number(8,2)
Careers Table Structure

NAME Varchar2(30) Not Null


PLACE Varchar2(30)
COURSE Varchar2(30)
FEES Number(8,2)
Product Table Structure

NAME Varchar2(30) Not Null


TITLE Varchar2(30)
ENVIRON Varchar2(30)
SCOST Number(8,2)
DCOST Number(8,2)
SOLD Number(3)
Nested Subquery : -
If a Subquery is nested with another query that is
Nested Subquery.
Example :-
If the user want to view the details of the
programmer who’s skill is VC++ and developed
projects in VC++ and has experience of 5 yrs atleast
then the following the query
SQL> Select * from developer
where skill1 =‘VC++’ or skill2=‘VC++’ and
name in(select name from product where
environ=‘VC++’ and name in(select name from
developer where to_char(sysdate,’yy’)-
to_char(doj,’yy’)>=5));
Multiple Subquery : -
Example used for Nested query itself can be
applied to Multiple subquery.
SQL>Select * from developer
where skill1 =‘VC++’ or skill2=‘VC++’
and name in(select name from product
where environ=‘VC++’) and name in
(select name from developer where
to_char(sysdate,’yy’)-to_char(doj,’yy’)>=5);
Correlated Subquery : -
A subquery is evaluated once for the entire
statement whereas a correlated subquery is evaluated
once for every row processed by the parent statement.
SQL> Select deptno,ename,sal from emp x
where sal> (select avg(sal) from emp where
x.deptno=deptno)
Operators Used in Subquery : -
Subqueries can also return more than one value.
In such cases we should include operators like any,all,in
or not in between the comparison operator and the
subquery.
SQL>Select * from emp where salary < any
(Select salary from emp
where ename in(‘Ram Kumar’,’Balaji’ ));
In the above example the subquery returns the salary of
‘Ram kumar’ and ‘Balaji’ and the main query will
display the details of the employee’s who are all drawing
less than these two employees.
All Operator :-
SQL>Select * from emp where salary > all
(Select salary from emp
where ename in(‘Ram Kumar’,’Balaji’ ));
In the above example the subquery returns the salary of
‘Ram kumar’ and ‘Balaji’ and the main query will
display the details of the employee’s who are all drawing
salary greater than these two employees.
Constraints
To maintain security and integrity of a database is the
most important factor in judging the success of a system.
An integrity constraint is a mechanism used by oracle to
prevent invalid data entry into the table.
The following are the various types of integrity
constraints : -
 Domain Integrity Constraints
 Entity Integrity Constraints
 Referential Integrity Constraints
Domain Integrity Constraints : -
These constraints set a range, and any violations
that take place will prevent the user from performing the
manipulation that caused the breach. There are basically
two types of domain integrity constraints.
 Not Null Constraint
 Check Constraint
By default the tables can contain null values. The
enforcement of Not Null constraints in a table ensures
that the table contains values. Oracle will not validate
the record until this is satisfied.
The other type of constraint available under this
classification is the ‘check’ constraint. This can be
defined to allow only a particular range of values. When
the demarcation specified in this range is violated Oracle
rejects the record.
Entity Integrity Constraint : -
Entity Integrity Constraints are two types.
 Unique Constraints
 Primary Key Constraints

The Unique Constraint designates a column or a group


of columns as a unique key. This constraint allows only
unique values to be stored in the column oracle rejects
duplication of records when the unique key constraint is
used.
The primary key constraint is similar to the unique key
constraint. The primary key constraint just like the
former avoids duplication of values. Its need is best felt
when a relation has to be set between tables, because in
addition to preventing duplication it also does not allow
null values.
Referential Integrity Constraint :-
The Referential Integrity constraint enforces
relationship between tables. It designates a column or
combination of columns as a foreign key.
The foreign key establishes a relationship with a
specified primary or unique key in another table, called
the referenced key. In this relationship, the table
containing the foreign key is called the child table and
the table containing the referenced key is called the
parent table.

Implementation of Constraints :-
Domain Integrity - ‘Not Null’ Constraint
Note:
 ‘Not Null’ integrity constraint can be define using
alter table command even when the table has rows.
 Zero and Null are not equivalent.
 One null is not equivalent to another null.
Example : -
SQL> create table emp (eno number(3),ename
varchar2(25) constraint nn not null ,salary number(8,2));
Check Constraint : -
This constraint is used to check the values in the
column satisfies the condition, i.e the user can restrict
the records to be inserted into the table with the help of
check constraint.
Example : -
SQL> create table test(no number(3),name varchar2(25)
constraint nn Not Null,salary number(8,2)constraint
chk_sal check(salary>=2500),phone number(8));
In the above table the user can insert records which
satisfies the condition.
Unique Constraints : -
This constraint checks for the uniqueness of the
record. If the user don’t want to have any duplication of
records at the time of insertion then the user can assign
unique constraint for that column.
How to add a constraint with the alter table statement
SQL>alter table test add constraint uni unique phone
number(8,2);
The user can assign composite unique constraint also. If
the user want to assign unique constraint for more than
one column then the user can prefer composite unique
constraint.
Example : -
SQL>Create table test (no number(3),
name varchar2(25),salary number(8,2),
phone number(8),E-Mail varchar2(25)
unique(phone,e-mail));
Composite unique constraint can be assigned for more
than one column.
Primary Key Constraint : -
Primary Key Constraint is a combination of Not
Null and Unique Constraint, i.e., primary key column
won’t accept duplicated records and null value. A table
can have only one primary key constraint and this
constraint is mainly introduced to set relationship
between tables.
If the user want to assign primary key constraint for
more than one column than they can use composite
primary key, the composite primary key can be assigned
for 16 columns maximum.
Primary key constraint is assigned to a column with the
keyword primary key.
Table Level Constraints & Column Level Constraints:-
 The table level constraint is part of the table
definition .
 An integrity constraint defined at table level can
impose rules on any columns in the table.
 Column level constraint being a part of the column
definition can be imposed only on the column level.
Example for a Table Level Constraint : -
SQL> Create table itemfile
(itemcode varchar2(5),
itemdesc varchar2(20),p_category varchar2(20),
qty_hand number(5),re_level number(5),
max_level number(5),itemrate number(9,2),
constraint max check(max_level<500),
constraint un_item unique(itemdesc));
Referential Integrity Constraints : -
To establish a ‘parent - child’ or a ‘master - detail’
relationship between two tables having a common
column, we make use of referential integrity constraints.
To implement this we should define the column in the
parent table as a primary key and the same column in the
child table as a foreign key referring to the corresponding
parent entry.
Example : -
SQL> Create table dept(deptno number(3)
constraint pk1 primary key,
deptname varchar2(30) constraint nn1 not null);
SQL>Create table emp (eno number(4) primary key,
ename varchar2(35),
designation varchar2(25),deptno number(3)
constraint fk1 references dept(deptno),salary
number(8,2));
Note: The referential integrity constraint does not use
foreign key keyword to identify the columns that make
up the foreign key. This is because the constraint is
defined at column level. The foreign key is
automatically enforced on the columns.
 Like other constraints it is also possible to define the
referential integrity constraint at table level.
 To alter an existing table for adding a referential
integrity constraint
SQL> alter table emp add constraint fk1 foreign
key(deptno)references dept(deptno);
On Delete Cascade Clause: -
The ‘On Delete Cascade’ clause specifies that
oracle maintains referential integrity by automatically
removing foreign key values if a referenced primary key
value is removed. The syntax for creating a table to
include this clause is
Example : -
SQL> Alter table order_master add constraint fk_code
foreign key (vencode) references vendor_master(vencode)
on delete cascade;
SQL>delete from vendor_master where vencode=‘v006’;
Deferrable Constraints
When a constraint is made deferrable, oracle 8
leaves the checking until the transaction is committed.
Each constraint has two additional attributes to support
deferred checking of constraints.
 It may be deferrable or not deferrable
 The initial state may be set to initially deferred or
initially immediate.
The three conditions, which can be set, are
 Deferrable initially immediate - this checks for
constraint violation at the time of insert.
 Deferrable initially deferred - this checks for
constraint violation at the time of commit.
 Non deferrable initially immediate - this is the
default Condition which need not be specified.
The syntax for setting the condition is
alter table <tablename> add constraint <constraintname>
foreign key<columnname> references <tablename>
deferrable initially deferred.
The above syntax when used will add a constraint which
will by default only be checked at commit time.
The following statement enables all constraints
set constraints all immediate;
the next command is used to disable all constraints.
Set constraint all deferred;
To Drop a Constraint Syntax is
alter table <table_name> drop constraint
<constraint_name>;
LOCKS & TABLE PARTITIONS

When a table is being accessed by different clients


concurrently transactions being performed simultaneously
can prove to be harmful at times. Oracle provides the
locking facility, which can be performed explicitly.
Another facility available to protect data is to partition
the tables. Doing so will minimize the chance of complete
data loss.
The need for locking can be clearly understood with this
example. Consider the users from two different
departments in ABC ENTERPRISES - sales and
accounts, wish to access the same table i.e..,
order_master. In such a case, the following situation may
arise.

Sales Accounts
updates row1 of order_master; deletes row1 of
commit; order_master;
commit;
Since both the users are accessing the same row on the
same table at the same time it may end up in a situation
where user in accounts will delete the row that user in
sales has updated. To overcome this situation oracle
incorporates a locking facility which permits or denies
access to other users on a table or a certain rows in a
table, when a user is still is in the process of operating on
them.
Types of Locks
Locks are the mechanisms used to prevent
destructive interaction between users accessing the same
resource simultaneously . A resource can be an entire
table or a specific row in a table. Thus locks provide a
high degree of the data concurrency. Locks can be
acquired at two different levels.
 Row level lock (for specific rows)
 Table level lock (for entire table)
Row level locks
In the row level lock, a row is locked exclusively
so that other users cannot modify the row until the
transaction holding the lock is committed or rolled back.
Row locks are acquired automatically by oracle as a
result of insert, update, delete and select.. for update
clause statement.
Select.. for update clause
The select command when used with for update of
clause places an exclusive lock on one or more rows of a
table. This command can be used to lock the rows that
would be updated later. The following example locks
rows in which the employees salary between 5000 to
15000.
Example : -
SQL> select * from emp where salary between 5000 and
15000 for update of name,designation;
Table level lock
A table level lock will protect table data there by
guaranteeing data integrity when data is being accessed
concurrently by multiple users. A table lock can be held
in several modes they are
 Share Lock
 Share Update Lock
 Exclusive Lock
The general syntax for locking a table is given below:
Lock table <table_name> in <share or share update or
exclusive mode>;
Share Lock :
A share lock locks the table allowing other users to
only query but not insert, update or delete rows in a
table. Multiple users can place share locks on the same
table at the same time, i.e., it allows resources to be
shared and hence the name share lock.
Example : -
SQL> lock table emp in share mode;
Share update lock
It locks rows that are to be updated in a table. It
permits other users to concurrently query, insert, update
or even lock other rows in the same table. It prevents the
other users from updating the row that has been locked.
We can enforce a share update lock by using the ‘for
update’ clause in the select statement.
Example:-
SQL>lock table emp in share update mode;
Note :-
 Although a share update lock falls under the table
level category, it is effective only for rows.
 It allows numerous users to concurrently lock
different rows of a table.
Exclusive Lock : -
Exclusive lock is the most restrictive of the table
locks. When issued by one user, it allows the other user
to only query but not insert, delete or update rows in a
table. It is almost similar to a share lock but only one
user can place an exclusive lock on a table at a time,
whereas many user can place a share lock on the same
table at the same time.
Example :-
SQL>lock table emp in exclusive mode;
Note :-
 Locks can be released by issuing either rollback or
commit.
Nowait:-
Consider a user has locked a table without a ‘nowait’
clause in the lock table format. If another user tries to
violate the above restrictions by trying to lock the table,
then, he will be made to wait indefinitely until the user
Initially locked the table issues a commit or rollback
statement. This delay could be avoided by appending a
‘nowait’ clause in the lock table command.
Example:-
SQL>lock table emp in exclusive mode nowait;
Deadlock:-
A deadlock occurs when two users have a lock, each
on separate object, and, they want to acquire a lock on the
each other’s object.
Oracle automatically detects the deadlock and solves the
problem by one of the two transactions.
Partitions
The additional feature in Oracle 8 is that the tables are
partitioned. And stored in different locations as per
requirement. A single logical table can be split can be
split into a number of physically separate pieces based
on ranges of key values. Each of the parts of the table
is called a partition. Although the partitions are held
and managed independently, they can be queried and
updated by reference to the name of the logical table.
There is difference between a table, which has a single
partition, and a table that has no partitions. A non-
partitioned table cannot be partitioned later. Each
partition is stored in a different segment and has
different physical attributes.
Table partitions can be stored in different tablespaces.
Oracle 8 provides partition independence. We can
access and manipulate data in one partition even if
some or all of the other partitions are unavailable. This
is the major benefit.
Storing the partitions in different table spaces has its
advantages.
 It reduces the possibility of data corruption in
multiple partitions.
 Back up and recovery of each partition can be done
independently.
Note:-
 Partitioned tables cannot contain any columns with
long or long raw datatypes, LOB datatypes
(BLOB,CLOB or BFILE), or object types.
Example to create a partitioned table :
SQL> Create table emp(empno number(3) primary key,
empname varchar2(25),designation
varchar2(30),salary number(8,2))partition by
range(salary)(partition p1 values less than(5000),
partition p2 values less than(10000));
In the above example table emp is created with
partition, and the table is partitioned on the column
salary. The data’s are stored in two partitions. Based
on the records the data’s are splitted and stored. In the
above example from 0 to 4999 the records are stored in
partition p1 and from 5000 to 9999 it is stored in p2
partition.
Inserting records into a partitioned table:-
The records are stored in the partitions of a table
based on the partition key specified. The partition key
specified in the insert statement is compared with
partition bound defined when creating the partitioned
table.
Example :-
SQL>insert into emp
values(‘101’,’Maya’,’Programmer’,5000);
SQL>insert into emp values(‘101’,’Meera’,’Systems
Analyst’,9500);
SQL>insert into emp
values(‘101’,’Megha’,’Programmer’,8000);
SQL>insert into emp values(‘101’,’snegha’,’Senior
Manager’,8000);
SQL>insert into emp
values(‘101’,’sathya’,’Accountant’,5000);
SQL>insert into emp
values(‘101’,’VijayKumar’,’Clerk’,4500);
To view the records in partition table
SQL> Select * from emp partition(p1);
SQL> Select * from emp partition(p2);
Maintaining Partitions :-
This section describes the various partition
maintenance operations, including:
 Moving Partitions
 Adding Partitions
 Dropping Partitions
Splitting Partitions
Exchanging Table Partitions
Moving Partitions:-
The MOVE PARTITION clause of the ALTER
TABLE statement is used to move a partition from a
most active tablespace to a different tablespace in order
to balance I/O operations.
Assuming that a tablespace called student_data exists
let’s try to move a partition from the system tablespace
into the student_data tablespace.
Example :-
SQL> alter table emp move partition p1 tablespace
student_data;
Adding Partitions :-
The ALTER TABLE ADD PARTITION
statement is used to add a new partition after the
existing last partition.
Example :-
SQL> alter table emp add partition p3 values less
than(‘15000’);
Note:-
 The add partition option shown above is only for
tables where the last existing partition has been defined
with a specific key value.
 If we wish to add a partition at the beginning or in
the middle of a table, or if the partition bound on the
highest partition is MAXVALUE, we should use the
SPLIT PARTITION statement.
Splitting Partitions :-
The SPLIT PARTITION clause can be used to split a
partition into two.
This is useful when a partition becomes too large and
causes backup, recovery or maintenance operations to
consume a lot of long time.
Example :-
SQL> alter table emp split partition p3 at(‘12000’) into
(partition p4, partition p5);
The partition p3 in the table emp is split into partitions
p4 and p5. Now p4 will contain records with salary
10,000 to 11,999 and p5 will contain the records from
12,000 to 14,999.
Dropping Partitions :-
To drop a partition the DROP PARTITION clause
can be made use of the ALTER TABLE statement.
Example:-
SQL> alter table emp drop partition p5;
Exchanging Table Partitions:-
Exchanging table partitions is used to convert a
partitioned table to non- partitioned table and non -
partitioned table to partitioned table.
Criteria in Exchanging the Table Partitions:-
 The structure of the tables should be same.
 The records in the table which the user want to
exchange the partition should satisfy the partition
condition.
Example :-
SQL> alter table emp exchange partition p2 with table
emp1;
Views
A view is a tailored presentation of the data contained in
one or more tables. A view takes the output of a query
and treats it as a table; therefore, a view can be thought
as “stored query” or a “virtual table”. We can use
views in most places where a table can be used. The
tables upon which a view is based are called base tables.
Syntax for creating views
Create [or replace][[no] [force]] view <view name>
[column alias name…] as <query>[with [check option]
[read only] [constraint]];
Example
SQL> Create view emp_view as select * from emp;
Creating view with conditions
SQL> Create or replace view emp_view as Select *
from emp where name like ‘M%’;
Updating the records in a view
SQL> Update emp_view set name =‘Geetha’
where name=‘Maya’;
Creating view with check option
SQL> Create or replace view emp_view as
select * from emp where name like ‘R%’
with check option constraint empv;
The above command creates a view called emp_view
which consists of records where employee name starts
with character ‘R’. Now the user tries to update a record
in the view by changing the name of employee Ram to
Sam.
SQL> Update view emp_view set ename=‘Sam’
where ename=‘Ram’;
For the above command oracle displays an error stating
view WITH CHECK OPTION where -clause violation.
Creating view with Read Only Option :-
SQL> Create or replace view emp_view as select *
from emp with read only ;
The above command creates a view called emp_view
and it won’t allow the user to update that view. The
user can just select the records they cannot perform any
manipulations.
Creating view with functions
SQL> Create or replace view
emp_view(name,designation,salary) as select
name,designation,salary from emp where dno=10;
Creating view by Force
Oracle by default creates a view for the existing table
and valid column names. If the user want to create a
view for a table which does not exists or invalid column
name then with the help of force option the user can
create the view.
SQL>Drop table emp;
SQL>Create force view emp_view as select * from emp;
for the above command the user displays
view created with compilation errors.
After creating the emp table the user can compile the
view and use the view.
SQL> alter view emp_view compile;
Creating view with Joins (view having more than one
base table)
SQL> create view emp_dept_view(emp_no,emp_name,
salary,dept_no,department_name) as select
(e.eno,e.ename,e.salary,d.no,d.dname) from emp
e,dept d where e.dno=d.dno;
The above view has two base tables emp and dept if the
user tries to update the view user will get an error
message.
Synonym
A synonym is a database object, which is used as
an alias for a table,view or sequence they are used to
 Simplify SQL Statements
Hide the name and owner of an object
Provide location transparency for remote objects of a
distributed database
Provide public access to an object
Synonym can be either private or public.
Public Synonyms are created by a Database
Administrator to hide the identity of the base table and
reduce the complexity of SQL statements. One such
example of a public synonym is TAB, which we use for
selecting the tables owned by the user. These public
synonyms are owned by user group PUBLIC.
Syntax for Creating a Synonym
Create [public] synonym <Synonym name> for
<tablename>
Example for Synonym
SQL>Create Synonym e1 for emp;
Granting Privileges to Synonym
SQL>Grant all on e1 to Scott;
The Scott user can do all DML manipulations such as
insert,delete,update o the synonym in the same way that
of the table but he cannot perform any DDL operations
on Synonym except dropping the synonym. The
synonym is just an alias of a table and all the
manipulations on it actually affect the table.
Sequences
A sequence is a database object, which ca generate
unique, sequential integer values. It can be used
automatically generate primary key or unique key
values. A sequence can be either in an ascending or in
descending order
Syntax for creating a sequence
Create sequence<sequence_name> [increment by n]
[start with n] [maxvalue n] [minvalue n] [cycle/nocycle]
[cache/nocache]
Increment by n: ‘n’ is an integer which specifies the
interval between sequence numbers. The default is 1. If
n is positive,then the sequence ascends and if it is
negative the sequence descends
Start with n: Specifies the first sequence numbers to be
generated
Minvalue n: Specifies the minimum value of the
sequence. By default, it is 1 for an ascending sequence
and 10e26-1 for a descending sequence.
Maxvalue n: It specifies the maximum value that the
sequence can generate. By default, it is -1 and 10e27-1
for descending and ascending sequences respectively
Cycle: Specifies that the sequence continues to generate
values from the beginning after reaching either its max
or min value.
No Cycle: Specifies that the sequence cannot generate
values from the beginning after reaching either its max
or min value. The default value is ‘no cycle’.
Cache: The CACHE option pre-allocates a set of
sequence numbers and retains them in memory so that
sequence numbers can be accessed faster. When the last
of the sequence numbers in the cache has been used
No Cache: The default value ‘nocache’, does not
preallocate sequence numbers for faster access.
Example for creating sequence:
SQL>Create sequence seq1 increment by 1
start with 1
maxvalue 10
minvalue 1
cycle
cache 4;
SQL> Insert into emp (no,name)
values(seq1.nextval,’Gettha’);
To view the values
SQL>Select seql.currval from dual;
Alter Sequence
The sequence can be altered when we want to perform
the following:

 Set or eliminate minvalue or maxvalue


 Change the increment value
 Change the number of cached sequence
numbers.
The following example will change the max value of
the sequence from 10 to 15.

SQL> alter sequence seq1 maxvalue 15.


Indexes
Indexes are optional structures associated with
tables. We can create indexes explicitly to speed up
SQL statement execution on a table. Similar to indexes
in books that helps us to locate information faster, an
oracle index provides a faster access path to table data.
User can create index on a column or combination of
column using CREATE INDEX command as follows.
SQL> create index empind on emp(eno);
Index is created on eno column which exists is table
emp.
Unique Indexes
Indexes can be unique or non - unique. Unique
indexes guarantee that no two rows of a table have
duplicate values in the columns that define the index.
Non-unique indexes do not impose this restriction on
the column values. Oracle enforces unique integrity
constraints by automatically defining a unique index
on the unique key. A unique index is created by using
create unique index command as follows.
SQL> create unique index ind1 on test(no);
Note :-
 A unique index is automatically created when we
create unique or primary key constraint. We cannot
create index for a column which is already indexed.
Composite Indexes :-
A composite index(also called a concatenated
index) is a index created on multiple columns on a table.
columns in a composite index can be in any order and
need not be adjacent columns of the table.
Example : -
SQL> Create index compind1 on
order_detail(orderno,itemcode);
Bitmap Indexes:-
Bitmap indexes are appropriate when nonselective
columns are used as limiting conditions in a query.
To create bitmap index, use BITMAP clause of the create
index command. Consider the following example.
Example :-
SQL> create bitmap index lodging on worker (lodging);
Index Organized Tables:-
SQL> create table indorg (vencode number(4) primary
key, venname varchar2(20)) organization index;
Note : -
Primary key is a must for creating index
organized table.
Regular Table : -
1. ROWID uniquely identifies a row; primary key
can be optionally specified.
2. Implicit ROWID column; allows building
physical secondary indexes.
3. ROWID based access
4. Sequential scan returns all rows
5. Unique constraint and triggers allowed.
Organized Table : -
1. Primary Key uniquely identifies the rows.
Primary key must be specified.
2. No Implicit ROWID column, cannot have
physical secondary indexes.
3. Primary key based access.
4. Full- index scan returns all rows in primary
key order
5. Unique constraint are not allowed. But
triggers are allowed.
SQLPLUS REPORTS COMMANDS
SQLPLUS is usually thought of as a kind of interactive
report writer. It uses SQL to get information from the
ORACLE database, and lets you create polished, well-
formatted reports by giving you easy control over
titles,column headings, subtotals and
totals,reformatting of numbers and text, and much
more.
SQLPLUS also has a tiny, built-in editor of its own,
sometimes called the command line editor, which
allows you to quickly modify a SQL query without
leaving SQLPLUS.
COMMAND DEFINITION
remark Tells SQLPLUS that the words
are to be treated as comments,
not instructions.
set headsep The heading separator
identifies the single character
tells SQLPLUS to split a title
onto two or more lines.
ttitle sets the top title for a each page
of a report.
btitle sets the bottom title for each
page of a report.
Column Gives SQLPLUS a variety of
instructions on the heading,
format,and treatment of a
column.
Break on Tells SQLPLUS where to put
spaces between sections of a
report, or where to break for
subtotals and totals.
Compute sum Makes SQLPLUS calculate
subtotals.
Set linesize Sets the maximum number of
line per page.
Set pagesize Sets the maximum number of
lines per page.
Set newpage Sets the number of blank
lines between pages.
Spool Moves a report you would
normally see displayed on the
screen into a files, so you
can print it.
/**/ Marks the beginning and end
of a comment within a SQL
query. Similar to remark.
-- Marks the beginning of an
inline comment within a SQL
query. Treats everything
from the mark to the end of
the line a s a comment.
Similar to remark.
Set pause Makes screen display stop
between pages of display.
Save Save the SQL query you’re
creating into the file of your
choice.
Host Sends any command to the
host operating system.
Edit Pops you out of SQLPLUS
and into an editor of your
choice.
Abstract Datatype
Example :-
SQL> Create or replace type address_ty as object
(street_no number(3), street_name varchar2(20), city
varchar2(20), state varchar2(20));
The above syntax creates a type named as address_ty
Implementing object type as a column object.
SQL> Create table emp (eno number(3), ename
varchar2(25),address address_ty, salary number(8,2));
Inserting records into Abstract Data types
SQL> insert into emp
values(101,’Sathya’,address_ty(110,’first St,
’chennai’,’tn’),15000);
Selecting from Abstract Data types
SQL> Select ename,e.address.street_no,
e.address.street_name from emp e;
Updating records in Abstract Data types
SQL> update emp e set e.address.street_no = 20 where
e.address.street_no=10;
Deleting records in Abstract Data types
SQL> delete from emp e
where e.address.street_no=10;
Dropping object Types
SQL > drop type address_ty;
*
ERROR at line 1:
ORA - 02303: cannot drop or replace a type with type or
table dependents.
Since the type is used by the table and table is not
dropped the user cannot drop the type. But oracle as a
FORCE clause to drop the type even dependencies are
there.
SQL> drop type address_ty force;
Indexing Abstract data type attributes
SQL> create index streetnum on emp
(address.street_no);
Varying Arrays :-
These help in storing repeating attributes of a
record in a single row. Varray cannot be extended
beyond the limit that was defined when the varray was
created.
Creating Varrays
SQL > create type itemcode as varray(5) of varchar2(5);
SQL > create type qty_ord as varray(5) of number(5);
SQL > create type qty_deld as varray(5) of number(5);
Implementing Varray in table
SQL> Create table order_detail(order_no varchar2(5),
item_va itemcode, qty_va qty_ord, qtyd qty_deld);
Inserting records into Varrays :-
SQL > insert into order_detail values
(‘o100’,itemcode(‘i100’,’i101,’i102’,’i103’,’i104’),
qty_ord(100,980,900,800,1000),
qty_deld(100,900,800,700, 600));
Selecting the data from varray:-
SQL> select item_va from order_detail;
Nested Tables :-
Varying arrays are used to create collectors
within the tables and data types. Varying arrays have a
limited number of entries, whereas nested tables have
no limit on the number of entries per row. A nested
table is table within a table. A table is represented as a
column within another table.
Let us assume that the table contains a structure as
shown below:
Column Type
Book_Id Varchar2(15)
Book_Name Varchar2(30)
Author_Name Varchar2(30)
Publications Varchar2(30)
Price Number(8,2)
For each book an unique id is maintained and that is
Book_Id . For example ORA001 is Id assigned for
oracle books. If the user uses the Varray there is a
limitation to specify the maximum limit.
The user don’t know how many books will be
purchased so he cannot give the maximum limit. This
drawback can be removed with the help of nested
tables. Let us see how to create a nested table.
SQL> create type book_ty as object(book_name
varchar2(30),author_name varchar2(30),publications
varchar2(30),price number(8,2));
type is created.
The book_ty contains a record for each book. To use
this datatype as the basis for a nested table a new
abstract data type has to be created and is as shown
below.
SQL> Create type book as table of book_ty;
Type created is the output for the above command.
The “as table of” clause tells oracle that this type will
be used as the basis of a nested table. This type i.e.,
book_ty can be used to create a table i.e., book_details
Example :-
SQL> Create table book_details(book_id varchar2(15),
book_particulars book)nested table book_particulars
store as nested_book_details;
The output of the above command is table created.
Book_id is an ordinary column which is of varchar2
data type in the table book_details
Book_particulars is the nested table column in the
table book_details.
The user has to specify that the column is a nested
table column by specifying nested table keyword
Inserting records into a nested table :-
SQL > insert into book_details values
(‘&book_id’,book(book_ty(‘&book_name’,’&author
_name’,’&publications’,&price)));
Uses of the keyword :-
Previous example is how to insert record into the table
which consist of nested table column first time. If the
user want to insert record only to the nested table not
to the main table then user has to for the keyword.
Assume that 3 books has purchased for oracle and the
user has to insert the details of those books then
Example :-
SQL > insert into the (select book_particulars from
book_details where book_id=‘ORA001’)
values(book_ty(‘How-To
Oracle8’ ,’John’,’BPB’,500));
Selecting records from the nested table:-
SQL > select a.book_name,a.author_name from
the(select book_particulars from book_details) a;
Updating the records in the nested table :-
SQL> update the (select book_particulars from
book_details where book_code =‘ORA001’) set price=
595 where book_name=‘How-To Oracle8’;
Uses of CAST and MULTISET keyword
If the user want to insert the same set of records in
nested table then the user can go for CAST and
MULTISET keyword.
For example in a library there will be more than one
book of the same series the user has to maintain the
details of all the books then.
Example :-
SQL > insert into the (select book_particulars from
book_details where book_id=‘VB001’)
values(book_ty(‘Visual Basic 6 Programming Black
Book’ ,’Steven Holzner’,’dream tech Press’,475));
Later on the same book has purchased that details has
to be maintained.
Example :-
SQL > insert into book_details values (‘VB002’ ,cast
(multiset (select * from the (select book_particulars
from book_details where book_id=‘VB001’)) as
book));
Introduction to PL/SQL
PL/SQL Stands for Procedural Language/SQL.
PL/SQL extends SQL by adding control structures
found in other procedural language.
Advantages of PL/SQL
 Supports the declaration and manipulation of
objects
 Allows the calling of external functions and
procedures
 Contains new libraries of built - in packages
Architecture of PL/SQL
The PL/SQL engine executes PL/SQL blocks.
The PL/SQL engine executes only the procedural
statements and sends the SQL statements to the SQL
statement executor in the Oracle server. The PL/SQL
engine can either reside in the Oracle server or on
Oracle tools such as Oracle Forms 5, Reports 3.
Introduction to PL/SQL block
A PL/SQL block can be divided into three parts,
namely, a declarative part, an executable part and an
exception handling part. The order is as shown below:
DECLARE
declarations
BEGIN
executable statements
EXCEPTION
handlers
END;
Before proceeding to learn about the above three parts,
we need to have a brief idea on the character set and
lexical units used in the PL/SQL block
The PL/SQL character set includes the following:
 Upper and lower case letters. They are not case
sensitive except within strings and character literals.
 Numerals from 0 to 9.
 All special symbols and characters.
 Tab, space and carriage return.
PL/SQL text can contain groups of characters known
as lexical units. The following are the lexical units:
 Identifiers
 Literals
 Comments
 Delimiters (simple and compound symbols)

Example:
Total :=salary * 0.90; -- to compute total
In the above example,
total and salary ---------- identifiers
* and ; ---------- simple symbols
:= ---------- compound symbols
0.90 ---------- numeric literals
-- ----------- represents comment
Some of the simple symbols are
+,-,*,/,=,<,>,% (attribute indicator)
;(statement terminator) and : (host variable indicator).
The compound symbols consist of two characters like
< >,!=,:=(assignment), || (concatenation),
-- (single line comment), ** ( exponentiation),
/* */ (multi line comment),<<>>(label delimiter)
Datatypes Used in PL/SQL
 Boolean
 Binary_integer ( used to store signed integer)
 Number (Dec/decimal, Int/integer/Real)
 Varchar2 (4000 bytes), char(2000 bytes) Long
(32,760 bytes)
 Raw (types are used to store binary data)
 Rowid
 Composite Types (Collections and objects can be
used in PL/SQL)
 LOB Types (BLOB, CLOB, BFILE)
Attributes
Attributes allow us to refer datatypes and objects
from the database. PL/SQL Variables and constants can
have attributes. The following are the types of attributes
by PL/SQL
%type
 %rowtype
%Type:
%type attribute is used when declaring that refer
to the database columns. Consider the following
example where a called vcode is declared to be of type
vencode in the item table using %type attribute.
Example:
declare
enum emp.eno%type;
where enum is the variable name, emp is the name of the
table and eno is the name of the column.
The advantages of using %Type is,
 We need not know the exact type of the column
 If the database definition is changed, then the data
type of the variable changes accordingly at run time.
%Rowtype
%Rowtype attribute provides a record type that
represents a row in a table. The record can store an entire
row of data selected from the table or fetched by a
cursor.
In the following example, a record named ‘vend_inf’
will have the same names and datatypes as the columns
in the customer table.
Example
Declare
vend_inf vendor_master%rowtype;
In the above example, vend_inf stores a row selected
from the vendor_master table.
Logical Comparisons
PL/SQL supports the comparison of variables and
constants in SQL and PL/SQL statements.
These comparisons, ‘Boolean expressions’, are often
connected by logical operators AND,OR and NOT.
Control Structures
In addition to SQL commands,PL/SQL can also
process data using flow of control statements. The flow
of control statements can be classified under the
following categories :
 Conditional Control
 Iterative Control
 Sequential Control
Conditional control
Sequence of statements can be executed based on a
certain condition using the if statements, namely if
then, if then else and if then elsif. The simplest form
of an if statement is the if then statement . The syntax
is
if condition then
sequence of statements;
end if;
Example
Declare
orderstatus order_master.ostatus%type;
Begin
select ostatus into orderstatus from
order_master where orderno=‘o001’;
if orderstatus =‘p’ then
update order_master set odate=
‘01-jan-99’where orderno=‘o001’;
Else
update order_master set odate=
‘26-jan-99’ where orderno=‘o001’;
end if;
End;
the output of the above command is,
PL/SQL procedure successfully completed.
Iterative control
A sequence of statements can be executed any
number of times using loop constructs. Loops can be
classified into
Simple Loop
 For Loop
 While Loop
Simple Loop
The keyword loop should be placed before the
first statement in the sequence and the keyword end
loop after the last statement in the sequence.
Syntax for a simple loop is:
loop
--sequence of statements;
end loop;
Example
Declare
a number:=100;
Begin
Loop
a:=a+25;
exit when a=250;
End Loop;
dbms_output.put_line(a);
End;
While Loop
The While loop statement includes a condition
associated with a sequence of statement. If the
condition evaluates to true, then the sequence of
statements will be executed, and again control
resumes at the beginning of the loop. If the condition
evaluates to false, then the loop is bypassed and the
control passes to the next statement.
Syntax for a while loop
while <condition>
loop
sequence_of_statements;
end loop;
Example
SQL> declare
i number:=0;
j number:=0;
Begin
while i<=100 loop
j:=j+i;
I:=I+2;
end loop;
dbms_output.put_line(‘The value of j is ’ || j)’
end;
The output of the above PL/SQL procedure is
given below.
The value of j is 2550
PL/SQL procedure successfully completed.
FOR Loop
The number of iterations for a while loop is
unknown until the loop terminates, whereas the number
of iterations in a for loop is known before the loop gets
executed.
The syntax is given below.
For counter in ,[REVERSE] lower bound ..Upper bound
loop
sequence_of_statements
end loop;
Example
Begin
For I in Reverse 100..1
Loop
DBMS_OUTPUT.PUT_LINE(I);
End Loop;
End;
Example

Begin
for i in 1..2
loop
update order_master set ostatus =‘p’
where odate<sysdate;
end loop;
end;
Sequential Control:
The goto statement allows to branch label unconditionally.
The label which is enclosed with angle brackets must
precede an executable SQL, statement a PL/SQL block.
When executed the goto statement transfers control to the
labeled statement or block.
Example:
Declare
qtyhand itemfile.qty_hand%type;
relevel itemfile.re_level%type;
Begin
select qty_hand,re_level into qtyhand,relevel
from itemfile where itemcode=‘i201’;
If qtyhand < relevel then
goto updation;
End If;
<< updation>>
update itemfile set qty_hand=qty_hand +relevel
where itemcode = ‘i201‘;
End;
Concept of Error Handling:
Error condition in PL/SQL is termed as an
exception, There are 2 types of exceptions They are:
Predefined Exception
User-defined Exception
Predefined Exception
An exception is raised implicitly when a PL/SQL
program violates Oracle rule. The following are the
predefined exceptions supported by PL/SQL
No_data_found Zero_Divide
Cursor_already_open Invalid_Cursor
Dup_val_on_index Program_error
Login_denied Storage_Error
Invalid _number Too_many_rows
Example:
declare
qtyhand itemfile.qty_hand%type;
relevel itemfile.re_level%type;
begin
select qty_hand,re_level into qtyhand,relevel
from itemfile where itemcode=‘i100’;
Exception
when no_data_found then
dbms_output.put_line(‘such an item number
not avaliable’);
End;
User defined Exception
declare
lo_value exception;
qty_hand itemfile.qty_hand%type;
begin
select qty_hand into qtyhand from
itemfile where itemcode=‘i201’;
If qty_hand < 200 then
raise lo_value;
End If;
Exception
when lo_value then
dbms_output.put_line(‘quantity not enough’);
End;
Cursor Management
Oracle allocates an area of memory known as context
area for the processing of SQL statements. The
context area contains information necessary to
complete the processing, including the number of rows
processed by the statement.
A cursor is a handle or pointer to the context area.The
three types of cursors are
 Explicit Cursor
Implicit Cursor
An Explicit Cursor is one in which the cursor name is
explicitly assigned to the select statement.
An implicit cursor is used for all other SQL statements.
Processing an explicit cursor involves 4 steps.
Processing of an implicit cursor is taken care by
PL/SQL. The declaration of the cursor is done in the
declarative part of the block.
A cursor variable is a reference type. A reference type
is similar to a pointer. It can name different storage
locations as the program runs.
Explicit Cursor
The set of rows returned by a query can
contain zero or multiple rows depending upon the
query defined. These rows are called the active set.
After declaring a cursor, we can use the following
commands to control the cursor.
 Open
 Fetch
 Close
The ‘Open’ statement executes the query, identifies the
active set and positions the cursor before the first row.
The syntax is
open <Cursor name>;
The ‘fetch’ statement retrieves the current row and
advances the cursor to the next row to fetch the
remaining rows. Syntax for ‘fetch’ is
fetch <Cursor name> into <column name>;
After processing the last row in the active set, the
cursor is disabled with the help of the ‘close’
command. The syntax is as follows.
close <Cursor name>;
Example for an Explicit Cursor:
declare
icode order_detail.itemcode%type;
cursor a is select itemcode from
order_detail where itemcode =‘i201’;
begin
open a;
Loop
fetch a into icode;
update itemfile set itemrate=22.05
where itemcode=icode;
exit when a%NOTFOUND;
End Loop;
dbms_output.put_line(‘table updated’);
Close a;
End;
Attributes in Explicit & Implicit Cursor
 %notfound
%found
%rowcount
%isopen

%Notfound
The attribute %notfound indicates fetch
statement returns from the active set. If the last fetch
fails to return a row,then %notfound evaluates to
true,else it evaluates to false.
Example for a %notfound Attribute
Declare
order_no order_detail.orderno%type;
cursor a is select orderno from order_detail
where orderno=‘o001’;
Begin
Open a;
Loop
Fetch a into order_no;
Update order_master set del_date=
sysdate where orderno=order_no;
Exit When a%NOTFOUND; End
Loop; Close a;
End;
%Found
The %found attribute is the logical opposite of
%notfound. It evaluates to true if the last Fetch
statement returns at least one record.
%Rowcont
The %rowcount attribute is used to return the
number of rows fetched. Before the first fetch
%rowcount is 0.
When the fetch statement returns a row, then the
number is incremented.
Example to illustrate %Rowcount
declare
cursor a is select * from order_detail where
orderno=‘o001’;
myorder order_detail%rowtype;
begin
open a;
loop
fetch a into myorder;
exit when %Notfound;
dbms_output.put_line(‘fetched’ || a%rowcount || ‘ from
table’);
Example to illustrate %Isopen
declare
cursor mycur is select * from order_master;
begin
if not mycur%isopen then
dbms_output.put_line(‘the cursor is yet o be
opened’);
end if;
open mycur;
if mycur%isopen then
dbms_output.put_line(‘the cursor is now
opened’);
end if;
close mycur;
end;
Implicit Cursor
PL/SQL implicitly declares cursors for all
SQL data manipulation statements, including
queries that return one row. For queries that return
more than one row, we should use explicit cursors
to access the rows individually.
Implicit cursor attributes can be used to access
information about the most recently executed
SQL statement. The most recently executed SQL
statement is referred as ‘SQLCURSOR’.
Example for %Notfound attribute (Implicit Cursor)
begin
delete from order_detail where orderno =‘o201’;
if sql%NOTFOUND then
dbms_output.put_line(‘value not found’);
else
dbms_output.put_line(‘value found and
deleted’);
end if;
end;
Example for %Rowcount attribute (Implicit Cursor)
declare
order_no order_master.orderno%type;
begin
select orderno into order_no from order_master
where orderno=‘o001’;
if sql%ROWCOUNT > 0 then
dbms_output.put_line(‘rows selected from
table’);
else
dbms_output.put_line(‘ no rows selected from
table’);
end if;
end;
Cursor For Loop
A ‘cursor for’ loop can be used instead of explicit
cursors to simplify coding. A ‘cursor for’ loop
implicitly opens a cursor, repeatedly fetches rows from
the active set, and then, closes the cursor when all rows
have been processed.
The syntax for the ‘cursor for’ loop is as follows.

For <record_name> in <cursor name> loop


sequence of statements;
end loop;
XYZ enterprise would like to delete those rows from
the database whose orders have been fulfilled to the
extent they have ordered. Also the deletion would
depend on the vendor also. This they achieved as
shown below.
Example
declare
cursor for_cur is select orderno from order_master
where vencode = ‘v002’;
cust_rec for_cur%rowtype;
begin
for cust_rec in for_cur loop
delete from order_detail
where orderno=cust_rec.orderno;
end loop;
dbms_output.put_line(‘details has been deleted’);
end;
Subprograms & Packages
Subprograms
Subprograms are named PL/SQL blocks that can
accept parameters and can be invoked whenever
required. Similar to a PL/SQL block, a subprogram can
also have a declarative part, an executable part and an
exception handling part. Some of the important features
offered by subprograms are given below.
 Modularity - Subprograms allow us to break a
program into manageable, well-defined logical modules.
 Reusability - Subprograms once executed can be used
in any number of applications
Maintainability - Subprograms can simplify
maintenance, because if a subprogram is affected,
only its definition changes.
PL/SQL supports two types of subprograms. They
are:
 Procedures
 Functions
Procedures are usually used to perform any specific
task and functions are used to compute a value.
Procedures
A procedure is a subprogram that performs a
specific action. The syntax for creating a procedure is
given below.
Create or replace procedure <proc_name>
[parameter list] is
<local declarations>;
begin
[executable statements]
[exception] (exception handlers)
end;
A procedure has two parts, namely, specification and
body. The procedure specification begins with the
procedure name or parameter list. The procedure body
begins with the keyword is and ends with keyword
end. It can also include declarative, executable and
exceptional parts within the keyword end.
Syntax to execute a procedure is given below.
SQL> exec <proce_name>(parameters);
While declaring variables in the declarative part of the
procedure body, we should not specify the width of the
datatype, For example,
Procedure width (name char(40)) is
begin
(set of statements);
end;
In the above example, char(40) should be replaced by
char. The example shown below explains the usage of
procedure. It accepts a single parameter and updated
the table based on a condition . It also arises an
exception if no data is retrieved.
Example
create or replace procedure items (orders varchar2))
is
qtyhand number;
relevel number;
maxlevel number;
begin
select qty_hand,re_level, max_level into
qtyhand,relevel,maxlevel from itemfile where
itemcode=orders;
If qtyhand<relevel then
update itemfile set qty_hand=relevel + qtyhand
where itemcode=orders;
else
dbms_output.put_line(‘item level ok’);
end if;
Exception
when no_data_found then
dbms_output.put_line(‘no data returned’);
end;
Execution of the procedure
SQL> exec items(‘i201’)
when the above command is given the procedure is
executed and the output is given as shown below.
PL/SQL procedure completed successfully.
Modes in Parameters
The parameter list(defined in the create procedure
command) can hold any of the following modes
 in ( by default)
 out
inout
In parameter
The in parameter mode is used to pass values to
the subprogram when invoked. It acts like a constant and
therefore it cannot be assigned a value.
Example for in parameter mode
create or replace procedure orders(a in varchar2) is
v_code varchar2(5);
o_stat char(1);
begin
select vencode,ostatus into v_code,o_stat
from order_master where orderno=a;
if o_stat=‘p’ then
dbms_output.put_line(‘pending order ’ || a);
else
dbms_output.put_line(‘completed order ‘ || a);
end if;
end;
On compilation the user will get the message
Procedure created
SQL> exec orders(‘o001’);
Out Parameter
The out parameter mode is used to return values to the
caller of a subprogram. Since the initial value for an out
parameter is undefined, its value can be assigned to
another variable.
Example
create or replace procedure test(a in varchar2,
b out number) is
identity number;
begin
select qty_ord into identity from order_detail
where orderno=a;
if identity <450 then
b:=100;
end if;
end;
After compilation of the above program procedure is
created.
Execution of the above Procedure
declare
a varchar2(5);
b number;
begin
test(‘o202’,b);
dbms_output.put_line(‘the value of b is ‘ ||
to_char(b));
end;
The value of b is 100 is the output of the above program
In out Parameter
The in out parameter is used to pass initial values
to the subprogram when invoked and it also returns
updated values to the caller. An in out parameter acts
like an initialized variable and, therefore, can be
assigned to other variables or to itself.
Example
create or replace procedure or_detail(orno in
varchar2,b in out varchar2) is
qtyord number;
qtydeld number;
code varchar2(5);
Begin
select qty_ord,qty_deld,itemcode into
qtyord,qtydeld,code from order_detail
where orderno=no;
if qtydeld <qtyord then
b:=code;
end if;
end;
The output of the above program is procedure
created. To execute the above procedure a block as
shown below is written and executed.
Declare
a varchar2(5);
b varchar2(5);
begin
or_detail(‘o202’,b);
dbms_output.put_line(‘the item code is ‘ || b);
end;
The output of the above program is
the item code is i201
PL/SQL procedure successfully completed.
Functions
A function is a subprogram that computes a value.
The syntax for creating a function is given below.
Create or replace function <function_name>[argument]
return datatype is
(local declaration)
begin
(executable statements)
[Exception]
(exception handlers)
end;
Example
create or replace function items(it varchar2)
return number is
args number;
qtyhand number;
relevel number;
maxlevel number;
begin
select qty_hand,re_level,max_level into
qtyhand,relevel,maxlevel from itemfile
where itemcode=it;
If (qtyhand-relevel ) > maxlevel then
args:=maxlevel;
return args;
else
args:=(qtyhand+relevel);
return args;
end if;
end;
The output of the above block of code is,
Function created.
To execute the function items the following block of
code is executed,
declare
a varchar2(5);
b number;
begin
a:=&a;
b:=items(a);
dbms_output.put_line(‘the value returned is ‘ || b);
end;
The output of the above program is
Enter the value for b: i201
old 5: b:=&b;
new 5: b:=‘i201’;
the value returned is 140
PL/SQL procedure successfully completed.
Packages
A package is a database object, which is an
encapsulation of related PL/SQL types, subprograms,
cursors, exceptions,variables and constants. It consists
of two parts, a specification and a body. In the package
specification we can declare types, variables,constants,
exceptions, cursors and subprograms. A package body
implements cursors, subprograms defined in the
package specification.
Note
 Packages cannot be called, hence, we cannot pass
parameters as we do in subprograms. Nesting of
packages is also not possible
Packages can be created using the following commands.
 Create Package command
 Create Package body command.
The package specification is declared using a ‘create
package’ command.
Syntax for create package command
create package <package_name> is <declarations>
begin
(executable statements);
end [package name];
The procedures and cursors declared in the ‘create
package’ command is fully defined and implemented by
the package body.
Syntax to create a package body
create package body <package_name> is declarations
begin
(executable statements)
end [body_name]
Example for Package Specification
Create or replace package pack_me is
procedure order_proc(orno varchar2);
function order_fun(ornos varchar2) return
varchar2;
end pack_me;
/
The output of the above package on successful
compilation is,
package created
The package body is coded as given below
Example for Package body
create or replace package body pack_me as
procedure order_proc(orno varchar2) is
stat char(1);
begin
select ostatus into stat from order_master
where orderno=orno;
if stat=‘p’ then
dbms_output.put_line(‘pending order’);
else
dbms_output.put_line(‘completed order’);
end if;
Function order_fun(ornos varchar2) return varchar2 is
icode varchar2(5);
ocode varchar2(5);
qtyord number;
qtydeld number;
begin
select qty_ord,qty_deld,itemcode,orderno into
qtyord,qtydeld,icode,ocode from order_detail
where orderno=ornos;
if qtyord<qtydeld then
return ocode;
else
return icode;
end if;
end order_fun;
end pack_me;
The output of the above block of code when compiled is
package body created.
Calling packaged subprograms
To reference the types, objects and subprograms
declared in a package specification the following
notation is used.
Package-name.typename.
Package-name.object-name.
Package-name.subprogram-name.
To execute the above package
SQL> exec pack_me.order_no(‘o001’);
The output of the above SQL command is
completed order
PL/SQL procedure successfully completed.
To execute the function that is given in the package a
block of code is written as shown below,
Declare
a varchar2(5);
b varchar2(5);
begin
b:=pack_me.order_fun(‘0202’);
dbms_output.put_line(‘the value is ‘ || b);
end;
/
The output of the above program is,
the value is i201
PL/SQL procedure successfully completed.
Database Triggers
A database trigger is a stored procedure that is fired
when an insert,update or delete statement is issued
against the associated table. Database triggers can be
used for the following purposes.
 To generate data automatically.
 To enforce complex integrity constraints.(e.g.
checking with sysdate, checking with data in another
table).
To customize complex security authorizations.
To maintain replicate tables.
To audit data modifications
Syntax for creating triggers
The syntax for creating a trigger is given below.
Create or replace trigger <trigger_name>
[before/after] [insert/update/delete] on
<table_name> [for each statement/for each
row][when condition];
A database trigger can also have declarative and
exception handling parts.
Parts of a triggers
A database trigger has three parts, namely, a trigger
statement, a trigger body and a trigger restriction.
Trigger Statement
A trigger statement specifies the DML statements
like update,delete and insert and it fires the trigger body.
It also specifies the table to which the trigger is
associated.
Trigger Body
Trigger body is a PL/SQL block that is executed
when a triggering statement is issued
Trigger Restriction
Restriction on a trigger can be achieved using the
WHEN clause as shown in the syntax for creating
triggers. They can be included in the definition of a row
trigger, wherein the condition in the WHEN clause is
evaluated for each row that is affected by the trigger.
Note
 A subquery cannot be included
Types of Triggers
 Before
 After
 for each row
 for each statement
Before/After Options
The Before/After options can be used to specify
when the trigger body should be fired with respect to the
triggering statement. If the user includes a before option,
then, Oracle fires the trigger before executing the trigger
statement. On the other hand, if AFTER is used, then,
Oracle fires the trigger after executing the triggering
statement.
For Each Row/Statement
When the for each/row statement option when
included in the ‘create trigger’ syntax specifies that the
trigger fires once per row. By default, a database trigger
fires for each statement.
Using the combination of the above options we can
assign 12 types of triggers to a database table.
 Before Update row/statement
 Before Delete row/statement
 Before Insert row/statement
 After Update row/statement
 After insert row/statement
 After Delete row/statement
Apart from above types of the Triggers one more type
is there that is Instead of ,this, trigger can be applied
only to views and not for tables and it can be defined
only in Row-Level and not in Statement Level.
Example
create or replace trigger orders before insert on
order_detail for each row
declare
orno order_detail.orderno%type;
begin
select orderno into orno from order_detail
where qty_ord<qty_deld;
if orno =‘o001’ then
raise_application_error(-20001,’enter some
other number’);
end if;
end;
There are two variables namely, :old and :new which
retain the old and new values of the column updated in
the database. The values in these variables can be used
in database triggers for manipulation.
Example using old and new variable
create or replace trigger new_old_trig before
update on itemfile for each row
begin
if :new.qty_hand<:old.qty_hand then
raise_application_error(- 20001,
’QUNATITY ON HAND IS LESS’);
end if;
end;
Instead of Triggers
In Oracle8 there is something new in the world of
triggers. INSTEAD OF triggers. These are the triggers
that are defined on a view rather than on a table. Such
triggers can be used to overcome the restrictions placed
by Oracle on any view, which is deemed to be non-
updateable. Prior to version 7.3 it was impossible to
issue DML statements -INSERT,UPDATE,DELETE
-against any view which contained a join.
There are few restrictions on INSTEAD OF triggers
 They are available only at the row level and not at the
statement level
 They can be applied only to view and not to tables.
Creating view with Joins
create view ord_view as select
order_master.order_no,order_master.ostatus,
order_detail.qty_Deld,order_detail.qty_ord from
order_master,order_detail where
order_master.order_no=order_detail.order_no
the above view is created with joins
Create or replace trigger order_mast_insert
INSTEAD OF insert on ord_view referencing new as n
for each row
declare
cursor ecur is select * from order_master
where order_master.order_no = :n.orderno;
cursor dcur is select * from order_detail
where order_detail.order_no=:n.orderno;
a ecur%rowtype;
b dcur%rowtype;
begin
open ecur;
open dcur;
fetch ecur into a;
fetch dcur into b; if
dcur%notfound then
insert into order_master(orderno,o_status)
values(:n.orderno,:n.o_status); else
update
order_master set
order_master.o_status=:n.o_status where
order_master.orderno=:n.orderno; end
if;
if ecur%notfound then
insert into order_detail
(qty_ord,qty_deld,ordern)
values(:n.qty_ord:n.qty_deld,:n.ordern);
else
update order_detail set
order_detail.qty_deld=:n.qty_deld where
order_detail.ordernoo=:n.orderno;
end if;
end;
Enabling and Disabling Triggers
alter table order_master disable order_mast_insert;
To disable all the triggers syntax is
alter table <table-name> disable all triggers;
To enable all the triggers syntax is
alter table <table-name> enable all triggers;
Dropping Triggers
drop trigger <trigger_name>;

You might also like