Basic Introduction of Oracle and SQL - PLSQL
Basic Introduction of Oracle and SQL - PLSQL
com
3. avg
4. Standard deviation
5. variance
6. stddev
2. Character Functions :
1. ascii()
2. chr()
3. lower()
4. upper()
5. concat()
6. substr()
7. initcap()
8. length()
3. Member Functions :
1. abs( )
2. power( )
3. mod( )
4. sqrt( )
4. Mathematical Functions :
1. log( )
2. sin( )
3. cos( )
4. tan( )
5. Date Functions :
1. add_months( )
2. last_day( )
3. next_day( )
4. months_between( )
6. Set Commands
7. Show Commands
8. Constraints in Oracle :
1. unique
2. not null
3. primary key
4. null
9. Constants in Oracle :
1. sysdate
2. user
3. uid
4. rowid
5. distinct
10. Clauses in sql :
1. where
2. order by
3. group by
4. having
5. starting with
11. Table Set Commands :
1. union
2. union all
3. intersect
4. minus
12. VIEWS :
13. Joins :
1. self join
2. equi join
3. non-equi join
14. Executing Multiple Queries from a file to sql
* plus editor
15. Bind Variables
PL/SQL
1. Conditional Statements :
1. if
2. if-else
2. Control Statements :
1. while
2. do-while
3. for loop
3. Data Types in pl/sql :
1. number
2. varchar
3. varchar2
4. date
4. Structure of the pl/sql Program
5. Procedures & Functions
6. Triggers
ORACLE
DataBase:
1.Storing in the information about particular thing Using
this database we can create the database
and we can store th information and we can access the
information and we can modify the database
2.Using this database we can create any type of data &
we can store the data in the form of information we have
different types databases , we can create.
Ex: If we want to create database regarding employee , we
Information :
Information is nothing but giving the meaning full data
about particular thing . Using this information we can
decide whether this information set to our database or not .
Types of DataBases :
1. FDBMS
2. NDBMS
3. RDBMS
1. number :
1. Using this number data type , we can store
numbers in a particular column in table.
2. If we create one column of number data type,then
that column allows only numbers, In that column
it doesn't allows characters or any decimal points.
3. Ex: empno number ;
We can giving number data type we want to store
decimal values then we can use this number data
10
[email protected]
For Clob & Blob data types we can find the data with the
help of locators.
Ex:
image blob ; //4GB
file clob ; //2GB
1. Grant:
Syn:-grant permissions on tablename to username;
Ex:- grant alter on student to scott;
Ex:- grant update on emp to bank;
Ex:- grant alter,update on student to dsnr;
DDL COMMANDS :
create :
1. create is a keyword.
2. It is using for creating one table in a database, after
executing create command table will be created.The
table contains zero records and structure with zero
values.
3. Table contains number of columns , in create query
we can give complete details of table.
4. In create command we give the column names with
data types.
5. Syntax : create table tablename(columnname
datatype);
Ex1: create table employee(empno number , dob date,
sal number );
Ex2: create table bank(bname varchar2(30) , bal
number );
Ex3: create table cell(cname varchar2(30) , cost
number(9,2) );
Ex4: create table school(sname varchar2(20) , splace
varchar2(30) );
Ex5: create table college(cid number , cname
varchar2(30) );
Ex5: create table course(cid number , cname
varchar2(30) );
delete :
1. deiete is a key word , using this keyword we can
delete perticular row in a database table .
2. Delete command using for delete rows only , but not
table.
3. Before executing the delete command that table name
must be exist.If we give the unknown table name we
willget an error
4. syntax : delete tablename where columnname=value;
Ex : delete employee where empno=10 ;
20 b 2000 20
30 c 3000 30
40 d 4000 50
6.
10 a 1000 10
20 b 2000 20
30 c 3000 30
40 d 4000 50
40 d 4000 50
alter :
• Using this alter command we can modified the table
and we can perform number of operations on the
table.
1. Add the new columns to the table
2. Modify the existing data types
3. Rename the existing column name
4. Drop the column in a table
40 d 4000 HR
Select :
1. This command is using for display the table with
values., this command is using for seeing the
informatiom of table.
2. This command is uesd for display the no. of records
reliable in a table.
3. First we create the table then we insert the values.
4. After inserting the values we get the message like one
row is inserted.
5. If we want to check that row and we want see that
values then go for select command
6. This is non-action statement.
7. After executing the select query it doesn't effect on
database.
8. After executing this query no modifications in the
table .
9. Using this select command we can see entire table at
once.
10. Using this select command we can select not
entire table , we can select particular no. of columns
also.
a% ;
6. _ :
5. In Operator :
o Using with in operator we can find the records in
written as output.
6. Between Operator :
o Using with between operator we can find the
Order by Cluse :
1. Using with order by class we can perform operations
on the table.
2. Using with command we can access the rows with 2
times
1. ascending order
2. descending order
FUNCTIONS
:
Grouping Functions :
Grouping Functions are
1. min( )
2. max( )
3. avg( )
1. min() :
min() function is used for finding the minimum value
in the given table, this min( ) function will return
which is the lowest value in the table on the given
conditions.
syntax : select min(salary) from employee ;
2. max() :
max() function is using for bring the highest salary in
the given condition or column name.
syntax : select max(salary) from employee ;
3. avg( ) :
2. Chr() :
This function is using for return the character of the
given value
This function will take the argument is number , that
number match to which character , that character
should be return.
7. InitCap() :
7.
set heading off ;
Member Functions :
1. abs( ) : This function is using for finding the absolute
value of the given number.
Ex : select abs(-10) from dual ;
output : 10
2. power( ) : This function is using for finding the power
of the given number.
Ex : select power(2,3) from dual ;
3. mod( ) : This function is using for finding the
remember of the given value.
Ex : select mod(5,2) from dual ;
4. sqrt( ) : This function is using for finding the sqrt of
the given number.
Ex : select sqrt(4) from dual ;
Mathematical Functions :
1. log( ) : log function is using for finding the log value
of the given numbers.
Ex : select log(2,1) from dual ;
2. sin( ) : sin function is using for finding the sin value
of the given radians.
Ex : select sin(90) from dual ;
Date Functions :
1. add_months( ) :
o This functions using for displaying the details
student ;
output : 31-jan-14
3. next_day( ) :
1. This function is using for finding the day of
given date.
42
[email protected]
Truncate :
1. This command is using for deleting the all rows in a
table.
2. Truncate is nothing but clearing the table with out
rows.
43
[email protected]
CONSTRAINTS IN ORACLE :
1. Unique
2. Not Null
3. Primary Key
4. Null
1. Unique :
1. unique constraint is using for declaring the
column .
2. unique does not apply to the table names , only
for columns.
3. Which column contains the unique constraint that
column value should be unique.
4. column doesn't contains repetative values or
redundency values.
5. syntax : create table employee(eno number ,
ename varchar2(20) unique );
Syn :- create table tablename (columnname
datatype constraint) ;
Ex :- create table emp2(eno number unique , ename
varchar2(20)) ;
2. Not Null :
1. This constraint is using for giving the column
names , it doesn't apply to table names.
2. When we create the table , if we contain
character datatypes instead of value , we can give
the null .
4. NULL :
1. null is a keyword in a Oracle.
2. null is not a value , it indicates this column
contains no value.
3. When we insert in the values if we doesn't find
any value to the given column then go for null.
4. When we declare one column with not null
constraint at the time we don't use the null key
word.
5. If we try to use the null keyword it will show
error, and that row doesn't insert.
Syn :- create table emp3(eno number , ename
varchar2(20)) ; Ex :- insert into emp3 values(1,'apec')
; Ex :- insert into emp3 values(1, null) ; Ex :- insert
into emp3 values(2, null) ;
Clauses in SQL :
clauses are using for accessing the records on the given
certain conditions , give any condition regarding the
condition is working.
empno empname salary empjob
10 ashok 1000 Security guard
20 arunkumar 2000 employ
30 akshay 3000 Team Leader
40 saicharan 4000 HR
1. where :
2. order by :
1. This clause is using for displaying the data in the
form of orders.
2. The orders are ascending order or descending
order .
3. Ascending order is nothing but small to big ,
descending order is nothing but big value to
small.
4. syntax : select * from employee order by salary
asc ;
3. group by :
1. This function is using for displaying the data in
the form of selecting multiple columns depending
on one column.
2. syntax : select * from employee group by salary ;
Ex : select sum(salary) , count(salary ) from
employee group by salary ;
4. Having :
1. This clause is using for finding the result of the
given having condition.
2. This will display the result of who are satisfy the
condition.
3. select * from employee having sno=10 ;
5. starting with :
1. Using with clause we can find out whether the
given string is starting with the given character or
not .
2. We give the character as a argument in a single
code.
3. syntax : select * from employee where empname
starting with('a');
Tab :
User_Objects :
• This command is using for displaying the all tables
and views , which are available in the oracle server.
• It is not only display the tablenames and also all those
details it will give.
• syntax : select * from user_objects ;
Views :
1. view is nothing but table .
2. When we want to create one table with same values
then go for views.
54
[email protected]
Joins :
1. Joins are using for combining the two tables
information.
2. When we want to see the 2 tables information at a
time then go for joins.
3. After joining the tables it will display the 2nd table
information at a time in a single table .
4. After joining the tables entire information in one
table.
5. Joins are 3 types :
1. self join
2. equi join
3. non-equi join
4. self join :
Bind Variables :
1. This variables are using for giving the values to the
where conditions.
2. At runtime to allocate the values to the variables.
3. If we directly assign the values it will execute only
one time.
4. If we want to execute 2nd time , then we have to write
the entire condition.
5. general : select * from emp where sal=100 ;
Use bind variable : select * from emp where
sal='&sal' ;
6. Characters (use bind variable) : select * from emp
where ename='&name' ;
vsize( ) function :
1. This function is using for displaying the size of the
perticular variable .
2. It will display the output of how many bytes accupied
by the variable.
3. syntax : select vsize(value) from dual ; //value=100
Set Command :
1. set space n : This cmd is using for giving the spaces
to the columns
2. If we want to give space between the column names
then go for space cmd. This default column space is
"Zero"
3. The highest column space is 10
4. set the n value is 0 to 10
59
[email protected]
5. set space n ;
Ex : set space 5 ;
• giving column names to the functions after executing .
• In general when we execute function it will display
the column name like function name only.
• If we want to give the column name to the function
then you can give.
• syntax : select function-name variable-name from
anytable ;
Ex : select max(sal) highest from dual ;
PL/SQL :
1. pl/sql is nothing but procedural language/sql , This
language is using for writing the programs in the sql
editor.
2. We can write the all programs like C , C++ .... this
language also provides variables data types , program
is nothing but executing set of instructions , statement
is nothing but group of words .
3. We write pl/sql programs in sql * plus editor , sql *
plus editor is using for writing pl/sql programs.
4. In generally once we write the program can be
compile & run the programs.
5. In pl/sql programs after writing the program we save
the file name as filename.sql
add.sql OR sub.sql
6. We can write the pl/sql programs in notepad also ,
after writing into the notepad , we save the filename
as filename.sql
3. varchar2
4. date
Structure of the pl/sql program : ......................
In the above structure describes how to write the pl/sql
programs
1. declare block :
1. In this block we can declare the variables , we
can declare the variables with the help of some
specified data type.
2. Every variable should have a one data type ,
every variable declaration ends with the
semicolon.
3. semicolon indicates end of the statement.
2. begin block :
1. This block is using writing the real code of the
program.
2. In begin part , we write the program & task of the
program.
3. For completion of this task it will use the declare
part .
4. Using the declare part is nothing but using the
variables .
3. end block : end is nothing but indicating the our
pl/sql program is over .
4. ' / ' is nothing but start the execution of the pl/sql
program.It is for oracle server , not for pl/sql program.
variablename datatype ;
x number ;
name varchar(20) ;
jdate date ;
6. output :welcome
If statement :
1. It is one type of conditional statement , it is using for
comparing the 2 values Or comparing the 2 variables.
2. if condition is satisfied Or condition is true then if
block will be executed.
3. if condition is false then does not execute any code.
4. if condition is true we get the output .
5. if condition is false we have no output.
INTRODUCTION
SQL is divided into the following
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Retrieval Language (DRL)
• Transaction Control Language (TCL)
64
[email protected]
Ex:
SQL> insert into student values (1, 'sudha', 100);
SQL> insert into student values (2, 'saketh', 200);
To insert a new record again you have to type entire
insert command, if there are lot of records this will be
difficult.
This will be avoided by using address method.
b. USING ADDRESS METHOD
Syntax:
insert into <table_name> values (&col1, &col2,
&col3 .... &coln);
This will prompt you for the values but for every
insert you have to use forward slash.
Ex:
SQL> insert into student values (&no, '&name',
&marks);
Enter value for no: 1
Enter value for name: Jagan
Enter value for marks: 300
old 1: insert into student values(&no,
'&name', &marks)
new 1: insert into student values(1,
'Jagan', 300)
SQL> /
Enter value for no: 2
Enter value for name: Naren
Enter value for marks: 400
old 1: insert into student values(&no,
'&name', &marks)
SQL> /
Enter value for no: 6
Enter value for name: Rattu
old 1: insert into student (no, name)
values(&no, '&name')
new 1: insert into student (no, name)
values(6, 'Rattu')
SELECTING DATA
Syntax:
Select * from <table_name>; -- here * indicates all
columns
or
Select col1, col2, ... coln from <table_name>;
Ex:
SQL> select * from student;
NO NAME MARKS
--- ------ --------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh
4 Madhu
5 Visu
6 Rattu
SQL> select no, name, marks from student;
NO NAME MARKS
--- ------ --------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh
68
[email protected]
4 Madhu
5 Visu
6 Rattu
SQL> select no, name from student;
NO NAME
--- -------
1 Sudha
2 Saketh
1 Jagan
2 Naren
3 Ramesh
4 Madhu
5 Visu
6 Rattu
▪ like
▪ Logical operators
▪ And
▪ Or -- lowest precedence
▪ not
NO NAME MARKS
--- ------- ----------
3 Ramesh
4 Madhu
5 Visu
6 Rattu
NO NAME MARKS
--- ------- ----------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
b. USING AND
71
[email protected]
c. USING OR
This will gives the output when either of the
conditions become true.
Syntax:
select * from <table_name> where <condition1>
and <condition2> or .. <conditionn>;
Ex:
SQL> select * from student where no = 2 or marks
>= 200;
NO NAME MARKS
--- ------- ---------
2 Saketh 200
1 Jagan 300
2 Naren 400
d. USING BETWEEN
72
[email protected]
This will gives the output based on the column and its
lower bound, upperbound.
Syntax:
select * from <table_name> where <col> between
<lower bound> and <upper bound>;
Ex:
SQL> select * from student where marks between
200 and 400;
NO NAME MARKS
--- ------- ---------
2 Saketh 200
1 Jagan 300
2 Naren 400
f. USING IN
This will gives the output based on the column and its
list of values specified.
Syntax:
select * from <table_name> where <col> in (
value1, value2, value3 ... valuen);
Ex:
SQL> select * from student where no in (1, 2, 3);
NO NAME MARKS
--- ------- ---------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh
g. USING NOT IN
This will gives the output based on the column which
values are not in the list of values specified.
Syntax:
select * from <table_name> where <col> not in (
value1, value2, value3 ... valuen);
Ex:
SQL> select * from student where no not in (1, 2,
3);
NO NAME MARKS
--- ------- ---------
4 Madhu
5 Visu
6 Rattu
h. USING NULL
This will gives the output based on the null values in
the specified column.
Syntax:
select * from <table_name> where <col> is null;
Ex:
SQL> select * from student where marks is null;
NO NAME MARKS
--- ------- ---------
3 Ramesh
4 Madhu
5 Visu
6 Rattu
j. USING LIKE
This will be used to search through the rows of
database column based on the pattern you specify.
Syntax:
select * from <table_name> where <col> like
<pattern>;
Ex:
i. This will give the rows whose marks are 100.
SQL> select * from student where marks like
100;
ii. NO NAME MARKS
iii. --- ------- ---------
iv. 1 Sudha 100
v. This will give the rows whose name start with
'S'.
SQL> select * from student where name like
'S%';
vi. NO NAME MARKS
vii. --- ------- ---------
viii. 1 Sudha 100
ix. 2 Saketh 200
x. This will give the rows whose name ends with
'h'.
SQL> select * from student where name like
'%h';
xi.
xii. NO NAME MARKS
xiii. --- ------- ---------
xiv. 2 Saketh 200
xv. 3 Ramesh
xvi. This will give the rows whose name's second
letter start with 'a'.
76
[email protected]
5 Visu
4 Madhu
3 Ramesh
2 Saketh 200
2 Naren 400
1 Sudha 100
1 Jagan 300
USING DML
USING UPDATE
This can be used to modify the table data.
Syntax:
Update <table_name> set <col1> = value1, <col2> =
value2 where <condition>;
Ex:
SQL> update student set marks = 500;
If you are not specifying any condition this will update
entire table.
SQL> update student set marks = 500 where no = 2;
SQL> update student set marks = 500, name = 'Venu'
where no = 1;
USING DELETE
This can be used to delete the table data temporarily.
Syntax:
Delete <table_name> where <condition>;
Ex:
SQL> delete student;
If you are not specifying any condition this will delete
entire table.
SQL> delete student where no = 2;
USING DDL
USING ALTER
This can be used to add or remove columns and to modify
the precision of the datatype.
a. ADDING COLUMN
Syntax:
alter table <table_name> add <col datatype>;
Ex:
SQL> alter table student add sdob date;
b. REMOVING COLUMN
Syntax:
alter table <table_name> drop <col datatype>;
Ex:
SQL> alter table student drop column sdob;
c. INCREASING OR DECREASING PRECISION
OF A COLUMN
Syntax:
alter table <table_name> modify <col datatype>;
80
[email protected]
Ex:
SQL> alter table student modify marks number(5);
* To decrease precision the column should be empty.
d. MAKING COLUMN UNUSED
Syntax:
alter table <table_name> set unused column <col>;
Ex:
SQL> alter table student set unused column
marks;
Even though the column is unused still it will occupy
memory.
e. DROPPING UNUSED COLUMNS
Syntax:
alter table <table_name> drop unused columns;
Ex:
SQL> alter table student drop unused columns;
* You can not drop individual unused columns of a
table.
f. RENAMING COLUMN
Syntax:
alter table <table_name> rename column
<old_col_name> to <new_col_name>;
Ex:
SQL> alter table student rename column marks to
smarks;
USING TRUNCATE
This can be used to delete the entire table data
permanently.
Syntax:
truncate table <table_name>;
Ex:
SQL> truncate table student;
USING DROP
This will be used to drop the database object;
Syntax:
Drop table <table_name>;
Ex:
SQL> drop table student;
USING RENAME
This will be used to rename the database object;
Syntax:
rename <old_table_name> to <new_table_name>;
Ex:
SQL> rename student to stud;
USING TCL
82
[email protected]
USING COMMIT
This will be used to save the work.
Commit is of two types.
• Implicit
• Explicit
a. IMPLICIT
This will be issued by oracle internally in two
situations.
When any DDL operation is performed.
o
b. EXPLICIT
This will be issued by the user.
Syntax:
Commit or commit work;
* When ever you committed then the transaction was
completed.
USING ROLLBACK
This will undo the operation.
This will be applied in two methods.
• Upto previous commit
• Upto previous rollback
Syntax:
Roll or roll work;
Or
Rollback or rollback work;
* While process is going on, if suddenly power goes then
oracle will rollback the transaction.
USING SAVEPOINT
You can use savepoints to rollback portions of your current
set of transactions.
Syntax:
Savepoint <savepoint_name>;
Ex:
SQL> savepoint s1;
SQL> insert into student values(1, 'a', 100);
SQL> savepoint s2;
SQL> insert into student values(2, 'b', 200);
SQL> savepoint s3;
SQL> insert into student values(3, 'c',
300);
SQL> savepoint s4;
SQL> insert into student values(4, 'd',
400);
Before rollback
SQL> select * from student;
NO NAME MARKS
--- ------- ----------
1 a 100
2 b 200
3 c 300
4 d 400
SQL> rollback to savepoint s3;
Or
SQL> rollback to s3;
USING DCL
DCL commands are used to granting and revoking the
permissions.
USING GRANT
This is used to grant the privileges to other users.
Syntax:
Grant <privileges> on <object_name> to <user_name>
[with grant option];
Ex:
Syntax:
Create table <new_table_name> [col1, col2, col3 ...
coln] as select * from <old_table_name>;
Ex:
SQL> create table student1 as select * from student;
Creating table with your own column names.
SQL> create table student2(sno, sname, smarks) as
select * from student;
Creating table with specified columns.
SQL> create table student3 as select no,name from
student;
Creating table with out table data.
SQL> create table student2(sno, sname, smarks) as
select * from student where 1 = 2;
In the above where clause give any condition which does
not satisfy.
INSERT WITH SELECT
Using this we can insert existing table data to a another
table in a single trip. But the table structure should be
same.
Syntax:
Insert into <table1> select * from <table2>;
Ex:
SQL> insert into student1 select * from student;
Ex:
SQL> Merge into student1 s1
Using (select *From student2) s2
On(s1.no=s2.no)
When matched then
Update set marks = s2.marks
When not matched then
Insert (s1.no,s1.name,s1.marks)
Values(s2.no,s2.name,s2.marks);
In the above the two tables are with the same structure but
we can merge different structured tables also but the
datatype of the columns should match.
Assume that student1 has columns like no,name,marks and
student2 has columns like no, name, hno, city.
SQL> Merge into student1 s1
Using (select *From student2) s2
On(s1.no=s2.no)
When matched then
Update set marks = s2.hno
When not matched then
Insert (s1.no,s1.name,s1.marks)
Values(s2.no,s2.name,s2.hno);
MULTIBLE INSERTS
We have table called DEPT with the following columns
and data
DEPTNO DNAME LOC
-------- -------- ----
10 accounting new york
20 research dallas
30 sales Chicago
40 operations boston
• Ceil
• Floor
• Round
• Trunk
• Bitand
• Greatest
• Least
• Coalesce
A. ABS
Absolute value is the measure of the magnitude of
value. Absolute value is always a positive number.
Syntax:
abs (value)
Ex:
SQL> select abs(5), abs(-5), abs(0), abs(null) from
dual;
ABS(5) ABS(-5) ABS(0) ABS(NULL)
------ ------- ------ ---------
5 -5 0
B. SIGN
Sign gives the sign of a value.
Syntax:
sign (value)
Ex:
SQL> select sign(5), sign(-5), sign(0), sign(null)
from dual;
SIGN(5) SIGN(-5) SIGN(0) SIGN(NULL)
C. SQRT
This will give the square root of the given value.
Syntax:
sqrt (value) -- here value must be positive.
Ex:
SQL> select sqrt(4), sqrt(0), sqrt(null), sqrt(1)
from dual;
SQRT(4) SQRT(0) SQRT(NULL) SQRT(1)
------- ------- ---------- ----------
2 0 1
D. MOD
This will give the remainder.
Syntax:
mod (value, divisor)
Ex:
SQL> select mod(7,4), mod(1,5), mod(null,null),
mod(0,0), mod(-7,4) from dual;
MOD(7,4) MOD(1,5) MOD(NULL,NULL) MOD(0,0)
MOD(-7,4)
-------- -------- -------------- --------
---------
3 1 0
-3
E. NVL
This will substitutes the specified value in the place of
null values.
95
[email protected]
Syntax:
nvl (null_col, replacement_value)
Ex:
SQL> select * from student; -- here for 3rd row
marks value is null
NO NAME MARKS
-- ---- ---------
1 a 100
2 b 200
3 c
F. POWER
Power is the ability to raise a value to a given
exponent.
Syntax:
power (value, exponent)
Ex:
SQL> select power(2,5), power(0,0), power(1,1),
power(null,null), power(2,-5) from dual;
POWER(2,5) POWER(0,0) POWER(1,1)
POWER(NULL,NULL) POWER(2,-5)
---------- ---------- --------- --------------
--- ---------------
32 1 1
.03125
G. EXP
This will raise e value to the give power.
Syntax:
exp (value)
Ex:
SQL> select exp(1), exp(2), exp(0), exp(null), exp(-
2) from dual;
EXP(1) EXP(2) EXP(0) EXP(NULL)
EXP(-2)
-------- --------- ------ ---------
----------
2.71828183 7.3890561 1
.135335283
H. LN
This is based on natural or base e logarithm.
97
[email protected]
Syntax:
ln (value) -- here value must be greater than zero
which is positive only.
Ex:
SQL> select ln(1), ln(2), ln(null) from dual;
LN(1) LN(2) LN(NULL)
------ ------- ------------
0 .693147181
1.09861229 1.09861229
J. CEIL
K. FLOOR
This will produce a whole number that is less than or
equal to the specified value.
Syntax:
floor (value)
Ex:
SQL> select floor(5), floor(5.1), floor(-5), floor( -
5.1), floor(0), floor(null) from dual;
FLOOR(5) FLOOR(5.1) FLOOR(-5) FLOOR(-5.1)
FLOOR(0) FLOOR(NULL)
-------- ---------- -------- ----------- --
------- -----------
5 5 -5 -6
0
L. ROUND
This will rounds numbers to a given number of digits
of precision.
Syntax:
round (value, precision)
Ex:
SQL> select round(123.2345), round(123.2345,2),
round(123.2354,2) from dual;
ROUND(123.2345) ROUND(123.2345,0)
ROUND(123.2345,2) ROUND(123.2354,2)
--------------- ----------------- -----------
------ -----------------
123 123 123.23
123.24
ROUND(123.2345,-1) ROUND(123.2345,-2)
ROUND(123.2345,-3) ROUND(123.2345,-4)
------------------ ------------------ --------
---------- ------------------
120 100 0
0
M. TRUNC
This will truncates or chops off digits of precision
from a number.
Syntax:
trunc (value, precision)
Ex:
SQL> select trunc(123.2345), trunc(123.2345,2),
trunc(123.2354,2) from dual;
TRUNC(123.2345) TRUNC(123.2345,2)
TRUNC(123.2354,2)
--------------- ----------------- ------------
-----
123 123.23 123.23
TRUNC(123.2345,-1) TRUNC(123.2345,-2)
TRUNC(123.2345,-3) TRUNC(123.2345,-4)
------------------ ------------------ --------
---------- ------------------
120 100 0
0
N. BITAND
This will perform bitwise and operation.
Syntax:
bitand (value1, value2)
Ex:
SQL> select bitand(2,3), bitand(0,0), bitand(1,1),
bitand(null,null), bitand(-2,-3) from dual;
O. GREATEST
This will give the greatest number.
Syntax:
greatest (value1, value2, value3 ... valuen)
Ex:
SQL> select greatest(1, 2, 3), greatest(-1, -2, -3)
from dual;
GREATEST(1,2,3) GREATEST(-1,-2,-3)
--------------- ------------------
3 -1
nothing.
o If any of the parameters is null it will display
nothing.
P. LEAST
This will give the least number.
Syntax:
least (value1, value2, value3 ... valuen)
Ex:
SQL> select least(1, 2, 3), least(-1, -2, -3) from
dual;
LEAST(1,2,3) LEAST(-1,-2,-3)
------------ ---------------
1 -3
nothing.
Q. COALESCE
This will return first non-null value.
Syntax:
coalesce (value1, value2, value3 ... valuen)
Ex:
SQL> select coalesce(1,2,3), coalesce(null,2,null,5)
from dual;
COALESCE(1,2,3) COALESCE(NULL,2,NULL,5)
--------------- -----------------------
1 2
STRING FUNCTIONS
• Initcap
• Upper
• Lower
• Length
• Rpad
• Lpad
• Ltrim
• Rtrim
• Trim
• Translate
• Replace
• Soundex
• Concat ( ' || ' Concatenation operator)
• Ascii
• Chr
• Substr
105
[email protected]
• Instr
• Decode
• Greatest
• Least
• Coalesce
A. INITCAP
This will capitalize the initial letter of the string.
Syntax:
initcap (string)
Ex:
SQL> select initcap('computer') from dual;
INITCAP
--------
Computer
B. UPPER
This will convert the string into uppercase.
Syntax:
upper (string)
Ex:
SQL> select upper('computer') from dual;
UPPER
---------
COMPUTER
C. LOWER
This will convert the string into lowercase.
Syntax:
lower (string)
Ex:
SQL> select lower('COMPUTER') from dual;
LOWER
---------
computer
D. LENGTH
This will give length of the string.
Syntax:
length (string)
Ex:
SQL> select length('computer') from dual;
LENGTH
-------
8
E. RPAD
This will allows you to pad the right side of a column
with any set of characters.
Syntax:
rpad (string, length [, padding_char])
Ex:
SQL> select rpad('computer',15,'*'),
rpad('computer',15,'*#') from dual;
RPAD('COMPUTER' RPAD('COMPUTER'
--------------- ----------------
computer******* computer*#*#*#*
LTRIM('C LTRIM('C
---------- ----------
computer computer
Syntax:
trim (unwanted_chars from string)
Ex:
SQL> select trim( 'i' from 'indiani') from dual;
TRIM(
-----
ndian
J. TRANSLATE
This will replace the set of characters, character by
character.
Syntax:
translate (string, old_chars, new_chars)
Ex:
SQL> select translate('india','in','xy') from dual;
TRANS
--------
xydxa
K. REPLACE
This will replace the set of characters, string by string.
Syntax:
replace (string, old_chars [, new_chars])
Ex:
SQL> select replace('india','in','xy'),
replace('india','in') from dual;
REPLACE REPLACE
----------- -----------
Xydia dia
L. SOUNDEX
This will be used to find words that sound like other
words, exclusively used in where clause.
Syntax:
soundex (string)
Ex:
SQL> select * from emp where soundex(ename) =
soundex('SMIT');
EMPNO ENAME JOB MGR HIREDATE
SAL DEPTNO
----- ------ ----- ---- ------------
----- --------
7369 SMITH CLERK 7902 17-DEC-80
500 20
M. CONCAT
This will be used to combine two strings only.
Syntax:
concat (string1, string2)
111
[email protected]
Ex:
SQL> select concat('computer',' operator') from
dual;
CONCAT('COMPUTER'
------------------
computer operator
'HOW'||'ARE
------------
how are you
N. ASCII
This will return the decimal representation in the
database character set of the first character of the
string.
Syntax:
ascii (string)
Ex:
SQL> select ascii('a'), ascii('apple') from dual;
ASCII('A') ASCII('APPLE')
------------ ------------
97 97
O. CHR
This will return the character having the binary
equivalent to the string in either the database character
set or the national character set.
112
[email protected]
Syntax:
chr (number)
Ex:
SQL> select chr(97) from dual;
CHR
-----
a
P. SUBSTR
This will be used to extract substrings.
Syntax:
substr (string, start_chr_count [, no_of_chars])
Ex:
SQL> select substr('computer',2),
substr('computer',2,5), substr('computer',3,7)
from dual;
SUBSTR( SUBST SUBSTR
-------- ------- --------
omputer omput mputer
12 3 4 5 6 7 8
CO M P U T E R
-8 -7 -6 -5 -4 -3 -2 -1
Q. INSTR
This will allows you for searching through a string for
set of characters.
Syntax:
instr (string, search_str [, start_chr_count [,
occurrence] ])
Ex:
SQL> select instr('information','o',4,1),
instr('information','o',4,2) from dual;
INSTR('INFORMATION','O',4,1)
INSTR('INFORMATION','O',4,2)
--------------------------- --------
--------------------
4
10
Syntax:
decode (value, if1, then1, if2, then2, ....... else);
Ex:
SQL> select sal,
decode(sal,500,'Low',5000,'High','Medium') from
emp;
SAL DECODE
----- ---------
500 Low
2500 Medium
2000 Medium
3500 Medium
3000 Medium
5000 High
4000 Medium
5000 High
1800 Medium
1200 Medium
2000 Medium
2700 Medium
2200 Medium
3200 Medium
display zero.
S. GREATEST
This will give the greatest string.
Syntax:
greatest (strng1, string2, string3 ... stringn)
Ex:
SQL> select greatest('a', 'b', 'c'),
greatest('satish','srinu','saketh') from dual;
GREAT GREAT
------- -------
c srinu
nothing.
T. LEAST
This will give the least string.
Syntax:
greatest (strng1, string2, string3 ... stringn)
Ex:
SQL> select least('a', 'b', 'c'),
least('satish','srinu','saketh') from dual;
LEAST LEAST
------- -------
a saketh
nothing.
o If any of the parameters is null it will display
nothing.
U. COALESCE
This will gives the first non-null string.
Syntax:
coalesce (strng1, string2, string3 ... stringn)
Ex:
SQL> select coalesce('a','b','c'),
coalesce(null,'a',null,'b') from dual;
COALESCE COALESCE
----------- -----------
a a
DATE FUNCTIONS
• Sysdate
• Current_date
• Current_timestamp
• Systimestamp
• Localtimestamp
• Dbtimezone
• Sessiontimezone
• To_char
• To_date
• Add_months
• Months_between
• Next_day
• Last_day
• Extract
117
[email protected]
• Greatest
• Least
• Round
• Trunc
• New_time
• Coalesce
Oracle default date format is DD-MON-YY.
We can change the default format to our desired format by
using the following command.
SQL> alter session set nls_date_format = 'DD-
MONTH-YYYY';
But this will expire once the session was closed.
A. SYSDATE
This will give the current date and time.
Ex:
SQL> select sysdate from dual;
SYSDATE
-----------
24-DEC-06
B. CURRENT_DATE
This will returns the current date in the session's
timezone.
Ex:
SQL> select current_date from dual;
CURRENT_DATE
------------------
24-DEC-06
C. CURRENT_TIMESTAMP
This will returns the current timestamp with the active
time zone information.
Ex:
SQL> select current_timestamp from dual;
CURRENT_TIMESTAMP
-----------------------------------------
24-DEC-06 03.42.41.383369 AM +05:30
D. SYSTIMESTAMP
This will returns the system date, including fractional
seconds and time zone of the database.
Ex:
SQL> select systimestamp from dual;
SYSTIMESTAMP
------------------------------------
24-DEC-06 03.49.31.830099 AM +05:30
E. LOCALTIMESTAMP
This will returns local timestamp in the active time
zone information, with no time zone information
shown.
Ex:
SQL> select localtimestamp from dual;
LOCALTIMESTAMP
-----------------------------
24-DEC-06 03.44.18.502874 AM
F. DBTIMEZONE
This will returns the current database time zone in
UTC format. (Coordinated Universal Time)
Ex:
SQL> select dbtimezone from dual;
DBTIMEZONE
---------------
-07:00
G. SESSIONTIMEZONE
This will returns the value of the current session's
time zone.
Ex:
SQL> select sessiontimezone from dual;
SESSIONTIMEZONE
----------------
+05:30
H. TO_CHAR
This will be used to extract various date formats. The
available date formats as follows.
Syntax:
to_char (date, format)
DATE FORMATS
D -- No of days in week
DD -- No of days in month
DDD -- No of days in year
MM -- No of month
MON -- Three letter abbreviation of
month
120
[email protected]
SP -- suffix to a number to be
spelled out
SPTH -- Suffix combination of TH and
SP to be both spelled out
THSP -- same as SPTH
Ex:
SQL> select to_char(sysdate,'dd month yyyy
hh:mi:ss am dy') from dual;
TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI
------------------------------------
24 december 2006 02:03:23 pm sun
-----------------------------
twenty-fourth TWENTY-FOURTH
I. TO_DATE
This will be used to convert the string into data
format.
Syntax:
to_date (date)
Ex:
SQL> select
to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd
* month * day') from dual;
TO_CHAR(TO_DATE('24/DEC/20
--------------------------
24 * december * Sunday
Ex:
SQL> select add_months(to_date('11-jan-
1990','dd-mon-yyyy'), 5) from dual;
ADD_MONTHS
-----------
11-JUN-90
nothing.
K. MONTHS_BETWEEN
This will give difference of months between two
dates.
Syntax:
months_between (date1, date2)
Ex:
SQL> select months_between(to_date('11-aug-
1990','dd-mon-yyyy'), to_date('11-jan- 1990','dd-
mon-yyyy')) from dual;
MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-
YYYY'),TO_DATE('11-JAN-1990','DD-MON-YYYY'))
----------------------------------------------
-----------------------------------------
7
L. NEXT_DAY
This will produce next day of the given day from the
specified date.
Syntax:
next_day (date, day)
Ex:
SQL> select next_day(to_date('24-dec-2006','dd-
mon-yyyy'),'sun') from dual;
NEXT_DAY(
----------
31-DEC-06
Ex:
SQL> select last_day(to_date('24-dec-2006','dd-
mon-yyyy'),'sun') from dual;
LAST_DAY(
----------
31-DEC-06
N. EXTRACT
This is used to extract a portion of the date value.
Syntax:
extract ((year | month | day | hour | minute |
second), date)
Ex:
SQL> select extract(year from sysdate) from dual;
EXTRACT(YEARFROMSYSDATE)
------------------------
2006
-----------
11-APR-90
P. LEAST
This will give the least date.
Syntax:
least (date1, date2, date3 ... daten)
Ex:
SQL> select least(to_date('11-jan-90','dd-mon-
yy'),to_date('11-mar-90','dd-mon- yy'),to_date('11-
apr-90','dd-mon-yy')) from dual;
LEAST(
-----------
11-JAN-90
Q. ROUND
Round will rounds the date to which it was equal to or
greater than the given date.
Syntax:
round (date, (day | month | year))
If the second parameter was year then round will
checks the month of the given date in the following
ranges.
JAN -- JUN
JUL -- DEC
ROUND(TO_ ROUND(TO_
-------------- --------------
24-DEC-06 31-DEC-06
R. TRUNC
Trunc will chops off the date to which it was equal to
or less than the given date.
Syntax:
trunc (date, (day | month | year))
o If the second parameter was year then it always
returns the first day of the current year.
o If the second parameter was month then it always
returns the first day of the current month.
o If the second parameter was day then it always
returns the previous sunday.
o If the second parameter was null then it returns
nothing.
o If the you are not specifying the second
parameter then trunk will resets the time to the
begining of the current day.
Ex:
SQL> select trunc(to_date('24-dec-04','dd-mon-
yy'),'year'), trunc(to_date('11-mar- 06','dd-mon-
yy'),'year') from dual;
TRUNC(TO_ TRUNC(TO_
------------- ------------
01-JAN-04 01-JAN-06
S. NEW_TIME
This will give the desired timezone's date and time.
Syntax:
new_time (date, current_timezone,
desired_timezone)
Available timezones are as
follows. TIMEZONES
AST/ADT -- Atlantic standard/day
light time
BST/BDT -- Bering standard/day
light time
CST/CDT -- Central standard/day
light time
EST/EDT -- Eastern standard/day
light time
GMT -- Greenwich mean time
HST/HDT -- Alaska-Hawaii
standard/day light time
MST/MDT -- Mountain standard/day
light time
Ex:
SQL> select
to_char(new_time(sysdate,'gmt','yst'),'dd mon
yyyy hh:mi:ss am') from dual;
TO_CHAR(NEW_TIME(SYSDAT
------------------------
24 dec 2006 02:51:20 pm
SQL> select
to_char(new_time(sysdate,'gmt','est'),'dd mon
yyyy hh:mi:ss am') from dual;
TO_CHAR(NEW_TIME(SYSDAT
-----------------------
24 dec 2006 06:51:26 pm
T. COALESCE
This will give the first non-null date.
Syntax:
coalesce (date1, date2, date3 ... daten)
Ex:
SQL> select coalesce('12-jan-90','13-jan-99'),
coalesce(null,'12-jan-90','23-mar-98',null) from
dual;
COALESCE( COALESCE(
---------- ------------
12-jan-90 12-jan-90
MISCELLANEOUS FUNCTIONS
• Uid
• User
• Vsize
• Rank
• Dense_rank
A. UID
This will returns the integer value corresponding to
the user currently logged in.
Ex:
SQL> select uid from dual;
UID
-----
319
B. USER
This will returns the login's user name.
Ex:
SQL> select user from dual;
USER
------
SAKETH
C. VSIZE
This will returns the number of bytes in the
expression.
Ex:
SQL> select vsize(123), vsize('computer'),
vsize('12-jan-90') from dual;
133
[email protected]
D. RANK
This will give the non-sequential ranking.
Ex:
SQL> select rownum,sal from (select sal from emp
order by sal desc);
ROWNUM SAL
---------- ----------
1 5000
2 3000
3 3000
4 2975
5 2850
6 2450
7 1600
8 1500
9 1300
10 1250
11 1250
12 1100
13 1000
14 950
15 800
RANK(2975)WITHINGROUP(ORDERBYSALDESC)
------------------------------------
4
E. DENSE_RANK
This will give the sequential ranking.
Ex:
SQL> select dense_rank(2975) within group(order
by sal desc) from emp;
DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)
------------------------------------------
3
CONVERSION FUNCTIONS
• Bin_to_num
• Chartorowid
• Rowidtochar
• To_number
• To_char
• To_date
A. BIN_TO_NUM
This will convert the binary value to its numerical
equivalent.
Syntax:
bin_to_num( binary_bits)
Ex:
SQL> select bin_to_num(1,1,0) from dual;
BIN_TO_NUM(1,1,0)
-----------------
6
B. CHARTOROWID
This will convert a character string to act like an
internal oracle row identifier or rowid.
C. ROWIDTOCHAR
This will convert an internal oracle row identifier or
rowid to character string.
D. TO_NUMBER
This will convert a char or varchar to number.
E. TO_CHAR
This will convert a number or date to character string.
F. TO_DATE
This will convert a number, char or varchar to a date.
GROUP FUNCTIONS
• Sum
• Avg
• Max
• Min
• Count
Group functions will be applied on all the rows but
produces single output.
A. SUM
This will give the sum of the values of the specified
column.
Syntax:
sum (column)
Ex:
C. ----------
D. 38600
E. AVG
This will give the average of the values of the
specified column.
Syntax:
avg (column)
Ex:
P. 500
Q. COUNT
This will give the count of the values of the specified
column.
Syntax:
count (column)
Ex:
CONSTRAINTS
Constraints are categorized as follows.
• Domain integrity constraints
o Not null
o Check
o Primary key
COLUMN LEVEL
COLUMN LEVEL
COLUMN LEVEL
TABLE LEVEL
TABLE LEVEL
SQL> Select sal, Case sal When 500 then 'low' When
5000 then 'high' Else 'medium' End case From emp;
SAL CASE
----- --------
500 low
2500 medium
2000 medium
3500 medium
3000 medium
5000 high
4000 medium
5000 high
1800 medium
1200 medium
2000 medium
2700 medium
2200 medium
3200 medium
DEFAULT
Default can be considered as a substitute behavior of not
null constraint when applied to new rows being entered
into the table.
When you define a column with the default keyword
followed by a value, you are actually telling the database
that, on insert if a row was not assigned a value for this
column, use the default value that you have specified.
Default is applied only during insertion of new rows.
Ex:
DROPPING ADT
Ex:
number(3),city varchar(10));/
SQL> Create type va as varray(5) of addr;/
2. Using varray in table
SQL> Create table student(no number(2),name
varchar(10),address va);
3. Inserting values into varray table
SQL> Insert into student
values(1,'sudha',va(addr(111,'hyd')));
SQL> Insert into student
values(2,'jagan',va(addr(111,'hyd'),addr(222,'bang')));
4. Selecting data from varray table
SQL> Select * from student;
-- This will display varray column data along with
varray and adt;
SQL> Select no,name, s.* from student s1,
table(s1.address) s; -- This will display in general
format
5. Instead of s.* you can specify the columns in varray
SQL> Select no,name, s.hno,s.city from student
s1,table(s1.address) s; -- Update and delete not
possible in varrays.
-- Here we used table function which will take the
varray column as input for producing output
excluding varray and types.
NESTED TABLES
A nested table is, as its name implies, a table within a
table.
In this case it is a table that is represented as a column
within another table.
Nested table has the same effect of varrays but has no
limit.
Ex:
Ex:
Ex:
SQL>
SQLplus system/manager
SQL> Create directory saketh_dir as
'/Visdb/visdb/9.2.0/external';
SQL> Grant all on directory saketh_dir to saketh;
SQL> Conn saketh/saketh
SQL> Spool dept.lst
SQL> Select deptno || ',' || dname || ',' || loc from dept;
SQL> Spool off
CREATING EXTERNAL TABLE
159
[email protected]
Ex:
Ex:
• Range partitions
• List partitions
• Hash partitions
• Sub partitions
ADVANTAGES
• Reducing downtime for scheduled maintenance,
which allows maintenance operations to be carried out
on selected partitions while other partitions are
available to users.
• Reducing downtime due to data failure, failure of a
particular partition will no way affect other partitions.
• Partition independence allows for concurrent use of
the various partitions for various purposes.
ADVANTAGES OF PARTITIONS BY STORING
THEM IN DIFFERENT TABLESPACES
• Reduces the possibility of data corruption in multiple
partitions.
• Back up and recovery of each partition can be done
independently.
DISADVANTAGES
• Partitioned tables cannot contain any columns with
long or long raw datatypes, LOB types or object
types.
RANGE PARTITIONS
a. Creating range partitioned table
SQL> Create table student(no number(2),name
o Drop
o Truncate
o Rename
o Split
o Move
o Exchange
e. Adding a partition
SQL> Alter table student add partition p5 values less
than(40);
f. Dropping a partition
SQL> Alter table student drop partition p4;
g. Renaming a partition
SQL> Alter table student rename partition p3 to p6;
h. Truncate a partition
SQL> Alter table student truncate partition p6;
i. Splitting a partition
SQL> Alter table student split partition p2 at(15) into
(partition p21,partition p22);
j. Exchanging a partition
SQL> Alter table student exchange partition p1 with
table student2;
k. Moving a partition
SQL> Alter table student move partition p21
tablespace saketh_ts;
LIST PARTITIONS
1. Creating list partitioned table
SQL> Create table student(no number(2),name
varchar(2)) partition by list(no) (partition p1
values(1,2,3,4,5), partition p2
values(6,7,8,9,10),partition p3 values(11,12,13,14,15),
partition p4 values(16,17,18,19,20));
2. Inserting records into list partitioned table
SQL> Insert into student values(1,'a'); -- this will go
to p1
SQL> Insert into student values(6,'b'); -- this will go
to p2
SQL> Insert into student values(11,'c'); -- this will go
to p3
SQL> Insert into student values(16,'d'); -- this will go
to p4
o Drop
o Truncate
o Rename
o Move
o Exchange
5. Adding a partition
SQL> Alter table student add partition p5
values(21,22,23,24,25);
6. Dropping a partition
SQL> Alter table student drop partition p4;
7. Renaming a partition
SQL> Alter table student rename partition p3 to p6;
8. Truncate a partition
SQL> Alter table student truncate partition p6;
9. Exchanging a partition
SQL> Alter table student exchange partition p1 with
table student2;
10. Moving a partition
SQL> Alter table student move partition p2
tablespace saketh_ts;
HASH PARTITIONS
a. Creating hash partitioned table
SQL> Create table student(no number(2),name
varchar(2)) partition by hash(no) partitions 5;
Here oracle automatically gives partition names like
SYS_P1
SYS_P2
SYS_P3
SYS_P4
SYS_P5
b. Inserting records into hash partitioned table it will
insert the records based on hash function calculated
by taking the partition key
SQL> Insert into student values(1,'a');
SQL> Insert into student values(6,'b');
SQL> Insert into student values(11,'c');
SQL> Insert into student values(16,'d');
c. Retrieving records from hash partitioned table
SQL> Select *from student;
SQL> Select *from student partition(sys_p1);
d. Possible operations with hash partitions
o Add
o Truncate
o Rename
o Move
o Exchange
e. Adding a partition
SQL> Alter table student add partition p6 ;
f. Renaming a partition
SQL> Alter table student rename partition p6 to p7;
g. Truncate a partition
SQL> Alter table student truncate partition p7;
h. Exchanging a partition
SQL> Alter table student exchange partition sys_p1
with table student2;
i. Moving a partition
SQL> Alter table student move partition sys_p2
tablespace saketh_ts;
SUB-PARTITIONS WITH RANGE AND HASH
Subpartitions clause is used by hash only.
We can not create subpartitions with list and hash
partitions.
1. Creating subpartitioned table
SQL> Create table student(no number(2),name
varchar(2),marks number(3)) Partition by range(no)
subpartition by hash(name) subpartitions 3 (Partition
p1 values less than(10),partition p2 values less
than(20));
This will create two partitions p1 and p2 with three
subpartitions for each partition
P1 - SYS_SUBP1
SYS_SUBP2
SYS_SUBP3
P2 - SYS_SUBP4
SYS_SUBP5
SYS_SUBP6
o Drop
o Truncate
o Rename
o Split
5. Adding a partition
SQL> Alter table student add partition p3 values less
than(30);
6. Dropping a partition
SQL> Alter table student drop partition p3;
7. Renaming a partition
SQL> Alter table student rename partition p2 to p3;
8. Truncate a partition
SQL> Alter table student truncate partition p1;
9. Splitting a partition
SQL> Alter table student split partition p3 at(15) into
(partition p31,partition p32);
DATA MODEL
• ALL_IND_PARTITIONS
• ALL_IND_SUBPARTITIONS
• ALL_TAB_PARTITIONS
• ALL_TAB_SUBPARTITIONS
• DBA_IND_PARTITIONS
• DBA_IND_SUBPARTITIONS
• DBA_TAB_PARTITIONS
• DBA_TAB_SUBPARTITIONS
• USER_IND_PARTITIONS
• USER_IND_SUBPARTITIONS
• USER_TAB_PARTITIONS
• USER_TAB_SUBPARTITIONS
GROUP BY AND HAVING
GROUP BY
• Using group by, we can create groups of related
information.
• Columns used in select must be used with group by,
otherwise it was not a group by expression.
Ex:
30 CLERK 950
30 MANAGER 2850
30 SALESMAN 5600
HAVING
This will work as where clause which can be used only
with group by because of absence of where clause in group
by.
Ex:
ORDER OF EXECUTION
• Group the rows together based on group by clause.
• Calculate the group functions for each group.
• Choose and eliminate the groups based on the having
clause.
• Order the groups based on the specified column.
ROLLUP GROUPING CUBE
USING GROUPING
In the above query it will give the total salary of the
individual departments but with a blank in the job column
and gives the total salary of all the departments with
blanks in deptno and job columns.
To replace these blanks with your desired string grouping
will be used
SQL> select decode(grouping(deptno),1,'All
Depts',deptno),decode(grouping(job),1,'All
jobs',job),sum(sal) from emp group by rollup(deptno,job);
DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR
SUM(SAL)
-------------------------- -----------------------
--------------
10 CLERK
1300
10 MANAGER
2450
10 PRESIDENT
5000
10 All jobs
8750
20 ANALYST
6000
20 CLERK
1900
20 MANAGER
2975
20 All jobs
10875
30 CLERK
950
30 MANAGER
2850
30 SALESMAN
5600
30 All jobs
9400
All Depts All jobs
29025
SET OPERATORS
TYPES
• Union
• Union all
• Intersect
• Minus
UNION
This will combine the records of multiple tables having the
same structure.
Ex:
INTERSECT
This will give the common records of multiple tables
having the same structure.
Ex:
Ex:
DROPPING VIEWS
Syntax:
Create sequence <seq_name> [increment bty n] [start
with n] [maxvalue n] [minvalue n] [cycle/nocycle]
[cache/nocache];
By defalult the sequence starts with 1, increments by 1
with minvalue of 1 and with nocycle, nocache.
Cache option pre-alloocates a set of sequence numbers and
retains them in memory for faster access.
Ex:
Ex:
EQUI JOIN
A join which contains an '=' operator in the joins
condition.
Ex:
USING CLAUSE
ON CLAUSE
NON-EQUI JOIN
A join which contains an operator other than '=' in the joins
condition.
Ex:
SELF JOIN
Joining the table itself is called self join.
Ex:
NATURAL JOIN
Natural join compares all the common columns.
Ex:
187
[email protected]
CROSS JOIN
This will gives the cross product.
Ex:
OUTER JOIN
Outer join gives the non-matching records along with
matching records.
LEFT OUTER JOIN
This will display the all matching records and the records
which are in left hand side table those that are not in right
hand side table.
Ex:
Ex:
Ex:
INNER JOIN
This will display all the records that have matched.
Ex:
Ex:
SQL> select * from emp where sal > (select sal from
emp where empno = 7566);
EMPNO ENAME JOB MGR
HIREDATE SAL COMM DEPTNO
---------- ------ --------- ------- -------
--- ----- ------ --------
7788 SCOTT ANALYST 7566 19-APR-
87 3000 20
7839 KING PRESIDENT 17-NOV-
81 5000 10
7902 FORD ANALYST 7566 03-DEC-
81 3000 20
Ex:
SQL> select * from emp where sal > any (select sal
from emp where sal between 2500 and 4000);
EMPNO ENAME JOB MGR HIREDATE
SAL COMM DEPTNO
------ ------- ------- ------ ----------
------ ------ ---------
7566 JONES MANAGER 7839 02-APR-81
2975 20
7788 SCOTT ANALYST 7566 19-APR-87
3000 20
7839 KING PRESIDENT 17-NOV-81
5000 10
7902 FORD ANALYST 7566 03-DEC-81
3000 20
SQL> select * from emp where sal > all (select sal from
emp where sal between 2500 and 4000);
EMPNO ENAME JOB MGR
HIREDATE SAL COMM DEPTNO
------ ------- --------- ----- --------
-- ------ ----- -------
7839 KING PRESIDENT 17-NOV-
81 5000 10
MULTIPLE SUBQUERIES
Ex:
CORRELATED SUBQUERIES
A subquery is evaluated once for the entire parent
statement where as a correlated subquery is evaluated once
for every row processed by the parent statement.
Ex:
EXISTS
Exists function is a test for existence. This is a logical test
for the return of rows from a query.
Ex:
Suppose we want to display the department numbers
which has more than 4 employees.
SQL> select deptno,count(*) from emp group by
deptno having count(*) > 4;
DEPTNO COUNT(*)
--------- ----------
20 5
30 6
From the above query can you want to display the names
of employees ?
20 SCOTT
20 SMITH
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD
NOT EXISTS
Ex:
ENAME||'==>'||PRIORENAM LEVEL
------------------------ --------
KING==> 1
JONES==>KING 2
SCOTT==>JONES 3
ADAMS==>SCOTT 4
FORD==>JONES 3
SMITH==>FORD 4
BLAKE==>KING 2
ALLEN==>BLAKE 3
WARD==>BLAKE 3
MARTIN==>BLAKE 3
TURNER==>BLAKE 3
JAMES==>BLAKE 3
CLARK==>KING 2
MILLER==>CLARK 3
Ex:
LOCKS
• Locks are the mechanisms used to prevent destructive
interaction between users accessing same resource
simultaneously.
• Locks provides high degree of data concurrency.
TYPES
• Row level locks
• Table level locks
ROW LEVEL LOCKS
• In the row level lock a row is locked exclusively so
that other cannot modify the row until the transaction
holding the lock is committed or rolled back.
• This can be done by using select..for update clause.
Ex:
SQL> select * from emp where sal > 3000 for update of
comm.;
TABLE LEVEL LOCKS
A table level lock will protect table data thereby
guaranteeing data integrity when data is being accessed
concurrently by multiple users.
• Descending index
• Domain index
• Object index
• Cluster index
• Text index
• Index organized table
• Partition index
• Local index
• Local prefixed
• Local non-prefixed
• Global index
• Global prefixed
• Global non-prefixed
UNIQUE INDEX
• Unique indexes guarantee that no two rows of a table
have duplicate values in the columns that define the
index.
• Unique index is automatically created when primary
key or unique constraint is created.
Ex:
Ex:
Ex:
Ex:
Ex:
Ex:
Ex:
Ex:
Ex:
Ex:
Suppose you have a table called BOOKS with the
following columns Title, Author, Info.
SQL> create index book_index on books(info)
indextype is ctxsys.context;
SQL> create index book_index on books(info)
indextype is ctxsys.ctxcat;
TEXT QUERIES
Once a text index is created on the info column of BOOKS
table, text-searching capabilities increase dynamically.
CONTAINS & CATSEARCH
CONTAINS function takes two parameters - the column
name and the search string.
Syntax:
Contains(indexed_column, search_str);
Syntax:
Contains(indexed_column, search_str, index_set);
HOW A TEXT QEURY WORKS ?
• When a function such as CONTAINS or
CATSEARCH is used in query, the text portion of the
query is processed by oracle text.
• The remainder of the query is processed just like a
regular query within the database.
• The result of the text query processing and the regular
query processing are merged to return a single set of
records to the user.
• SEARCHING FOR AN EXACT MATCH OF A
WORD The following queries will search for a word
called 'prperty' whose score is greater than zero.
OR harvests') > 0;
Instead of OR you can use a vertical line (|).
INDEX SETS
• Historically, problems with queries of text indexes
have occurred when other criteria are used alongside
text searches as part of the where clause.
• To improve the mixed query capability, oracle
features index sets.
• The indexes within the index set may be structured
relational columns or on text columns.
• To create an index set, use the CTX_DDL package to
create the index set and add indexes to it.
• When you create a text index, you can then specify
the index set it belongs to.
SQL> exec
CTX_DDL.CREATE_INDEX_SET('books_index_set');
The add non-text indexes.
SQL> exec CTX_DDL.ADD_INDEX('books_index_set',
'title_index'); Now create a CTXCAT text index.
Ex:
Ex:
Ex:
Ex:
Syntax:
alter index index_name monitoring usage;
then check for the details in V$OBJECT_USAGE view.
Syntax:
alter index index_name nomonitoring usage;
DATA MODEL
• ALL_INDEXES
• DBA_INDEXES
• USER_INDEXES
• ALL_IND-COLUMNS
• DBA-IND_COLUMNS
• USER_IND_COLUMNS
• ALL_PART_INDEXES
• DBA_PART_INDEXES
• USER_PART_INDEXES
• V$OBJECT_USAGE
SQL*PLUS COMMNANDS
Syntax:
Break or bre [on <column_name> on report]
COMPUTE
This will be used to perform group functions on the data.
Syntax:
Compute or comp [group_function of column_name on
breaking_column_name or report]
TTITLE
This will give the top title for your report. You can on or
off the ttitle.
Syntax:
Ttitle or ttit [left | center | right] title_name skip n
other_characters
Ttitle or ttit [on or off]
BTITLE
This will give the bottom title for your report. You can on
or off the btitle.
Syntax:
Btitle or btit [left | center | right] title_name skip n
other_characters
Btitle or btit [on or off]
Ex:
EMPLOYEE DETAILS
------------------
-----
--------- **********
8750 sum
---------- **********
10875 sum
---------- **********
9400 sum
----------
sum
29025
** THANKQ **
CLEAR
This will clear the existing buffers or break or
computations or columns formatting.
Syntax:
Clear or cle buffer | bre | comp | col;
Ex:
Syntax:
Change or c/old_string/new_string
Ex:
COLUMN
This will be used to increase or decrease the width of the
table columns.
Syntax:
Column or col <column_name> format
<num_format|text_format>
Ex:
Syntax:
Save or sav <file_name>.[extension] replace or rep
Ex:
SQL> save ss
Created file ss.sql
SQL> save ss replace
Wrote file ss.sql
EXECUTE
This will be used to execute stored subprograms or
packaged subprograms.
Syntax:
Execute or exec <subprogram_name>
Ex:
Syntax:
Spool on | off | out | <file_name>.[Extension]
224
[email protected]
Ex:
SQL> spool on
SQL> select * from dept;
DEPTNO DNAME LOC
------- ------------ ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Syntax:
List or li [start_line_number] [end_line_number]
Ex:
SQL> select
2 *
3 from
4 dept;
SQL> list
1 select
2 *
3 from
4 * dept
SQL> list 1
1 * select
SQL> list 3
3 * from
SQL> list 1 3
1 select
2 *
3 * from
INPUT
This will insert the new line to the current SQL statement.
Syntax:
Input or in <string>
Ex:
SQL> select *
SQL> list
1 * select *
SQL> input from dept
SQL> list
1 select *
2 * from dept
APPEND
This will adds a new string to the existing string in the
SQL statement without any space.
Syntax:
Append or app <string>
Ex:
SQL> select *
SQL> list
1 * select *
SQL> append from dept
1 * select * from dept
SQL> list
1 * select * from dept
DELETE
This will delete the current SQL statement lines.
Syntax:
Delete or del <start_line_number>
[<end_line_number>]
Ex:
SQL> select
2 *
3 from
4 dept
5 where
6 deptno
7 >10;
SQL> list
1 select
2 *
3 from
4 dept
5 where
6 deptno
7 * >10
SQL> del 1
SQL> list
1 *
2 from
3 dept
4 where
5 deptno
6 * >10
SQL> del 2
SQL> list
1 *
2 dept
3 where
4 deptno
5 * >10
SQL> del 2 4
SQL> list
1 *
2 * >10
SQL> del
SQL> list
1 *
VARIABLE
This will be used to declare a variable.
Syntax:
Variable or var <variable_name> <variable_type>
Ex:
Syntax:
Print <variable_name>
Ex:
START
This will be used to execute SQL scripts.
Syntax:
start <filename_name>.sql
Ex:
Syntax:
Host [operation]
Ex:
230
[email protected]
SQL> host
SQL> host dir
SHOW
Using this, you can see several commands that use the set
command and status.
Syntax:
Show all | <set_command>
Ex:
flagger OFF
flush ON
Syntax:
Run | /
Ex:
SQL> run
SQL> /
STORE
This will save all the set command statuses in a file.
Syntax:
Store set <filename>.[extension] [create] | [replace] |
[append]
Ex:
Syntax:
Column <column_name> fold_after [no_of_lines]
Ex:
20
RESEARCH
DALLAS
30
SALES
CHICAGO
40
OPERATIONS
BOSTON
FOLD_BEFORE
Syntax:
Column <column_name> fold_before [no_of_lines]
DFINE
This will give the list of all the variables currently
defined.
Syntax:
Define [variable_name]
Ex:
SQL> define
DEFINE _DATE = "16-MAY-07" (CHAR)
DEFINE _CONNECT_IDENTIFIER = "oracle" (CHAR)
DEFINE _USER = "SCOTT" (CHAR)
DEFINE _PRIVILEGE = "" (CHAR)
DEFINE _SQLPLUS_RELEASE = "1001000200" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g
Enterprise Edition Release 10.1.0.2.0 -
Production With the
Partitioning, OLAP and Data Mining
options" (CHAR)
DEFINE _O_RELEASE = "1001000200" (CHAR)
SET COMMANDS
These commands does not require statement terminator
and applicable to the sessions , those will be automatically
cleared when session was closed.
LINESIZE
This will be used to set the linesize.
Default linesize is 80.
Syntax:
Set linesize <value>
Ex:
Syntax:
Set pagesize <value>
Ex:
Syntax:
Describe or desc <object_name>
Ex:
PAUSE
• When the displayed data contains hundreds or
thousands of lines, when you select it then it will
automatically scrolls and displays the last page data.
• To prevent this you can use this pause option.
• By using this it will display the data correspoinding to
the pagesize with a break which will continue by
hitting the return key.
• By default this will be off.
Syntax:
Set pause on | off
Ex:
Syntax:
Set feedback <value>
Ex:
4 rows selected.
HEADING
• If you want to display data without headings, then you
can achieve with this.
• By default heading is on.
Syntax:
Set heading on | off
Ex:
30 SALES CHICAGO
40 OPERATIONS BOSTON
SERVEROUTPUT
• This will be used to display the output of the PL/SQL
programs.
• By default this will be off.
Syntax:
Set serveroutput on | off
Ex:
Syntax:
Set time on | off
Ex:
TIMING
Syntax:
Set timing on | off
Ex:
Elapsed: 00:00:00.06
SQLPROMPT
This will be used to change the SQL prompt.
Syntax:
Set sqlprompt <prompt>
Ex:
SQLCASE
• This will be used to change the case of the SQL
statements.
• By default the case is mixed.
Syntax:
Set sqlcase upper | mixed | lower
Ex:
Syntax:
Set sqlterminator <termination_character>
Ex:
Syntax:
Set define on | off
Ex:
Syntax:
Set newpage <value>
Ex:
Syntax:
Set headsep <separation_char>
Ex:
ECHO
• When using a bind variable, the SQL statement is
maintained by echo.
• By default this is off.
Syntax:
Set echo on | off
VERIFY
• When using a bind variable, the old and new
statements will be maintained by verify.
• By default this is on.
Syntax:
Set verify on | off
Ex:
PNO
• This will give displays the page numbers.
• By default the value would be zero.
Ex:
0 - No optimization
1 - Moderate optimization
2 - Aggressive optimization
These settings are also modifiable for the current
session.
SQL> alter session set plsql_optimze_level=2;
Oracle retains optimizer settings on a module-by-
module basis. When you recompile a particular
module with nondefault settings, the settings will stick
allowing you to recompile later on using REUSE
SETTINGS.
▪ REGEXP_INSTR
▪ REGEXP_SUBSTR
▪ REGEXP_REPLACE
Ex:
DECLARE
v varchar(10) := 'computer';
BEGIN
dbms_output.put_line(q'*v = *' || v);
dbms_output.put_line(q'$v = $' || v);
END;
Output:
v = computer
v = computer
• Anonymous blocks
• Named blocks
o Labeled blocks
o Subprograms
o Triggers
ANONYMOUS BLOCKS
Anonymous blocks implies basic block structure.
Ex:
BEGIN
Dbms_output.put_line('My first
program'):
END;
LABELED BLOCKS
Labeled blocks are anonymous blocks with a label which
gives a name to the block.
Ex:
<<my_bloock>>
BEGIN
Dbms_output.put_line('My first program'):
END;
SUBPROGRAMS
Subprograms are procedures and functions. They can be
stored in the database as stand-alone objects, as part of
package or as methods of an object type.
TRIGGERS
Ex:
DECLARE
"a" number := 5;
"A" number := 6;
BEGIN
dbms_output.put_line('a = ' || a);
dbms_output.put_line('A = ' || A);
END;
Output:
a = 6
A = 6
COMMENTS
253
[email protected]
MULTILINE COMMENTS
Multiline comments start with the /* delimiter and ends
with */ delimiter.
Ex:
BEGIN
Dbms_output.put_line('hello');
/* sample program */
END;
VARIABLE DECLERATIONS
Variables can be declared in declarative section of the
block;
Ex:
DECLARE
a number;
b number := 5;
c number default 6;
CONSTANT DECLERATIONS
To declare a constant, you include the CONSTANT
keyword, and you must supply a default value.
Ex:
DECLARE
b constant number := 5;
c constant number default 6;
ANCHORED DECLERATIONS
PL/SQL offers two kinds of achoring.
• Scalar anchoring
• Record anchoring
SCALAR ANCHORING
Use the %TYPE attribute to define your variable based on
table's column of some other PL/SQL scalar variable.
Ex:
DECLARE
dno dept.deptno%type;
Subtype t_number is number;
a t_number;
Subtype t_sno is
student.sno%type;
V_sno t_sno;
RECORD ANCHORING
Use the %ROWTYPE attribute to define your record
structure based on a table.
Ex:
DECLARE
V_dept dept%rowtype;
Ex:
Subtype positive is binary_integer range
1..2147483647;
UNCONSTRAINED SUBTYPE
A subtype that does not restrict the values of the original
datatype in variables declared with the subtype.
Ex:
Subtype float is number;
DATATYPE CONVERSIONS
PL/SQL can handle conversions between different families
among the datatypes. Conversion can be done in two ways.
• Explicit conversion
• Implicit conversion
EXPLICIT CONVERSION
This can be done using the built-in functions available.
IMPLICIT CONVERSION
PL/SQL will automatically convert between datatype
families when possible.
Ex:
DECLARE
a varchar(10);
BEGIN
select deptno into a from dept where
dname='ACCOUNTING';
END;
In the above variable a is char type and deptno is number
type even though, oracle will automatically converts the
numeric data into char type assigns to the variable.
DECLARE
a number; -- scope of a
BEGIN
--------
DECLARE
b number; -- scope of b
BEGIN
-----
END;
------
END;
Ex2:
DECLARE
a number;
b number;
BEGIN
-- a , b available here
DECLARE
b char(10);
BEGIN
-- a and char type b is available here
END;
-----
END;
Ex3:
<<my_block>>
DECLARE
a number;
b number;
BEGIN
-- a , b available here
DECLARE
b char(10);
BEGIN
-- a and char type b is available here
-- number type b is available using
<<my_block>>.b
END;
------
END;
Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where
dname = 'ACCOUNTING';
if dno = 10 then
dbms_output.put_line('Location is NEW
YORK');
elsif dno = 20 then
dbms_output.put_line('Location is
DALLAS');
elsif dno = 30 then
dbms_output.put_line('Location is
CHICAGO');
else
dbms_output.put_line('Location is
BOSTON');
end if;
END;
Output:
Location is NEW YORK
CASE
Syntax:
Case test-variable
When value1 then sequence of
statements;
When value2 then sequence of
statements;
......
When valuen then sequence of
statements;
Else sequence of statements;
End case;
Ex:
DECLARE
dno number(2);
BEGIN
261
[email protected]
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
Location is NEW YORK
Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where
dname = 'ACCOUNTING';
262
[email protected]
case dno
when 10 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
when 40 then
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
Location is NEW YORK
LABELED CASE
Syntax:
<<label>>
Case test-variable
When value1 then sequence of
statements;
When value2 then sequence of
statements;
......
When valuen then sequence of
statements;
End case;
Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where
dname = 'ACCOUNTING';
<<my_case>>
263
[email protected]
case dno
when 10 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
when 40 then
dbms_output.put_line('Location is BOSTON');
end case my_case;
END;
Output:
Location is NEW YORK
SEARCHED CASE
Syntax:
Case
When <condition1> then sequence of
statements;
When <condition2> then sequence of
statements;
......
When <conditionn> then sequence of
statements;
End case;
Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where
dname = 'ACCOUNTING';
case dno
when dno = 10 then
264
[email protected]
dbms_output.put_line('Location is DALLAS');
when dno = 30 then
dbms_output.put_line('Location is CHICAGO');
when dno = 40 then
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
Location is NEW YORK
SIMPLE LOOP
Syntax:
Loop
Sequence of statements;
Exit when <condition>;
End loop;
In the syntax exit when <condition> is equivalent to
If <condition> then
Exit;
End if;
Ex:
DECLARE
i number := 1;
BEGIN
loop
dbms_output.put_line('i = ' || i);
i := i + 1;
exit when i > 5;
end loop;
END;
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
WHILE LOOP
Syntax:
While <condition> loop
Sequence of statements;
End loop;
Ex:
DECLARE
i number := 1;
BEGIN
While i <= 5 loop
dbms_output.put_line('i = ' || i);
i := i + 1;
end loop;
END;
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
FOR LOOP
Syntax:
For <loop_counter_variable> in
low_bound..high_bound loop
Sequence of statements;
End loop;
Ex1:
BEGIN
For i in 1..5 loop
dbms_output.put_line('i = ' || i);
end loop;
END;
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
Ex2:
BEGIN
For i in reverse 1..5 loop
dbms_output.put_line('i = ' || i);
end loop;
END;
Output:
i = 5
i = 4
i = 3
i = 2
i = 1
NULL STATEMENT
Usually when you write a statement in a program, you
want it to do something.
There are cases, however, when you want to tell PL/SQL
to do absolutely nothing, and that is where the NULL
comes.
Ex:
BEGIN
268
[email protected]
Output:
i = 1
i = 2
i = 3
i = 4
RESTRICTIONS ON GOTO
• It is illegal to branch into an inner block, loop.
• At least one executable statement must follow.
• It is illegal to branch into an if statement.
• It is illegal to branch from one if statement to another
if statement.
• It is illegal to branch from exception block to the
current block.
PRAGMAS
Pragmas are compiler directives. They serve as
instructions to the PL/SQL compiler. The compiler will act
on the pragma during the compilation of the block.
Syntax:
PRGAMA instruction_to_compiler.
PL/SQL offers several pragmas:
• AUTONOMOUS_TRANSACTION
• EXCEPTION_INIT
• RESTRICT_REFERENCES
• SERIALLY_REUSABLE
SUBPROGRAMS
PROCEDURES
A procedure is a module that performs one or more
actions.
Syntax:
Procedure [schema.]name [(parameter1
[,parameter2 ...])]
[authid definer |
current_user] is
-- [declarations]
Begin
-- executable statements
[Exception
-- exception handlers]
End [name];
Syntax:
Function [schema.]name [(parameter1
[,parameter2 ...])]
Return return_datatype
[authid definer |
current_user]
[deterministic]
[parallel_enable] is
-- [declarations]
Begin
-- executable statements
[Exception
-- exception handlers]
End [name];
Ex:
Suppose we have a procedure proc(a number,b number,c
number) and we have one anonymous block which
contains v1,v2, and v3;
DECLARE
v1 number := 4;
v2 number := 5;
v3 number := 6;
BEGIN
dbms_output.put_line('Before call');
dbms_output.put_line('v1 = ' || v1 || ' v2 =
' || v2 || ' v3 = ' || v3);
sample(v1,v2,v3);
dbms_output.put_line('After completion of
call');
dbms_output.put_line('v1 = ' || v1 || ' v2 =
' || v2 || ' v3 = ' || v3);
END;
Output:
Before call
v1 = 4 v2 = 5 v3 = 6
After call
a = 4 b = c = 6
After assignment
a = 4 b = 10 c = 20
274
[email protected]
DECLARE
v1 number := 1;
v2 number := 2;
v3 number := 3;
v number;
BEGIN
dbms_output.put_line('Before call');
dbms_output.put_line('v1 = ' || v1 || ' v2 =
' || v2 || ' v3 = ' || v3);
v := fun(v1,v2,v3);
dbms_output.put_line('After call
completed');
dbms_output.put_line('v1 = ' || v1 || ' v2 =
' || v2 || ' v3 = ' || v3);
dbms_output.put_line('Result = ' || v);
END;
Output:
Before call
v1 = 1 v2 = 2 v3 = 3
After call
a = 1 b = c = 3
Before assignement Result = 3
After assignment
a = 1 b = 5 c = 7
After call completed
v1 = 1 v2 = 5 v3 = 7
Result = 35
Ex:
CREATE OR REPLACE PROCEDURE PROC(a in out
nocopy number) IS
BEGIN
----
END PROC;
Output:
Output:
SQL> print v
hello world
Ex:
SQL> create or replace type t1 as object(a number);/
SQL> create or replace type t1 as object(a number);/
DECLARE
i t1 := t1(5);
j t2 := t2(5);
PROCEDURE P(m t1) IS
278
[email protected]
BEGIN
dbms_output.put_line('a = ' || m.a);
END P;
PROCEDURE P(n t2) IS
BEGIN
dbms_output.put_line('b = ' || n.b);
END P;
PROCEDURE PRODUCT(a number,b number) IS
BEGIN
dbms_output.put_line('Product of a,b = '
|| a * b);
END PRODUCT;
PROCEDURE PRODUCT(a number,b number,c
number) IS
BEGIN
dbms_output.put_line('Product of a,b = '
|| a * b * c);
END PRODUCT;
BEGIN
p(i);
p(j);
product(4,5);
product(4,5,6);
END;
Output:
a = 5
b = 5
Product of a,b = 20
Product of a,b = 120
BENEFITS OF OVERLOADING
• Supporting many data combinations
• Fitting the program to the user.
RESTRICTIONS ON OVERLOADING
Output:
SQL> exec p
Stored subprogram
Ex2:
DECLARE
PROCEDURE P IS
BEGIN
dbms_output.put_line('Local
subprogram');
END;
BEGIN
p;
END;
Output:
Local subprogram
COMPILING SUBPROGRAMS
SQL> Alter procedure P1 compile;
SQL> Alter function F1 compile;
SUBPROGRAMS DEPENDECIES
• A stored subprogram is marked as invalid in the data
dictionary if it has compile errors.
• A stored subprogram can also become invalid if a
DDL operation is performed on one of its dependent
objects.
• If a subprogram is invalidated, the PL/SQL engine
will automatically attempt to recompile in the next
time it is called.
• If we have two procedures like P1 and P2 in which P1
depends on P2. If we compile P2 then P1 is
invalidated.
SUBPROGRAMS DEPENDENCIES IN REMOTE
DATABASES
o Signature Model
TIMESTAMP MODEL
• This is the default model used by oracle.
• With this model, the timestamps of the last
modifications of the two objects are compared.
• The last_ddl_time field of user_objects contains the
timestamp.
• If the base object has a newer timestamp than the
dependent object, the dependent object will be
recompiled.
ISSUES WITH THIS MODEL
• If the objects are in different time zones, the
comparison is invalid.
• When P1 is in a client side PL/SQL engine such as
oracle forms, in this case it may not possible to
284
[email protected]
Ex1:
DECLARE
PROCEDURE P1 IS
BEGIN
dbms_output.put_line('From procedure
p1');
p2;
END P1;
PROCEDURE P2 IS
BEGIN
dbms_output.put_line('From procedure
p2');
p3;
END P2;
PROCEDURE P3 IS
BEGIN
dbms_output.put_line('From procedure
p3');
END P3;
BEGIN
p1;
END;
Output:
p2;
*
ERROR at line 5:
ORA-06550: line 5, column 1:
PLS-00313: 'P2' not declared in this scope
ORA-06550: line 5, column 1:
PL/SQL: Statement ignored
ORA-06550: line 10, column 1:
PLS-00313: 'P3' not declared in this scope
ORA-06550: line 10, column 1:
PL/SQL: Statement ignored
Ex2:
DECLARE
PROCEDURE P2; -- forward declaration
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
dbms_output.put_line('From procedure
p1');
p2;
END P1;
PROCEDURE P2 IS
BEGIN
dbms_output.put_line('From procedure
p2');
p3;
END P2;
PROCEDURE P3 IS
BEGIN
dbms_output.put_line('From procedure
p3');
END P3;
BEGIN
p1;
END;
Output:
From procedure p1
From procedure p2
From procedure p3
PRIVILEGES AND STORED SUBPROGRAMS
EXECUTE PREVILEGE
• For stored subprograms and packages the relevant
privilege is EXECUTE.
• If user A had the procedure called emp_proc then user
A grants execute privilege on procedure to user B
with the following command.
SQL> Grant execute on emp_proc to user B.
• Then user B can run the procedure by issuing
SQL> Exec user A.emp_proc
userA created the following procedure
CREATE OR REPLACE PROCEDURE P IS
cursor is select *from student1;
BEGIN
for v in c loop
insert into student2
values(v.no,v.name,v.marks);
end loop;
END P;
userA granted execute privilege to userB using
SQL> grant execute on p to userB
Then userB executed the procedure
SQL> Exec userA.p
If suppose userB also having student2 table then which
288
[email protected]
Ename = WARD
Ename = JONES
Ename = MARTIN
Ename = BLAKE
Ename = CLARK
Ename = SCOTT
Ename = KING
Ename = TURNER
Syntax:
PRAGMA
RESTRICT_REFERENCES(subprogram_name or
package_name, WNDS [,WNPS] [,RNDS] [,RNPS]);
Ex:
CREATE OR REPLACE PACKAGE PKG IS
function fun1 return varchar;
pragma restrict_references(fun1,wnds);
function fun2 return varchar;
pragma restrict_references(fun2,wnds);
END PKG;
Ex:
CREATE OR REPLACE PACKAGE PKG IS
pragma restrict_references(default,wnds);
function fun1 return varchar;
function fun2 return varchar;
END PKG;
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
update dept set deptno = 11;
return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
Ex:
CREATE OR REPLACE PACKAGE PKG IS
function fun1 return varchar;
pragma restrict_references(fun1,wnds,trust);
function fun2 return varchar;
pragma restrict_references(fun2,wnds,trust);
END PKG;
Syntax:
PROCEDURE KEEP(object_name varchar2,flag char
default 'P');
Syntax:
PROCEDURE UNKEEP(object_name varchar2, flag
char default 'P');
SIZES
SIZES will echo the contents of the shared pool to the
screen.
Syntax:
PROCEDURE SIZES(minsize number);
Syntax:
PROCEDURE
ABORTED_REQUEST_THRESHOLD(threshold_size
number);
Ex:
Cursor c(dno in number) return dept%rowtype is
select *from dept;
In the above
Header - cursor c(dno in number) return dept%rowtype
Body - select *from dept
CURSOR TYPES
• Implicit (SQL)
• Explicit
o Parameterized cursors
o REF cursors
CURSOR STAGES
• Open
306
[email protected]
• Fetch
• Close
CURSOR ATTRIBUTES
• %found
• %notfound
• %rowcount
• %isopen
• %bulk_rowcount
• %bulk_exceptions
CURSOR DECLERATION
Syntax:
Cursor <cursor_name> is select statement;
Ex:
Cursor c is select *from dept;
CURSOR LOOPS
• Simple loop
• While loop
• For loop
SIMPLE LOOP
Syntax:
Loop
Fetch <cursor_name> into
<record_variable>;
Exit when <cursor_name> % notfound;
307
[email protected]
<statements>;
End loop;
Ex:
DECLARE
cursor c is select * from student;
v_stud student%rowtype;
BEGIN
open c;
loop
fetch c into v_stud;
exit when c%notfound;
dbms_output.put_line('Name = ' ||
v_stud.name);
end loop;
close c;
END;
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
WHILE LOOP
Syntax:
While <cursor_name> % found loop
Fetch <cursor_name> nto
<record_variable>;
<statements>;
End loop;
Ex:
DECLARE
FOR LOOP
Syntax:
for <record_variable> in <cursor_name> loop
<statements>;
End loop;
Ex:
DECLARE
cursor c is select * from student;
BEGIN
for v_stud in c loop
dbms_output.put_line('Name = ' ||
v_stud.name);
end loop;
END;
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
PARAMETARIZED CURSORS
• This was used when you are going to use the cursor in
more than one place with different values for the same
where clause.
• Cursor parameters must be in mode.
• Cursor parameters may have default values.
• The scope of cursor parameter is within the select
statement.
Ex:
DECLARE
cursor c(dno in number) is select * from
dept where deptno = dno;
v_dept dept%rowtype;
BEGIN
open c(20);
loop
fetch c into v_dept;
exit when c%notfound;
dbms_output.put_line('Dname = ' ||
v_dept.dname ||
' Loc = ' ||
v_dept.loc);
end loop;
close c;
END;
Output:
Dname = RESEARCH Loc = DALLAS
Ex:
END PKG;
Output:
SQL> exec pkg.proc
Deptno = 10 Dname = ACCOUNTING Loc = NEW
YORK
Deptno = 20 Dname = RESEARCH Loc =
DALLAS
Deptno = 30 Dname = SALES Loc =
CHICAGO
Deptno = 40 Dname = OPERATIONS Loc =
BOSTON
Output:
SQL> exec pkg.proc
Deptno = 30 Dname = SALES Loc = CHICAGO
Deptno = 40 Dname = OPERATIONS
Loc = BOSTON
Ex:
sal emp.sal%type);
v_emp r;
v_stud student.name%type;
BEGIN
if table_name = 'DEPT' then
open c for select * from dept;
elsif table_name = 'EMP' then
open c for select ename,job,sal from
emp;
elsif table_name = 'STUDENT' then
open c for select name from student;
end if;
loop
if table_name = 'DEPT' then
fetch c into v_dept;
exit when c%notfound;
dbms_output.put_line('Deptno = ' ||
v_dept.deptno ||
' Dname = ' || v_dept.dname || ' Loc = '
|| v_dept.loc);
elsif table_name = 'EMP' then
fetch c into v_emp;
exit when c%notfound;
dbms_output.put_line('Ename = ' ||
v_emp.ename ||
' Job = ' || v_emp.job || '
Sal = ' || v_emp.sal);
elsif table_name = 'STUDENT' then
fetch c into v_stud;
exit when c%notfound;
dbms_output.put_line('Name = ' ||
v_stud);
end if;
end loop;
close c;
END;
Output:
SQL> exec ref_cursor('DEPT')
Name = saketh
Name = srinu
Name = satish
Name = sudha
CURSOR EXPRESSIONS
• You can use cursor expressions in explicit cursors.
• You can use cursor expressions in dynamic SQL.
• You can use cursor expressions in REF cursor
declarations and variables.
• You can not use cursor expressions in implicit
cursors.
Ex:
DECLARE
cursor c is select ename,cursor(select dname from
dept d
where e.empno =
d.deptno) from emp e;
type t is ref cursor;
c1 t;
c2 t;
v1 emp.ename%type;
v2 dept.dname%type;
BEGIN
open c;
loop
fetch c1 into v1;
exit when c1%notfound;
fetch c2 into v2;
exit when c2%notfound;
dbms_output.put_line('Ename = ' || v1 ||
' Dname = ' || v2);
end loop;
end loop;
close c;
END;
CURSOR CLAUSES
• Return
• For update
• Where current of
• Bulk collect
RETURN
Cursor c return dept%rowtype is select *from dept;
Or
Cursor c1 is select *from dept;
Syntax:
Select ...from ... for update of column_name [wait n];
Syntax:
Where current of cursor;
Ex:
DECLARE
cursor c is select * from dept for update
of dname;
BEGIN
for v in c loop
update dept set dname = 'aa' where
current of c;
commit;
end loop;
END;
BULK COLLECT
• This is used for array fetches
• With this you can retrieve multiple rows of data with
a single roundtrip.
• This reduces the number of context switches between
the pl/sql and sql engines.
• Reduces the overhead of retrieving data.
• You can use bulk collect in both dynamic and static
sql.
• You can use bulk collect in select, fetch into and
returning into clauses.
• SQL engine automatically initializes and extends the
collections you reference in the bulk collect clause.
• Bulk collect operation empties the collection
referenced in the into clause before executing the
query.
319
[email protected]
Ex:
DECLARE
Type t is table of dept%rowtype;
nt t;
Cursor c is select *from dept;
BEGIN
Open c;
Fetch c bulk collect into nt;
Close c;
For i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' ||
nt(i).dname || ' Loc = ' || nt(i).loc);
end loop;
END;
Output:
Dname = ACCOUNTING Loc = NEW YORK
Dname = RESEARCH Loc = DALLAS
Dname = SALES Loc = CHICAGO
Dname = OPERATIONS Loc = BOSTON
DECLARE
Type t is table of dept%rowtype;
320
[email protected]
Nt t;
BEGIN
Select * bulk collect into nt from dept;
for i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' ||
nt(i).dname || ' Loc = ' || nt(i).loc);
end loop;
END;
Output:
Dname = ACCOUNTING Loc = NEW YORK
Dname = RESEARCH Loc = DALLAS
Dname = SALES Loc = CHICAGO
Dname = OPERATIONS Loc = BOSTON
DECLARE
Type t is table of dept%rowtype;
nt t;
Cursor c is select *from dept;
BEGIN
Open c;
Fetch c bulk collect into nt limit 2;
Close c;
For i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' ||
nt(i).dname || ' Loc = ' || nt(i).loc);
end loop;
END;
Output:
Dname = ACCOUNTING Loc = NEW YORK
Dname = RESEARCH Loc = DALLAS
Output:
Dname = ACCOUNTING
Dname = RESEARCH
Dname = SALES
Dname = OPERATIONS
Loc = NEW YORK
Loc = DALLAS
Loc = CHICAGO
Loc = BOSTON
Ex2:
DECLARE
type t is table of dept.dname%type;
type t1 is table of dept.loc%type;
nt t;
nt1 t1;
BEGIN
Output:
Dname = ACCOUNTING
Dname = RESEARCH
Dname = SALES
Dname = OPERATIONS
Loc = NEW YORK
Loc = DALLAS
Loc = CHICAGO
Loc = BOSTON
DECLARE
type t is table of number(2);
nt t := t(1,2,3,4);
type t1 is table of varchar(2);
nt1 t1;
type t2 is table of student%rowtype;
nt2 t2;
BEGIN
select name bulk collect into nt1 from
student;
forall v in nt1.first..nt1.last
Output:
Marks = 100
Marks = 200
Marks = 300
Marks = 400
POINTS TO REMEMBER
• Cursor name can be up to 30 characters in length.
• Cursors declared in anonymous blocks or
subprograms closes automatically when that block
terminates execution.
• %bulk_rowcount and %bulk_exceptions can be used
only with forall construct.
• Cursor declarations may have expressions with
column aliases.
• These expressions are called virtual columns or
calculated columns.
SQL IN PL/SQL
The only statements allowed directly in pl/sql are DML
and TCL.
BINDING
Ex:
BEGIN
Execute immediate 'create table student(no
number(2),name varchar(10))';
or
Execute immediate ('create table student(no
number(2),name varchar(10))');
END;
Ex:
DECLARE
v varchar(100);
BEGIN
v := 'create table student(no number(2),name
varchar(10))';
execute immediate v;
END;
Ex:
DECLARE
v varchar(100);
BEGIN
v := 'insert into student
values(:v1,:v2,:v3)';
execute immediate v using 6,'f',600;
END;
Ex:
CREATE OR REPLACE PROCEDURE P(smarks in number) IS
s varchar(100) := 'select *from student
where marks > :m';
type t is ref cursor;
c t;
v student%rowtype;
BEGIN
open c for s using smarks;
loop
fetch c into v;
exit when c%notfound;
dbms_output.put_line('Student Marks = '
|| v.marks);
end loop;
close c;
END;
Output:
SQL> exec p(100)
Ex:
DECLARE
d_name dept.dname%type;
lc dept.loc%type;
v varchar(100);
BEGIN
v := 'select dname from dept where deptno
= 10';
execute immediate v into d_name;
dbms_output.put_line('Dname = '|| d_name);
v := 'select loc from dept where dname =
:dn';
execute immediate v into lc using d_name;
dbms_output.put_line('Loc = ' || lc);
END;
Output:
Dname = ACCOUNTING
Loc = NEW YORK
VARIABLE NAMES
Ex:
DECLARE
Marks number(3) := 100;
BEGIN
Delete student where marks = marks; --
this will delete all the rows
<<my_block>>
DECLARE
Marks number(3) := 100;
BEGIN
Delete student where marks = my_block.marks;
-- delete rows which has a
marks of 100
END;
Ex:
DECLARE
V1 number;
V2 varchar(2);
BEGIN
Select no,name into v1,v2 from student where
marks = 100;
END;
Ex:
CREATE OR REPLACE PROCEDURE P(srow in
student%rowtype) IS
BEGIN
insert into student values srow;
END P;
DECLARE
s student%rowtype;
BEGIN
s.no := 11;
s.name := 'aa';
s.marks := 100;
p(s);
END;
Ex:
DECLARE
srow student%rowtype;
BEGIN
srow.no := 7;
srow.name := 'cc';
srow.marks := 500;
insert into student values srow;
END;
Ex:
DECLARE
srow student%rowtype;
BEGIN
srow.no := 6;
srow.name := 'cc';
srow.marks := 500;
update student set row=srow where no =
srow.no;
END;
Ex:
DECLARE
srow student%rowtype;
sreturn student%rowtype;
BEGIN
srow.no := 8;
srow.name := 'dd';
srow.marks := 500;
insert into student values srow returning
no,name,marks into sreturn;
dbms_output.put_line('No = ' || sreturn.no);
dbms_output.put_line('No = ' ||
sreturn.name);
dbms_output.put_line('No = ' ||
sreturn.marks);
END;
Output:
No = 8
No = dd
No = 500
FORALL STATEMENT
This can be used to get the data from the database at once
by reducting the number of context switches which is a
transfer of control between PL/SQL and SQL engine.
Syntax:
Forall index_var in
[ Lower_bound..upper_bound |
Indices of indexing_collection |
Values of indexing_collection ]
SQL statement;
Ex:
DECLARE
type t is table of student.no%type index by
binary_integer;
ibt t;
BEGIN
ibt(1) := 1;
ibt(10) := 2;
forall i in ibt.first..ibt.last
update student set marks = 900 where
no = ibt(i);
END;
Ex:
DECLARE
type t is table of student.no%type index by
binary_integer;
ibt t;
type t1 is table of boolean index by
binary_integer;
ibt1 t1;
BEGIN
ibt(1) := 1;
ibt(10) := 2;
ibt(100) := 3;
ibt1(1) := true;
ibt1(10) := true;
ibt1(100) := true;
forall i in indices of ibt1
update student set marks = 900
where no = ibt(i);
END;
Ex:
DECLARE
type t is table of student.no%type index by
binary_integer;
ibt t;
332
[email protected]
Syntax:
Type <TYPE_NAME> is varray | varying array
(<LIMIT>) of <ELEMENT_TYPE>;
Ex1:
DECLARE
type t is varray(10) of varchar(2);
va t := t('a','b','c','d');
flag boolean;
BEGIN
dbms_output.put_line('Limit = ' ||
va.limit);
dbms_output.put_line('Count = ' ||
va.count);
VARRAY ELEMENTS');
for i in va.first..va.last loop
dbms_output.put_line('va[' || i || ']
= ' || va(i));
end loop;
va.extend(3,2);
dbms_output.put_line('After extend of three
indexes,
Output:
Limit = 10
Count = 4
First Index = 1
Last Index = 4
Next Index = 3
Previous Index = 2
VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
Index 3 exists with an element c
After extend of one index, Count = 5
Index 5 exists with an element
Index 6 does not exists
After extend of two indexes, Count = 7
VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] =
va[6] =
va[7] =
AFTER ASSINGNING VALUES TO EXTENDED ELEMENTS,
VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] = e
va[6] = f
va[7] = g
After extend of three indexes, Count = 10
337
[email protected]
VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] = e
va[6] = f
va[7] = g
va[8] = b
va[9] = b
va[10] = b
After trim of one index, Count = 9
After trim of three indexs, Count = 6
AFTER TRIM, VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] = e
va[6] = f
After delete of entire varray, Count = 0
Ex2:
DECLARE
type t is varray(4) of student%rowtype;
va t := t(null,null,null,null);
BEGIN
for i in 1..va.count loop
select * into va(i) from student where sno
= i;
dbms_output.put_line('Sno = ' || va(i).sno
|| ' Sname = ' || va(i).sname);
end loop;
END;
Output:
Sno = 1 Sname = saketh
Sno = 2 Sname = srinu
Ex3:
DECLARE
type t is varray(4) of student.smarks%type;
va t := t(null,null,null,null);
BEGIN
for i in 1..va.count loop
select smarks into va(i) from student
where sno = i;
dbms_output.put_line('Smarks = ' ||
va(i));
end loop;
END;
Output:
Smarks = 100
Smarks = 200
Smarks = 300
Smarks = 400
Ex4:
DECLARE
type r is record(c1 student.sname%type,c2
student.smarks%type);
type t is varray(4) of r;
va t := t(null,null,null,null);
BEGIN
for i in 1..va.count loop
select sname,smarks into va(i) from
student where sno = i;
dbms_output.put_line('Sname = ' ||
va(i).c1 || ' Smarks = '
|| va(i).c2);
end loop;
339
[email protected]
END;
Output:
Sname = saketh Smarks = 100
Sname = srinu Smarks = 200
Sname = divya Smarks = 300
Sname = manogni Smarks = 400
Ex5:
DECLARE
type t is varray(1) of addr;
va t := t(null);
cursor c is select * from employ;
i number := 1;
BEGIN
for v in c loop
select address into va(i) from employ
where ename = v.ename;
dbms_output.put_line('Hno = ' ||
va(i).hno || ' City = '
|| va(i).city);
end loop;
END;
Output:
Hno = 11 City = hyd
Hno = 22 City = bang
Hno = 33 City = kochi
Ex6:
DECLARE
type t is varray(5) of varchar(2);
va1 t;
va2 t := t();
BEGIN
if va1 is null then
340
[email protected]
dbms_output.put_line('va1 is null');
else
dbms_output.put_line('va1 is not null');
end if;
if va2 is null then
dbms_output.put_line('va2 is null');
else
dbms_output.put_line('va2 is not null');
end if;
END;
Output:
va1 is null
va2 is not null
NESTED TABLES
• A nested table is thought of a database table which
has no limit on its size.
• Elements are inserted into nested table starting at
index 1.
• The maximum size of the varray is 2 giga bytes.
Syntax:
Type <TYPE_NAME> is table of <TABLE_TYPE>;
Ex1:
DECLARE
type t is table of varchar(2);
nt t := t('a','b','c','d');
flag boolean;
BEGIN
if nt.limit is null then
dbms_output.put_line('No limit to
Nested Tables');
else
dbms_output.put_line('Limit = ' ||
nt.limit);
end if;
dbms_output.put_line('Count = ' ||
nt.count);
dbms_output.put_line('First Index = ' ||
nt.first);
dbms_output.put_line('Last Index = ' ||
nt.last);
dbms_output.put_line('Next Index = ' ||
nt.next(2));
dbms_output.put_line('Previous Index = ' ||
nt.prior(3));
dbms_output.put_line('NESTED TABLE
ELEMENTS');
for i in 1..nt.count loop
dbms_output.put_line('nt[' || i || ']
= ' || nt(i));
end loop;
flag := nt.exists(3);
if flag = true then
dbms_output.put_line('Index 3 exists
with an element ' || nt(3));
else
dbms_output.put_line('Index 3 does not
exists');
end if;
nt.extend;
dbms_output.put_line('After extend of one
index, Count = ' || nt.count);
flag := nt.exists(5);
if flag = true then
dbms_output.put_line('Index 5 exists
with an element ' || nt(5));
else
dbms_output.put_line('Index 5 does not
exists');
end if;
flag := nt.exists(6);
if flag = true then
342
[email protected]
dbms_output.put_line('Index 6 exists
with an element ' || nt(6));
else
dbms_output.put_line('Index 6 does not
exists');
end if;
nt.extend(2);
dbms_output.put_line('After extend of two
indexes, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE
ELEMENTS');
for i in 1..nt.count loop
dbms_output.put_line('nt[' || i || ']
= ' || nt(i));
end loop;
nt(5) := 'e';
nt(6) := 'f';
nt(7) := 'g';
dbms_output.put_line('AFTER ASSINGNING
VALUES TO EXTENDED ELEMENTS,
Output:
No limit to Nested Tables
Count = 4
First Index = 1
Last Index = 4
Next Index = 3
344
[email protected]
Previous Index = 2
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
Index 3 exists with an element c
After extend of one index, Count = 5
Index 5 exists with an element
Index 6 does not exists
After extend of two indexes, Count = 7
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] =
nt[6] =
nt[7] =
AFTER ASSINGNING VALUES TO EXTENDED ELEMENTS,
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
After extend of five indexes, Count = 12
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
nt[9] = b
nt[10] = b
nt[11] = b
345
[email protected]
nt[12] = b
After trim of one index, Count = 11
After trim of three indexs, Count = 8
AFTER TRIM, NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
After delete of first index, Count = 7
NESTED TABLE ELEMENTS
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
After delete of fourth index, Count = 6
NESTED TABLE ELEMENTS
nt[2] = b
nt[3] = c
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
After delete of entire nested table, Count = 0
Ex2:
DECLARE
type t is table of student%rowtype;
nt t := t(null,null,null,null);
BEGIN
for i in 1..nt.count loop
Output:
Sno = 1 Sname = saketh
Sno = 2 Sname = srinu
Sno = 3 Sname = divya
Sno = 4 Sname = manogni
Ex3:
DECLARE
type t is table of student.smarks%type;
nt t := t(null,null,null,null);
BEGIN
for i in 1..nt.count loop
select smarks into nt(i) from student
where sno = i;
dbms_output.put_line('Smarks = ' ||
nt(i));
end loop;
END;
Output:
Smarks = 100
Smarks = 200
Smarks = 300
Smarks = 400
Ex4:
DECLARE
type r is record(c1 student.sname%type,c2
student.smarks%type);
type t is table of r;
347
[email protected]
nt t := t(null,null,null,null);
BEGIN
for i in 1..nt.count loop
select sname,smarks into nt(i) from
student where sno = i;
dbms_output.put_line('Sname = ' ||
nt(i).c1 || ' Smarks = ' || nt(i).c2);
end loop;
END;
Output:
Sname = saketh Smarks = 100
Sname = srinu Smarks = 200
Sname = divya Smarks = 300
Sname = manogni Smarks = 400
Ex5:
DECLARE
type t is table of addr;
nt t := t(null);
cursor c is select * from employ;
i number := 1;
BEGIN
for v in c loop
select address into nt(i) from employ
where ename = v.ename;
dbms_output.put_line('Hno = ' ||
nt(i).hno || ' City = ' || nt(i).city);
end loop;
END;
Output:
Hno = 11 City = hyd
Hno = 22 City = bang
Hno = 33 City = kochi
Ex6:
DECLARE
348
[email protected]
Output:
nt1 is null
nt2 is not null
INDEX-BY TABLES
• An index-by table has no limit on its size.
• Elements are inserted into index-by table whose index
may start non-sequentially including negative
integers.
Syntax:
Type <TYPE_NAME> is table of <TABLE_TYPE>
index by binary_integer;
Ex:
DECLARE
type t is table of varchar(2) index by
binary_integer;
ibt t;
flag boolean;
BEGIN
ibt(1) := 'a';
ibt(-20) := 'b';
ibt(30) := 'c';
ibt(100) := 'd';
if ibt.limit is null then
dbms_output.put_line('No limit to Index
by Tables');
else
dbms_output.put_line('Limit = ' ||
ibt.limit);
end if;
dbms_output.put_line('Count = ' ||
ibt.count);
dbms_output.put_line('First Index = ' ||
ibt.first);
dbms_output.put_line('Last Index = ' ||
ibt.last);
dbms_output.put_line('Next Index = ' ||
ibt.next(2));
dbms_output.put_line('Previous Index = ' ||
ibt.prior(3));
dbms_output.put_line('INDEX BY TABLE
ELEMENTS');
dbms_output.put_line('ibt[-20] = ' || ibt(-
20));
dbms_output.put_line('ibt[1] = ' ||
ibt(1));
dbms_output.put_line('ibt[30] = ' ||
ibt(30));
dbms_output.put_line('ibt[100] = ' ||
ibt(100));
flag := ibt.exists(30);
if flag = true then
dbms_output.put_line('Index 30 exists
with an element ' || ibt(30));
else
dbms_output.put_line('Index 30 does not
exists');
end if;
350
[email protected]
flag := ibt.exists(50);
if flag = true then
dbms_output.put_line('Index 50 exists
with an element ' || ibt(30));
else
dbms_output.put_line('Index 50 does not
exists');
end if;
ibt.delete(1);
dbms_output.put_line('After delete of first
index, Count = ' || ibt.count);
ibt.delete(30);
dbms_output.put_line('After delete of index
thirty, Count = ' || ibt.count);
dbms_output.put_line('INDEX BY TABLE
ELEMENTS');
dbms_output.put_line('ibt[-20] = ' || ibt(-
20));
dbms_output.put_line('ibt[100] = ' ||
ibt(100));
ibt.delete;
dbms_output.put_line('After delete of
entire
index-by table,
Count = ' || ibt.count);
END;
Output:
No limit to Index by Tables
Count = 4
First Index = -20
Last Index = 100
Next Index = 30
Previous Index = 1
INDEX BY TABLE ELEMENTS
ibt[-20] = b
ibt[1] = a
ibt[30] = c
ibt[100] = d
Index 30 exists with an element c
Index 50 does not exists
351
[email protected]
MULTILEVEL COLLECTIONS
Collections of more than one dimension which is a
collection of collections, known as multilevel collections.
Syntax:
Type <TYPE_NAME1> is table of <TABLE_TYPE>
index by binary_integer; Type <TYPE_NAME2> is
varray(<LIMIT>) | table | of <TYPE_NAME1> | index
by binary_integer;
Ex1:
DECLARE
type t1 is table of varchar(2) index by
binary_integer;
type t2 is varray(5) of t1;
va t2 := t2();
c number := 97;
flag boolean;
BEGIN
va.extend(4);
dbms_output.put_line('Count = ' ||
va.count);
dbms_output.put_line('Limit = ' ||
va.limit);
for i in 1..va.count loop
for j in 1..va.count loop
va(i)(j) := chr(c);
c := c + 1;
end loop;
end loop;
dbms_output.put_line('VARRAY ELEMENTS');
for i in 1..va.count loop
for j in 1..va.count loop
dbms_output.put_line('va[' || i || ']['
|| j || '] = ' || va(i)(j));
353
[email protected]
end loop;
end loop;
dbms_output.put_line('First index = ' ||
va.first);
dbms_output.put_line('Last index = ' ||
va.last);
dbms_output.put_line('Next index = ' ||
va.next(2));
dbms_output.put_line('Previous index = '
|| va.prior(3));
flag := va.exists(2);
if flag = true then
dbms_output.put_line('Index 2
exists');
else
dbms_output.put_line('Index 2
exists');
end if;
va.extend;
va(1)(5) := 'q';
va(2)(5) := 'r';
va(3)(5) := 's';
va(4)(5) := 't';
va(5)(1) := 'u';
va(5)(2) := 'v';
va(5)(3) := 'w';
va(5)(4) := 'x';
va(5)(5) := 'y';
dbms_output.put_line('After extend of one
index, Count = ' || va.count);
dbms_output.put_line('VARRAY ELEMENTS');
for i in 1..va.count loop
for j in 1..va.count loop
dbms_output.put_line('va[' || i ||
'][' || j || '] = ' || va(i)(j));
end loop;
end loop;
va.trim;
dbms_output.put_line('After trim of one
index, Count = ' || va.count);
va.trim(2);
354
[email protected]
Output:
Count = 4
Limit = 5
VARRAY ELEMENTS
va[1][1] = a
va[1][2] = b
va[1][3] = c
va[1][4] = d
va[2][1] = e
va[2][2] = f
va[2][3] = g
va[2][4] = h
va[3][1] = i
va[3][2] = j
va[3][3] = k
va[3][4] = l
va[4][1] = m
va[4][2] = n
va[4][3] = o
va[4][4] = p
First index = 1
Last index = 4
Next index = 3
Previous index = 2
Index 2 exists
After extend of one index, Count = 5
VARRAY ELEMENTS
355
[email protected]
va[1][1] = a
va[1][2] = b
va[1][3] = c
va[1][4] = d
va[1][5] = q
va[2][1] = e
va[2][2] = f
va[2][3] = g
va[2][4] = h
va[2][5] = r
va[3][1] = i
va[3][2] = j
va[3][3] = k
va[3][4] = l
va[3][5] = s
va[4][1] = m
va[4][2] = n
va[4][3] = o
va[4][4] = p
va[4][5] = t
va[5][1] = u
va[5][2] = v
va[5][3] = w
va[5][4] = x
va[5][5] = y
After trim of one index, Count = 4
After trim of two indexes, Count = 2
VARRAY ELEMENTS
va[1][1] = a
va[1][2] = b
va[2][1] = e
va[2][2] = f
After delete of entire varray, Count = 0
Ex2:
DECLARE
type t1 is table of varchar(2) index by
binary_integer;
end loop;
nt.trim;
dbms_output.put_line('After trim of one
indexe, Count = ' || nt.count);
nt.trim(2);
dbms_output.put_line('After trim of two
indexes, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE
ELEMENTS');
for i in 1..nt.count loop
for j in 1..nt.count loop
dbms_output.put_line(
'nt[' || i || '][' || j
|| '] = ' || nt(i)(j));
end loop;
end loop;
nt.delete(2);
dbms_output.put_line(
'After delete of second
index, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE
ELEMENTS');
loop
exit when v = 4;
for j in 1..nt.count+1 loop
dbms_output.put_line(
'nt[' || v || '][' || j
|| '] = ' || nt(v)(j));
end loop;
v := v + 1;
if v= 2 then
v := 3;
end if;
end loop;
nt.delete;
dbms_output.put_line('After delete of
entire nested table,
Count = ' || nt.count);
END;
Output:
359
[email protected]
Count = 4
No limit to Nested Tables
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[1][4] = D
nt[2][1] = E
nt[2][2] = F
nt[2][3] = G
nt[2][4] = H
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
nt[3][4] = L
nt[4][1] = M
nt[4][2] = N
nt[4][3] = O
nt[4][4] = P
First index = 1
Last index = 4
Next index = 3
Previous index = 2
Index 2 exists
After extend of one index, Count = 6
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[1][4] = D
nt[1][5] = Q
nt[1][6] = R
nt[2][1] = E
nt[2][2] = F
nt[2][3] = G
nt[2][4] = H
nt[2][5] = S
nt[2][6] = T
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
360
[email protected]
nt[3][4] = L
nt[3][5] = U
nt[3][6] = V
nt[4][1] = M
nt[4][2] = N
nt[4][3] = O
nt[4][4] = P
nt[4][5] = W
nt[4][6] = X
nt[5][1] = Y
nt[5][2] = Z
nt[5][3] = a
nt[5][4] = b
nt[5][5] = c
nt[5][6] = d
nt[6][1] = e
nt[6][2] = f
nt[6][3] = g
nt[6][4] = h
nt[6][5] = i
nt[6][6] = j
After trim of one indexe, Count = 5
After trim of two indexes, Count = 3
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[2][1] = E
nt[2][2] = F
nt[2][3] = G
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
After delete of second index, Count = 2
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
361
[email protected]
Ex3:
DECLARE
type t1 is table of varchar(2) index by
binary_integer;
type t2 is table of t1 index by
binary_integer;
ibt t2;
flag boolean;
BEGIN
dbms_output.put_line('Count = ' ||
ibt.count);
if ibt.limit is null then
dbms_output.put_line('No limit to
Index-by Tables');
else
dbms_output.put_line('Limit = ' ||
ibt.limit);
end if;
ibt(1)(1) := 'a';
ibt(4)(5) := 'b';
ibt(5)(1) := 'c';
ibt(6)(2) := 'd';
ibt(8)(3) := 'e';
ibt(3)(4) := 'f';
dbms_output.put_line('INDEX-BY TABLE
ELEMENTS');
dbms_output.put_line('ibt([1][1] = ' ||
ibt(1)(1));
dbms_output.put_line('ibt([4][5] = ' ||
ibt(4)(5));
dbms_output.put_line('ibt([5][1] = ' ||
ibt(5)(1));
dbms_output.put_line('ibt([6][2] = ' ||
ibt(6)(2));
dbms_output.put_line('ibt([8][3] = ' ||
ibt(8)(3));
dbms_output.put_line('ibt([3][4] = ' ||
ibt(3)(4));
dbms_output.put_line('First Index = ' ||
ibt.first);
dbms_output.put_line('Last Index = ' ||
ibt.last);
dbms_output.put_line('Next Index = ' ||
ibt.next(3));
dbms_output.put_line('Prior Index = ' ||
ibt.prior(8));
ibt(1)(2) := 'g';
ibt(1)(3) := 'h';
ibt(1)(4) := 'i';
ibt(1)(5) := 'k';
ibt(1)(6) := 'l';
ibt(1)(7) := 'm';
ibt(1)(8) := 'n';
dbms_output.put_line('Count = ' ||
ibt.count);
dbms_output.put_line('INDEX-BY TABLE
ELEMENTS');
for i in 1..8 loop
dbms_output.put_line('ibt[1][' || i
|| '] = ' || ibt(1)(i));
end loop;
dbms_output.put_line('ibt([4][5] = ' ||
ibt(4)(5));
dbms_output.put_line('ibt([5][1] = ' ||
ibt(5)(1));
dbms_output.put_line('ibt([6][2] = ' ||
ibt(6)(2));
dbms_output.put_line('ibt([8][3] = ' ||
ibt(8)(3));
dbms_output.put_line('ibt([3][4] = ' ||
ibt(3)(4));
flag := ibt.exists(3);
if flag = true then
dbms_output.put_line('Index 3 exists');
else
dbms_output.put_line('Index 3 exists');
end if;
363
[email protected]
ibt.delete(1);
dbms_output.put_line('After delete of first
index, Count = ' || ibt.count);
ibt.delete(4);
dbms_output.put_line('After delete of
fourth index, Count = ' || ibt.count);
dbms_output.put_line('INDEX-BY TABLE
ELEMENTS');
dbms_output.put_line('ibt([5][1] = ' ||
ibt(5)(1));
dbms_output.put_line('ibt([6][2] = ' ||
ibt(6)(2));
dbms_output.put_line('ibt([8][3] = ' ||
ibt(8)(3));
dbms_output.put_line('ibt([3][4] = ' ||
ibt(3)(4));
ibt.delete;
dbms_output.put_line('After delete
of entire index-by table, Count =
' || ibt.count);
END;
Output:
Count = 0
No limit to Index-by Tables
INDEX-BY TABLE ELEMENTS
ibt([1][1] = a
ibt([4][5] = b
ibt([5][1] = c
ibt([6][2] = d
ibt([8][3] = e
ibt([3][4] = f
First Index = 1
Last Index = 8
Next Index = 4
Prior Index = 6
Count = 6
INDEX-BY TABLE ELEMENTS
ibt[1][1] = a
ibt[1][2] = g
ibt[1][3] = h
364
[email protected]
ibt[1][4] = i
ibt[1][5] = k
ibt[1][6] = l
ibt[1][7] = m
ibt[1][8] = n
ibt([4][5] = b
ibt([5][1] = c
ibt([6][2] = d
ibt([8][3] = e
ibt([3][4] = f
Index 3 exists
After delete of first index, Count = 5
After delete of fourth index, Count = 4
INDEX-BY TABLE ELEMENTS
ibt([5][1] = c
ibt([6][2] = d
ibt([8][3] = e
ibt([3][4] = f
After delete of entire index-by table, Count = 0
Ex4:
DECLARE
type t1 is table of varchar(2) index by
binary_integer;
type t2 is table of t1 index by
binary_integer;
type t3 is table of t2;
nt t3 := t3();
c number := 65;
BEGIN
nt.extend(2);
dbms_output.put_line('Count = ' ||
nt.count);
for i in 1..nt.count loop
for j in 1..nt.count loop
for k in 1..nt.count loop
nt(i)(j)(k) := chr(c);
c := c + 1;
end loop;
end loop;
end loop;
dbms_output.put_line('NESTED TABLE
ELEMENTS');
for i in 1..nt.count loop
for j in 1..nt.count loop
for k in 1..nt.count loop
dbms_output.put_line(
'nt[' || i || '][' || j ||
'][' || k || '] = ' ||nt(i)(j)(k));
end loop;
end loop;
end loop;
END;
Output:
Count = 2
NESTED TABLE ELEMENTS
nt[1][1][1] = A
nt[1][1][2] = B
nt[1][2][1] = C
nt[1][2][2] = D
nt[2][1][1] = E
nt[2][1][2] = F
nt[2][2][1] = G
nt[2][2][2] = H
ERROR HANDLING
ERROR TYPES
• Compile-time errors
• Runtime errors
• Errors that occur during the compilation phase are
detected by the PL/SQL engine and reported back to
the user, we have to correct them.
Syntax:
EXCEPTION
When exception_name then
Sequence_of_statements;
When exception_name then
Sequence_of_statements;
When others then
Sequence_of_statements;
END;
EXCEPTION TYPES
• Predefined exceptions
• User-defined exceptions
PREDEFINED EXCEPTIONS
Ex1:
DECLARE
a number;
b varchar(2);
v_marks number;
cursor c is select * from student;
type t is varray(3) of varchar(2);
va t := t('a','b');
va1 t;
BEGIN
-- NO_DATA_FOUND
BEGIN
select smarks into v_marks from
student where sno = 50;
EXCEPTION
when no_data_found then
dbms_output.put_line('Invalid
student number');
END;
-- CURSOR_ALREADY_OPEN
BEGIN
open c;
open c;
EXCEPTION
when cursor_already_open then
dbms_output.put_line('Cursor is
already opened');
END;
-- INVALID_CURSOR
BEGIN
close c;
open c;
close c;
close c;
EXCEPTION
when invalid_cursor then
dbms_output.put_line('Cursor is
already closed');
END;
-- TOO_MANY_ROWS
BEGIN
select smarks into v_marks from
student where sno > 1;
EXCEPTION
when too_many_rows then
dbms_output.put_line('Too many values
are coming to marks variable');
END;
-- ZERO_DIVIDE
BEGIN
a := 5/0;
EXCEPTION
when zero_divide then
dbms_output.put_line('Divided by zero
- invalid operation');
END;
-- VALUE_ERROR
BEGIN
b := 'saketh';
EXCEPTION
when value_error then
dbms_output.put_line('Invalid string
length');
END;
-- INVALID_NUMBER
BEGIN
Output:
Invalid student number
Cursor is already opened
Cursor is already closed
Too many values are coming to marks variable
Divided by zero - invalid operation
Invalid string length
371
[email protected]
Invalid number
Index is greater than the limit
Index is greater than the count
Collection is empty
Ex2:
DECLARE
c number;
BEGIN
c := 5/0;
EXCEPTION
when zero_divide then
dbms_output.put_line('Invalid
Operation');
when others then
dbms_output.put_line('From OTHERS
handler: Invalid Operation');
END;
Output:
Invalid Operation
USER-DEFINED EXCEPTIONS
• A user-defined exception is an error that is defined by
the programmer.
• User-defined exceptions are declared in the
declarative secion of a PL/SQL block.
• Just like variables, exeptions have a type
EXCEPTION and scope.
• RAISING EXCEPTIONS User-defined exceptions
are raised explicitly via the RAISE statement.
Ex:
DECLARE
372
[email protected]
e exception;
BEGIN
raise e;
EXCEPTION
when e then
dbms_output.put_line('e is
raised');
END;
Output:
e is raised
Ex1:
DECLARE
e exception;
v_dname varchar(10);
BEGIN
-- USER-DEFINED EXCEPTION
BEGIN
raise e;
EXCEPTION
when e then
-- PREDEFINED EXCEPTION
BEGIN
select dname into v_dname from dept
where deptno = 50;
EXCEPTION
when no_data_found then
Output:
1 User-Defined Exception
100 ORA-01403: no data found
Ex2:
BEGIN
dbms_output.put_line(SQLERRM(100));
dbms_output.put_line(SQLERRM(0));
dbms_output.put_line(SQLERRM(1));
dbms_output.put_line(SQLERRM(-100));
dbms_output.put_line(SQLERRM(-500));
dbms_output.put_line(SQLERRM(200));
dbms_output.put_line(SQLERRM(-900));
END;
Output:
ORA-01403: no data found
ORA-0000: normal, successful completion
User-Defined Exception
ORA-00100: no data found
ORA-00500: Message 500 not found; product=RDBMS;
facility=ORA
-200: non-ORACLE exception
ORA-00900: invalid SQL statement
DBMS_UTILITY.FORMAT_ERROR_STACK
Ex:
DECLARE
v number := 'ab';
BEGIN
null;
EXCEPTION
when others then
dbms_output.put_line(dbms_utility.format_error_sta
ck);
END;
Output:
declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error:
character to number conversion error
ORA-06512: at line 2
DBMS_UTILITY.FORMAT_CALL_STACK
• This function returns a formatted string showing the
execution call stack inside your PL/SQL application.
375
[email protected]
Ex:
BEGIN
dbms_output.put_line(dbms_utility.format_call_stac
k);
END;
Output:
----- PL/SQL Call Stack -----
Object_handle line_number
object_name
69760478 2
anonymous block
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE
• It displays the execution stack at the point where an
exception was raised.
• Thus , you can call this function with an exception
section at the top level of your stack and still find out
where the error was raised deep within the call stack.
Ex:
CREATE OR REPLACE PROCEDURE P1 IS
BEGIN
dbms_output.put_line('from procedure 1');
raise value_error;
END P1;
dbms_output.put_line(dbms_utility.format_error_bac
ktrace);
END P3;
Output:
SQL> exec p3
from procedure 3
from procedure 2
from procedure 1
ORA-06512: at "SAKETH.P1", line 4
ORA-06512: at "SAKETH.P2", line 4
ORA-06512: at "SAKETH.P3", line 4
EXCEPTION_INIT PRAGMA
• Using this you can associate a named exception with a
particular oracle error.
• This gives you the ability to trap this error
specifically, rather than via an OTHERS handler.
Syntax:
PRAGMA EXCEPTION_INIT(exception_name,
oracle_error_number);
Ex:
DECLARE
e exception;
pragma exception_init(e,-1476);
c number;
BEGIN
c := 5/0;
EXCEPTION
when e then
dbms_output.put_line('Invalid
Operation');
END;
Output:
Invalid Operation
RAISE_APPLICATION_ERROR
You can use this built-in function to create your own error
messages, which can be more descriptive than named
exceptions.
Syntax:
RAISE_APPLICATION_ERROR(error_number,
error_message,, [keep_errors_flag]);
Ex:
DECLARE
c number;
BEGIN
c := 5/0;
EXCEPTION
when zero_divide then
raise_application_error(-
20222,'Invalid Operation');
END;
Output:
DECLARE
*
ERROR at line 1:
ORA-20222: Invalid Operation
ORA-06512: at line 7
EXCEPTION PROPAGATION
Exceptions can occur in the declarative, the executable, or
the exception section of a PL/SQL block.
Ex1:
DECLARE
e exception;
BEGIN
BEGIN
raise e;
END;
EXCEPTION
when e then
dbms_output.put_line('e is raised');
END;
Output:
e is raised
Ex2:
DECLARE
e exception;
BEGIN
BEGIN
raise e;
END;
END;
Output:
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined
exception
ORA-06512: at line 5
Ex1:
DECLARE
c number(3) := 'abcd';
BEGIN
dbms_output.put_line('Hello');
EXCEPTION
Output:
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error:
character to number conversion error
ORA-06512: at line 2
Ex2:
BEGIN
DECLARE
c number(3) := 'abcd';
BEGIN
dbms_output.put_line('Hello');
EXCEPTION
when others then
dbms_output.put_line('Invalid
string length');
END;
EXCEPTION
when others then
dbms_output.put_line('From outer block:
Invalid string length');
END;
Output:
From outer block: Invalid string length
Ex1:
DECLARE
e1 exception;
e2 exception;
BEGIN
raise e1;
EXCEPTION
when e1 then
dbms_output.put_line('e1 is
raised');
raise e2;
when e2 then
dbms_output.put_line('e2 is
raised');
END;
Output:
e1 is raised
DECLARE
*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined
exception
ORA-06512: at line 9
ORA-06510: PL/SQL: unhandled user-defined
exception
Ex2:
DECLARE
e1 exception;
e2 exception;
BEGIN
BEGIN
raise e1;
EXCEPTION
when e1 then
dbms_output.put_line('e1 is
raised');
raise e2;
when e2 then
dbms_output.put_line('e2 is
raised');
END;
EXCEPTION
when e2 then
dbms_output.put_line('From outer block:
e2 is raised');
END;
Output:
e1 is raised
From outer block: e2 is raised
Ex3:
DECLARE
e exception;
BEGIN
raise e;
EXCEPTION
when e then
dbms_output.put_line('e is
raised');
raise e;
END;
Output:
e is raised
DECLARE
*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined
exception
ORA-06512: at line 8
ORA-06510: PL/SQL: unhandled user-defined
exception
RESTRICTIONS
You can not pass exception as an argument to a
subprogram.
DATABASE TRIGGERS
• Triggers are similar to procedures or functions in that
they are named PL/SQL blocks with declarative,
executable, and exception handling sections.
• A trigger is executed implicitly whenever the
triggering event happens.
• The act of executing a trigger is known as firing the
trigger.
RESTRICTIONS ON TRIGGERES
• Like packages, triggers must be stored as stand-alone
objects in the database and cannot be local to a block
or package.
• A trigger does not accept arguments.
USE OF TRIGGERS
• Maintaining complex integrity constraints not
possible through declarative constraints enable at
table creation.
• Auditing information in a table by recording the
changes made and who made them.
• Automatically signaling other programs that action
needs to take place when chages are made to a table.
• Perform validation on changes being made to tables.
• Automate maintenance of the database.
TYPES OF TRIGGERS
• DML Triggers
• Instead of Triggers
• DDL Triggers
• System Triggers
• Suspend Triggers
CATEGORIES
Timing -- Before or After
Level -- Row or Statement
DML TRIGGERS
• A DML trigger is fired on an INSERT, UPDATE, or
DELETE operation on a database table.
END TRIGGER1;
Output:
SQL> select * from trigger_firing_order;
no rows selected
1 row created.
FIRING_ORDER
--------------------------------------------------
Before Statement Level
Before Row Level
After Row Level
387
[email protected]
NO NAME MARKS
---- -------- ----------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
Ex:
Suppose we have a table called marks with fields no,
old_marks, new_marks.
CREATE OR REPLACE TRIGGER OLD_NEW
before insert or update or delete on student
for each row
BEGIN
insert into marks
values(:old.no,:old.marks,:new.marks);
END OLD_NEW;
Output:
SQL> select * from student;
NO NAME MARKS
---- ------- -------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
SQL> select * from marks;
no rows selected
1 row created.
REFERENCING CLAUSE
If desired, you can use the REFERENCING clause to
specify a different name for :old ane :new.
This clause is found after the triggering event, before the
WHEN clause.
Syntax:
REFERENCING [old as old_name] [new as
new_name]
Ex:
CREATE OR REPLACE TRIGGER REFERENCE_TRIGGER
before insert or update or delete on student
values(:old_student.no,:old_student.marks,:new_stu
dent.marks);
END REFERENCE_TRIGGER;
WHEN CLAUSE
WHEN clause is valid for row-level triggers only.
If present, the trigger body will be executed only for those
rows that meet the condition specified by the WHEN
clause.
Syntax:
WHEN trigger_condition;
Ex:
CREATE OR REPLACE TRIGGER WHEN_TRIGGER
before insert or update or delete on student
referencing old as old_student new as
new_student
for each row
when (new_student.marks > 500)
BEGIN
insert into marks
values(:old_student.no,:old_student.marks,:new_stu
dent.marks);
END WHEN_TRIGGER;
TRIGGER PREDICATES
There are three Boolean functions that you can use to
determine what the operation is.
The predicates are
• INSERTING
• UPDATING
• DELETING
Ex:
CREATE OR REPLACE TRIGGER PREDICATE_TRIGGER
before insert or update or delete on
student
BEGIN
if inserting then
insert into predicates values('I');
elsif updating then
insert into predicates values('U');
elsif deleting then
insert into predicates values('D');
end if;
END PREDICATE_TRIGGER;
Output:
SQL> delete student where no=1;
1 row deleted.
MSG
---------------
D
1 row created.
MSG
---------------
D
I
1 row updated.
MSG
---------------
D
I
U
INSTEAD-OF TRIGGERS
Instead-of triggers fire instead of a DML operation.
Also, instead-of triggers can be defined only on views.
395