SlideShare a Scribd company logo
History .................................................................................................................................2
Built in datatypes:........................................................................................................2
Types Of Language.............................................................................................................2
Table creation with timestamp.............................................................................................4
TIMESTAMP WITH TIME ZONE...................................................................................18
CASE Expressions.............................................................................................................62
Cursor FOR loops..............................................................................................................75
Cursor FOR loops Using Subqueries.................................................................................75
Cursor with Parameters......................................................................................................76
Cursor with For update clause..........................................................................................76
WHERE CURRENT OF clause.........................................................................................77
Nested Procedure and Exception handling......................................................................81
1
History
Oracle stands for Oak Ridge Automatic Computing Logical Engine.
The Oracle Corporation was started in 1917 with name ‘Rational Software
Incorporated’ (RSI) by Larry Ellison and his associates. During the release of
version 3 of Oracle the company changed its name from RSI to Oracle
Corporation.
Datatypes -- specify the format of data
2 types - built in - user defined
Built in datatypes:
character datatypes -- char(n) - max size 2000 bytes
sy : coln_name datatypes Example : s char(3);
varchar2(size) --4000 bytes Example : name varchar2 (30)
diff between char and varchar2
char defines entire memory space.
But varchar2 it defines only how much we use (i.e name varchar2(30) here
we insert data only 15 characters the remaining space will be used to others names
In varchar2 doesn’t waste the memory space.
numeric datatypes
The number datatypes can store numeric values.
The precision can range between 1 to 38.
number(size) number(p,s) number(3) -- col allows only 3 digit
number(5,2) --- it allows 5digits and 2 decimal points -- 100.50
date datatypes
date stores 7 bytes DD-MON-YY
Example : 23-jun-06
RAW datatype - is used to store binary data –maximum size is 255 bytes. raw(n)
long datatype -- it stores upto 2 GB character data
long raw datatype -- upto stores 2 GB of Binary data
LOB datatypes - LARGE OBJECTS - upto 4GB
BLOB - binary LOB CLOB – character LOB
NCLOB - national character set data and Unicode data
BFILEs are large binary data objects stored in operating system files.
Types Of Language
 Data Definition Language (DDL)
• CREATE – create new table definition
• ALTER -- Modifies the existing table definition
• DROP -- Removes a table
• RENAME -- Change the name of a table
2
• TRUNCATE – Delete all the data in a table without removing the
Table’s structure
 Data Manipulation Language (DML)
• INSERT – Add new rows of data into a table or view
• UPDATE – Change column values in existing rows of a table or view
• DELETE – Removes rows from tables or views
• SELECT – Retrieve data from one or more tables or views
 Transaction Control Language(TCL)
• COMMIT -- Make a transaction ‘s changes permanent
• ROLLBACK – Undo the changes in a transaction, either since the
Transaction started or since a savepoint
• SAVEPOINT – set a point to which you can roll back
 Data Control Language(DCL)
• GRANT – Gives privileges to other users
• REVOKE – Removes privileges from other users
DDL
Create table command
It is used to create a table
syn:
create table tablename(coln1 datatype,......);
Desc -- describe structure Desc tablename;
Example : Desc salary;
Alter Table Command
alter my existing table - it changes your existing table
add - it adds new columns
alter table tablename add (coln datatype);
modify -- it modifies existing column values
alter table tablename modify (coln datatype);
to drop particular from existing table.
alter table emp drop column newsal;
Drop Table command
3
it delete all record and table.
syn  drop table tablename;
ex:  drop table emp;
truncate command
it removes all the records in the particular table
syntax:
TRUNCATE TABLE <tablename>;
Ex:
TRUNCATE TABLE praveen;
Rename command – to rename the existing table name
Syntax RENAME existname TO newname;
Example RENAME stud1 TO students;
Dropping column
You want to drop a particular column by using alter table command
Syn: ALTER TABLE <tablebname> DROP<column name>;
Ex:
Alter table praveen drop sal;
Dropping two or more columns
 more than one column can be removed from table
ex:
ALTER TABLE praveen DROP(eno,name);
Table creation with timestamp
create table temp(name varchar2(20), jdate timestamp, edate date);
insert into temp values('praveen',systimestamp, sysdate);
create table sam(d date default sysdate,name varchar2(20));
Data Manipulation Language (DML)
INSERT command
- It is used to add one or more rows to a table.
- The values are separated by commas
- It can be done different ways :
 Inserting records into all fields
 Inserting records into selective fields
 Continuous insertions
4
 Inserting records using SELECT statement
1) Inserting records into all fields
Syntax:
INSERT INTO <tablename> VALUES (value1,value2,……);
Ex:
INSERT INTO praveen VALUES (101,’praveen’,’10-mar-2000’,5000);
2) Inserting records into selective fields
Syntax :
INSERT INTO <tablename> (Column1,column2,..) VALUES
(value1,value2,…);
Ex:
INSERT INTO praveen (no,name) VALUES (102,’kumar’);
3) Continuous insertions
it insert record continuously
Syntax:
INSERT INTO <tablename> VALUES (&column1,’&column2’….);
Ex:
INSERT INTO praveen VALUES (&no,’&name’);
4) Inserting Records Using SELECT statement
insert into jkk3 select empno,ename from emp;
insert into jkk4 select empno,ename from emp where deptno=20;
insert into sala(no,name) select empno,ename from emp where deptno=40;
Update Command
 it is used to modify one or a set of records at a time.
Syn:
UPDATE <tablename> SET column1=value1,column2=value2…
[WHERE <condition>];
Ex1 : UPDATE praveen SET deptno=10;
Ex2:
UPDATE praveen SET sal=5000, name = ‘anand’ where empno=101;
Ex3:
UPDATE praveen set sal=7000,doj=‘25-JUN-2006’ where doj is NULL:
Delete Command
It is used to removes all the records from the table.
Syntax : DELETE FROM <tablename> WHERE <condition>;
Example
DELETE FROM employ where deptno=20;
- it removes records those who are having 20 as deptno.
Example
DELETE FROM employ;
5
 it removes all the rows.
Working with Transactions
Two commands are :
• COMMIT
• ROLLBACK
• SAVEPOINT
Commit : It used to store data permanently
Syntax: Commit;
Rollback : It is used get existing data from the buffer.
Syntax Rollback;
Savepoint - we creates some savepoint for retrieving data from particular point.
Sy : savepoint name;
Ex: Savepoint s1;
Rollback to s1;
Select Comand :
Select * from <tablename>;
Tablename – it is already created table
*  it is denotes all columns
select * from tab; --- it list all tables and views and synonyms
select * from gp2;
select ename,sal,job from emp;
select ename “Employee name”,sal “SALARY” from emp;
Condition
Syntax
Select * from tablename where <condition>;
Ex:
Select * from emp where deptno=10;
select * from emp where sal>=1250;
select * from emp where sal>=1250 and deptno=30;
select * from emp where comm is null;
select * from emp where ename=‘BLAKE’;
Sorting The Data
ascending
select ename,sal from emp order by sal;
6
select ename,sal from emp order by sal asc;
descending
select ename,sal from emp order by sal desc;
copying the structure and records of a Table
A new Table created from existing table
Syntax
Create table <tablename> as select <columnname> from <tablename> [where
<condition> ];
Example
Create table jkk as select * from emp;
Create table jkk1 as select ename,sal from emp;
Copying the structure
Here we give any false condition only structure will be copied.
Ex create table jkk2 as select * from emp where 1=2;
Inserting Records Using SELECT statement
Syntax : INSERT INTO <tablename> SELECT <column name> FROM
<tablename>;
Example : insert into jkk3 select empno,ename from emp;
insert into jkk4 select empno,ename from emp where deptno=20;
Constraints:
Constraints are used to prevent invalid data entry into tables and thereby
maintain the integrity of the data. They are otherwise called as business rule.
There are two levels of constraints
• column level constraints
it is in the part of the column definition and is imposed only on the
column in which the constraint is defined.
• Table level constraints
This is a part of the table definition. Constraints defined in the table
level can restrict the data in any column in the table.
- Here we give some name to our constraints
- 3 Types of constraints
 Domain constraint
 Entity constraint
 Referential integrity constraint
7
Domain constraint
- it is used to check the values entered into a particular column is valid or not.
Two types
- NOT NULL  that column doesn’t have null values
- Check
NOT NULL
Create table praveen1 (no number(5)not null, name varchar2(20));
insert into praveen1(name) values ('sailaja')  it shows error
insert into praveen1(no) values(102);  it will not show error
Check Constraint
- it is used to checking the column values
- here we define some logical expression and relational expression
create table gp3(no number(4) check(no between 1000 and 9000),dob date,doj
date, check(dob<doj));
- IN, NOT IN , BETWEEN, LIKE
IN
Check ( colname IN (“set of permitted values”))
Create table gp4(no number(5), sex varchar2(5) constraint ch_sex check(sex
in(‘m’,’M’,’f’,’F’)));
NOT IN
Check ( colname not in(“set of not permitted values”))
Create table gp5(no number(5), sex varchar2(5) constraint ch_sex1 check(sex not
in(‘m’,’M’,’f’,’F’)));
BETWEEN
create table gp6(no number(4)constraint chk_gno check(no between 2000 and
3000));  here no column accept numbers between 2000 to 3000.
LIKE  it is used to pattern matching
Two pattern %  one or more spaces or characters
_  only one space or character
check(columnname like ‘S%’)
create table gp7(no number(3),name varchar2(20) check(name like '%p'));
create table gp8(no number(3),name varchar2(20) check(name like 's_i%'));
8
create table gp9 (no number(3),name varchar2(20) check(name like 'p_a_'));
alter table student add check(age>=18);
alter table student add(constraint agecons check(age>=18));
Entity integrity constraint
 To avoid duplicate data’s.
Two types
1. Primary key
2. Unique
Primary Key
 Here we define a column or group of column should be primary key
 It doesn’t allow duplicate values and null values
Syntax : create table <tablename>(colname datatype PRIMARY KEY);
Create table r11(no number(4)primary key,name varchar2(20));
Create table rad2(no number(4)constraint rad_no primary key,name
varchar2(20));
Error : Create table gp11(no number(4)primary key,name varchar2(20), dep
number(4)primary key);
Composite primary key
Create table g11(no number(4),name varchar2(20), dep number(4),primary
key(no,dep)); Example for Table level constraints
 it checks two columns i.e if the two columns having same data it shows
error.
UNIQUE
 Here we define a column or group of column should be primary key
 It doesn’t allow duplicate values .
 It allows any number of null values
Create table gj4(no number(4)unique, name varchar2(20));
Create table r5(no number(4)constraint ra5_no unique,name varchar2(20));
Composite unique key
A unique key constraints more than one column called a composite unique
key. The maximum no. of columns in a composite unique key is 16.
Create table r6(no number(4),name varchar2(20), dep number(4),
unique(no,dep));
9
create table gp13(no number(4)primary key,name varchar2(20),dep
number(3)unique);
Referential Integrity Constraint:
 it is used to give relationship between tables
 references uses table called child table
 primary defined table is parent table of child
Create table stu1( rollno Number(6) PRIMARY KEY, Name Varchar2(40) , Sex
Varchar2(5)); //Parent Table
Create table game_details ( rollno number(6) references stu1, game varchar2(40));
// Child Table
Create table Cul1 ( id number(6) references stu1(rollno), event Varchar2(40));
create table attend(aid number(6), atten varchar2(20), FOREIGN KEY(aid)
REFERENCES stu1(rollno));
On-delete-cascade clause
If a row in the referenced key (primary key) column in the parent table is deleted,
then all the rows in the child table with dependent foreign key column will also be
deleted automatically when On delete cascade clause is used.
Example
create table gpa (roll number(6)PRIMARY KEY,name varchar2(20));
create table pers(no number(6), mark1 number(3), foreign key(no) references
st1(rollno) ON DELETE CASCADE);
delete from gpa where roll=102;
 this query delete record from parent table but oracle internally deletes child
table records.
Self Referential Integrity
A column in a table if referencing to another column in the same table it is called
“Self Referential Integrity”. A primary key and a foreign key is present in the
same table.
Example
Create table emp11( empno number(4) PRIMARY KEY,
Name varchar2(20),job varchar2(20), mgr number(4),
FOREIGN KEY(mgr) REFERENCES emp11(empno));
10
Using ALTER Table Statement
Alter table <tablename> add primary key(Column Name);
Alter table gptest add primary key(test);
it is used to add primary key existing table.
• if the table have duplicate values it is not possible
If you want to disable primary key by using this.
Alter table gptest disable Primary Key;
ALTER TABLE dept DISABLE CONSTRAINT dname_ukey;
ALTER TABLE dept DISABLE UNIQUE(dname,loc);
it is used to enable primary key if you already disable.
• if the table have duplicate values it is not possible
ALTER TABLE gptest ENABLE PRIMARY KEY;
ALTER TABLE emp ENABLE UNIQUE(DNAME,LOC);
Dropping Integrity constraints
To drop primary key by using this .
Alter table gptest DROP PRIMARY KEY;
drop table emp cascade constraints;
 drops the Emp table along with all the constraints.
Deferred constraints checking
Constraints can be deferred for validity until the end of the transaction.
• A constraint is deferred if the system checks that it is satisfied only on
commit. If a deferred constraint is violated, then commit causes the
transaction to roll back.
11
• If a constraint is immediate (not deferred), then it is checked at the end of
each statement if it is violated, the statement is rolled back immediately.
create table kann(name varchar2(20),no number constraint pkk primary key
deferrable);
set constraint pkk deferred;
Expressions and operators
Expressions are a combination of formula and constant and/or variables using
operators.
 Arithmetic
 Character
 Comparison/Relational
 Logical
 SET
Arithmetic operators
It performs arithmetic operations
+ adds Values Select sal+200 from emp;
- Subtract select sal-200 from emp;
* Multiplication select comm.*0.2 from emp;
/ Divides select sal/100 from emp;
Character Operator
Concatenation operator ( || )
Select ename ||’is working in MNC’ from emp;
Select ‘gp’||’from Anna Nagar’ ||’ working in MNC’ from dual;
Relational operator
select * from emp where mgr=7788; equal to
select * from emp where mgr != 888; not equal to
select * from emp where mgr<=7698; less than or equal to
select * from emp where sal between 1000 and 7000;
select * from emp where deptno in(20,30);
select * from emp where deptno not in(20,30);
select * from emp where mgr is null;
select * from emp where mgr is null
select * from emp where ename like ‘p_a%’;
12
Logical Operator
AND
OR
NOT
AND Operator
Both the condition should be satisfied the corresponding rows will be displayed
Select * from emp where deptno=10 and sal=1300;
OR operator
Any one of the condition should be satisfied the corresponding rows will be
displayed
Select * from emp where deptno=10 or sal=3300;
NOT Operator
NOT operator returns TRUE if the enclosed condition evaluates FALSE and
FALSE if the enclosed condition evaluates TRUE.
select * from emp where NOT(mgr is null);
SET Operators
Set operators are used to combine the results of two queries into a single
result. Queries contain set operators are called compound queries. The individual
queries are called component queries.
Union - returns all distinct rows selected by the component queries.
select city from pa1 union select * from pa2;
Union all – returns all rows selected by the component queries including duplicate
rows.
Select city from pa1 union all select * from pa2;
Intersect – Returns all distinct rows selected by both the component queries.
Select city from pa1 intersect select * from pa2;
Minus -- Returns all distinct rows selected by the first query but not by the
second query.
Select city from pa1 minus select * from pa2;
Functions
Two types
- Built in function v
- User defined function
Built in function
 Scalar or single row function
13
 Aggregate function or group function
Scalar functions
Scalar functions can be classified as follows.
• Number function
• Character function
• Return Number values
• Returning Character values
• Date functions
• Conversion functions
• Other functions
Selecting from the DUAL table
DUAL is a table automatically created by oracle along with the data
dictionary. DUAL is the schema of the user SYS, but is accessible by the name
DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2 (1),
and contains one row with a value ‘X’. Selecting from the DUAL table is useful
for computing a constant expression with the SELECT command. Because DUAL,
has only one row, the constant is returned only once.
Desc dual;
Select * from dual;
Number function
ABS -- it returns absolute values
Select abs(-30) from dual;
Select abs(30) "absolute” from dual;
Floor (n)
 it returns largest integer equal to or less than n
select floor(15.7) from dual;
ceil (n)
 it returns largest integer equal to or greater than n
select ceil(15.7) from dual;
select ceil(15.3) from dual;
store the function output  insert into inss select ceil(sal) from sala;
update fun set no=ceil(no);
14
EXP(n) -- E to the power of n
Select exp(4) from dual;
Ln(n)  It returns log values
Select ln(20) from dual;
Log(m,n) m-base value , n- number
Select log(10,100) from dual;
MOD(m,n) function  It returns remainder
Select mod(4,3) from dual;
Select mod(4,2) from dual;
Power(m,n)  It returns m to the power of n.
Select power(3,2) from dual;
Round (n,[m])  It returns round of the particular value
Select round(13.788,2) from dual;
Select round(13.788) from dual;
Sign(n)  It returns sign of n.
Select sign(-10) from dual;
Select sign(10) from dual;
Select sign(0) from dual;
SQRT(n) square root
Select sqrt(4) from dual;
Trunc (n,[m])  it returns n with m decimal places
select trunc(152.78999,2) from dual;
select trunc(152.78999) from dual; -- it removes all the decimal values
Character functions
Character functions can return both numeric and character values.
ASCII(char) it returns ascii value of the char
select ASCII(‘A’) from dual;
select ascii(‘a’) from dual;
select ascii('*') from dual;
INSTR
(char1,char2[,n[,m]]) Find occurrence of one string inside another.
Char1  string , Char2  search characters
15
n  occurrence , m  no of search characters
Select instr(‘corporate floor’,’or’,3,2) from dual;  o/p 14
Select instr(‘corporate floor’,’r’,2,1) from dual;
 it gives position of ‘or’ in 3rd
occurrence
Select instr('corporate floor','or',2,2) from dual;  o/p 5
Length (char) it gives size of the character
Example select length(‘praveen’) from dual;
Lengthb(char) This function returns the length of a string in bytes.
Example select lengthb(‘praveen ‘) from dual;
CHR(n) binary equivalent of the specified number
select chr(65) from dual;
select chr(42) from dual;
concat(char1,char2)  it concats two strings
select concat(‘praveen’,’kumar’) from dual;
initcap(char) it returns first letter uppercase
select initcap(‘praveen’) from dual;
select initcap(ename) from emp;
Lpad(char1,n,char2)  it is used to add a string to the left of another string
select lpad(‘gpp’,10,’$’) from dual;
select lpad(ename,30,’%’ ) from emp;
Ltrim(char1,set) it removes particular set of characters from left side.
Select ltrim(‘aadfdfepraveen’,’aad’) from dual;
Replace(char,se_char,re_char)  replaces the string with another string
select replace(‘jack’,’j’,’bl’) from dual;
Rpad(char1,n,char2)  it is used to add a string to the right of another string
select rpad(‘gpp’,20,’#’) from dual;
select rpad(ename,20,’@’) from emp;
Rtrim  it removes particular set of characters from right side.
Select rtrim(‘GPPeeqwaad’,’aad’) from dual;
16
Soundex -- it is used to find the phonetic representation of a string.
Select ename from emp where soundex(ename) = soundex(‘symth’);
Substr(char,m.n) -- It returns m th position and n characters from char.
Select substr(‘srminfo’,4,4) from dual;
Select substr(‘srminfotech’,-2,4) from dual;
select substr(‘welcome india’,-5) from dual
Substrb(char,m.n)
Select substrb(‘praveen’,4,4) from dual;
Translate (char,ser_char,chan_char)
- it changes character from sear_char character and translate to chan_char
character.
Select translate(‘praveen’,’v’,’V’) from dual;
Upper(char) – it returns character to uppercase
Select upper(‘praveen’) from dual;
Lower(char) -- it returns character to lowercase
select lower(‘PRAVEEN’) from dual;
Date Functions -- Date functions operate on values of the date datatype
ADD_MONTHS(d,n) -this function adds specified number of months to date.
Ex
Select add_months(sysdate,2) from dual;
Select add_months(‘12-jul-06’,2) from dual;
LAST_DAY(d) --it returns month last day
select last_day(sysdate) from dual;
select last_day(‘20-sep-06’) from dual;
MONTHS_BETWEEN(d1,d2)
select months_between(‘12-jun-07’,’13-jun-06’) from dual;
NEXT_DAY(d,char)
Select next_day(sysdate,’Saturday’) from dual;
Select next_day(‘23-jun-07’,’Saturday’) from dual;
It displays date with time
select to_char(sysdate,'dd-mon-yy, HH:MI') from dual
17
in oracle 9i;
TIMESTAMP datatype
It extends the DATE datatype, stores the year, month, day, hour,minute and
second. The sytax is TIMESTAMP[Precision];
SQL> create table timetable(timm timestamp);
Table created.
SQL> desc timetable
Name Null? Type
----------------------------------------- -------- ----------------------------
TIMM TIMESTAMP(6)
insert into timetable values('13-nov-06,04:38:30 PM');
select to_char(timm,'HH:mi:ss') from timetable;
TIMESTAMP WITH TIME ZONE
It extends from TIMESTAMP datatype, includes a time zone displacement. The
time zone displacement is the difference (in hours and minutes) between local time
and Coordinated Universal Time (UTC), formerly known as Greenwich Mean
Time . Syntax TIMESTAMP [Precision] WITH TIME ZONE
create table timetable1 ( timee timestamp with time zone);
insert into timetable1 values('21-nov-06, 04:32:33 pm')
insert into timetable1 values('21-nov-06,04:20:22 am +7.30')
ROUND(d,[fmt) --This function used to round off a date to the required format.
Select round(sysdate,’year’) from dual;
Select round(sysdate,’month’) from dual;
TRUNC (d[,fmt]) -- This function is used to truncate the value of a date to the
required format.
Select trunc(sysdate,’mm’) from dual;
Select trunc(sysdate,’dd’) from dual;
Select trunc(sysdate,’yy’) from dual;
Conversion functions --Conversion functions convert a value from one datatype
to another.
TO_CHAR – date conversion
This function is used to convert a date to character format.
TO_CHAR(d[,fmt])
Select to_char(sysdate,’month dd, yyyy’) from dual;
Select to_char(sysdate,’month/dd/yyyy’) from dual;
18
TO_CHAR – Number conversion
It is used to convert a number to character format.
TO_CHAR(d[,fmt])
Select to_char (56764890,’099G999G999’) from dual;
TO_DATE(char[,fmt])
String to date conversion
Select to_date(‘june 25,1983,09:15 P.M.’,’Month dd, yyyy, HH:MI P.M.’ ) from
dual;
select to_char(to_date(‘25-oct-2098’,’dd-mon-yyyy’),’yy’) from dual;
TO_NUMBER(char)
It converts String to number
select sal+to_number(‘45’) from emp;
Other Functions
greatest(expr1,expr2,…)
select greatest(‘praveen’,’radha’) from dual;
select greatest (‘radha’,’ragu’, ‘rajesh’,’radhakumari’) from dual;
select greatest(89,77) from dual;
least(expr1,expr2,…)
select least(‘praveen’,’radha’) from dual;
select least (‘radha’,’ragu’, ‘rajesh’,’radhakumari’) from dual;
NVL
This function is used to replace null values by specified values, for computational
purpose,
Example
select empno, nvl(to_char(comm),’comm is null’) "commission" from emp;
NVL2(expr1,expr2,expr3)
it accept three arguments. If the first argument is not null then the second
argument, if the first argument is null then the third argument is returned.
select empno, nvl2(to_char(comm),’comm is avail’,’comm is null’) "commission"
from emp;
19
uid - it returns current user id
Select uid from dual;
user – it returns user name
select user from dual;
sysdate – it returns current date
Select sysdate from dual;
Decode  this function works like if…then condition
decode(variable,<condition1>,<value1>,<condition2>,<value2>….)
select empno,decode(deptno,10,’sales’,20,’manager’,30,’research’,
40,’management’) from emp;
AGGREGATE FUNCTION
Avg()  it returns average of some set of values.
Select avg(sal) from emp;
Max() -- it returns maximum value from set of values
select max(sal) from emp;
Min() -- it returns minimum value from set of values
select min(sal) from emp;
Count () --it returns total no. of records in a table.
Select count (comm) from emp;
select count(1) from emp;
Select count(*) from emp;
Group by clause
The GROUP BY clause is another section of the SELECT statement. This clause
is used to group rows based on the distinct values that exist for the specified
columns. The GROUP BY clause divides a table into groups of rows in each
group has the same value in a specified column.
Select deptno,count(*) from emp group by deptno;
select deptno,avg(sal) from emp group by deptno;
select deptno,min(sal) from emp group by deptno;
order by clause
it is used to display the rows either ascending order or descending order.
select * from emp order by empno; --- > ascending order
select * from emp order by empno desc;  descending order
20
ROLLUP Operator
The ROLLUP operator is used to generate aggregates and super aggregates
for expressions with in group by clause.
select deptno,job,sum(sal) from emp group by rollup(deptno,job);
Cube operator
- The CUBE operator is used to produce cross tabular reports. it is also used
with group by clause.
Example
select deptno,job,sum(sal) from emp group by Cube(deptno,job);
grouping function
The grouping function can be used with either CUBE or ROLLUP operator. This
helps us to understand how a summary value has been obtained. The Grouping
function receives one argument that should match one of the expressions in the
GROUP BY clause. The return value is either 0 or 1. The return value is used to
determine which columns are used to generate the corresponding row.
Example
select deptno,job,sum(sal),grouping(deptno),grouping(job) from emp group by
Cube(deptno,job);
HAVING clause
HAVING clause is used to restrict the group of rows defined by the
GROUP BY clause. it similar to the “where clause” in select statement.
select deptno,min(sal),max(sal) from emp group by deptno;
select deptno,min(sal),max(sal) from emp group by deptno having min(sal)>=1000
;
JOINS
– it is used to collect information from more than one table.
This allows data to be selected from one or more tables and to combine the
selected data into a single result.
Three types of joins
 Simple join
 Self Join
 Outer join
Simple Join
21
It is most common type of join. It retrieves rows from two tables having
common column. It can be classified into two. They are
 Equi join
 Non-Equi join
Equi join
- This join contains a condition containing an equality operator.
- A equi join combines rows that have equivalent values for the columns
specified in the join.
Select ename,dname from emp,dept where emp.deptno=dept.deptno;
Non – Equi joins
Non equi joins specify the relationship between the tables not in terms of
columns but in terms of the relational operators or any comparison operators
used.
select ename,grade from emp, salgrade where sal between losal and hisal;
Table aliasing
To prevent ambiguity in a query we include table name in the Select statements.
Table aliases are used to make multiple table queries shorter and more readable.
Select ename, dname from emp e, dept d where e.deptno=d.deptno;
Select ename,dname,e.deptno from emp e,dept d where e.deptno=d.deptno;
Self join
In a self join, two rows from the same table combine to form a result row.
To join a table to itself, two copies of the same table have to opened in memory.
Example
select e1.ename ||’ Work for ‘||e2.deptno from emp e1,emp e2 where
e1.deptno=e2.deptno;
select e1.ename ||'work for' || e2.ename from emp e1, emp e2 where
e1.mgr=e2.empno;
Outer Join
The outer join extends the result of a simple join or equi join. An outer join
returns all the rows returned by a simple join as well as those rows from one
table that do not match any row from other table.
The symbols (+) represents outer join.
Example
LEFT OUTER JOIN
select ename,e.deptno,d.dname,d.loc from emp e,dept d where
e.deptno(+)=d.deptno;
22
select ename,e.deptno,d.dname,d.loc from empgp e,deptgp d where
e.deptno(+)=d.deptno;
The above example will retrieve all the rows that are matching and also
retrieves the rows of DEPT table that does not match with EMP table because of
the presence of (+) operator.
23
select ename,e.deptno,d.dname,d.loc from deptgp d LEFT OUTER JOIN empgp e
ON e.deptno=d.deptno;
SELECT d.department_id, e.last_name
FROM departments d LEFT OUTER JOIN employees e
ON d.department_id = e.department_id
ORDER BY d.department_id;
Right outer join
Select ename,e.deptno,d.dname,d.loc from emp1 e,dept1 d where
e.deptno=d.deptno(+);
Select ename,e.deptno,d.dname,d.loc from empgp e,deptgp d where
e.deptno=d.deptno(+);
select ename,e.deptno,d.dname,d.loc from deptgp d RIGHT OUTER JOIN
empgp e ON e.deptno=d.deptno;
The above example will retrieve all the rows that are matching and also
retrieves the rows of EMP1 table that do not match with DEPT1 table because
of the presence of (+) operator.
SELECT d.department_name, d.manager_id, l.city
FROM departments d RIGHT OUTER JOIN locations l
ON d.location_id = l.location_id
ORDER BY d.department_name;
Full Outer join
The following query uses a full outer join to return all rows from the customers
table and all rows from the orders table. Rows that do not satisfy the ON condition
are extended with nulls:
SELECT c.customer_id, c.o.order_id, c.account_mgr_id, o.sales_rep_id
FROM customers c FULL OUTER JOIN orders o
ON c.customer_id = o.customer_id
ORDER BY c.customer_id;
Cartesian product
24
When data is retrieved from tables we go for joins. When we select columns from
two tables and if we do not specify a join condition it leads to a Cartesian product.
Select * from emp, dept;
13 * 9 =117 rows are selected.
Sub Queries
A Subquery is a group that can contain multiple query statements nested
within another. It is also called nested query.
Subqueries are queries that appear within a where or having clause of
another SQL statement. Subquery is used to handle results that are expressed as
the results of other queries.
A statement that includes a Subquery operates on rows from one table
based on evaluation of the subquery’s select list, which can refer to same table as
the outer query, or to a different table.
Select statements that contain one or more subqueries are sometimes called
nested queries or nested select statement.
A statement containing sub query is called parent query.
Select ename, deptno, sal from emp where sal=(select MAX(sal) from emp);
 Always enclose subquery in parenthesis.
 Subqueries will be evaluated first followed by the main query.
ANY operator
When this operator is used, a record will be selected is the value in the
outer query satisfies the condition with any one of the values retrieved from
subquery or inner query.
select ename,sal,deptno from emp where sal>= any(select avg(sal) from
emp group by deptno);
ALL Operator
The ALL operator is used to check for all the values returned by the list.
The condition is checked for all the values and the records that match all the
values are displayed.
select ename,sal,deptno from emp where sal>=all(select avg (sal) from emp
group by deptno);
IN operator
25
IN operator checks if the value of the outer query is equal to any of the
values in the inner query (or the list).
=ANY is equivalent to IN
!=ANY is equivalent to NOT IN
select ename,deptno,sal from emp where sal in(select max(sal) from emp group
by deptno);
select ename,deptno,sal from emp where sal not in(select max(sal) from emp
group by deptno);
EXISTS operator
When this operator is used, the outer query is executed if inner query
evaluates to TRUE.
select deptno,dname,loc from dept where exists(select * from emp);
Multiple Subqueries
A subquery can include one or more subqueries. Up to 16 subqueries can be
nested in a statement.
select ename,empno,sal from emp where job in
(select distinct job from emp where deptno=(select deptno from dept where
dname='SALES'));
A subquery can retrieve multiple information also
select * from emp where (job,sal) in (select a.job,b.losal from emp a,salary b
where a.job=b.job);
Subqueries in Update, Insert and Delete statements
In a delete statement subquery can be included in the ‘where’ clause whereas in
Update statement it can be included in ‘set’ clause as well as ‘where’ clause’.
Example
update emp set sal=(select sal from emp where empno=10) where
deptno=(select deptno from dept where dname='RESEARCH') and
job='ANALYST';
delete from emp where sal<(select avg(sal) from emp);
Correlated Subquery
A correlated subquery cannot be evaluated as an independent query, but it
can reference columns in a table listed in the ‘from’ list of the outer query. The
subquery is executed repeatedly once for each row that is selected by the outer
query or processed by the parent statement
26
select empno,ename,a.deptno from emp a where sal>=(select avg(sal) from
emp where a.deptno=deptno);
unlike most of the queries , subquery in this statement cannot be resolved
independently of the main query. It needs the value for ‘a.deptno’ but this value is
a variable, it changes as the SQL server examines different rows of ‘emp’ table.
SQL consider each row of emp(a) table for inclusion in the results by substituting
the value in each row in the inner query.
IN-LINE Queries
inline queries are those queries that can be selected from the ‘FROM’
clause of the select statement.
Example
select ename,sal,x "Average sal",deptno from (select avg(sal)x,deptno b
from emp group by deptno),emp where deptno=b;
by using in-line queries we make calculation
select ename,x-sal "difference from Asal",deptno from (select
avg(sal)x,deptno b from emp group by deptno),emp where deptno=b;
n th maximum sal
select distinct(sal) from emp a where &n=(select count(distinct(sal)) from emp
where a.sal<=sal);
select min(sal) from (select sal from (select * from emp order by sal desc) where
rownum<=&n);
Subquery restrications
• Subqueries cannot be used in order by and group by clauses.
• The subquery is limited to 16 nesting levels.
Pseudo columns
ROWNUM
For each row returned by a query, the ROWNUM pseudocolumn returns a
number indicating the order in which oracle retrieves the record.
The ROWNUM holds a numeric value.
select empno,empname,ROWNUM from emp;
ROWID
A ROWID is created by oracle for each new row in every table.
select rowid,no,name from ex1;
LEVEL
27
For each row returned by a hierarchical query.
example
select lpad(ename,8*level) from gjp5 start with mgr is null connect by
mgr=PRIOR empno;
Interview Questions – answers
1) SQL> select * from emi;
EMPNO NAME DEPTNO
--------- -------------------- ---------
101 praveen 10
102 raja 10
103 sekar 20
104 arun 20
105 arvind 10
SQL> select * from depi;
DNAME DEPTNO
------------------------------ ---------
software 10
software1 20
hr 30
SQL> select * from depi where deptno not in ( select deptno from emi);
DNAME DEPTNO
----------------------------- ---------
hr 30
2) SQL> select * from emi;
EMPNO NAME DEPTNO
-------- -------------------- ---------
101 praveen 10
102 raja 10
103 sekar 20
104 arun 20
105 arvind 10
106 praveen 20
107 praveen 30
108 sekar 10
109 sekar 10
110 raja 10
10 rows selected.
SQL>select distinct(name) from emi where name in (select name from emi group
by name having count(name)>1);
28
NAME
-------------------
Praveen0
raja
sekar
Database objects
• Views -- is a subset of data from one or more tables
• Synonyms – it gives one alternative name to object
• Sequences – it is used to give numbers automatically
• Indexes – it improves the performance of some queries by using a pointer
Views
- We can present logical subsets or combination of data by creating views of
tables .
- A view is a logical table based on a table or another view.
- A View can be defined as a logical table built upon one or more tables in a
database.
The Advantages of views
 Restricted Access to specific columns of a table there by providing
additional security
 Oracle stores the definition of the view only
 It simplifies queries
 It avoids data redundancy
 To hide the data complexity
Simple View
The definition of the view will contain the column names given in the
query.
Syntax : Create view <viewname> as query
Example
Create view empview as select ename, deptno, sal from emp;
Join View
Joining of tables results in creation of join views. A join view is a view that
is created using a join condition. There are certain in join views.
create view joinv as select empno,ename.dept.deptno from emp, dept where
emp.deptno =dept.deptno;
Restrictions
- A view creation cannot contain on order by clause
- If a view is defined with check option , a row cannot be inserted into or
updated in the base table.
Renaming the columns of view
29
We can rename the column of a view so that the data in the column have a
meaningful name.
Syntax
create view view_name (column1,column2,…) as select column1,column2 from
basetable where condition;
Example
create view gpview (number,name) as select empno,ename from emp;
desc gpview; - it describes the view structure
Force view
If you want to create view without an existing table.That is, table is
already created.
syntax create force view viewname as <query>;
example create force view fv as select * from emp;
Read only views
Certain views can be created only for selection purpose. Such views will
not permit the user or the owner of the view to perform any DML operations.
Example
create view read_view as select * from dept with read only;
Updatable views
Views that allow data manipulation (insert,update,delete) are called
updatable views.
Reasonly views
views that donot allow data manipulation are called reasonly views.
Criteria for updateable views
1. The view must be created over a single base table.
2. the view must include the primary key.
3. The view should not contain any aggregate functions.
4. The view should not contain any subquery in its select statement.
5. The view should not contain DISTINCT,HAVING and GROUP BY clause
in the SELECT statement.
6. If the view is constructed over another view than the base view must be
updated.
7. The view should not contain any constants,strings and expressions in the
SELECT statement.
8. The view must contain all the NOT NULL columns of the base table.
Destroying views
views can be destroyed using the DROP view command.
Syntax drop view <view name>;
Example drop view client_balance;
Synonyms
30
A synonym is a database object that is used as an alias name for any object.
A synonym is an alternative name for a table, view, sequence, procedure,
stored function and package.
Advantages
- Simplify SQL statements
- Hide the real identify of an object.
Creating Synonym
create synonym<synname> for <objectname>;
Example
create synonym syemp for emp;
insert into gpsyn values(22,34);
select * from gpsyn;
Drop synonym – to drop synonym
Syntax Drop synonym <synname>;
Example drop synonym gpsyn;
Select * from user_synonyms; to display the list of synonyms.
Sequences
Sequences are a set of database objects, which can generate sequential
integer value. They are used to automatically generate primary key or unique key
values. A sequence can be created in ascending or descending order.
Creating sequence
Syntax
create sequence <sequencename>
[<increment by> <value>]
[<start with > <value>]
[<minvalue> <value>] [NOMINVALUE]
[<maxvalue> <value>] [NOMAXVALUE]
[<cycle> <value>] [NOCYCLE]
[<cache> <value>]
where
increment by
Specifies the interval between sequence numbers. This value can be any
positive or negative Oracle integer, nut it cannot be 0. if this value is negative then
the sequence descends. If increment is positive, then the sequence ascends.
minvalue
Specifies the sequence’s minimum value.
Nominvalue
Specifies a minimum value of 1 for an ascending sequence or -10 for a
descending sequence. The default is NOMINVALUE.
31
Maxvalue
Specifies the maximum value the sequence can generate.
Nomaxvalue
Specifies a maximum value of 10 for a descending sequence can generate.
Start with
Specifies the first sequence number to be generated.
Cycle
Specifies that the sequence continue to generate values after reaching either
its maximum or minimum value.
Nocycle
Specifies that the sequence cannot generate more values after reaching its
maximum or minimum values. The default is NOCYCLE.
Cache
Specifies how many values of the sequence oracle preallocates and keeps in
memory for faster access. The minimum value for this parameter is 2. For
sequences that cycle, this value must be less than the number of values in the
cycle.
Nocache
Specifies that values of the sequence are not preallocated. If you omit both
the cache parameter and the NOCACHE option, Oracle caches 20 sequence
numbers by default.
Example
create sequence gpseq2
start with 10
minvalue 10
maxvalue 20
increment by 2
cycle
cache 5;
select gpseq1.NEXTVAL from dual;
insert into gjp20 values(gpseq1.nextval,&dno);
Altering a sequence
The following specifications of a sequence can be altered.
• Minimum value
• maximum value
• Incremental value
• Number of cached sequence number.
Alter sequence s1 maxvalue 25;
32
Dropping Sequence
Drop sequence command is used to drop a sequence from the database.
Syntax Drop sequence <seq_name>;
Example Drop sequence gpseq;
To list Sequences
Select * from USER_SEQUENCES;
INDEX:
Index on table is used to speed up the execution of queries in the table. This
concept is similar to that of the index in a book.
An index can be considered as an ordered list of data of a column or a
group of columns, together with a location.
Simple Index :
A index is said to be simple if the index is created on only one column.
Upto 16 indexes can be used on a table.
Syntax:
Create index <indexname> on <tablename> (column name);
Example  Create index empi on emp(job);
Composite Index:
If the index is created on more than one column. It is called composite
index.
Example  Create index empii on emp(ename,job);
- Indexed column of a table can have duplicate value.
Creating unique index
- it can be done in two ways
- 1st
while creating table we give primary key
- 2nd
one is we create index as unique
Syntax
Create unique index indname on tablename(colname);
Example:
33
Create unique index stui on student(rollno);
-- now “rollno” column does not accept duplicate values
Reverse Index
It can be done by using “REVERSE” keyword
Normal Index Reverse Index
E1001 1001E
E2004 4002E
Syntax
Create index indname on tablename (columnname) REVERSE;
Example
Create index reind on emp(empno)REVERSE;
Alter the reverse index into normal
Alter index reind REBUILD NOREVERSE;
Bitmap Indexes
The advantages of using bitmap indexes are greatest for low cardinality
columns : that is columns in which the number of distinct values is small
compared to the number of rows in the table. If the table values in a column are
repeated more than a hundred times, then the column is a candidate for a bitmap
index. Even columns with a lower number of repetitions and thus higher
cardinality, can be candidates if they tend to be involved in complex conditions in
the WHERE clauses of queries.
For Example, on a table with one million rows, a column with 10,000 distinct
values is a candidate for a bitmap index.
Syntax
CREATE BITMAP INDEX <indexname> ON <table>(column);
Example
CREATE BITMAP INDEX gpbi ON emp (no, deptno);
Index organized tables
- An index organized table differs from regular table in that data for the table is
held in its associated index. When changes are made to the table, only the
index is updated.
- Index organized table is similar to a regular table with an index on one or
more columns; it can be having two separate storage places for the table and
the index.
34
- Index-organized tables suitable for accessing data by the primary or any key
that is a valid prefix of the primary key. There is no duplication of key values
because only one non key column values are stored with the key. You can
build secondary indexes to provide efficient access by other columns.
- Applications manipulate the index organized table just like an ordinary table,
using SQL statements. However the database system performs all operations
by manipulating the corresponding index.
Example
Create table stud (num number (5) primary key, name varchar2 (20))
ORGANIZATION INDEX;
If you want create organized index that table must have one primary key.
Advantages:
 Since the rows are stored in the index, an index – organized table provides a
faster key based access to table data for queries involving exact match or
range search.
 Table occupies less space
 Key columns are not duplicated in the table and the index
Dropping Index
By using drop index
Syntax Drop index <indname>;
Example
Drop index empind;
Clusters
 Clusters are optional method of storing data.
 A cluster is a group of tables that share the same data blocks because they
share common columns and are used together.
for Example:
EMP and DEPT table share deptno column . when we use cluster for these
two tables . Oracle physically stores all rows from both tables in the same data
blocks.
 clusters store related rows of different tables together in the same data
blocks.
benefits
 Disk I/O is reduced and access time improves for joins of clustered tables
35
In a cluster, a cluster key value is the value of cluster columns for a particular
row.
Each cluster key value is stored only once in the cluster and the cluster index.
- less storage space required to store related table and index data in a cluster.
Cluster key
The cluster key is a column, or group of columns, that the clustered table
have in common. We specify the columns of the cluster key when creating the
cluster. We subsequently specify the same columns when creating another table
added to the cluster.
 no more than 16 columns can form the cluster key.
 Cluster key cannot include LONG or LONG RAW column.
Hash Cluster
 Storing a table in a hash cluster is an optional way to improve the
performance of data retrieval.
 A hash cluster provides an alternative to a non- clustered table with an
index or an index cluster.
 Oracle locates the rows in a table using key value that it stored in a separate
index. In order to use hashing, a hash cluster is created and tables are
loaded into it.
 Oracle physically stores the rows of a table in a hash cluster and retrieves
them according to the results of a hash function.
To find or store a row in an indexed table or cluster, a minimum of two I/Os
must be performed:
• One or more I/Os to find or store the key value in the index.
• Another I/Os read or write the row in the table or cluster.
In contrast, Oracle uses a hash function to locate a row in a hash cluster, no I/O
is required. As a result, minimum of one I/O operations is necessary to read or
write a row in a hash cluster.
Advantages of Hashing
• Most queries are equality queries on the cluster key
Select … where cluster_key=…;
• In such cases, the cluster key in the equality condition is hashed, and the
Corresponding hash key is usually found with single read. In comparison,
for an indexed table the key value must first be found in the index (usually
several reads) and then the row is read from the table (another read).
36
• The tables in the hash cluster are primarily static in size so that we can
determine the number of rows and amount of space required for the tables in
the cluster. If the tables in a hash cluster require more space than the initial
allocation for the cluster, performance degradation can be substantial
because overflow blocks are required.
Disadvantages of Hashing
• Most queries on the table retrieve rows over a range of cluster key values.
(Example full table scans, or queries like the following , a hash function
cannot be used to determine the location of specific hash keys
• The table is not static and continually growing. if a table grows without
limit, the space required over the life of the table(its cluster) cannot be pre-
determined.
• Applications frequently perform full- table scans on the table and the table is
sparsely populated. A full-table scan in this situation takes longer under
hashing.
Creating Hash Clusters
After a hash cluster is created, tables can be created in the cluster.
create cluster gc(dn number(5));
create index gci on cluster gc;
create table gct1(dn number(5),name varchar2(20)) cluster gc(dn);
create table gct2(dn number(5),dna varchar2(30)) cluster gc(dn);
select ROWID from cluster gpa;
 rowid of the two tables are same, Because these two tables uses cluster.
Drop Cluster
To drop a cluster by using Drop cluster command.
Syntax
Drop cluster clustername;
drop cluster gpc including tables;
37
 here it deletes table also.
drop cluster gpc;
- if the tables are already deleted means we directly drop the particular cluster
“gpc”.
LOCKING
Concurrency control in Oracle
In a multi-user environment, the database is centralized and all users
can access data from the database. Since data are stored in tables, a table in the
database may be accessed by more than one user at the same time
(concurrently). A true RDBMS must tackle this situation to prevent damage to
the table or the data in the table. This problem is effectively handled by the
Oracle by means of the technique Concurrency control locking.
Locking is a method of Concurrency control. Oracle uses this method for
concurrently control. The following are
Lock
Lock is a mechanism implemented on a resource by a user that restricts
other users to access the same resource temporarily. The resource may be a
table or a row.
Oracle automatically locks a resource when a transaction begins. The lock
is released only after the transaction is committed or rolled back. Thus Oracle
prevents destructive interaction between users.
Example
Let two users user1 and user2 access the data with the following transactions
user1 : update emp set cos=100 where empno=‘1001’;
user2 : delete from emp where empno=‘1001’;
Both the users are accessing the same table and same row concurrently. So
it makes some problem. Hence Oracle uses the locking process to overcome
this situation.
Types of locks
There are two types of locks. They are
1. Share lock
2. Exclusive lock
38
1. Share lock
This lock allows other users also to share the same resources. But the other
users can only query the resource (Select statement) and they can’t execute DML
statements.
More than one user can place share lock on the same resource.
2. Exclusive Lock
This lock restricts the sharing of resources by other users. However it
allows other users to query.
only one user can place an exclusive lock on a table at a time.
Implicit and Explicit Locking
While Oracle automatically locking a table a user can lock a table explicitly
also
Implicit Locking
To maintain a high degree of data concurrency, Oracle performs different
locks automatically depending upon the SQL statements. The lock applied
implicitly by the oracle is called implicit lock.
Oracle acquires the necessary lock implicitly based on the following situations.
• A user who is querying data from the database need not wait for other users
who are accessing (inserting, updating, selecting) the same data
simultaneously.
• A user who is accessing data (inserting, updating) in the database need not
wait for others who are querying the same data simultaneously.
• A user who is inserting or updating data in the database only needs to wait
for other users who are trying to insert or update the same data
simultaneously.
A table comprises of rows and each row can be divided into items. Thus if a
user is updating a particular set of records, lock placed on the particular rows is
more flexible so that other users can access the remaining portion of the same
table. Further, when a user tries to modify particular item in a row, the most
flexible locking is to place a lock only on those items.
Explicit locking
During a transaction, some time a consistent set of data may be required.
So, the particular set of data should not be allowed to be accessed by other users
39
till the transaction is over. this is called transaction level read consistency and this
can be achieved only by explicit locking.
Explicit lock can be acquired using
i) SELECT …… FOR UPDATE statement
ii) LOCK TABLE … statement
Levels of Locking
Locks can be acquired at two level.
1. Row level lock
2. Table – level lock
1. Row level lock
implicit row lock
Oracle automatically places an exclusive lock on every row that is
modified by the statements INSERT, DELETE and UPDATE. This is
called implicit row locking.
Explicit row lock
Implicit row locking can be overridden by explicit row locking.
SELECT .. FOR UPDATE statement overrides the implicit locking on the
rows and acquire exclusive row locks for the selected rows.
SELECT … FOR UPDATE statement
Syntax
SELECT column1,column2,column3 .. FROM <table-name>
WHERE <search_condition> FOR UPDATE [OF column , column,…]
[NOWAIT];
Example
select * from employe where empno=1003 FOR UPDATE;
select empno, ename from emp where empno=1003 for update;
Restrictions
• DISTINCT and GROUP BY clauses should not be used.
• Should not include set operators (UNION, INTERSECT, MINUS, UNION)
and group functions.
• All the tables must be in the same database
40
• This must be followed by an update statement or COMMIT or ROLLBACK,
Otherwise the lock will not be released.
• if some other user locked the same rows, Oracle will wait till the lock is
released NOWAIT option terminates the statement in this case.
Table level locks
Implicit Table lock
Oracle implicitly places a lock on the tables that is modified by INSERT,
UPDATE and DELETE commands.
Explicit table lock
We can place locks explicitly on tables to override implicit table locks
Tables can be locked explicitly by using
Table level locks
lock table employe in share mode;
lock table employe in share update mode;
lock table employe in exclusive mode;
Permission
Granting and revoking privileges add an additional security to the Oracle
database system.
In multiple – user environment, we need to maintain security of the
database access and use. Using Oracle Server database security
Creating user
The oracle system has two users SYSTEM with password Manager and
another user SYS.
SYSTEM has all privileges, logon to SYSTEM and create a user using
CREATE USER command.
Syntax
CREATE USER username IDENTIFIED BY password;
41
CREATE USER praveen IDENTIFIED BY srm;
Logging on to one user from another user
By using CONNECT command
Syntax
CONNECT username/password;
Example
CONNECT praveen/srm;
At this stage User Praveen has no privilege to ‘Create session’. Hence we have
to grant the privilege to create session to Praveen. Then only we can log on the
user Praveen.
Types of Privileges
A permission granted to a user to do some action is called a privilege. A
user can not do any action if he does not have the privilege to do that action.
There are two types of privileges. They are
1. System privilege
2. Object privilege
1. System privilege
The Permission granted to execute various data definition, commands like
CREATE TABLE , CREATE SEQUENCE, CREATE SESSION are called
System privileges.
Some of the System privileges are
CREATE SESSION : Log on to database
CREATE TABLE : to create table
CREATE ANY TABLE : allow creating table in any schema (user)
CREATE SEQUENCE : to Create a sequence
CREATE ANY SEQUENCE : to Create a sequence in any schema
CREATE PROCEDURE : to create procedure
CREATE TRIGGER : to create trigger
42
CREATE ANY TRIGGER : To create trigger in any schema
CREATE VIEW : to create view
CREATE ANY VIEW : to create view in any schema
ALTER ANY TABLE : to alter any table
ALTER ANY SEQUENCE: to alter any sequence in any schema
ALTER ANY VIEW : to alter an view
ALTER ANY PROCEDURE To alter any procedure in any schema
DROP ANY TABLE : to drop any table
DROP ANY TRIGGER : To drop any trigger
DROP ANY SEQUENCE : To drop any sequence in any schema.
example
create user gpj identified by jum;
alter user gpj identified by jumu;
- it changes the password
Granting System privilege
GRANT command is used to give system privileges to an Oracle USER.
Syntax : GRANT system privilege to user;
Example : grant create session to gpj;
Connect gpj/jum;
Object Privileges
An Object privilege enables a user to execute some command on database
objects like table, view, sequence etc.
43
NO Privileges Table View Sequence Procedure
1. ALTER * *
2. DELETE * *
3. EXECUTE *
4. INDEX *
5. INSERT * *
6. REFERENCES *
7. SELECT * * *
8. UPDATE * *
Granting Object Privileges
Different object privileges are available for different types of schema
objects. A user automatically has all object privileges for schema objects
contained in the user’s schema. A user can grant any object privilege on any
schema object that the user owns to any other user. If the grant includes the
GRANT OPTION, the grantee can further grant the object privilege to other users.
Otherwise , the grantee can use the privilege but cannot grant it to other users.
The syntax is given below
GRANT object_priv [(columns)]
ON object
TO {user|PUBLIC}
[WITH GRANT OPTION]
where,
object_priv is an object privilege to be granted
columns specifies the Column from a table or view on which privileges are
granted
ON Object is the object on which the privilege are granted
TO identifies to whom the privilege is granted
PUBLIC grants object privileges to all users
WITH GRANT OPTION allows the grantee to grant the object privilege to
other users.
Example
GRANT select ON emp TO gpp;
Example
44
GRANT update(dname,loc) ON dept TO gpp,Praveen;
update scott.dept set dname=‘pur’ where deptno=30
GRANT SELECT,UPDATE,DELETE on staff to student;
Referencing a table belonging to another user
The objects in a user could not be used by another user, if the owner of the
objects has not granted the required privileges to the user on those objects. If a
user is granted privileges on some objects then the user can refer the object
preceded by the user name of the owner of the object.
Example
Assuming you are in user staff
1. select * from student.student_master;
2. select * from gp.client_master;
Granting Permission to users when the grantor has been given GRANT
permission
The owner of an object can grant any privilege on the object to other users.
If a user wants to grant privileges on objects of the other users, then the user must
have been granted the same privileges on those objects with the GRANT
OPTION.
Example
Execute from the user scott
GRANT SELECT ON emp TO gpp;
here user gpp could not grant the SELECT privilege to any other user.
GRANT SELECT ON emp TO gpp WITH GRANT OPTION;
Now the user gpp can grant the privilege SELECT on the object emp in the user
scott.
First log on to gpp then Execute
GRANT SELECT ON scott.emp TO student;
45
Revoking the Permissions
Permissions granted to a user can also be taken back by the grantor. This is
done by the REVOKE command.
Revoking System privileges
The REVOKE statement is used to remove the system privileges granted to
the user.
Revoke create table to Praveen;
To remove the create table privilege to the user Praveen.
Revoking Object Privileges
The REVOKE statement is used to remove privileges granted to other users.
Syntax
REVOKE objectprivilege [object privilege] … ON objectname FROM
username;
Example
REVOKE SELECT,INSERT ON emp from scott;
Drop user
if you want to drop a particular user by using drop user command;
drop user username;
Example
drop user gpp;
note : it will be executed from the SYSTEM user.
Partitions
ORDBMS
The realization
Single row object type
Single Row Object types are object types that are defined for specific
columns and can hold singular value only like other datatypes. They are created as
objects, which are further embedded as a datatype to a column.
Example
create or replace type user_date as object
(
day number(2),
46
month number(2),
year number (2)
);
create or replace type user_name as object
(
fname varchar2(20),
mname varchar2(20),
lname varchar2(20)
);
// object type user_date
// object type user_name
create table employee_data13
( empno number(3),
ename user_name,
dob user_date,
salary number (9,2)
);
Inserting values
Every object type has a system defined constructor method that is a method
that makes a new object according to the object type’s specification. The name
of the constructor method is the name of the object type. The constructor
method is a function. It returns the new object as its value. It is used to
initialize the attributes with values.
insert into employee_data13 values(101,user_name(‘jam’,’praveen’,’kumar’),
user_date(25,06,83),10000);
SQL> select * from employee_data;
EMPNO
---------
ENAME(FNAME, MNAME, LNAME)
-------------------------------------------
DOB(DAY, MONTH, YEAR)
-------------------------------------------
SALARY
---------
101
USER_NAME(‘jam’, ‘praveen’, ‘kumar’)
USER_DATE(25, 6, 83)
10000
47
SQL> select e.ename.fname, e.ename.lname from employee_data13 e;
ENAME.FNAME ENAME.LNAME
-------------------- --------------------
jam kumar
select e.empno, e.dob.day from employee_data13 e;
Updating values
Updating is done similar to the select statement. The dot notation and an alias
of the table is used.
update employee_data13 a set a.ename.lname=‘vignesh’ where a.empno=101;
deleting a record
Deleting a record is similar to updating and selecting values from rows
abstract data types
insert into employee_data values(102,user_name(‘j’,’pravee’,’kum’),
user_date(29,06,85),15000);
delete from employee_data13 a where a.ename.fname=‘j’;
Dropping Types
To get rid of a type such as user_date, the following command is used.
SQL> drop type user_date;
drop type user_date
*
ERROR at line 1:
ORA-02303: cannot drop or replace a type with type or table dependents
Object type cannot be changed or dropped without dropping its dependents.
However the FORCE clause can be used to forcefully drop an object type.
SQL> drop type user_date force;
Type dropped.
CREATE OR REPLACE TYPE TYP_synch_bill_customer AS OBJECT (
DEBTORNUM NUMBER(10),
48
DATE_EFFECTIVE DATE,
END_DATE DATE,
STATUS VARCHAR(5)
);
CREATE OR REPLACE TYPE table_synch_customers AS TABLE OF
TYP_synch_bill_customer;
/
created.
SQL> desc table_synch_customers;
table_synch_customers TABLE OF TYP_SYNCH_BILL_CUSTOMER
Name Null? Type
----------------------------------------------------- -------- ------------------
DEBTORNUM NUMBER(10)
DATE_EFFECTIVE DATE
END_DATE DATE
STATUS VARCHAR2(5)
Collections
Varrays
Nested Tables
Introduction
A collection is an ordered group of elements of the same datatype.
- Varray (Varying Array)
- Nested table (multiple records)
Varrays
An array is an ordered set data elements. All elements of a given array are of
the same datatype. Each element has an index, which is a number
corresponding to the element’s position in the array. The number of elements
in an array is the size of the array.Oracle arrays are of variable size, which is
why they are called Varrays. The maximum size must be specified while
creating Varrays.
Declaring a Varray does not occupy space. It defines a type, which can be used
as
1.The datatype of a column of a relational table.
2.An object type attribute.
49
3.A PL/SQL variable, parameter, or function return type.
An array object is stored in line, that is, in the same tablespace as the other data
in its row. The following example illustrates this concept.
EXAMPLE :
CREATE OR REPLACE TYPE price_list AS VARRAY(5) OF number(3);
When the above statement is executed, the specified type is created.
CREATE TABLE prods
(
pno number,
rate price_list,
);
Nested tables
A nested table is like an object table without the object identifiers. It has a
single column, and the type of that column is a built in type or an object type.
If it is an object type , the table can also be viewed as a multi-column table,
with a column for each attribute of the object type.
A nested table definition does not allocate space. It defines a type, which you
can use as
* The datatype of a column of a relational table.
* An object type attributes
When a nested table appears as the type of a column in a relational table or as
an attribute of the underlying object type of an object table. Oracle stores all of the
nested table data in a single table which it associates with the enclosing relational
or object table. They are also called Multiple Row Object type. There are no
restrictions on the number of records to be created.
Example
CREATE OR REPLACE TYPE stud_type1 AS OBJECT
(studno number, studname char(20), sex char(1));
CREATE OR REPLACE TYPE stud_nt1 AS TABLE OF stud_type1;
CREATE TABLE faculty1
( factno number,
name varchar2(30),
students stud_nt1
50
)NESTED TABLE students STORE AS stud_nt_tab;
here
NESTED TABLE <nested _item> STORE AS <storage _table>
Specifies <storage_table> as the name of the storage table in which the rows of all
<nested_item> values reside.
insert into faculty1 values (1,’vignesh’,
stud_nt1(
stud_type1(10,’Praveen’,’M’),
stud_type1(20,’kumar’,’M’),
stud_type1(30,’chellam’,’F’)
)
);
insert into faculty1 values (2,’Pravee’,
stud_nt1(
stud_type1(10,’Praveena’,’F’),
stud_type1(20,’kumari’,’F’),
stud_type1(30,’anbu’,’M’)
)
);
Using Flattened Subqueries
To manipulate the individual rows of a nested table stored in a database
column, use the keyword THE. THE keyword must be prefixed to a subquery that
returns a single column value or an expression that yields a nested table. If a
subquery returns more than a single column value, a runtime error occurs. Because
the value is a nested table , not a scalar value. Oracle must be informed, which is
what THE does.
Quering Nested Table Values Alone using THE
select nt.studno,nt.studname,nt.sex from THE (Select students from faculty1
where factno=1)nt;
Note: Here only one main subset value can be selected.
Here, if a user needs to enter another record, this can be done using the following
syntax.
51
INSERT INTO THE (SELECT students FROM faculty1
WHERE factno=1) nt
VALUES (14,'kalai','F');
PL / SQL
- Procedural language / Structured Query Language.
- It is an extension of SQL and bridges the gap between the application
program, the Oracle database system and the database.
- PL/SQL is a language that has programming features that serve as an
extension to SQL.
- Using PL/SQL we can manipulate data in the database insert data into the
database and also retrieve data.
- Also we can group PL/SQL codes logically and this group of PL/SQL code
called block. If a block is not given a name. It is called on anonymous block.
- PL/SQL incorporates many of the advanced features of programming
languages that were designed during the 1970’s and 1980’s.
Need for PL /SQL for programmers
 PL/SQL enables the programmers to write procedural programs to
access and manipulate data in the database.
 Using SQL data manipulation languages in PL/SQL, data in the tables
can be manipulated.
 Using the data transaction languages in PL/SQL, Changes of data in a
table can be made or can be undone as whole.
 All sorts of SQL functions can be used in PL/SQL.
 All operators that we are using in SQL statements can also be used in
PL/SQL.
 In Addition, we can declare variables and constants in PL/SQL to store
results of a query during process, which can be used later in the
PL/SQL block.
PL/SQL Executing Environment
Diagram of Oracle server
52
PL/SQL in Oracle RDBMS
If the PL/SQL engine is placed in the Oracle Server, then the execution of
PL/SQL will be more efficient.
Modularize program development
Using PL/SQL block in SQL Environment
A PL/SQL block has three parts namely; Declaration, execution and
exception. Declaration and exception parts are optional.
53
ORACLE SERVER
SQL Statements
PL/SQL Engine
Procedural
Statements
Procedural
Statement
Executor
PL/SQL
Block
SQL Statement Executor
DECLARE
BEGIN
EXCEPTION
END;
Declaration part begin with keyword DECLARE.
Execution part begin with keyword BEGIN and ends with the keyword END.
Declarative  contains all variables, constants, cursors and user defined
exceptions
Executable  Contains SQL statements to manipulate data in the database and
PL/SQL statements to manipulate data in the block.
Exception  Specifies the actions to perform when errors and abnormal
conditions arise in the executable section.
Method – 1
Step 1
If we type DECLARE or BEGIN at the SQL prompt. SQL understand that the
user is going to execute a PL/SQL and it will ignore the semicolon, we type at the
end of SQL statements, Type END as the last statement.
Step 2
Type / at the SQL prompt. The block will be stored in the SQL buffer and then
The block will be executed.
Example
SQL> begin
2 update emp set comm=200 where comm=100;
3 update emp set comm=500 where empno=7788;
4 end;
5 /
PL/SQL procedure successfully completed.
SQL>
Method -2 (Through another editor)
Here we are going to use the notepad as the editor.
Step 1:
Type ed <filename> at the SQL prompt
SQL>ed <filename>
This will create a new file with extension SQL
Step 2:
Type the PL/SQL block codes in the file let / be last line after the key
word end.
Step 3:
54
Save and exit
Step 4:
Type @ <filename> at the SQL prompt
SQL> @ <filename>
The block will be executed.
Example
SQL> ed new1
SQL> @ new1;
Input truncated to 1 characters
PL/SQL procedure successfully completed.
SQL>
PL/SQL syntax
It also have own character set, variables and literals
PL/SQL character set:
a) Upper case alphabets
b) Lower case alphabets
c) Numbers
d) Special symbols : ( , ) , +, - ,* , / , @ ,%,$ ,^
Simple symbols used in PL/SQL Block
( ) + , * , - ,< ,> , =
Compound symbols
<>,<= ,>= ,!=, :=, =, **
Literals
A sequence of valid PL/SQL characters is called a literal.
There are four types of literals
a) String literal
A sequence of one or more characters from the PL/SQL character set
enclosed with in single quotes ( ‘ ) is called string literal.
Example
1) ‘welcome to all ‘
2) ‘123.44’
3) ‘Mr. Praveen welcome’
b) Character literal
55
A string literal with only one character is called a character literal
Example
‘Y’ , ‘7’
c) Numeric literal
Any valid number is called Numeric literals
d) Boolean literal
The value TRUE , FALSE, NULL are called Boolean literal.
Comments
This line is not executable. We can place comment any where in PL/SQL
block.
There are two types of comments are available.
Single line Comment
A comment having only one line is called single line comment.
It begins with --
Multiline comment
If the comment runs over more than one line is called multiline comment.
It begins with /* and ends with */
PL/SQL Data types
A PL/SQL variable can be declared as any of the oracle internal data types.
Also there are many other data types
1. Varchar2.
2. Char.
3. Number.
i. Decimal
ii. Integer
iii. Real
4. Binary_integer
The variable of this data types is used to store signed integers in the
range -2 31
- 1 to 2 31
-1 .
5. Date
This data type stores a date values SQL stores all date and time in its
own floating point format.
6. Boolean
The variable of this data type is used to store TRUE, FALSE or NULL.
7. %Type
This attribute is used to declare a variable similar to the data type of
a column in an existing table or that of a variable defined earlier in the block.
Syntax :
Variable_name tablename.column_name%type;
ex
basicpay staffacd.basic%type; staffacd  tablename , basic  column of table
56
salary emp.sal%type;  salary number(7,2);
b_pay basicpay%type :=10;
 A NOT NULL database column constraint does not apply to variables that are
declared using %TYPE.
PL/SQL variable
PL/SQL variables are declared in the declarative part of a block.
Rules:
 A variable name must start with alphabets followed alpha numerals. It’s
maximum length of a variable is 30 characters.
 Only underscore allowed
 Avoid using keyword as variable
Example: sal_pay, sle122
Example:
Stud_name varchar2 (30);
Salary number (5, 2);
Assigning values to variables
There are two methods are available to assign a value
1. Assigning a variable with the value retrieved from a table.
The SELECT …… INTO statement
It used to assign values to variables
Syntax
SELECT column1,column2,. .. INTO variable1,variable2.. from
<table> where <condition>;
Example
Declare
sname varchar2(30);
salary emp.sal%type; -- salary number(7,2);
Begin
Select ename, sal into sname, salary from emp where empno=7902;
dbms_output.put_line (sname ||' salary is '||salary);
End;
/
2. Assigning a value with the assignment operator
The assignment operator := is used to assign values.
Example - salc.sql
declare
basic number(7,2);
57
hra number(2);
da number(3);
salary number(8,2);
begin
select sal into basic from emp where empno=7902;
hra := 20;
da := 5;
salary := basic + basic*da/100 +basic *hra/100;
dbms_output.put_line(salary);
end;
Remark
If we declare a PL/SQL variable to be NOT NULL then we must assign a
value at once.
Example
Salary number (8,2) NOT NULL :=0;
Here Salary have “zero” value at the time of declaration.
dbms_output.put_line  it is used to print the output in sql prompt
Constants
If a particular value does not change its value in a PL/SQL block.
We declare that variable as constant
Example:
da constant number(3) := 20;
sub constant varchar2(25) := ‘english’;
Boolean expressions
Expression separated by a comparison operator is called a Boolean
expression. The values are TRUE , FALSE, NULL.
Example
sal >= 10000; subject <> ‘english’; subject !=’english’
Logical Expressions
Two are more Boolean expression connected with logical operator is called
logical expression.
Example
Sal >1000 and dept = ‘software’
Sal >1000 or dept = ‘software’
PL/SQL block structure
Three parts
1. Declarative part
2. Execution part
3. Exception part
58
Nested block
Declare
test number(2);
begin
test :=10;
declare
test number(2);
begin
test :=20;
dbms_output.put_line (test);  prints 20
end;
dbms_output.put_line (test);  prints 10
end;
Entering values while running time- gp3.sql
Declare
test number(2);
begin
test:=&test;
dbms_output.put_line (‘the result is’ || test);
end;
Screen Message
To display message first we must type SET SERVEROUTPUT ON
command at the SQL prompt.
Qualify an Identifier
Qualify an identifier by using the block label prefix.
<<outer>>
declare
bdate date:='25-jun-83';
begin
declare
bdate date :='29-jun-85';
begin
dbms_output.put_line('Inner block variable '|| bdate);
dbms_output.put_line('Outer block variable '|| outer.bdate);
end;
end;
Bind variables
A bind variable is a variable that you declare in a host environment.
Bind variables can be used to pass run time values, either number or
character.
59
Creating Bind variables:
By using VARIABLE command used to create bind variables
Syntax
VARIABLE b_varname NUMBER
VARIABLE b_varmsg VARCHAR2(30)
Displaying Bind variables
By using PRINT command
Syntax : PRINT bname;
Example - gpvar.sql
variable gsal number
begin
select sal into :gsal from emp where mgr=7788;
end;
/
print gsal
Programming with PL/SQL
1. Conditional controls
a) IF … THEN …….. END IF
Syntax
IF <condition> THEN
Statements
END IF;
Example - gpif.sql
DECLARE
sno number;
BEGIN
sno := &sno;
IF sno>=10 THEN
dbms_output.put_line(‘sno is greater than 10’);
END IF;
END ;
b) IF … THEN …ELSE….. END IF
Syntax
60
IF <condition> THEN
Statements set 1
ELSE
Statement set 2
END IF;
Example – gpife.sql
DECLARE
sno number(3);
BEGIN
sno := &sno;
IF sno>=10 THEN
dbms_output.put_line (‘sno is greater than 10’);
ELSE
dbms_output.put_line (‘sno is not greater than 10’);
END IF;
END;
c) IF … THEN …ELSIF….ELSIF….. END IF
Syntax
IF <condition1> THEN
Statements
ELSIF <condition2> THEN
Statement
ELSIF <condition3> THEN
Statement
ELSE
Statement
END IF;
Example – gpifeif.sql
DECLARE
a number(3) :=&a;
b number(3):=&b;
BEGIN
IF a>b THEN
dbms_output.put_line (‘a is greater than’);
ELSIF a<b THEN
dbms_output.put_line(‘b is greater than’);
ELSE
dbms_output.put_line(‘Both are equal’);
END IF;
END;
Nested IF…… THEN
Syntax
61
IF <condition1> THEN
Statements
IF <condition2> THEN
Statement
ELSE
Statement
ENDIF;
ELSE
Statement
END IF;
Ex
DECLARE
a number(3) :=&a;
b number(3):=&b;
BEGIN
IF a>b THEN
dbms_output.put_line(‘a is greater than’);
IF a<b THEN
dbms_output.put_line(‘b is greater than’);
END IF;
END IF;
END;
CASE Expressions
A CASE expressions selects a result and return it.
Syntax:
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
…
WHEN expression n THEN result n
[ ELSE result ]
End;
62
Example
DEFINE p_grade = a; // define variable only number or character
declare
v_grade char(1) := upper('&p_grade');
v_appraisal varchar2(20);
begin
v_appraisal :=
CASE v_grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
ELSE 'No such grade'
END;
dbms_output.put_line('Grade : '||v_grade ||' Appraisal : ' || v_appraisal);
end;
/
Loop ….. END loop
The statement placed between the keywords LOOP and END LOOP will be
executed repeatedly.
Example
Declare
i number(2);
Begin
i :=1;
Loop
Dbms_output.put_line (i);
Exit when i=100;
i:=i+1;
end loop;
end;
The while loop
This loop is used to execute a set of PL/SQL codes whenever the
given condition is true. It is false control is transferred to next statement.
Syntax
While <condition>
Loop
Statement
End loop;
63
Ex:
while i<=100
loop
dbms_output.put_line(i);
i:=i+1;
end loop;
---
The FOR Loop
For variable in [REVERSE] startno ..end no
Loop
Statements block;
End loop;
For i in 10 ..20
Loop
Dbms_output.put_line(i);
End loop;
for I in reverse 10 .. 20
loop
Dbms_output.put_line(i);
End loop;
Factorial
declare
n number := &n;
i number :=1;
fact number:=1;
begin
for i in 1..n
loop
fact := fact * i;
end loop;
dbms_output.put_line('the result is ' ||fact);
end;
nCr expansion
64
declare
n number := &n;
r number :=&r;
x number:=1;
y number:=1;
res number:=1;
i number:=1;
begin
for i in 1..r
loop
x:=x*n;
n:=n-1;
y:=y*i;
end loop;
res:=x/y;
dbms_output.put_line('the result is ' ||res);
end;
Goto statement
Sy
Goto label;
<<label>>
ex
goto 10;
<<10>>
Merging Rows
The MERGE statement inserts or updates rows in one table, using data
from another table. Each row is inserted or updated in the target table, depending
upon an equijoin condition.
The example shown matches the eno in the copy_emp1 table to the eno in the
emp1 table. If a match is found, a row is updated to match the row in the emp1
table. If the row is not found, it is inserted into the copy_emp1 table.
Declare
65
v_eno emp1.eno%type := 7499;
begin
merge into copy_emp1 c
using emp1 e
on (c.eno=v_eno)
when matched then
update set
c.eno = e.eno,
c.ename =e.ename,
c.sal = e.sal
when not matched then
insert values (e.eno,e.ename,e.sal);
end;
Exception
An error is an abnormal condition that arises during the execution of a
program.
In PL/SQL block, an error condition called as Exception
Exceptions can be broadly classified into :
• Pre-defined Exception
• User – defined Exception
• Undefined Exception
Pre – defined Exceptions
It is already defined in Oracle.
Exception Raised when
ACCESS_INTO_NULL User tries to assign values to the
attributes of an uninitialized
(automatically null) object.
NO_DATA_FOUND Refer in book
ZERO_DIVIDE User tries to divide a number by zero
OTHERS Common Exception handling
Example
DECLARE
X NUMBER :=&X;
66
Y NUMBER:=&Y;
BEGIN
DBMS_OUTPUT.PUT_LINE(‘RESULT IS ‘||X/Y);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE(‘VALUE IS DIVIDED BY ZERO’);
END;
Example -2
Declare
myename varchar2(20);
begin
select ename into myename from emp where empno=&x;
dbms_output.put_line(‘the name of the employee is ‘ ||myename);
exception
when no_data_found then
dbms_output.put_line(‘no record’);
end;
Example 3
Declare
mysal number;
begin
select sal into mysal from emp where deptno=10;
dbms_output.put_line(mysal);
exception
when too_many_rows then
dbms_output.put_line(‘use cursors’);
end;
Example 3
Declare
mysal number;
begin
select sal into mysal from emp where deptno=&x;
dbms_output.put_line(mysal);
exception
when too_many_rows then
dbms_output.put_line(‘use cursors’);
when others then
dbms_output.put_line(‘other exception’);
end;
User Defined Exception
67
PL/SQL allows users to define their own exceptions. Unlike predefined
exceptions, user defined exceptions must be declared exceptions and can be raised
using one of the following :
• RAISE
• RAISE_APPLICATION_ERROR
RAISE
In the case of user defined exception, the following three steps must be
performed:
• declare the exception
• Raise the exception
• Handle the exception
Declaring exception
Exceptions are declared in the declarative part of a PL/SQL block.
Declare
myex EXCEPTION;
Raising Exceptions
RAISE myex;
Handling Exceptions
When myex then
Example
Declare
eno number:=&no;
name varchar2(20):=‘&b’;
salary number:=&p;
salary_ex exception;
begin
if salary>50000 then
raise salary_ex;
else
insert into sala(no,name,sal)values(eno,name,salary);
end if;
exception
when salary_ex then
dbms_output.put_line(‘Salary exceeds 50000’);
end;
68
RAISE_APPLICATION_ERROR
Raise_Application_error stops the program and terminates the block
abruptly. Raise_Application_Error is primarily used in triggers to rollback the
transaction and give suitable error messages. The syntax
RAISE_APPLICATION_ERROR (errornumber,MESSAGE);
Where the error messages span between -20000 and -20999. Message is a
character data that can hold upto 2000 bytes.
Declare
empid number :=&empid;
curr_sal Number;
inc number:=&inc;
begin
select salary into curr_sal from employe where empno=empid;
if curr_sal is null then
raise_application_error(-20101,’Salary missing’);
else
update employe set salary=curr_sal+inc where empno=empid;
end if;
exception
when NO_DATA_FOUND then
raise_application_error(-20000,’no matching record’);
end;
CURSORS - is a private SQL work area.
Processing of SQL statements in ORACLE
When a user fires an SQL statement, Oracle executes the SQL statement as
follows.
i) First oracle reserves a location in the main memory, which is called private
SQL area.
ii) Secondly, the private SQL area is populated with the data pertaining to the SQL
statement.
iii) Thirdly the populated data are processed by the Oracle as per the SQL
statement.
iv) Finally Oracle clears the memory area as soon as the execution is completed.
69
CURSOR
Defn: A cursor is defined as the work area in memory where oracle stores
the data while executing the current SQL statement.
Whenever you issue a SQL statement, the Oracle server opens an area of
memory in which the command is parsed and executed. This area is called a
cursor.
Active set
The set of all data stored in a cursor is called the active data set.
Row pointer
Oracle maintains a row pointer along with the rows in the cursor, if a query
returns multiple records. Using this row pointer we can locate the desired row in
the active data set.
Use of cursors in PL/SQL
Cursors can be used in effectively in PL/SQL. if a set of records selected
from a table by means of a query has to be processed , then we must use explicit
cursor .
Types of cursors
There are two types of cursors .They are
1. Implicit cursor
2. Explicit cursor
Implicit cursor
Each DML statement creates an implicit cursor, including the select
statement that returns only one row we need no declare such cursor.
SQL cursor Attributes
SQL%ROWCOUNT No. of rows affected by most recent SQL statement ( an
integer value)
SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL
statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent
SQL statement does not affect any rows.
70
SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes implicit
cursors immediately after they are executed.
example - gpcur1.sql
variable rowd varchar2(30);
declare
dep emp.deptno%type :=&dep;
begin
select * from emp where deptno=dep;
:rowd :=(SQL%ROWCOUNT ||’rows displayed’);
end;
/
print rowd;
Explicit Cursor
Apart from implicit cursors, we can also define cursors explicitly. cursors
declared by a user explicitly are called explicit cursors.
Explicit cursor management
The following are the various steps involved in explicit cursor management.
1. Declaring a cursor
2. Opening the cursor
3. fetching individual row one at a time
4. closing the cursor
1. Declaring a cursor
In PL/SQL , a cursor must be declared in the declaration section like any
other variables.
syntax :
cursor <cursor_name> is select ..
Example
cursor dc is select deptno,dname,loc from dept;
2. Opening the cursor
The active data is created when the cursor is opened. OPEN statement is
used to open a cursor.
Syntax open <cursor_name>;
71
Example
open dc;
3. Fetching a record from the cursor
The active data set is defined when the cursor is declared. The
records are placed in the cursor when the cursor is opened. The records are
retrieved from the active set using the FETCH statement one by one.
FETCH Statement
FETCH statement retrieves the current record in the active set and
moves the row pointer to the next row.
Syntax :
FETCH <cursor_name> INTO var1, var2 ….
fetch dc into dno,dna,lo;
Closing a cursor
The system resources used by a cursor are freed when the cursor is
closed. Further, if we try to open a cursor which is already opened. Oracle
displays an error message.
close statement
cursor is closed using the CLOSE statement.
Syntax
CLOSE <cursor_name>;
Example
close dc;
example for cursor
declare
dno number(3);
dna varchar2(20);
lo varchar2(20);
cursor dc is select deptno,dname,loc from dept;
begin
open dc;
loop
fetch dc into dno,dna,lo;
exit when dc%notfound;
dbms_output.put_line(‘deptno -->‘||dno ||’dname-->‘||dna ||’location--->‘||lo);
end loop;
close dc;
72
end;
/
Explicit cursor attributes
1. %NOT FOUND
usage: <cursor_name>%NOT FOUND is TRUE if the FETCH statement
does not retrieve a row and FALSE if the FETCH statement retrieves a row.
This is very useful to check whether the active data set is empty and all the
rows in the cursor are processed.
2. %FOUND
Usage : <cursor_name>%FOUND is TRUE if the FETCH statement
retrieves a row and FALSE if it doesn’t.
3. %ROWCOUNT
Usage : <cursor_name>%ROWCOUNT returns the number of rows
fetched from the active data set. Its value is zero when the cursor is opened.
4. %ISOPEN
Usage :<cursor_name>%ISOPEN returns TRUE if the cursor is already
open.
This is very useful to check whether the cursor is already open
before opening the cursor.
Example
create table sales(ino number(5),iname varchar2(20),iprice number(6,2));
create table bill(bno number(5),bname varchar2(20),bprice number(6,2));
insert into sales values(101,’pen’,20.00);
insert into sales values(102,’pencil’,25.00);
insert into sales values(103,’box’,500.00);
declare
cursor cur_s is select * from sales;
no number(5);
name varchar2(20);
price number(6,2);
begin
open cur_s;
loop
73
fetch cur_s into no,name,price;
exit when cur_s%NOTFOUND;
insert into bill values(no,name,price);
end loop;
close cur_s;
end;
Cursor and records
Using %ROWTYPE attribute provides a record type that represents a row
in a table. The variable declared as this type can store an entire row of data
selected from the table of fetched from a cursor. This type is used in cases where
al the column names need to be retrieved from the table.
Example:
declare
cursor c1 is select * from emp;
erec emp%rowtype;
begin
open c1;
loop
fetch c1 into erec;
exit when c1%NOTFOUND;
dbms_output.put_line(erec.ename||’ is a ‘||erec.job||’ and earns ‘||erec.sal);
end loop;
close c1;
end;
example 2:
declare
cursor mycur is select * from sales;
code number(6);
items varchar2(20);
prices number(6,2);
date2 date;
dates date;
begin
open mycur;
date2:=‘&date2’;
loop
fetch mycur into code,items,prices,dates;
74
if dates=date2 then
insert into billing values(code,items,prices,dates);
end if;
exit when mycur%NOTFOUND;
end loop;
close mycur;
end;
Cursor FOR loops
Syntax
FOR record_name IN Cursor_name LOOP
Statement 1
Statement 2
Statement 3
END LOOP;
 The Cursor FOR loop is a shortcut to process explicit cursors.
 Implicit open, fetch , exit and close cursor.
 The record is implicitly declared.
Example
declare
cursor emp_cursor is select ename,deptno from emp;
begin
for emp_record in emp_cursor
Loop
if emp_record.deptno=20 then
dbms_output.put_line(' Employee '|| emp_record.ename||
'work in software dept.');
end if ;
end loop;
end;
Cursor FOR loops Using Subqueries
When you use a subquery in a FOR loop, you do not need to declare a cursor.
begin
for emp_record in (select ename,deptno from emp)
Loop
if emp_record.deptno=20 then
dbms_output.put_line(' Employee '|| emp_record.ename||
'work in software dept.');
75
end if;
end loop;
end;
Cursor with Parameters
You can pass parameters to the cursor in a cursor FOR loop. This means
that you can open and close an explicit cursor several times in a block, returning a
different active set on each occasion. For each execution, the previous cursor is
closed and re-opened with a new set of parameters.
Syntax
CURSOR cursor_name
[ (parameter_name datatype, …)]
IS
Select Statement ;
OPEN cursor_name (parameter_value,….);
Example
declare
v_no number;
v_name varchar2(30);
cursor emp_cur (p_no number)
is
select no, name from employe where no=p_no;
begin
open emp_cur(102);
loop
fetch emp_cur into v_no,v_name;
exit when emp_cur%NOTFOUND;
dbms_output.put_line('No : '||v_no || 'Name : '||v_name);
end loop;
close emp_cur;
end;
Cursor with For update clause
FOR UPDATE
The FOR UPDATE clause identifies the rows that will be updated or deleted,
and then locks the rows in the result set.
Syntax
76
Select … from tablename FOR UPDATE [OF column _reference][NOWAIT]
WHERE CURRENT OF clause
Syntax WHERE CURRENT OF cursorname
(i.e) When referencing the current row from an explicit cursor, use WHERE
CURRENT OF clause. This allows you to apply updates and deletes to the row
currently being addressed, without the need to explicitly reference the ROWID.
Example
declare
cursor c1 is select * from emp for update;
cursor c2 is select * from emp;
begin
for emp_rec in c1
loop
if emp_rec.job='MANAGER' then
update emp set sal=sal+500 where current of c1;
update emp set sal=sal+500 where empno=emp_rec.empno;
elsif emp_rec.job='CLERK' then
update emp set sal=sal+200 where current of c1;
end if;
end loop;
for erec in c2
loop
dbms_output.put_line(erec.ename || ' Now earns '||erec.sal);
end loop;
end;
SUBPROGRAMS
Subprograms are named PL/SQL blocks that can take parameters and be
invoked. PL/SQL has two types of subprograms called procedures and functions
Benefits of Subprograms
- Easy maintenance that enables you to modify:
 Routines online without interfering with other users
 One routine to affect multiple applications
 One routine to eliminate duplicate testing.
- Improved data security and integrity by doing the following:
77
 Control indirect access to database objects from nonprivileged users
with security privileges.
 Ensure that related actions are performed together , or not at all, by
funneling activity for related tables through a single path.
- Improved performance that allows you to do the following
 Avoid reparsing for multiple users by exploiting the shared SQL area.
 Avoid PL/SQL parsing at run time by parsing at compilation time.
 Reduce the number of calls to the database and decrease network traffic
by bundling commands.
- Improved code clarity:
 Using appropriate identifier names to describe the action of the routines
reduces the need for comments and enhances the clarity of the code.
PROCEDURES
 Procedure is a subprogram that performs a specific action.
 A procedure is named PL/SQL block that can accept parameters and
perform an action
Advantages
 Reusability: it is enough to just revoke the appropriate procedure or
function whenever required. We need not write the entire coding.
 Modularity: Using procedures and functions are program can be divided
into small manageable sub programs.
 Performance: Since the procedures and functions are stored along with
the server, the performance is improved.
 Modify one routine to affect multiple applications
 As a subprogram is executed with its definer’s right by default, it is
easy to restrict the access privilege by granting a privilege only to
execute the subprogram to a user.
 After a subprogram is compiled, the parsed code is available in the
shared SQL area of the server and subsequent calls to the subprogram
use this parsed code. This avoids reparsing for multiple users.
Syntax
CREATE OR REPLACE PROCEDURE <procedurename>
[(argument [IN| OUT|INOUT] datatype
[,(argument [IN| OUT|INOUT] datatype]
…
{ IS | AS }
78
variable datatype;
begin
PL/SQL coding (executing part)
exception
exception part
end;
where
CREATE OR REPLACE PROCEDURE -- creates new procedure or replace
exist procedure
argument -- Variable used to input and retrieve parameters.
IN - Specifies that a value for the argument must be given when
the procedure is invoked
OUT -- Specifies that a value is passed to this argument and we can get the
values through this argument.
INOUT -- Specifies that a value for the argument must be given when invoking
the procedure and procedure passes a value for the argument.
datatype -- it is datatype for argument Example number, varchar2
note
1) IN , OUT , INPUT are called qualifiers of the arguments . The
default qualifier is IN.
2) A procedure may have no argument
execute a procedure
exec procedurename(argumentvalue)
Example
create or replace procedure dispe (eno in number default 7499) is
mn varchar2(20);
begin
select ename into mn from emp where empno=eno;
dbms_output.put_line(‘The name is ‘||mn);
end;
Example
exec dispe(7698)
79
exec dispe()
here the procedure take default argument as input.(i.e 7499).
invoke procedure in another PL/SQL program
declare
en number:=&en;
begin
dispe(en);
end;
/
Example - out parameter
create or replace procedure disps(eno in number,sal out number)
as
mn varchar2(20);
begin
select sal,ename into sal,mn from emp where empno=eno;
dbms_output.put_line(‘the employee name is ‘||mn);
end;
accessing the previous procedure
declare
sa number;
begin
disps(7698,sa);
dbms_output.put_line(‘the salary of the person ‘||sa);
end;
/
Example of IN OUT parameter
create or replace procedure espn(num IN OUT number) as
begin
select sal into num from new1 where no=num;
end;
accessing in IN OUT
declare
num number:=&no;
begin
espn(num);
80
dbms_output.put_line (‘the result is’||num);
End;
Nested Procedure and Exception handling
create or replace procedure proc1
is
procedure proc2
is
v_a number :=10;
v_b number :=0;
begin
dbms_output.put_line('This is inner procedure');
dbms_output.put_line('the result ' || v_a/v_b);
exception
when zero_divide then -- inner proc2 handles the exception
if suppose it will not handle this error in prco2, it will be handled in proc1
exception block
dbms_output.put_line(' exception in proc2 inner');
end proc2;
begin
dbms_output.put_line('this is outer procedure');
proc2;
exception
when ZERO_DIVIDE then
dbms_output.put_line('exception in proc1 outer');
end proc1;
Drop procedure
Drop procedure procedurename;
Example
Drop procedure espn;
Functions
• A function is a subprogram that computes a value.
• A function is a named PL/SQL block that can accept argument and return a
value to the caller. The value is returned using keyword RETURN with in
the function.
• A function can return only one value while a procedure can return any
number of values through OUT parameters.
81
Advantages of functions
 It promotes security
 It improves the performance of the database
 It minimizes the use of system resources (memory)
 It increases the productivity of application program
 It enhances the integrity of programs
Security
Users may be permitted to access data only through functions and not
permitted to access the table.
Performance
Since functions are loaded in the shared pool of the System Global
Area(SGA). They are not retrieved from the list and hence the speed of the
execution is very fast.
note : function cannot be called using EXEC statement.
Example
create or replace function getname(eno in number) return varchar2
is
name varchar2(20);
begin
select ename into name from emp where empno=eno;
return name;
end;
Calling function
select getname(7698) from dual;
Calling a function in PL/SQL program
declare
no number:=&no;
v_name varchar2(200);
begin
dbms_output.put_line(‘the name of the person is’||getname(no)); --function
82
v_name := getname(no);
calling
end;
Normally a function is used to compute specific values. They are not meant to
perform any DML operations on the table. For Example if a function tries to
insert a record onto a table, Oracle throws an error.
The function has to satisfy some purity levels for performing any DML
operations. Purity Level determines to what extent the function does not do any
alterations to the database object.
The four levels of purity levels are shown in the following table.
Purity Level Expansion Description
WNDS Write No Database State Function does not
perform any DML
operations on tables.
RNDS Read No Database State Reading is restricted from
any table.
RNPS Read No Package State Functions must not alter
any packaged variables
WNPS Write No Package State Function cannot write
onto any package
variable.
Depending on the purity level, a function is restricted to the following restrictions
1. A function callable from a SELECT statement must not perform any
operation to any tables.
2. Functions can take only IN parameter and not OUT and IN OUT .
3. Return type of a function must be a database type.
Notations
When calling a subprogram, the actual parameters are written using either
positional or named notation. That is , the association between an actual and
formal parameter can be indicated by position or name. for Example , given the
declarations
Example
83
create or replace function getsal(fno number,fname varchar2) return number
is
saly number;
begin
select sal into saly from sala where no=fno and name=fname;
return saly;
end;
select getsal(12,’praveen’) from dual;
Positional notation
The function call uses positional notation. The PL/SQL compiler associates the
first actual parameter, no with the first formal parameter fno. And, the compiler
associates the second actual parameter, na with the second formal parameter,
fname
declare
no number:=&no;
na varchar2(30):=‘&name’;
begin
dbms_output.put_line(‘the salary of the person is’||getsal(no,na));
end;
Named notation
This function uses the named notation. The arrow (called an association
operator) associates the formal parameter to the left of the arrow with the actual
parameter to the right of the arrow.
declare
no number:=&no;
na varchar2(30):=‘&name’;
begin
dbms_output.put_line(‘the salary of the person is’|| getsal (fno=>no,
fname=>na));
end;
Mixed notation
declare
84
no number:=&no;
na varchar2(30):=‘&name’;
begin
dbms_output.put_line(‘the salary of the person is’||getsal(no,fname=>na));
end;
dbms_output.put_line(‘the salary of the person is’||getsal(fno=>no,na)); --illegal
Viewing Procedures and functions
Procedures and functions are viewed using the data_dictionary views:
SELECT *FROM USER_SOURCE;
Drop function
Drop function functionname;
Example
Drop function getsal;
TRIGGERS
A stored procedure that is fired implicitly whenever the data in the
associated table are changed is called a trigger.
Introduction
Oracle enables us to define triggers that are executed automatically
whenever a row is inserted into a table or an existing row updated or deleted.
while other procedures are to be called explicitly for execution , triggers are
executed implicitly by Oracle.
Use of Database Triggers
 A trigger can be used to avoid invalid transaction
 A trigger can be used to keep duplicate data.
 A trigger can be used to audit changes to data in table.
(i.e store the particulars of the modified and deleted rows in a separate
table).
 A trigger can be used to enforce additional referential integrity.
 A trigger can be used to enforce complex business rules.
85
Parts of Triggers
A database trigger has three parts.
They are
1. Triggering statement
2. Trigger restriction
3. Trigger action
Triggering statement
The SQL statement that includes the trigger is called the triggering
statement. it may be any DML statement (INSERT , UPDATE or DELETE).
Trigger Restriction
This is optional.This is available for triggers that are fired for each row. The
trigger is fired only if this condition is true.
Trigger Action
The PL/SQL block executed when a trigger is fired is called trigger action.
here triggering restriction is true.
Types of Triggers
Triggers are classified into different types depending on when the trigger is to be
fired.
They are
• Before
• After
• INSTEAD OF
BEFORE / AFTER
The BEFORE option of a trigger is used to specify when the trigger must
be fired. if the option BEFORE is chosen. The trigger is fired before the
triggering statement is executed. In case of AFTER the trigger is fired after
executing the statement.
BEFORE
 Before triggers are used when the triggering action determines whether
the triggering statement must be allowed to be completed or not.
 To derive the values of a specific column before the execution of the
triggering statement(INSERT or UPDATE).
86
AFTER
 AFTER triggers execute the trigger action after the execution of the
triggering statement.
 To perform the trigger action immediately after the execution of
triggering statement.
 if there is already a BEFORE trigger, we can use the AFTER trigger to
perform a different action.
Based on how many records are to be affected by the trigger, triggers can
be classified as :
o ROW level
o Statement level
Row level triggers
These types of triggers are fired for each row that I affected by the
triggering statement. for example UPDATE statement for multiple rows of a
table. In this case , the ROW level triggers are executed for every row that is
affected by the UPDATE statement.
Statement level triggers
A trigger that is fired only once for the execution of the triggering statement
is called a statement trigger.
Syntax for creating triggers
CREATE OR REPLACE TRIGGER <trigger_name>
[BEFORE / AFTER]
[INSERT/DELETE/UPDATE]
ON <tablename>
[FOR EACH ROW]
[WHEN <condition>]
keywords and parameters
CREATE OR REPLACE -- create new one or replacing existing one.
<trigger_name> -- name of the trigger
BEFORE -- indicates that Oracle fires the triggers before the execution of the
triggering statement
87
AFTER -- indicates that Oracle fires the triggers after the execution of the
triggering statement
[INSERT/DELETE/UPDATE] – when the trigger fires i.e which statement
<tablename> -- specifies the name of the table
FOR EACH ROW – specifies that the trigger fires at row level.
WHEN -- Restricts the trigger to fire when the condition true.
Example1
create or replace trigger insdept before insert on dept
begin
dbms_output.put_line(‘inserting records’);
end;
example2
create or replace trigger insemp before insert on sales
declare
x number;
begin
select count(*) into x from sales;
dbms_output.put_line(x+1 ||’Number of records are available’);
end;
Accessing column values
When a trigger action or the trigger body contains statements that require
access to the table values or for checking the new value with the old value.
Two correlation names are used  :new , :old
:new  refers to the new values entered in the trigger statement
:old  refers to the old existing values in the table.
These are also called as pseudorecords since they do not contain any permanent
record.
Statement :new :old
Insert New values entered in the
Insert command
Null
Update New values entered in Old values available in
88
Update statement the table
Delete Null Old Values in the table
example3
create or replace trigger insdep after insert on dept for each row
BEGIN
DBMS_OUTPUT.PUT_LINE(:new.deptno || ‘ ‘ || :new.dname || ‘ ‘
||:new.loc);
End;
Insert into dept values (12, ‘sales’, ‘chennai’);
This trigger when sal exceed
create or replace trigger chksal after insert on emp1 for each row
begin
if not(:new.job='MANAGER' AND (:new.sal>4000 and :new.sal<6000)) then
raise_application_error(-20000,'manager salary cannot exceed 8000 and
cannot be less than 4000');
end if;
end;
/
example the number less than 100 trigger executed no insert ,update
create or replace trigger checkn before insert or update on trigg
for each row
when (new.num<100)
begin
raise_application_error(-20001,'sorry number not a valid');
end;
/
Here set trigger in particular column (no in g4 table)
create or replace trigger chekno before insert or update of no on g4
for each row
when (new.no<100)
begin
raise_application_error(-20002,'number not a valid');
end;
/
Packages
A package is a schema object that groups logically PL/SQL types, items
and sub programs.
89
Understanding packages
Packages are usually have two parts, a specification and a body, although
sometimes the body is unnecessary. The specification is the interface to your
applications: it declares the types, variables, constants, exceptions cursors and
subprograms available for use.the body fully defines cursors and subprograms,
and so implements the specification
Package specification
The package specification contains public declarations. The scope of these
declarations is local to the database schema and global to the package. So, the
declared items are accessible from the application and from anywhere in the
package.
The specification lists the package resources available to applications. All
the information that the application needs to use is in the specification.
Format of package
CREATE OR REPLACE PACKAGE package_name
IS | AS
Public type and item declarations
Sub program specifications
END package_name;
The following points needs to be noted about the above syntax
• REPLACE keyword which is optional drops or recreates the package
specification.
• All the constructs declared in a package specification are visible to users
who are granted privileges on the package.
• Variables declared in the package specification are initialized to NULL
by default.
The package specification can be divided into three parts. They are
• Package_name – declares the name of the package
• Public type and item declarations – declares variables,
constants,cursors,exception of types.
• Subprogram specifications – declare the PL/SQL subprograms
Example
90
This is example creates a package specification
create or replace package packdemo is
message varchar2(25) := ‘Divide by zero’;
end;
example – using procedure we access the package message
create or replace procedure packproc(x number, y number, c char) is
begin
if c=‘+’ then
dbms_output.put_line(‘Added :’ ||to_char(x+y));
elsif c=‘-’ then
dbms_output.put_line(‘Sub :’ ||to_char(x-y));
elsif c=‘/’ then
dbms_output.put_line(‘division :’ ||x/y);
end if;
exception
when ZERO_DIVIDE then
dbms_output.put_line(packdemo.message);
end;
/
Package Body
The package body implements the package specification. That is the package
body contains the definition of every cursor and sub programs declared in the
package specification.
The package body can also contain private declarations. Which define types
and items necessary for the internal workings of the package. The scope of
these declarations is local to the package body.
example
SQL> create or replace package gppdemo is
2 procedure getdetails(enos number);
3 end gppdemo;
4 /
Package created.
Package Body
91
SQL> create or replace package body gppdemo is
2 procedure getdetails(enos number) is
3 eno number(4);
4 empname varchar2(50);
5 jobs varchar2(50);
6 mgrs varchar2(25);
7 hdate date;
8 sals number(12,2);
9 comms number(12,2);
10 dno number(5);
11 begin
12 select empno,ename,job,mgr,hiredate,sal,comm,deptno into
13 eno,empname,jobs,mgrs,hdate,sals,comms,dno from emp where
empno=enos;
14 dbms_output.put_line(‘Ename: ‘||empname);
15 dbms_output.put_line(‘Job : ‘||jobs);
16 dbms_output.put_line(‘Mgr : ‘||mgrs);
17 dbms_output.put_line(‘HireDate: ‘||hdate);
18 dbms_output.put_line(‘Salary :’||sals);
19 if comms is null then
20 dbms_output.put_line(‘Commission : NULL’);
21 else
22 dbms_output.put_line(‘Commission :’||comms);
23 end if;
24 dbms_output.put_line(‘Deptno :’||dno);
25 exception
26 when no_data_found then
27 dbms_output.put_line(‘Data Not found’);
28 when others then
29 dbms_output.put_line(‘Some Error’);
30 end getdetails;
31 end ;
32 /
Package body created.
92
SQL> exec gppdemo.getdetails(7566);
Ename: JONES
Job : MANAGER
Mgr : 7839
HireDate: 02-APR-81
Salary :2975
Commission : NULL
Deptno :20
PL/SQL procedure successfully completed.
Ex 2
create or replace package billdata is
procedure billinsert(bn number,bna varchar2,bpr number);
procedure billdelete(bn number);
end;
create or replace package body billdata is
message varchar2(50) := ‘The given number is not found’;
procedure billinsert(bn number,bna varchar2,bpr number) is
begin
insert into bill values(bn,bna,bpr);
end;
procedure billdelete(bn number) is
begin
delete from bill where bno=bn;
exception
when NO_DATA_FOUND then
dbms_output.put_line(message);
end;
end;
/
SQL> exec billdata.billinsert(12,’gff’,67);
PL/SQL procedure successfully completed.
SQL> exec billdata.billdelete(1076);
PL/SQL procedure successfully completed.
93
Create or replace package hrpackage is
Procedure getname(eno number);
Function gettotalpay(eno number);
Procedure getdetails(eno number);
End hrpackage;
create or replace package body hrpackage1 is
procedure getname(eno number) is
empname varchar2(25);
begin
select ename into empname from emp where empno=eno;
exception
when no_data_found then
dbms_output.put_line(‘Data Not found’);
when others then
dbms_output.put_line(‘Some Error’);
end;
function gettotalpay(empnos number) return number is
totals number;
begin
select sal+nvl(comm,0) into totals from emp where empno=empnos;
return totals;
exception
when no_data_found then
dbms_output.put_line(‘Data Not found’);
when others then
dbms_output.put_line(‘Some Error’);
end;
procedure getdetails(enos number) is
eno number(5);
empname varchar2(50);
jobs varchar2(50);
mgrs varchar2(25);
hdate date;
sals number(12,2);
comms number(12,2);
dno number(5);
begin
select empno,ename,job,mgr,hiredate,sal,comm,deptno into
eno,empname,jobs,mgrs,hdate,sals,comms,dno from emp where wmpno=enos;
dbms_output.put_line(‘Ename: ‘||empname);
94
dbms_output.put_line(‘Job : ‘||jobs);
dbms_output.put_line(‘Mgr : ‘||mgrs);
dbms_output.put_line(‘HireDate: ‘||hdate);
dbms_output.put_line(‘Salary :’||sals);
if comms is null then
dbms_output.put_line(‘Commission : NULL’);
else
dbms_output.put_line(‘Commission :’||comms);
end if;
dbms_output.put_line(‘Deptno :’||dno);
exception
when no_data_found then
dbms_output.put_line(‘Data Not found’);
when others then
dbms_output.put_line(‘Some Error’);
end;
end;
/
95
REF Cursors
A REF Cursor is a datatype that holds a cursor value in the same way that a VARCHAR2 variable will
hold a string value.
A REF Cursor can be opened on the server and passed to the client as a unit rather than fetching one
row at a time. One can use a Ref Cursor as target of an assignment, and it can be passed as
parameter to other program units. Ref Cursors are opened with an OPEN FOR statement. In most
other ways they behave similar to normal cursors.
-- Strongly typed REF CURSOR.
DECLARE
TYPE t_ref_cursor IS REF CURSOR RETURN cursor_variable_test%ROWTYPE;
c_cursor t_ref_cursor;
l_row cursor_variable_test%ROWTYPE;
BEGIN
DBMS_OUTPUT.put_line('Strongly typed REF CURSOR');
OPEN c_cursor FOR
SELECT *
FROM cursor_variable_test;
LOOP
FETCH c_cursor
INTO l_row;
EXIT WHEN c_cursor%NOTFOUND;
DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description);
END LOOP;
CLOSE c_cursor;
END;
/
-- Weakly typed REF CURSOR.
DECLARE
TYPE t_ref_cursor IS REF CURSOR;
c_cursor t_ref_cursor;
l_row cursor_variable_test%ROWTYPE;
BEGIN
DBMS_OUTPUT.put_line('Weakly typed REF CURSOR');
OPEN c_cursor FOR
SELECT *
FROM cursor_variable_test;
LOOP
FETCH c_cursor
INTO l_row;
EXIT WHEN c_cursor%NOTFOUND;
96
DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description);
END LOOP;
CLOSE c_cursor;
OPEN c_cursor FOR
SELECT *
FROM emp;
LOOP
FETCH c_cursor
INTO l_row;
EXIT WHEN c_cursor%NOTFOUND;
DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description);
END LOOP;
CLOSE c_cursor;
END;
/
++++++++++++++
Table Type – Sample Package
Package Spec
create or replace package xxgp_type_test_pkg
is
TYPE t_gptest_rec_type IS RECORD (
EMPNO NUMBER(4) ,
ENAME VARCHAR2(10 BYTE),
JOB VARCHAR2(9 BYTE),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2)
);
TYPE t_gptest_tab IS TABLE OF t_gptest_rec_type;
procedure p_emp_insert ( p_gptest_tab IN t_gptest_tab);
end xxgp_type_test_pkg;
Package Body
create or replace package body xxgp_type_test_pkg
is
97
procedure p_emp_insert ( p_gptest_tab IN t_gptest_tab)
is
begin
for i in p_gptest_tab.FIRST..p_gptest_tab.LAST
LOOP
insert into empgp (EMPNO ,
ENAME ,
JOB ,
MGR ,
HIREDATE ,
SAL ,
COMM ,
DEPTNO ) values
( p_gptest_tab(i).EMPNO,
p_gptest_tab(i).ENAME ,
p_gptest_tab(i).JOB ,
p_gptest_tab(i).MGR ,
p_gptest_tab(i).HIREDATE ,
p_gptest_tab(i).SAL ,
p_gptest_tab(i).COMM ,
p_gptest_tab(i).DEPTNO );
commit;
END LOOP;
end p_emp_insert;
end xxgp_type_test_pkg;
Sample Execution Script
declare
l_gptest_tab apps.xxgp_type_test_pkg.t_gptest_tab;
begin
-- Value Passing to Table Type 
l_gptest_tab := apps.xxgp_type_test_pkg.t_gptest_tab();
l_gptest_tab.extend(3); -- To Mention How many records going to
insert
l_gptest_tab(1).empno := 8000 ;
l_gptest_tab(1).ename := 'Praveen';
l_gptest_tab(1).job := 'Job';
l_gptest_tab(1).mgr := NULL;
l_gptest_tab(1).hiredate := TRUNC(SYSDATE);
l_gptest_tab(1).sal := 10000;
98
l_gptest_tab(1).comm := NULL;
l_gptest_tab(1).deptno := 20;
l_gptest_tab(2).empno := 8001 ;
l_gptest_tab(2).ename := 'Rahul';
l_gptest_tab(2).job := 'Job';
l_gptest_tab(2).mgr := NULL;
l_gptest_tab(2).hiredate := TRUNC(SYSDATE);
l_gptest_tab(2).sal := 12000;
l_gptest_tab(2).comm := NULL;
l_gptest_tab(2).deptno := 20;
l_gptest_tab(3).empno := 8002 ;
l_gptest_tab(3).ename := 'Vasanth';
l_gptest_tab(3).job := 'Job';
l_gptest_tab(3).mgr := NULL;
l_gptest_tab(3).hiredate := TRUNC(SYSDATE);
l_gptest_tab(3).sal := 11000;
l_gptest_tab(3).comm := NULL;
l_gptest_tab(3).deptno := 30;
-- Here l_gptest_tab contains 3 records. It passed as parameter to
store in table
apps.xxgp_type_test_pkg.p_emp_insert ( l_gptest_tab );
commit;
end;
99
Sample Example Type and Bulk Collect
INTO
DECLARE
TYPE t_gptest_rec_type IS RECORD (
EMPNO NUMBER(4) ,
ENAME VARCHAR2(10 BYTE),
JOB VARCHAR2(9 BYTE),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2)
);
TYPE t_gptest_tab IS TABLE OF t_gptest_rec_type;
TYPE t_gptest_rec_type1 IS TABLE OF empgp%ROWTYPE;
l_gptest_tab t_gptest_tab ;
l_start NUMBER;
BEGIN
SELECT *
BULK COLLECT INTO l_gptest_tab
FROM empgp;
DBMS_OUTPUT.put_line('Total Records :' || l_gptest_tab.count ) ;
FOR i IN l_gptest_tab.FIRST..l_gptest_tab.LAST
LOOP
DBMS_OUTPUT.put_line(i||'- Employee Details :'||
l_gptest_tab(i).empno ||' - '||l_gptest_tab(i).ename);
END LOOP;
END;
/
100
Introduction to iSQL
iSQL * Plus is an Oracle tool that recognizes and submits SQL statement to
the Oracle server for execution. iSQL * Plus contains its own language.
Following are features of iSQL * Plus :
• The database is accessed from the browser
• It provides online editing for modifying SQL Statements
• It controls environmental settings
• It formats query results into a basic report
• Local as well as remote databases can be accessed.
The iSQL Interface
The following figure illustrates SQL and iSQL * Plus Interaction
SQL Statements
Using iSQL * Plus the user can perform the following tasks:
 Retrieve, Modify , Insert and Delete data by executing SQL statements
 Script files can be created to store SQL statements that can be run later
 Store the output of a query in a file
 Print query results in the form of reports, perform formatting and
calculation on query results
Formatted
Reports
Client
iSQL Plus Query Results
101
iSQL * Plus
Internet Browser
Oracle Server

More Related Content

PPTX
SQL(DDL & DML)
PPTX
DDL And DML
PPTX
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
PPTX
Presentation slides of Sequence Query Language (SQL)
PPTX
Normal forms
PPT
Introduction to SQL
PPTX
Data models
PPTX
SQL(DDL & DML)
DDL And DML
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
Presentation slides of Sequence Query Language (SQL)
Normal forms
Introduction to SQL
Data models

What's hot (20)

DOC
DB2 utilities
PPTX
SQL - Structured query language introduction
PPTX
Normalization in DBMS
PPTX
Introduction to triggers
PPT
02 Writing Executable Statments
PPT
SQL subquery
PPTX
Sql subquery
PDF
Sql tutorial
PPTX
Sql operator
PPTX
Oracle: Functions
PDF
SQL_NOTES.pdf
DOC
DBMS Practical File
PDF
View & index in SQL
PPTX
PPTX
set operators.pptx
PPTX
Sub query example with advantage and disadvantages
PPTX
Sql - Structured Query Language
DOCX
Complex queries in sql
PPTX
Python programming -Tuple and Set Data type
DB2 utilities
SQL - Structured query language introduction
Normalization in DBMS
Introduction to triggers
02 Writing Executable Statments
SQL subquery
Sql subquery
Sql tutorial
Sql operator
Oracle: Functions
SQL_NOTES.pdf
DBMS Practical File
View & index in SQL
set operators.pptx
Sub query example with advantage and disadvantages
Sql - Structured Query Language
Complex queries in sql
Python programming -Tuple and Set Data type
Ad

Similar to Oracle SQL AND PL/SQL (20)

PDF
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
PPTX
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
PPT
Oracle Sql & PLSQL Complete guide
PDF
dbms lab manual
PPT
Sql tables
PPT
Sql tables
DOC
PPSX
DBMS Chapter-3.ppsx
PDF
Rdbms day3
PPTX
DBMS UNIT-2.pptx ggggggggggggggggggggggg
PDF
PDF
DBMS.pdf
PPTX
introdution to SQL and SQL functions
PDF
CS3481_Database Management Laboratory .pdf
PPTX
SQL LECTURE.pptx
PDF
STRUCTURED QUERY LANGUAGE
PPTX
Fundamentals of Database management system Lab Manual.pptx
PPT
Sql dml & tcl 2
PPTX
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
PPTX
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
Oracle Sql & PLSQL Complete guide
dbms lab manual
Sql tables
Sql tables
DBMS Chapter-3.ppsx
Rdbms day3
DBMS UNIT-2.pptx ggggggggggggggggggggggg
DBMS.pdf
introdution to SQL and SQL functions
CS3481_Database Management Laboratory .pdf
SQL LECTURE.pptx
STRUCTURED QUERY LANGUAGE
Fundamentals of Database management system Lab Manual.pptx
Sql dml & tcl 2
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
Ad

More from suriyae1 (7)

DOCX
List of api in tca
DOCX
Customer account creation API & query
TXT
Create cust acct api
TXT
Api error handling
PPT
Les06 oracle business_intelligence_obiee
DOCX
P2P table
DOCX
Oracle Application Framework
List of api in tca
Customer account creation API & query
Create cust acct api
Api error handling
Les06 oracle business_intelligence_obiee
P2P table
Oracle Application Framework

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Approach and Philosophy of On baking technology
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Electronic commerce courselecture one. Pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Modernizing your data center with Dell and AMD
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Reach Out and Touch Someone: Haptics and Empathic Computing
Network Security Unit 5.pdf for BCA BBA.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Approach and Philosophy of On baking technology
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Monthly Chronicles - July 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Electronic commerce courselecture one. Pdf
Digital-Transformation-Roadmap-for-Companies.pptx

Oracle SQL AND PL/SQL

  • 1. History .................................................................................................................................2 Built in datatypes:........................................................................................................2 Types Of Language.............................................................................................................2 Table creation with timestamp.............................................................................................4 TIMESTAMP WITH TIME ZONE...................................................................................18 CASE Expressions.............................................................................................................62 Cursor FOR loops..............................................................................................................75 Cursor FOR loops Using Subqueries.................................................................................75 Cursor with Parameters......................................................................................................76 Cursor with For update clause..........................................................................................76 WHERE CURRENT OF clause.........................................................................................77 Nested Procedure and Exception handling......................................................................81 1
  • 2. History Oracle stands for Oak Ridge Automatic Computing Logical Engine. The Oracle Corporation was started in 1917 with name ‘Rational Software Incorporated’ (RSI) by Larry Ellison and his associates. During the release of version 3 of Oracle the company changed its name from RSI to Oracle Corporation. Datatypes -- specify the format of data 2 types - built in - user defined Built in datatypes: character datatypes -- char(n) - max size 2000 bytes sy : coln_name datatypes Example : s char(3); varchar2(size) --4000 bytes Example : name varchar2 (30) diff between char and varchar2 char defines entire memory space. But varchar2 it defines only how much we use (i.e name varchar2(30) here we insert data only 15 characters the remaining space will be used to others names In varchar2 doesn’t waste the memory space. numeric datatypes The number datatypes can store numeric values. The precision can range between 1 to 38. number(size) number(p,s) number(3) -- col allows only 3 digit number(5,2) --- it allows 5digits and 2 decimal points -- 100.50 date datatypes date stores 7 bytes DD-MON-YY Example : 23-jun-06 RAW datatype - is used to store binary data –maximum size is 255 bytes. raw(n) long datatype -- it stores upto 2 GB character data long raw datatype -- upto stores 2 GB of Binary data LOB datatypes - LARGE OBJECTS - upto 4GB BLOB - binary LOB CLOB – character LOB NCLOB - national character set data and Unicode data BFILEs are large binary data objects stored in operating system files. Types Of Language  Data Definition Language (DDL) • CREATE – create new table definition • ALTER -- Modifies the existing table definition • DROP -- Removes a table • RENAME -- Change the name of a table 2
  • 3. • TRUNCATE – Delete all the data in a table without removing the Table’s structure  Data Manipulation Language (DML) • INSERT – Add new rows of data into a table or view • UPDATE – Change column values in existing rows of a table or view • DELETE – Removes rows from tables or views • SELECT – Retrieve data from one or more tables or views  Transaction Control Language(TCL) • COMMIT -- Make a transaction ‘s changes permanent • ROLLBACK – Undo the changes in a transaction, either since the Transaction started or since a savepoint • SAVEPOINT – set a point to which you can roll back  Data Control Language(DCL) • GRANT – Gives privileges to other users • REVOKE – Removes privileges from other users DDL Create table command It is used to create a table syn: create table tablename(coln1 datatype,......); Desc -- describe structure Desc tablename; Example : Desc salary; Alter Table Command alter my existing table - it changes your existing table add - it adds new columns alter table tablename add (coln datatype); modify -- it modifies existing column values alter table tablename modify (coln datatype); to drop particular from existing table. alter table emp drop column newsal; Drop Table command 3
  • 4. it delete all record and table. syn  drop table tablename; ex:  drop table emp; truncate command it removes all the records in the particular table syntax: TRUNCATE TABLE <tablename>; Ex: TRUNCATE TABLE praveen; Rename command – to rename the existing table name Syntax RENAME existname TO newname; Example RENAME stud1 TO students; Dropping column You want to drop a particular column by using alter table command Syn: ALTER TABLE <tablebname> DROP<column name>; Ex: Alter table praveen drop sal; Dropping two or more columns  more than one column can be removed from table ex: ALTER TABLE praveen DROP(eno,name); Table creation with timestamp create table temp(name varchar2(20), jdate timestamp, edate date); insert into temp values('praveen',systimestamp, sysdate); create table sam(d date default sysdate,name varchar2(20)); Data Manipulation Language (DML) INSERT command - It is used to add one or more rows to a table. - The values are separated by commas - It can be done different ways :  Inserting records into all fields  Inserting records into selective fields  Continuous insertions 4
  • 5.  Inserting records using SELECT statement 1) Inserting records into all fields Syntax: INSERT INTO <tablename> VALUES (value1,value2,……); Ex: INSERT INTO praveen VALUES (101,’praveen’,’10-mar-2000’,5000); 2) Inserting records into selective fields Syntax : INSERT INTO <tablename> (Column1,column2,..) VALUES (value1,value2,…); Ex: INSERT INTO praveen (no,name) VALUES (102,’kumar’); 3) Continuous insertions it insert record continuously Syntax: INSERT INTO <tablename> VALUES (&column1,’&column2’….); Ex: INSERT INTO praveen VALUES (&no,’&name’); 4) Inserting Records Using SELECT statement insert into jkk3 select empno,ename from emp; insert into jkk4 select empno,ename from emp where deptno=20; insert into sala(no,name) select empno,ename from emp where deptno=40; Update Command  it is used to modify one or a set of records at a time. Syn: UPDATE <tablename> SET column1=value1,column2=value2… [WHERE <condition>]; Ex1 : UPDATE praveen SET deptno=10; Ex2: UPDATE praveen SET sal=5000, name = ‘anand’ where empno=101; Ex3: UPDATE praveen set sal=7000,doj=‘25-JUN-2006’ where doj is NULL: Delete Command It is used to removes all the records from the table. Syntax : DELETE FROM <tablename> WHERE <condition>; Example DELETE FROM employ where deptno=20; - it removes records those who are having 20 as deptno. Example DELETE FROM employ; 5
  • 6.  it removes all the rows. Working with Transactions Two commands are : • COMMIT • ROLLBACK • SAVEPOINT Commit : It used to store data permanently Syntax: Commit; Rollback : It is used get existing data from the buffer. Syntax Rollback; Savepoint - we creates some savepoint for retrieving data from particular point. Sy : savepoint name; Ex: Savepoint s1; Rollback to s1; Select Comand : Select * from <tablename>; Tablename – it is already created table *  it is denotes all columns select * from tab; --- it list all tables and views and synonyms select * from gp2; select ename,sal,job from emp; select ename “Employee name”,sal “SALARY” from emp; Condition Syntax Select * from tablename where <condition>; Ex: Select * from emp where deptno=10; select * from emp where sal>=1250; select * from emp where sal>=1250 and deptno=30; select * from emp where comm is null; select * from emp where ename=‘BLAKE’; Sorting The Data ascending select ename,sal from emp order by sal; 6
  • 7. select ename,sal from emp order by sal asc; descending select ename,sal from emp order by sal desc; copying the structure and records of a Table A new Table created from existing table Syntax Create table <tablename> as select <columnname> from <tablename> [where <condition> ]; Example Create table jkk as select * from emp; Create table jkk1 as select ename,sal from emp; Copying the structure Here we give any false condition only structure will be copied. Ex create table jkk2 as select * from emp where 1=2; Inserting Records Using SELECT statement Syntax : INSERT INTO <tablename> SELECT <column name> FROM <tablename>; Example : insert into jkk3 select empno,ename from emp; insert into jkk4 select empno,ename from emp where deptno=20; Constraints: Constraints are used to prevent invalid data entry into tables and thereby maintain the integrity of the data. They are otherwise called as business rule. There are two levels of constraints • column level constraints it is in the part of the column definition and is imposed only on the column in which the constraint is defined. • Table level constraints This is a part of the table definition. Constraints defined in the table level can restrict the data in any column in the table. - Here we give some name to our constraints - 3 Types of constraints  Domain constraint  Entity constraint  Referential integrity constraint 7
  • 8. Domain constraint - it is used to check the values entered into a particular column is valid or not. Two types - NOT NULL  that column doesn’t have null values - Check NOT NULL Create table praveen1 (no number(5)not null, name varchar2(20)); insert into praveen1(name) values ('sailaja')  it shows error insert into praveen1(no) values(102);  it will not show error Check Constraint - it is used to checking the column values - here we define some logical expression and relational expression create table gp3(no number(4) check(no between 1000 and 9000),dob date,doj date, check(dob<doj)); - IN, NOT IN , BETWEEN, LIKE IN Check ( colname IN (“set of permitted values”)) Create table gp4(no number(5), sex varchar2(5) constraint ch_sex check(sex in(‘m’,’M’,’f’,’F’))); NOT IN Check ( colname not in(“set of not permitted values”)) Create table gp5(no number(5), sex varchar2(5) constraint ch_sex1 check(sex not in(‘m’,’M’,’f’,’F’))); BETWEEN create table gp6(no number(4)constraint chk_gno check(no between 2000 and 3000));  here no column accept numbers between 2000 to 3000. LIKE  it is used to pattern matching Two pattern %  one or more spaces or characters _  only one space or character check(columnname like ‘S%’) create table gp7(no number(3),name varchar2(20) check(name like '%p')); create table gp8(no number(3),name varchar2(20) check(name like 's_i%')); 8
  • 9. create table gp9 (no number(3),name varchar2(20) check(name like 'p_a_')); alter table student add check(age>=18); alter table student add(constraint agecons check(age>=18)); Entity integrity constraint  To avoid duplicate data’s. Two types 1. Primary key 2. Unique Primary Key  Here we define a column or group of column should be primary key  It doesn’t allow duplicate values and null values Syntax : create table <tablename>(colname datatype PRIMARY KEY); Create table r11(no number(4)primary key,name varchar2(20)); Create table rad2(no number(4)constraint rad_no primary key,name varchar2(20)); Error : Create table gp11(no number(4)primary key,name varchar2(20), dep number(4)primary key); Composite primary key Create table g11(no number(4),name varchar2(20), dep number(4),primary key(no,dep)); Example for Table level constraints  it checks two columns i.e if the two columns having same data it shows error. UNIQUE  Here we define a column or group of column should be primary key  It doesn’t allow duplicate values .  It allows any number of null values Create table gj4(no number(4)unique, name varchar2(20)); Create table r5(no number(4)constraint ra5_no unique,name varchar2(20)); Composite unique key A unique key constraints more than one column called a composite unique key. The maximum no. of columns in a composite unique key is 16. Create table r6(no number(4),name varchar2(20), dep number(4), unique(no,dep)); 9
  • 10. create table gp13(no number(4)primary key,name varchar2(20),dep number(3)unique); Referential Integrity Constraint:  it is used to give relationship between tables  references uses table called child table  primary defined table is parent table of child Create table stu1( rollno Number(6) PRIMARY KEY, Name Varchar2(40) , Sex Varchar2(5)); //Parent Table Create table game_details ( rollno number(6) references stu1, game varchar2(40)); // Child Table Create table Cul1 ( id number(6) references stu1(rollno), event Varchar2(40)); create table attend(aid number(6), atten varchar2(20), FOREIGN KEY(aid) REFERENCES stu1(rollno)); On-delete-cascade clause If a row in the referenced key (primary key) column in the parent table is deleted, then all the rows in the child table with dependent foreign key column will also be deleted automatically when On delete cascade clause is used. Example create table gpa (roll number(6)PRIMARY KEY,name varchar2(20)); create table pers(no number(6), mark1 number(3), foreign key(no) references st1(rollno) ON DELETE CASCADE); delete from gpa where roll=102;  this query delete record from parent table but oracle internally deletes child table records. Self Referential Integrity A column in a table if referencing to another column in the same table it is called “Self Referential Integrity”. A primary key and a foreign key is present in the same table. Example Create table emp11( empno number(4) PRIMARY KEY, Name varchar2(20),job varchar2(20), mgr number(4), FOREIGN KEY(mgr) REFERENCES emp11(empno)); 10
  • 11. Using ALTER Table Statement Alter table <tablename> add primary key(Column Name); Alter table gptest add primary key(test); it is used to add primary key existing table. • if the table have duplicate values it is not possible If you want to disable primary key by using this. Alter table gptest disable Primary Key; ALTER TABLE dept DISABLE CONSTRAINT dname_ukey; ALTER TABLE dept DISABLE UNIQUE(dname,loc); it is used to enable primary key if you already disable. • if the table have duplicate values it is not possible ALTER TABLE gptest ENABLE PRIMARY KEY; ALTER TABLE emp ENABLE UNIQUE(DNAME,LOC); Dropping Integrity constraints To drop primary key by using this . Alter table gptest DROP PRIMARY KEY; drop table emp cascade constraints;  drops the Emp table along with all the constraints. Deferred constraints checking Constraints can be deferred for validity until the end of the transaction. • A constraint is deferred if the system checks that it is satisfied only on commit. If a deferred constraint is violated, then commit causes the transaction to roll back. 11
  • 12. • If a constraint is immediate (not deferred), then it is checked at the end of each statement if it is violated, the statement is rolled back immediately. create table kann(name varchar2(20),no number constraint pkk primary key deferrable); set constraint pkk deferred; Expressions and operators Expressions are a combination of formula and constant and/or variables using operators.  Arithmetic  Character  Comparison/Relational  Logical  SET Arithmetic operators It performs arithmetic operations + adds Values Select sal+200 from emp; - Subtract select sal-200 from emp; * Multiplication select comm.*0.2 from emp; / Divides select sal/100 from emp; Character Operator Concatenation operator ( || ) Select ename ||’is working in MNC’ from emp; Select ‘gp’||’from Anna Nagar’ ||’ working in MNC’ from dual; Relational operator select * from emp where mgr=7788; equal to select * from emp where mgr != 888; not equal to select * from emp where mgr<=7698; less than or equal to select * from emp where sal between 1000 and 7000; select * from emp where deptno in(20,30); select * from emp where deptno not in(20,30); select * from emp where mgr is null; select * from emp where mgr is null select * from emp where ename like ‘p_a%’; 12
  • 13. Logical Operator AND OR NOT AND Operator Both the condition should be satisfied the corresponding rows will be displayed Select * from emp where deptno=10 and sal=1300; OR operator Any one of the condition should be satisfied the corresponding rows will be displayed Select * from emp where deptno=10 or sal=3300; NOT Operator NOT operator returns TRUE if the enclosed condition evaluates FALSE and FALSE if the enclosed condition evaluates TRUE. select * from emp where NOT(mgr is null); SET Operators Set operators are used to combine the results of two queries into a single result. Queries contain set operators are called compound queries. The individual queries are called component queries. Union - returns all distinct rows selected by the component queries. select city from pa1 union select * from pa2; Union all – returns all rows selected by the component queries including duplicate rows. Select city from pa1 union all select * from pa2; Intersect – Returns all distinct rows selected by both the component queries. Select city from pa1 intersect select * from pa2; Minus -- Returns all distinct rows selected by the first query but not by the second query. Select city from pa1 minus select * from pa2; Functions Two types - Built in function v - User defined function Built in function  Scalar or single row function 13
  • 14.  Aggregate function or group function Scalar functions Scalar functions can be classified as follows. • Number function • Character function • Return Number values • Returning Character values • Date functions • Conversion functions • Other functions Selecting from the DUAL table DUAL is a table automatically created by oracle along with the data dictionary. DUAL is the schema of the user SYS, but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2 (1), and contains one row with a value ‘X’. Selecting from the DUAL table is useful for computing a constant expression with the SELECT command. Because DUAL, has only one row, the constant is returned only once. Desc dual; Select * from dual; Number function ABS -- it returns absolute values Select abs(-30) from dual; Select abs(30) "absolute” from dual; Floor (n)  it returns largest integer equal to or less than n select floor(15.7) from dual; ceil (n)  it returns largest integer equal to or greater than n select ceil(15.7) from dual; select ceil(15.3) from dual; store the function output  insert into inss select ceil(sal) from sala; update fun set no=ceil(no); 14
  • 15. EXP(n) -- E to the power of n Select exp(4) from dual; Ln(n)  It returns log values Select ln(20) from dual; Log(m,n) m-base value , n- number Select log(10,100) from dual; MOD(m,n) function  It returns remainder Select mod(4,3) from dual; Select mod(4,2) from dual; Power(m,n)  It returns m to the power of n. Select power(3,2) from dual; Round (n,[m])  It returns round of the particular value Select round(13.788,2) from dual; Select round(13.788) from dual; Sign(n)  It returns sign of n. Select sign(-10) from dual; Select sign(10) from dual; Select sign(0) from dual; SQRT(n) square root Select sqrt(4) from dual; Trunc (n,[m])  it returns n with m decimal places select trunc(152.78999,2) from dual; select trunc(152.78999) from dual; -- it removes all the decimal values Character functions Character functions can return both numeric and character values. ASCII(char) it returns ascii value of the char select ASCII(‘A’) from dual; select ascii(‘a’) from dual; select ascii('*') from dual; INSTR (char1,char2[,n[,m]]) Find occurrence of one string inside another. Char1  string , Char2  search characters 15
  • 16. n  occurrence , m  no of search characters Select instr(‘corporate floor’,’or’,3,2) from dual;  o/p 14 Select instr(‘corporate floor’,’r’,2,1) from dual;  it gives position of ‘or’ in 3rd occurrence Select instr('corporate floor','or',2,2) from dual;  o/p 5 Length (char) it gives size of the character Example select length(‘praveen’) from dual; Lengthb(char) This function returns the length of a string in bytes. Example select lengthb(‘praveen ‘) from dual; CHR(n) binary equivalent of the specified number select chr(65) from dual; select chr(42) from dual; concat(char1,char2)  it concats two strings select concat(‘praveen’,’kumar’) from dual; initcap(char) it returns first letter uppercase select initcap(‘praveen’) from dual; select initcap(ename) from emp; Lpad(char1,n,char2)  it is used to add a string to the left of another string select lpad(‘gpp’,10,’$’) from dual; select lpad(ename,30,’%’ ) from emp; Ltrim(char1,set) it removes particular set of characters from left side. Select ltrim(‘aadfdfepraveen’,’aad’) from dual; Replace(char,se_char,re_char)  replaces the string with another string select replace(‘jack’,’j’,’bl’) from dual; Rpad(char1,n,char2)  it is used to add a string to the right of another string select rpad(‘gpp’,20,’#’) from dual; select rpad(ename,20,’@’) from emp; Rtrim  it removes particular set of characters from right side. Select rtrim(‘GPPeeqwaad’,’aad’) from dual; 16
  • 17. Soundex -- it is used to find the phonetic representation of a string. Select ename from emp where soundex(ename) = soundex(‘symth’); Substr(char,m.n) -- It returns m th position and n characters from char. Select substr(‘srminfo’,4,4) from dual; Select substr(‘srminfotech’,-2,4) from dual; select substr(‘welcome india’,-5) from dual Substrb(char,m.n) Select substrb(‘praveen’,4,4) from dual; Translate (char,ser_char,chan_char) - it changes character from sear_char character and translate to chan_char character. Select translate(‘praveen’,’v’,’V’) from dual; Upper(char) – it returns character to uppercase Select upper(‘praveen’) from dual; Lower(char) -- it returns character to lowercase select lower(‘PRAVEEN’) from dual; Date Functions -- Date functions operate on values of the date datatype ADD_MONTHS(d,n) -this function adds specified number of months to date. Ex Select add_months(sysdate,2) from dual; Select add_months(‘12-jul-06’,2) from dual; LAST_DAY(d) --it returns month last day select last_day(sysdate) from dual; select last_day(‘20-sep-06’) from dual; MONTHS_BETWEEN(d1,d2) select months_between(‘12-jun-07’,’13-jun-06’) from dual; NEXT_DAY(d,char) Select next_day(sysdate,’Saturday’) from dual; Select next_day(‘23-jun-07’,’Saturday’) from dual; It displays date with time select to_char(sysdate,'dd-mon-yy, HH:MI') from dual 17
  • 18. in oracle 9i; TIMESTAMP datatype It extends the DATE datatype, stores the year, month, day, hour,minute and second. The sytax is TIMESTAMP[Precision]; SQL> create table timetable(timm timestamp); Table created. SQL> desc timetable Name Null? Type ----------------------------------------- -------- ---------------------------- TIMM TIMESTAMP(6) insert into timetable values('13-nov-06,04:38:30 PM'); select to_char(timm,'HH:mi:ss') from timetable; TIMESTAMP WITH TIME ZONE It extends from TIMESTAMP datatype, includes a time zone displacement. The time zone displacement is the difference (in hours and minutes) between local time and Coordinated Universal Time (UTC), formerly known as Greenwich Mean Time . Syntax TIMESTAMP [Precision] WITH TIME ZONE create table timetable1 ( timee timestamp with time zone); insert into timetable1 values('21-nov-06, 04:32:33 pm') insert into timetable1 values('21-nov-06,04:20:22 am +7.30') ROUND(d,[fmt) --This function used to round off a date to the required format. Select round(sysdate,’year’) from dual; Select round(sysdate,’month’) from dual; TRUNC (d[,fmt]) -- This function is used to truncate the value of a date to the required format. Select trunc(sysdate,’mm’) from dual; Select trunc(sysdate,’dd’) from dual; Select trunc(sysdate,’yy’) from dual; Conversion functions --Conversion functions convert a value from one datatype to another. TO_CHAR – date conversion This function is used to convert a date to character format. TO_CHAR(d[,fmt]) Select to_char(sysdate,’month dd, yyyy’) from dual; Select to_char(sysdate,’month/dd/yyyy’) from dual; 18
  • 19. TO_CHAR – Number conversion It is used to convert a number to character format. TO_CHAR(d[,fmt]) Select to_char (56764890,’099G999G999’) from dual; TO_DATE(char[,fmt]) String to date conversion Select to_date(‘june 25,1983,09:15 P.M.’,’Month dd, yyyy, HH:MI P.M.’ ) from dual; select to_char(to_date(‘25-oct-2098’,’dd-mon-yyyy’),’yy’) from dual; TO_NUMBER(char) It converts String to number select sal+to_number(‘45’) from emp; Other Functions greatest(expr1,expr2,…) select greatest(‘praveen’,’radha’) from dual; select greatest (‘radha’,’ragu’, ‘rajesh’,’radhakumari’) from dual; select greatest(89,77) from dual; least(expr1,expr2,…) select least(‘praveen’,’radha’) from dual; select least (‘radha’,’ragu’, ‘rajesh’,’radhakumari’) from dual; NVL This function is used to replace null values by specified values, for computational purpose, Example select empno, nvl(to_char(comm),’comm is null’) "commission" from emp; NVL2(expr1,expr2,expr3) it accept three arguments. If the first argument is not null then the second argument, if the first argument is null then the third argument is returned. select empno, nvl2(to_char(comm),’comm is avail’,’comm is null’) "commission" from emp; 19
  • 20. uid - it returns current user id Select uid from dual; user – it returns user name select user from dual; sysdate – it returns current date Select sysdate from dual; Decode  this function works like if…then condition decode(variable,<condition1>,<value1>,<condition2>,<value2>….) select empno,decode(deptno,10,’sales’,20,’manager’,30,’research’, 40,’management’) from emp; AGGREGATE FUNCTION Avg()  it returns average of some set of values. Select avg(sal) from emp; Max() -- it returns maximum value from set of values select max(sal) from emp; Min() -- it returns minimum value from set of values select min(sal) from emp; Count () --it returns total no. of records in a table. Select count (comm) from emp; select count(1) from emp; Select count(*) from emp; Group by clause The GROUP BY clause is another section of the SELECT statement. This clause is used to group rows based on the distinct values that exist for the specified columns. The GROUP BY clause divides a table into groups of rows in each group has the same value in a specified column. Select deptno,count(*) from emp group by deptno; select deptno,avg(sal) from emp group by deptno; select deptno,min(sal) from emp group by deptno; order by clause it is used to display the rows either ascending order or descending order. select * from emp order by empno; --- > ascending order select * from emp order by empno desc;  descending order 20
  • 21. ROLLUP Operator The ROLLUP operator is used to generate aggregates and super aggregates for expressions with in group by clause. select deptno,job,sum(sal) from emp group by rollup(deptno,job); Cube operator - The CUBE operator is used to produce cross tabular reports. it is also used with group by clause. Example select deptno,job,sum(sal) from emp group by Cube(deptno,job); grouping function The grouping function can be used with either CUBE or ROLLUP operator. This helps us to understand how a summary value has been obtained. The Grouping function receives one argument that should match one of the expressions in the GROUP BY clause. The return value is either 0 or 1. The return value is used to determine which columns are used to generate the corresponding row. Example select deptno,job,sum(sal),grouping(deptno),grouping(job) from emp group by Cube(deptno,job); HAVING clause HAVING clause is used to restrict the group of rows defined by the GROUP BY clause. it similar to the “where clause” in select statement. select deptno,min(sal),max(sal) from emp group by deptno; select deptno,min(sal),max(sal) from emp group by deptno having min(sal)>=1000 ; JOINS – it is used to collect information from more than one table. This allows data to be selected from one or more tables and to combine the selected data into a single result. Three types of joins  Simple join  Self Join  Outer join Simple Join 21
  • 22. It is most common type of join. It retrieves rows from two tables having common column. It can be classified into two. They are  Equi join  Non-Equi join Equi join - This join contains a condition containing an equality operator. - A equi join combines rows that have equivalent values for the columns specified in the join. Select ename,dname from emp,dept where emp.deptno=dept.deptno; Non – Equi joins Non equi joins specify the relationship between the tables not in terms of columns but in terms of the relational operators or any comparison operators used. select ename,grade from emp, salgrade where sal between losal and hisal; Table aliasing To prevent ambiguity in a query we include table name in the Select statements. Table aliases are used to make multiple table queries shorter and more readable. Select ename, dname from emp e, dept d where e.deptno=d.deptno; Select ename,dname,e.deptno from emp e,dept d where e.deptno=d.deptno; Self join In a self join, two rows from the same table combine to form a result row. To join a table to itself, two copies of the same table have to opened in memory. Example select e1.ename ||’ Work for ‘||e2.deptno from emp e1,emp e2 where e1.deptno=e2.deptno; select e1.ename ||'work for' || e2.ename from emp e1, emp e2 where e1.mgr=e2.empno; Outer Join The outer join extends the result of a simple join or equi join. An outer join returns all the rows returned by a simple join as well as those rows from one table that do not match any row from other table. The symbols (+) represents outer join. Example LEFT OUTER JOIN select ename,e.deptno,d.dname,d.loc from emp e,dept d where e.deptno(+)=d.deptno; 22
  • 23. select ename,e.deptno,d.dname,d.loc from empgp e,deptgp d where e.deptno(+)=d.deptno; The above example will retrieve all the rows that are matching and also retrieves the rows of DEPT table that does not match with EMP table because of the presence of (+) operator. 23
  • 24. select ename,e.deptno,d.dname,d.loc from deptgp d LEFT OUTER JOIN empgp e ON e.deptno=d.deptno; SELECT d.department_id, e.last_name FROM departments d LEFT OUTER JOIN employees e ON d.department_id = e.department_id ORDER BY d.department_id; Right outer join Select ename,e.deptno,d.dname,d.loc from emp1 e,dept1 d where e.deptno=d.deptno(+); Select ename,e.deptno,d.dname,d.loc from empgp e,deptgp d where e.deptno=d.deptno(+); select ename,e.deptno,d.dname,d.loc from deptgp d RIGHT OUTER JOIN empgp e ON e.deptno=d.deptno; The above example will retrieve all the rows that are matching and also retrieves the rows of EMP1 table that do not match with DEPT1 table because of the presence of (+) operator. SELECT d.department_name, d.manager_id, l.city FROM departments d RIGHT OUTER JOIN locations l ON d.location_id = l.location_id ORDER BY d.department_name; Full Outer join The following query uses a full outer join to return all rows from the customers table and all rows from the orders table. Rows that do not satisfy the ON condition are extended with nulls: SELECT c.customer_id, c.o.order_id, c.account_mgr_id, o.sales_rep_id FROM customers c FULL OUTER JOIN orders o ON c.customer_id = o.customer_id ORDER BY c.customer_id; Cartesian product 24
  • 25. When data is retrieved from tables we go for joins. When we select columns from two tables and if we do not specify a join condition it leads to a Cartesian product. Select * from emp, dept; 13 * 9 =117 rows are selected. Sub Queries A Subquery is a group that can contain multiple query statements nested within another. It is also called nested query. Subqueries are queries that appear within a where or having clause of another SQL statement. Subquery is used to handle results that are expressed as the results of other queries. A statement that includes a Subquery operates on rows from one table based on evaluation of the subquery’s select list, which can refer to same table as the outer query, or to a different table. Select statements that contain one or more subqueries are sometimes called nested queries or nested select statement. A statement containing sub query is called parent query. Select ename, deptno, sal from emp where sal=(select MAX(sal) from emp);  Always enclose subquery in parenthesis.  Subqueries will be evaluated first followed by the main query. ANY operator When this operator is used, a record will be selected is the value in the outer query satisfies the condition with any one of the values retrieved from subquery or inner query. select ename,sal,deptno from emp where sal>= any(select avg(sal) from emp group by deptno); ALL Operator The ALL operator is used to check for all the values returned by the list. The condition is checked for all the values and the records that match all the values are displayed. select ename,sal,deptno from emp where sal>=all(select avg (sal) from emp group by deptno); IN operator 25
  • 26. IN operator checks if the value of the outer query is equal to any of the values in the inner query (or the list). =ANY is equivalent to IN !=ANY is equivalent to NOT IN select ename,deptno,sal from emp where sal in(select max(sal) from emp group by deptno); select ename,deptno,sal from emp where sal not in(select max(sal) from emp group by deptno); EXISTS operator When this operator is used, the outer query is executed if inner query evaluates to TRUE. select deptno,dname,loc from dept where exists(select * from emp); Multiple Subqueries A subquery can include one or more subqueries. Up to 16 subqueries can be nested in a statement. select ename,empno,sal from emp where job in (select distinct job from emp where deptno=(select deptno from dept where dname='SALES')); A subquery can retrieve multiple information also select * from emp where (job,sal) in (select a.job,b.losal from emp a,salary b where a.job=b.job); Subqueries in Update, Insert and Delete statements In a delete statement subquery can be included in the ‘where’ clause whereas in Update statement it can be included in ‘set’ clause as well as ‘where’ clause’. Example update emp set sal=(select sal from emp where empno=10) where deptno=(select deptno from dept where dname='RESEARCH') and job='ANALYST'; delete from emp where sal<(select avg(sal) from emp); Correlated Subquery A correlated subquery cannot be evaluated as an independent query, but it can reference columns in a table listed in the ‘from’ list of the outer query. The subquery is executed repeatedly once for each row that is selected by the outer query or processed by the parent statement 26
  • 27. select empno,ename,a.deptno from emp a where sal>=(select avg(sal) from emp where a.deptno=deptno); unlike most of the queries , subquery in this statement cannot be resolved independently of the main query. It needs the value for ‘a.deptno’ but this value is a variable, it changes as the SQL server examines different rows of ‘emp’ table. SQL consider each row of emp(a) table for inclusion in the results by substituting the value in each row in the inner query. IN-LINE Queries inline queries are those queries that can be selected from the ‘FROM’ clause of the select statement. Example select ename,sal,x "Average sal",deptno from (select avg(sal)x,deptno b from emp group by deptno),emp where deptno=b; by using in-line queries we make calculation select ename,x-sal "difference from Asal",deptno from (select avg(sal)x,deptno b from emp group by deptno),emp where deptno=b; n th maximum sal select distinct(sal) from emp a where &n=(select count(distinct(sal)) from emp where a.sal<=sal); select min(sal) from (select sal from (select * from emp order by sal desc) where rownum<=&n); Subquery restrications • Subqueries cannot be used in order by and group by clauses. • The subquery is limited to 16 nesting levels. Pseudo columns ROWNUM For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which oracle retrieves the record. The ROWNUM holds a numeric value. select empno,empname,ROWNUM from emp; ROWID A ROWID is created by oracle for each new row in every table. select rowid,no,name from ex1; LEVEL 27
  • 28. For each row returned by a hierarchical query. example select lpad(ename,8*level) from gjp5 start with mgr is null connect by mgr=PRIOR empno; Interview Questions – answers 1) SQL> select * from emi; EMPNO NAME DEPTNO --------- -------------------- --------- 101 praveen 10 102 raja 10 103 sekar 20 104 arun 20 105 arvind 10 SQL> select * from depi; DNAME DEPTNO ------------------------------ --------- software 10 software1 20 hr 30 SQL> select * from depi where deptno not in ( select deptno from emi); DNAME DEPTNO ----------------------------- --------- hr 30 2) SQL> select * from emi; EMPNO NAME DEPTNO -------- -------------------- --------- 101 praveen 10 102 raja 10 103 sekar 20 104 arun 20 105 arvind 10 106 praveen 20 107 praveen 30 108 sekar 10 109 sekar 10 110 raja 10 10 rows selected. SQL>select distinct(name) from emi where name in (select name from emi group by name having count(name)>1); 28
  • 29. NAME ------------------- Praveen0 raja sekar Database objects • Views -- is a subset of data from one or more tables • Synonyms – it gives one alternative name to object • Sequences – it is used to give numbers automatically • Indexes – it improves the performance of some queries by using a pointer Views - We can present logical subsets or combination of data by creating views of tables . - A view is a logical table based on a table or another view. - A View can be defined as a logical table built upon one or more tables in a database. The Advantages of views  Restricted Access to specific columns of a table there by providing additional security  Oracle stores the definition of the view only  It simplifies queries  It avoids data redundancy  To hide the data complexity Simple View The definition of the view will contain the column names given in the query. Syntax : Create view <viewname> as query Example Create view empview as select ename, deptno, sal from emp; Join View Joining of tables results in creation of join views. A join view is a view that is created using a join condition. There are certain in join views. create view joinv as select empno,ename.dept.deptno from emp, dept where emp.deptno =dept.deptno; Restrictions - A view creation cannot contain on order by clause - If a view is defined with check option , a row cannot be inserted into or updated in the base table. Renaming the columns of view 29
  • 30. We can rename the column of a view so that the data in the column have a meaningful name. Syntax create view view_name (column1,column2,…) as select column1,column2 from basetable where condition; Example create view gpview (number,name) as select empno,ename from emp; desc gpview; - it describes the view structure Force view If you want to create view without an existing table.That is, table is already created. syntax create force view viewname as <query>; example create force view fv as select * from emp; Read only views Certain views can be created only for selection purpose. Such views will not permit the user or the owner of the view to perform any DML operations. Example create view read_view as select * from dept with read only; Updatable views Views that allow data manipulation (insert,update,delete) are called updatable views. Reasonly views views that donot allow data manipulation are called reasonly views. Criteria for updateable views 1. The view must be created over a single base table. 2. the view must include the primary key. 3. The view should not contain any aggregate functions. 4. The view should not contain any subquery in its select statement. 5. The view should not contain DISTINCT,HAVING and GROUP BY clause in the SELECT statement. 6. If the view is constructed over another view than the base view must be updated. 7. The view should not contain any constants,strings and expressions in the SELECT statement. 8. The view must contain all the NOT NULL columns of the base table. Destroying views views can be destroyed using the DROP view command. Syntax drop view <view name>; Example drop view client_balance; Synonyms 30
  • 31. A synonym is a database object that is used as an alias name for any object. A synonym is an alternative name for a table, view, sequence, procedure, stored function and package. Advantages - Simplify SQL statements - Hide the real identify of an object. Creating Synonym create synonym<synname> for <objectname>; Example create synonym syemp for emp; insert into gpsyn values(22,34); select * from gpsyn; Drop synonym – to drop synonym Syntax Drop synonym <synname>; Example drop synonym gpsyn; Select * from user_synonyms; to display the list of synonyms. Sequences Sequences are a set of database objects, which can generate sequential integer value. They are used to automatically generate primary key or unique key values. A sequence can be created in ascending or descending order. Creating sequence Syntax create sequence <sequencename> [<increment by> <value>] [<start with > <value>] [<minvalue> <value>] [NOMINVALUE] [<maxvalue> <value>] [NOMAXVALUE] [<cycle> <value>] [NOCYCLE] [<cache> <value>] where increment by Specifies the interval between sequence numbers. This value can be any positive or negative Oracle integer, nut it cannot be 0. if this value is negative then the sequence descends. If increment is positive, then the sequence ascends. minvalue Specifies the sequence’s minimum value. Nominvalue Specifies a minimum value of 1 for an ascending sequence or -10 for a descending sequence. The default is NOMINVALUE. 31
  • 32. Maxvalue Specifies the maximum value the sequence can generate. Nomaxvalue Specifies a maximum value of 10 for a descending sequence can generate. Start with Specifies the first sequence number to be generated. Cycle Specifies that the sequence continue to generate values after reaching either its maximum or minimum value. Nocycle Specifies that the sequence cannot generate more values after reaching its maximum or minimum values. The default is NOCYCLE. Cache Specifies how many values of the sequence oracle preallocates and keeps in memory for faster access. The minimum value for this parameter is 2. For sequences that cycle, this value must be less than the number of values in the cycle. Nocache Specifies that values of the sequence are not preallocated. If you omit both the cache parameter and the NOCACHE option, Oracle caches 20 sequence numbers by default. Example create sequence gpseq2 start with 10 minvalue 10 maxvalue 20 increment by 2 cycle cache 5; select gpseq1.NEXTVAL from dual; insert into gjp20 values(gpseq1.nextval,&dno); Altering a sequence The following specifications of a sequence can be altered. • Minimum value • maximum value • Incremental value • Number of cached sequence number. Alter sequence s1 maxvalue 25; 32
  • 33. Dropping Sequence Drop sequence command is used to drop a sequence from the database. Syntax Drop sequence <seq_name>; Example Drop sequence gpseq; To list Sequences Select * from USER_SEQUENCES; INDEX: Index on table is used to speed up the execution of queries in the table. This concept is similar to that of the index in a book. An index can be considered as an ordered list of data of a column or a group of columns, together with a location. Simple Index : A index is said to be simple if the index is created on only one column. Upto 16 indexes can be used on a table. Syntax: Create index <indexname> on <tablename> (column name); Example  Create index empi on emp(job); Composite Index: If the index is created on more than one column. It is called composite index. Example  Create index empii on emp(ename,job); - Indexed column of a table can have duplicate value. Creating unique index - it can be done in two ways - 1st while creating table we give primary key - 2nd one is we create index as unique Syntax Create unique index indname on tablename(colname); Example: 33
  • 34. Create unique index stui on student(rollno); -- now “rollno” column does not accept duplicate values Reverse Index It can be done by using “REVERSE” keyword Normal Index Reverse Index E1001 1001E E2004 4002E Syntax Create index indname on tablename (columnname) REVERSE; Example Create index reind on emp(empno)REVERSE; Alter the reverse index into normal Alter index reind REBUILD NOREVERSE; Bitmap Indexes The advantages of using bitmap indexes are greatest for low cardinality columns : that is columns in which the number of distinct values is small compared to the number of rows in the table. If the table values in a column are repeated more than a hundred times, then the column is a candidate for a bitmap index. Even columns with a lower number of repetitions and thus higher cardinality, can be candidates if they tend to be involved in complex conditions in the WHERE clauses of queries. For Example, on a table with one million rows, a column with 10,000 distinct values is a candidate for a bitmap index. Syntax CREATE BITMAP INDEX <indexname> ON <table>(column); Example CREATE BITMAP INDEX gpbi ON emp (no, deptno); Index organized tables - An index organized table differs from regular table in that data for the table is held in its associated index. When changes are made to the table, only the index is updated. - Index organized table is similar to a regular table with an index on one or more columns; it can be having two separate storage places for the table and the index. 34
  • 35. - Index-organized tables suitable for accessing data by the primary or any key that is a valid prefix of the primary key. There is no duplication of key values because only one non key column values are stored with the key. You can build secondary indexes to provide efficient access by other columns. - Applications manipulate the index organized table just like an ordinary table, using SQL statements. However the database system performs all operations by manipulating the corresponding index. Example Create table stud (num number (5) primary key, name varchar2 (20)) ORGANIZATION INDEX; If you want create organized index that table must have one primary key. Advantages:  Since the rows are stored in the index, an index – organized table provides a faster key based access to table data for queries involving exact match or range search.  Table occupies less space  Key columns are not duplicated in the table and the index Dropping Index By using drop index Syntax Drop index <indname>; Example Drop index empind; Clusters  Clusters are optional method of storing data.  A cluster is a group of tables that share the same data blocks because they share common columns and are used together. for Example: EMP and DEPT table share deptno column . when we use cluster for these two tables . Oracle physically stores all rows from both tables in the same data blocks.  clusters store related rows of different tables together in the same data blocks. benefits  Disk I/O is reduced and access time improves for joins of clustered tables 35
  • 36. In a cluster, a cluster key value is the value of cluster columns for a particular row. Each cluster key value is stored only once in the cluster and the cluster index. - less storage space required to store related table and index data in a cluster. Cluster key The cluster key is a column, or group of columns, that the clustered table have in common. We specify the columns of the cluster key when creating the cluster. We subsequently specify the same columns when creating another table added to the cluster.  no more than 16 columns can form the cluster key.  Cluster key cannot include LONG or LONG RAW column. Hash Cluster  Storing a table in a hash cluster is an optional way to improve the performance of data retrieval.  A hash cluster provides an alternative to a non- clustered table with an index or an index cluster.  Oracle locates the rows in a table using key value that it stored in a separate index. In order to use hashing, a hash cluster is created and tables are loaded into it.  Oracle physically stores the rows of a table in a hash cluster and retrieves them according to the results of a hash function. To find or store a row in an indexed table or cluster, a minimum of two I/Os must be performed: • One or more I/Os to find or store the key value in the index. • Another I/Os read or write the row in the table or cluster. In contrast, Oracle uses a hash function to locate a row in a hash cluster, no I/O is required. As a result, minimum of one I/O operations is necessary to read or write a row in a hash cluster. Advantages of Hashing • Most queries are equality queries on the cluster key Select … where cluster_key=…; • In such cases, the cluster key in the equality condition is hashed, and the Corresponding hash key is usually found with single read. In comparison, for an indexed table the key value must first be found in the index (usually several reads) and then the row is read from the table (another read). 36
  • 37. • The tables in the hash cluster are primarily static in size so that we can determine the number of rows and amount of space required for the tables in the cluster. If the tables in a hash cluster require more space than the initial allocation for the cluster, performance degradation can be substantial because overflow blocks are required. Disadvantages of Hashing • Most queries on the table retrieve rows over a range of cluster key values. (Example full table scans, or queries like the following , a hash function cannot be used to determine the location of specific hash keys • The table is not static and continually growing. if a table grows without limit, the space required over the life of the table(its cluster) cannot be pre- determined. • Applications frequently perform full- table scans on the table and the table is sparsely populated. A full-table scan in this situation takes longer under hashing. Creating Hash Clusters After a hash cluster is created, tables can be created in the cluster. create cluster gc(dn number(5)); create index gci on cluster gc; create table gct1(dn number(5),name varchar2(20)) cluster gc(dn); create table gct2(dn number(5),dna varchar2(30)) cluster gc(dn); select ROWID from cluster gpa;  rowid of the two tables are same, Because these two tables uses cluster. Drop Cluster To drop a cluster by using Drop cluster command. Syntax Drop cluster clustername; drop cluster gpc including tables; 37
  • 38.  here it deletes table also. drop cluster gpc; - if the tables are already deleted means we directly drop the particular cluster “gpc”. LOCKING Concurrency control in Oracle In a multi-user environment, the database is centralized and all users can access data from the database. Since data are stored in tables, a table in the database may be accessed by more than one user at the same time (concurrently). A true RDBMS must tackle this situation to prevent damage to the table or the data in the table. This problem is effectively handled by the Oracle by means of the technique Concurrency control locking. Locking is a method of Concurrency control. Oracle uses this method for concurrently control. The following are Lock Lock is a mechanism implemented on a resource by a user that restricts other users to access the same resource temporarily. The resource may be a table or a row. Oracle automatically locks a resource when a transaction begins. The lock is released only after the transaction is committed or rolled back. Thus Oracle prevents destructive interaction between users. Example Let two users user1 and user2 access the data with the following transactions user1 : update emp set cos=100 where empno=‘1001’; user2 : delete from emp where empno=‘1001’; Both the users are accessing the same table and same row concurrently. So it makes some problem. Hence Oracle uses the locking process to overcome this situation. Types of locks There are two types of locks. They are 1. Share lock 2. Exclusive lock 38
  • 39. 1. Share lock This lock allows other users also to share the same resources. But the other users can only query the resource (Select statement) and they can’t execute DML statements. More than one user can place share lock on the same resource. 2. Exclusive Lock This lock restricts the sharing of resources by other users. However it allows other users to query. only one user can place an exclusive lock on a table at a time. Implicit and Explicit Locking While Oracle automatically locking a table a user can lock a table explicitly also Implicit Locking To maintain a high degree of data concurrency, Oracle performs different locks automatically depending upon the SQL statements. The lock applied implicitly by the oracle is called implicit lock. Oracle acquires the necessary lock implicitly based on the following situations. • A user who is querying data from the database need not wait for other users who are accessing (inserting, updating, selecting) the same data simultaneously. • A user who is accessing data (inserting, updating) in the database need not wait for others who are querying the same data simultaneously. • A user who is inserting or updating data in the database only needs to wait for other users who are trying to insert or update the same data simultaneously. A table comprises of rows and each row can be divided into items. Thus if a user is updating a particular set of records, lock placed on the particular rows is more flexible so that other users can access the remaining portion of the same table. Further, when a user tries to modify particular item in a row, the most flexible locking is to place a lock only on those items. Explicit locking During a transaction, some time a consistent set of data may be required. So, the particular set of data should not be allowed to be accessed by other users 39
  • 40. till the transaction is over. this is called transaction level read consistency and this can be achieved only by explicit locking. Explicit lock can be acquired using i) SELECT …… FOR UPDATE statement ii) LOCK TABLE … statement Levels of Locking Locks can be acquired at two level. 1. Row level lock 2. Table – level lock 1. Row level lock implicit row lock Oracle automatically places an exclusive lock on every row that is modified by the statements INSERT, DELETE and UPDATE. This is called implicit row locking. Explicit row lock Implicit row locking can be overridden by explicit row locking. SELECT .. FOR UPDATE statement overrides the implicit locking on the rows and acquire exclusive row locks for the selected rows. SELECT … FOR UPDATE statement Syntax SELECT column1,column2,column3 .. FROM <table-name> WHERE <search_condition> FOR UPDATE [OF column , column,…] [NOWAIT]; Example select * from employe where empno=1003 FOR UPDATE; select empno, ename from emp where empno=1003 for update; Restrictions • DISTINCT and GROUP BY clauses should not be used. • Should not include set operators (UNION, INTERSECT, MINUS, UNION) and group functions. • All the tables must be in the same database 40
  • 41. • This must be followed by an update statement or COMMIT or ROLLBACK, Otherwise the lock will not be released. • if some other user locked the same rows, Oracle will wait till the lock is released NOWAIT option terminates the statement in this case. Table level locks Implicit Table lock Oracle implicitly places a lock on the tables that is modified by INSERT, UPDATE and DELETE commands. Explicit table lock We can place locks explicitly on tables to override implicit table locks Tables can be locked explicitly by using Table level locks lock table employe in share mode; lock table employe in share update mode; lock table employe in exclusive mode; Permission Granting and revoking privileges add an additional security to the Oracle database system. In multiple – user environment, we need to maintain security of the database access and use. Using Oracle Server database security Creating user The oracle system has two users SYSTEM with password Manager and another user SYS. SYSTEM has all privileges, logon to SYSTEM and create a user using CREATE USER command. Syntax CREATE USER username IDENTIFIED BY password; 41
  • 42. CREATE USER praveen IDENTIFIED BY srm; Logging on to one user from another user By using CONNECT command Syntax CONNECT username/password; Example CONNECT praveen/srm; At this stage User Praveen has no privilege to ‘Create session’. Hence we have to grant the privilege to create session to Praveen. Then only we can log on the user Praveen. Types of Privileges A permission granted to a user to do some action is called a privilege. A user can not do any action if he does not have the privilege to do that action. There are two types of privileges. They are 1. System privilege 2. Object privilege 1. System privilege The Permission granted to execute various data definition, commands like CREATE TABLE , CREATE SEQUENCE, CREATE SESSION are called System privileges. Some of the System privileges are CREATE SESSION : Log on to database CREATE TABLE : to create table CREATE ANY TABLE : allow creating table in any schema (user) CREATE SEQUENCE : to Create a sequence CREATE ANY SEQUENCE : to Create a sequence in any schema CREATE PROCEDURE : to create procedure CREATE TRIGGER : to create trigger 42
  • 43. CREATE ANY TRIGGER : To create trigger in any schema CREATE VIEW : to create view CREATE ANY VIEW : to create view in any schema ALTER ANY TABLE : to alter any table ALTER ANY SEQUENCE: to alter any sequence in any schema ALTER ANY VIEW : to alter an view ALTER ANY PROCEDURE To alter any procedure in any schema DROP ANY TABLE : to drop any table DROP ANY TRIGGER : To drop any trigger DROP ANY SEQUENCE : To drop any sequence in any schema. example create user gpj identified by jum; alter user gpj identified by jumu; - it changes the password Granting System privilege GRANT command is used to give system privileges to an Oracle USER. Syntax : GRANT system privilege to user; Example : grant create session to gpj; Connect gpj/jum; Object Privileges An Object privilege enables a user to execute some command on database objects like table, view, sequence etc. 43
  • 44. NO Privileges Table View Sequence Procedure 1. ALTER * * 2. DELETE * * 3. EXECUTE * 4. INDEX * 5. INSERT * * 6. REFERENCES * 7. SELECT * * * 8. UPDATE * * Granting Object Privileges Different object privileges are available for different types of schema objects. A user automatically has all object privileges for schema objects contained in the user’s schema. A user can grant any object privilege on any schema object that the user owns to any other user. If the grant includes the GRANT OPTION, the grantee can further grant the object privilege to other users. Otherwise , the grantee can use the privilege but cannot grant it to other users. The syntax is given below GRANT object_priv [(columns)] ON object TO {user|PUBLIC} [WITH GRANT OPTION] where, object_priv is an object privilege to be granted columns specifies the Column from a table or view on which privileges are granted ON Object is the object on which the privilege are granted TO identifies to whom the privilege is granted PUBLIC grants object privileges to all users WITH GRANT OPTION allows the grantee to grant the object privilege to other users. Example GRANT select ON emp TO gpp; Example 44
  • 45. GRANT update(dname,loc) ON dept TO gpp,Praveen; update scott.dept set dname=‘pur’ where deptno=30 GRANT SELECT,UPDATE,DELETE on staff to student; Referencing a table belonging to another user The objects in a user could not be used by another user, if the owner of the objects has not granted the required privileges to the user on those objects. If a user is granted privileges on some objects then the user can refer the object preceded by the user name of the owner of the object. Example Assuming you are in user staff 1. select * from student.student_master; 2. select * from gp.client_master; Granting Permission to users when the grantor has been given GRANT permission The owner of an object can grant any privilege on the object to other users. If a user wants to grant privileges on objects of the other users, then the user must have been granted the same privileges on those objects with the GRANT OPTION. Example Execute from the user scott GRANT SELECT ON emp TO gpp; here user gpp could not grant the SELECT privilege to any other user. GRANT SELECT ON emp TO gpp WITH GRANT OPTION; Now the user gpp can grant the privilege SELECT on the object emp in the user scott. First log on to gpp then Execute GRANT SELECT ON scott.emp TO student; 45
  • 46. Revoking the Permissions Permissions granted to a user can also be taken back by the grantor. This is done by the REVOKE command. Revoking System privileges The REVOKE statement is used to remove the system privileges granted to the user. Revoke create table to Praveen; To remove the create table privilege to the user Praveen. Revoking Object Privileges The REVOKE statement is used to remove privileges granted to other users. Syntax REVOKE objectprivilege [object privilege] … ON objectname FROM username; Example REVOKE SELECT,INSERT ON emp from scott; Drop user if you want to drop a particular user by using drop user command; drop user username; Example drop user gpp; note : it will be executed from the SYSTEM user. Partitions ORDBMS The realization Single row object type Single Row Object types are object types that are defined for specific columns and can hold singular value only like other datatypes. They are created as objects, which are further embedded as a datatype to a column. Example create or replace type user_date as object ( day number(2), 46
  • 47. month number(2), year number (2) ); create or replace type user_name as object ( fname varchar2(20), mname varchar2(20), lname varchar2(20) ); // object type user_date // object type user_name create table employee_data13 ( empno number(3), ename user_name, dob user_date, salary number (9,2) ); Inserting values Every object type has a system defined constructor method that is a method that makes a new object according to the object type’s specification. The name of the constructor method is the name of the object type. The constructor method is a function. It returns the new object as its value. It is used to initialize the attributes with values. insert into employee_data13 values(101,user_name(‘jam’,’praveen’,’kumar’), user_date(25,06,83),10000); SQL> select * from employee_data; EMPNO --------- ENAME(FNAME, MNAME, LNAME) ------------------------------------------- DOB(DAY, MONTH, YEAR) ------------------------------------------- SALARY --------- 101 USER_NAME(‘jam’, ‘praveen’, ‘kumar’) USER_DATE(25, 6, 83) 10000 47
  • 48. SQL> select e.ename.fname, e.ename.lname from employee_data13 e; ENAME.FNAME ENAME.LNAME -------------------- -------------------- jam kumar select e.empno, e.dob.day from employee_data13 e; Updating values Updating is done similar to the select statement. The dot notation and an alias of the table is used. update employee_data13 a set a.ename.lname=‘vignesh’ where a.empno=101; deleting a record Deleting a record is similar to updating and selecting values from rows abstract data types insert into employee_data values(102,user_name(‘j’,’pravee’,’kum’), user_date(29,06,85),15000); delete from employee_data13 a where a.ename.fname=‘j’; Dropping Types To get rid of a type such as user_date, the following command is used. SQL> drop type user_date; drop type user_date * ERROR at line 1: ORA-02303: cannot drop or replace a type with type or table dependents Object type cannot be changed or dropped without dropping its dependents. However the FORCE clause can be used to forcefully drop an object type. SQL> drop type user_date force; Type dropped. CREATE OR REPLACE TYPE TYP_synch_bill_customer AS OBJECT ( DEBTORNUM NUMBER(10), 48
  • 49. DATE_EFFECTIVE DATE, END_DATE DATE, STATUS VARCHAR(5) ); CREATE OR REPLACE TYPE table_synch_customers AS TABLE OF TYP_synch_bill_customer; / created. SQL> desc table_synch_customers; table_synch_customers TABLE OF TYP_SYNCH_BILL_CUSTOMER Name Null? Type ----------------------------------------------------- -------- ------------------ DEBTORNUM NUMBER(10) DATE_EFFECTIVE DATE END_DATE DATE STATUS VARCHAR2(5) Collections Varrays Nested Tables Introduction A collection is an ordered group of elements of the same datatype. - Varray (Varying Array) - Nested table (multiple records) Varrays An array is an ordered set data elements. All elements of a given array are of the same datatype. Each element has an index, which is a number corresponding to the element’s position in the array. The number of elements in an array is the size of the array.Oracle arrays are of variable size, which is why they are called Varrays. The maximum size must be specified while creating Varrays. Declaring a Varray does not occupy space. It defines a type, which can be used as 1.The datatype of a column of a relational table. 2.An object type attribute. 49
  • 50. 3.A PL/SQL variable, parameter, or function return type. An array object is stored in line, that is, in the same tablespace as the other data in its row. The following example illustrates this concept. EXAMPLE : CREATE OR REPLACE TYPE price_list AS VARRAY(5) OF number(3); When the above statement is executed, the specified type is created. CREATE TABLE prods ( pno number, rate price_list, ); Nested tables A nested table is like an object table without the object identifiers. It has a single column, and the type of that column is a built in type or an object type. If it is an object type , the table can also be viewed as a multi-column table, with a column for each attribute of the object type. A nested table definition does not allocate space. It defines a type, which you can use as * The datatype of a column of a relational table. * An object type attributes When a nested table appears as the type of a column in a relational table or as an attribute of the underlying object type of an object table. Oracle stores all of the nested table data in a single table which it associates with the enclosing relational or object table. They are also called Multiple Row Object type. There are no restrictions on the number of records to be created. Example CREATE OR REPLACE TYPE stud_type1 AS OBJECT (studno number, studname char(20), sex char(1)); CREATE OR REPLACE TYPE stud_nt1 AS TABLE OF stud_type1; CREATE TABLE faculty1 ( factno number, name varchar2(30), students stud_nt1 50
  • 51. )NESTED TABLE students STORE AS stud_nt_tab; here NESTED TABLE <nested _item> STORE AS <storage _table> Specifies <storage_table> as the name of the storage table in which the rows of all <nested_item> values reside. insert into faculty1 values (1,’vignesh’, stud_nt1( stud_type1(10,’Praveen’,’M’), stud_type1(20,’kumar’,’M’), stud_type1(30,’chellam’,’F’) ) ); insert into faculty1 values (2,’Pravee’, stud_nt1( stud_type1(10,’Praveena’,’F’), stud_type1(20,’kumari’,’F’), stud_type1(30,’anbu’,’M’) ) ); Using Flattened Subqueries To manipulate the individual rows of a nested table stored in a database column, use the keyword THE. THE keyword must be prefixed to a subquery that returns a single column value or an expression that yields a nested table. If a subquery returns more than a single column value, a runtime error occurs. Because the value is a nested table , not a scalar value. Oracle must be informed, which is what THE does. Quering Nested Table Values Alone using THE select nt.studno,nt.studname,nt.sex from THE (Select students from faculty1 where factno=1)nt; Note: Here only one main subset value can be selected. Here, if a user needs to enter another record, this can be done using the following syntax. 51
  • 52. INSERT INTO THE (SELECT students FROM faculty1 WHERE factno=1) nt VALUES (14,'kalai','F'); PL / SQL - Procedural language / Structured Query Language. - It is an extension of SQL and bridges the gap between the application program, the Oracle database system and the database. - PL/SQL is a language that has programming features that serve as an extension to SQL. - Using PL/SQL we can manipulate data in the database insert data into the database and also retrieve data. - Also we can group PL/SQL codes logically and this group of PL/SQL code called block. If a block is not given a name. It is called on anonymous block. - PL/SQL incorporates many of the advanced features of programming languages that were designed during the 1970’s and 1980’s. Need for PL /SQL for programmers  PL/SQL enables the programmers to write procedural programs to access and manipulate data in the database.  Using SQL data manipulation languages in PL/SQL, data in the tables can be manipulated.  Using the data transaction languages in PL/SQL, Changes of data in a table can be made or can be undone as whole.  All sorts of SQL functions can be used in PL/SQL.  All operators that we are using in SQL statements can also be used in PL/SQL.  In Addition, we can declare variables and constants in PL/SQL to store results of a query during process, which can be used later in the PL/SQL block. PL/SQL Executing Environment Diagram of Oracle server 52
  • 53. PL/SQL in Oracle RDBMS If the PL/SQL engine is placed in the Oracle Server, then the execution of PL/SQL will be more efficient. Modularize program development Using PL/SQL block in SQL Environment A PL/SQL block has three parts namely; Declaration, execution and exception. Declaration and exception parts are optional. 53 ORACLE SERVER SQL Statements PL/SQL Engine Procedural Statements Procedural Statement Executor PL/SQL Block SQL Statement Executor DECLARE BEGIN EXCEPTION END;
  • 54. Declaration part begin with keyword DECLARE. Execution part begin with keyword BEGIN and ends with the keyword END. Declarative  contains all variables, constants, cursors and user defined exceptions Executable  Contains SQL statements to manipulate data in the database and PL/SQL statements to manipulate data in the block. Exception  Specifies the actions to perform when errors and abnormal conditions arise in the executable section. Method – 1 Step 1 If we type DECLARE or BEGIN at the SQL prompt. SQL understand that the user is going to execute a PL/SQL and it will ignore the semicolon, we type at the end of SQL statements, Type END as the last statement. Step 2 Type / at the SQL prompt. The block will be stored in the SQL buffer and then The block will be executed. Example SQL> begin 2 update emp set comm=200 where comm=100; 3 update emp set comm=500 where empno=7788; 4 end; 5 / PL/SQL procedure successfully completed. SQL> Method -2 (Through another editor) Here we are going to use the notepad as the editor. Step 1: Type ed <filename> at the SQL prompt SQL>ed <filename> This will create a new file with extension SQL Step 2: Type the PL/SQL block codes in the file let / be last line after the key word end. Step 3: 54
  • 55. Save and exit Step 4: Type @ <filename> at the SQL prompt SQL> @ <filename> The block will be executed. Example SQL> ed new1 SQL> @ new1; Input truncated to 1 characters PL/SQL procedure successfully completed. SQL> PL/SQL syntax It also have own character set, variables and literals PL/SQL character set: a) Upper case alphabets b) Lower case alphabets c) Numbers d) Special symbols : ( , ) , +, - ,* , / , @ ,%,$ ,^ Simple symbols used in PL/SQL Block ( ) + , * , - ,< ,> , = Compound symbols <>,<= ,>= ,!=, :=, =, ** Literals A sequence of valid PL/SQL characters is called a literal. There are four types of literals a) String literal A sequence of one or more characters from the PL/SQL character set enclosed with in single quotes ( ‘ ) is called string literal. Example 1) ‘welcome to all ‘ 2) ‘123.44’ 3) ‘Mr. Praveen welcome’ b) Character literal 55
  • 56. A string literal with only one character is called a character literal Example ‘Y’ , ‘7’ c) Numeric literal Any valid number is called Numeric literals d) Boolean literal The value TRUE , FALSE, NULL are called Boolean literal. Comments This line is not executable. We can place comment any where in PL/SQL block. There are two types of comments are available. Single line Comment A comment having only one line is called single line comment. It begins with -- Multiline comment If the comment runs over more than one line is called multiline comment. It begins with /* and ends with */ PL/SQL Data types A PL/SQL variable can be declared as any of the oracle internal data types. Also there are many other data types 1. Varchar2. 2. Char. 3. Number. i. Decimal ii. Integer iii. Real 4. Binary_integer The variable of this data types is used to store signed integers in the range -2 31 - 1 to 2 31 -1 . 5. Date This data type stores a date values SQL stores all date and time in its own floating point format. 6. Boolean The variable of this data type is used to store TRUE, FALSE or NULL. 7. %Type This attribute is used to declare a variable similar to the data type of a column in an existing table or that of a variable defined earlier in the block. Syntax : Variable_name tablename.column_name%type; ex basicpay staffacd.basic%type; staffacd  tablename , basic  column of table 56
  • 57. salary emp.sal%type;  salary number(7,2); b_pay basicpay%type :=10;  A NOT NULL database column constraint does not apply to variables that are declared using %TYPE. PL/SQL variable PL/SQL variables are declared in the declarative part of a block. Rules:  A variable name must start with alphabets followed alpha numerals. It’s maximum length of a variable is 30 characters.  Only underscore allowed  Avoid using keyword as variable Example: sal_pay, sle122 Example: Stud_name varchar2 (30); Salary number (5, 2); Assigning values to variables There are two methods are available to assign a value 1. Assigning a variable with the value retrieved from a table. The SELECT …… INTO statement It used to assign values to variables Syntax SELECT column1,column2,. .. INTO variable1,variable2.. from <table> where <condition>; Example Declare sname varchar2(30); salary emp.sal%type; -- salary number(7,2); Begin Select ename, sal into sname, salary from emp where empno=7902; dbms_output.put_line (sname ||' salary is '||salary); End; / 2. Assigning a value with the assignment operator The assignment operator := is used to assign values. Example - salc.sql declare basic number(7,2); 57
  • 58. hra number(2); da number(3); salary number(8,2); begin select sal into basic from emp where empno=7902; hra := 20; da := 5; salary := basic + basic*da/100 +basic *hra/100; dbms_output.put_line(salary); end; Remark If we declare a PL/SQL variable to be NOT NULL then we must assign a value at once. Example Salary number (8,2) NOT NULL :=0; Here Salary have “zero” value at the time of declaration. dbms_output.put_line  it is used to print the output in sql prompt Constants If a particular value does not change its value in a PL/SQL block. We declare that variable as constant Example: da constant number(3) := 20; sub constant varchar2(25) := ‘english’; Boolean expressions Expression separated by a comparison operator is called a Boolean expression. The values are TRUE , FALSE, NULL. Example sal >= 10000; subject <> ‘english’; subject !=’english’ Logical Expressions Two are more Boolean expression connected with logical operator is called logical expression. Example Sal >1000 and dept = ‘software’ Sal >1000 or dept = ‘software’ PL/SQL block structure Three parts 1. Declarative part 2. Execution part 3. Exception part 58
  • 59. Nested block Declare test number(2); begin test :=10; declare test number(2); begin test :=20; dbms_output.put_line (test);  prints 20 end; dbms_output.put_line (test);  prints 10 end; Entering values while running time- gp3.sql Declare test number(2); begin test:=&test; dbms_output.put_line (‘the result is’ || test); end; Screen Message To display message first we must type SET SERVEROUTPUT ON command at the SQL prompt. Qualify an Identifier Qualify an identifier by using the block label prefix. <<outer>> declare bdate date:='25-jun-83'; begin declare bdate date :='29-jun-85'; begin dbms_output.put_line('Inner block variable '|| bdate); dbms_output.put_line('Outer block variable '|| outer.bdate); end; end; Bind variables A bind variable is a variable that you declare in a host environment. Bind variables can be used to pass run time values, either number or character. 59
  • 60. Creating Bind variables: By using VARIABLE command used to create bind variables Syntax VARIABLE b_varname NUMBER VARIABLE b_varmsg VARCHAR2(30) Displaying Bind variables By using PRINT command Syntax : PRINT bname; Example - gpvar.sql variable gsal number begin select sal into :gsal from emp where mgr=7788; end; / print gsal Programming with PL/SQL 1. Conditional controls a) IF … THEN …….. END IF Syntax IF <condition> THEN Statements END IF; Example - gpif.sql DECLARE sno number; BEGIN sno := &sno; IF sno>=10 THEN dbms_output.put_line(‘sno is greater than 10’); END IF; END ; b) IF … THEN …ELSE….. END IF Syntax 60
  • 61. IF <condition> THEN Statements set 1 ELSE Statement set 2 END IF; Example – gpife.sql DECLARE sno number(3); BEGIN sno := &sno; IF sno>=10 THEN dbms_output.put_line (‘sno is greater than 10’); ELSE dbms_output.put_line (‘sno is not greater than 10’); END IF; END; c) IF … THEN …ELSIF….ELSIF….. END IF Syntax IF <condition1> THEN Statements ELSIF <condition2> THEN Statement ELSIF <condition3> THEN Statement ELSE Statement END IF; Example – gpifeif.sql DECLARE a number(3) :=&a; b number(3):=&b; BEGIN IF a>b THEN dbms_output.put_line (‘a is greater than’); ELSIF a<b THEN dbms_output.put_line(‘b is greater than’); ELSE dbms_output.put_line(‘Both are equal’); END IF; END; Nested IF…… THEN Syntax 61
  • 62. IF <condition1> THEN Statements IF <condition2> THEN Statement ELSE Statement ENDIF; ELSE Statement END IF; Ex DECLARE a number(3) :=&a; b number(3):=&b; BEGIN IF a>b THEN dbms_output.put_line(‘a is greater than’); IF a<b THEN dbms_output.put_line(‘b is greater than’); END IF; END IF; END; CASE Expressions A CASE expressions selects a result and return it. Syntax: CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 … WHEN expression n THEN result n [ ELSE result ] End; 62
  • 63. Example DEFINE p_grade = a; // define variable only number or character declare v_grade char(1) := upper('&p_grade'); v_appraisal varchar2(20); begin v_appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; dbms_output.put_line('Grade : '||v_grade ||' Appraisal : ' || v_appraisal); end; / Loop ….. END loop The statement placed between the keywords LOOP and END LOOP will be executed repeatedly. Example Declare i number(2); Begin i :=1; Loop Dbms_output.put_line (i); Exit when i=100; i:=i+1; end loop; end; The while loop This loop is used to execute a set of PL/SQL codes whenever the given condition is true. It is false control is transferred to next statement. Syntax While <condition> Loop Statement End loop; 63
  • 64. Ex: while i<=100 loop dbms_output.put_line(i); i:=i+1; end loop; --- The FOR Loop For variable in [REVERSE] startno ..end no Loop Statements block; End loop; For i in 10 ..20 Loop Dbms_output.put_line(i); End loop; for I in reverse 10 .. 20 loop Dbms_output.put_line(i); End loop; Factorial declare n number := &n; i number :=1; fact number:=1; begin for i in 1..n loop fact := fact * i; end loop; dbms_output.put_line('the result is ' ||fact); end; nCr expansion 64
  • 65. declare n number := &n; r number :=&r; x number:=1; y number:=1; res number:=1; i number:=1; begin for i in 1..r loop x:=x*n; n:=n-1; y:=y*i; end loop; res:=x/y; dbms_output.put_line('the result is ' ||res); end; Goto statement Sy Goto label; <<label>> ex goto 10; <<10>> Merging Rows The MERGE statement inserts or updates rows in one table, using data from another table. Each row is inserted or updated in the target table, depending upon an equijoin condition. The example shown matches the eno in the copy_emp1 table to the eno in the emp1 table. If a match is found, a row is updated to match the row in the emp1 table. If the row is not found, it is inserted into the copy_emp1 table. Declare 65
  • 66. v_eno emp1.eno%type := 7499; begin merge into copy_emp1 c using emp1 e on (c.eno=v_eno) when matched then update set c.eno = e.eno, c.ename =e.ename, c.sal = e.sal when not matched then insert values (e.eno,e.ename,e.sal); end; Exception An error is an abnormal condition that arises during the execution of a program. In PL/SQL block, an error condition called as Exception Exceptions can be broadly classified into : • Pre-defined Exception • User – defined Exception • Undefined Exception Pre – defined Exceptions It is already defined in Oracle. Exception Raised when ACCESS_INTO_NULL User tries to assign values to the attributes of an uninitialized (automatically null) object. NO_DATA_FOUND Refer in book ZERO_DIVIDE User tries to divide a number by zero OTHERS Common Exception handling Example DECLARE X NUMBER :=&X; 66
  • 67. Y NUMBER:=&Y; BEGIN DBMS_OUTPUT.PUT_LINE(‘RESULT IS ‘||X/Y); EXCEPTION WHEN ZERO_DIVIDE THEN DBMS_OUTPUT.PUT_LINE(‘VALUE IS DIVIDED BY ZERO’); END; Example -2 Declare myename varchar2(20); begin select ename into myename from emp where empno=&x; dbms_output.put_line(‘the name of the employee is ‘ ||myename); exception when no_data_found then dbms_output.put_line(‘no record’); end; Example 3 Declare mysal number; begin select sal into mysal from emp where deptno=10; dbms_output.put_line(mysal); exception when too_many_rows then dbms_output.put_line(‘use cursors’); end; Example 3 Declare mysal number; begin select sal into mysal from emp where deptno=&x; dbms_output.put_line(mysal); exception when too_many_rows then dbms_output.put_line(‘use cursors’); when others then dbms_output.put_line(‘other exception’); end; User Defined Exception 67
  • 68. PL/SQL allows users to define their own exceptions. Unlike predefined exceptions, user defined exceptions must be declared exceptions and can be raised using one of the following : • RAISE • RAISE_APPLICATION_ERROR RAISE In the case of user defined exception, the following three steps must be performed: • declare the exception • Raise the exception • Handle the exception Declaring exception Exceptions are declared in the declarative part of a PL/SQL block. Declare myex EXCEPTION; Raising Exceptions RAISE myex; Handling Exceptions When myex then Example Declare eno number:=&no; name varchar2(20):=‘&b’; salary number:=&p; salary_ex exception; begin if salary>50000 then raise salary_ex; else insert into sala(no,name,sal)values(eno,name,salary); end if; exception when salary_ex then dbms_output.put_line(‘Salary exceeds 50000’); end; 68
  • 69. RAISE_APPLICATION_ERROR Raise_Application_error stops the program and terminates the block abruptly. Raise_Application_Error is primarily used in triggers to rollback the transaction and give suitable error messages. The syntax RAISE_APPLICATION_ERROR (errornumber,MESSAGE); Where the error messages span between -20000 and -20999. Message is a character data that can hold upto 2000 bytes. Declare empid number :=&empid; curr_sal Number; inc number:=&inc; begin select salary into curr_sal from employe where empno=empid; if curr_sal is null then raise_application_error(-20101,’Salary missing’); else update employe set salary=curr_sal+inc where empno=empid; end if; exception when NO_DATA_FOUND then raise_application_error(-20000,’no matching record’); end; CURSORS - is a private SQL work area. Processing of SQL statements in ORACLE When a user fires an SQL statement, Oracle executes the SQL statement as follows. i) First oracle reserves a location in the main memory, which is called private SQL area. ii) Secondly, the private SQL area is populated with the data pertaining to the SQL statement. iii) Thirdly the populated data are processed by the Oracle as per the SQL statement. iv) Finally Oracle clears the memory area as soon as the execution is completed. 69
  • 70. CURSOR Defn: A cursor is defined as the work area in memory where oracle stores the data while executing the current SQL statement. Whenever you issue a SQL statement, the Oracle server opens an area of memory in which the command is parsed and executed. This area is called a cursor. Active set The set of all data stored in a cursor is called the active data set. Row pointer Oracle maintains a row pointer along with the rows in the cursor, if a query returns multiple records. Using this row pointer we can locate the desired row in the active data set. Use of cursors in PL/SQL Cursors can be used in effectively in PL/SQL. if a set of records selected from a table by means of a query has to be processed , then we must use explicit cursor . Types of cursors There are two types of cursors .They are 1. Implicit cursor 2. Explicit cursor Implicit cursor Each DML statement creates an implicit cursor, including the select statement that returns only one row we need no declare such cursor. SQL cursor Attributes SQL%ROWCOUNT No. of rows affected by most recent SQL statement ( an integer value) SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more rows. SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows. 70
  • 71. SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed. example - gpcur1.sql variable rowd varchar2(30); declare dep emp.deptno%type :=&dep; begin select * from emp where deptno=dep; :rowd :=(SQL%ROWCOUNT ||’rows displayed’); end; / print rowd; Explicit Cursor Apart from implicit cursors, we can also define cursors explicitly. cursors declared by a user explicitly are called explicit cursors. Explicit cursor management The following are the various steps involved in explicit cursor management. 1. Declaring a cursor 2. Opening the cursor 3. fetching individual row one at a time 4. closing the cursor 1. Declaring a cursor In PL/SQL , a cursor must be declared in the declaration section like any other variables. syntax : cursor <cursor_name> is select .. Example cursor dc is select deptno,dname,loc from dept; 2. Opening the cursor The active data is created when the cursor is opened. OPEN statement is used to open a cursor. Syntax open <cursor_name>; 71
  • 72. Example open dc; 3. Fetching a record from the cursor The active data set is defined when the cursor is declared. The records are placed in the cursor when the cursor is opened. The records are retrieved from the active set using the FETCH statement one by one. FETCH Statement FETCH statement retrieves the current record in the active set and moves the row pointer to the next row. Syntax : FETCH <cursor_name> INTO var1, var2 …. fetch dc into dno,dna,lo; Closing a cursor The system resources used by a cursor are freed when the cursor is closed. Further, if we try to open a cursor which is already opened. Oracle displays an error message. close statement cursor is closed using the CLOSE statement. Syntax CLOSE <cursor_name>; Example close dc; example for cursor declare dno number(3); dna varchar2(20); lo varchar2(20); cursor dc is select deptno,dname,loc from dept; begin open dc; loop fetch dc into dno,dna,lo; exit when dc%notfound; dbms_output.put_line(‘deptno -->‘||dno ||’dname-->‘||dna ||’location--->‘||lo); end loop; close dc; 72
  • 73. end; / Explicit cursor attributes 1. %NOT FOUND usage: <cursor_name>%NOT FOUND is TRUE if the FETCH statement does not retrieve a row and FALSE if the FETCH statement retrieves a row. This is very useful to check whether the active data set is empty and all the rows in the cursor are processed. 2. %FOUND Usage : <cursor_name>%FOUND is TRUE if the FETCH statement retrieves a row and FALSE if it doesn’t. 3. %ROWCOUNT Usage : <cursor_name>%ROWCOUNT returns the number of rows fetched from the active data set. Its value is zero when the cursor is opened. 4. %ISOPEN Usage :<cursor_name>%ISOPEN returns TRUE if the cursor is already open. This is very useful to check whether the cursor is already open before opening the cursor. Example create table sales(ino number(5),iname varchar2(20),iprice number(6,2)); create table bill(bno number(5),bname varchar2(20),bprice number(6,2)); insert into sales values(101,’pen’,20.00); insert into sales values(102,’pencil’,25.00); insert into sales values(103,’box’,500.00); declare cursor cur_s is select * from sales; no number(5); name varchar2(20); price number(6,2); begin open cur_s; loop 73
  • 74. fetch cur_s into no,name,price; exit when cur_s%NOTFOUND; insert into bill values(no,name,price); end loop; close cur_s; end; Cursor and records Using %ROWTYPE attribute provides a record type that represents a row in a table. The variable declared as this type can store an entire row of data selected from the table of fetched from a cursor. This type is used in cases where al the column names need to be retrieved from the table. Example: declare cursor c1 is select * from emp; erec emp%rowtype; begin open c1; loop fetch c1 into erec; exit when c1%NOTFOUND; dbms_output.put_line(erec.ename||’ is a ‘||erec.job||’ and earns ‘||erec.sal); end loop; close c1; end; example 2: declare cursor mycur is select * from sales; code number(6); items varchar2(20); prices number(6,2); date2 date; dates date; begin open mycur; date2:=‘&date2’; loop fetch mycur into code,items,prices,dates; 74
  • 75. if dates=date2 then insert into billing values(code,items,prices,dates); end if; exit when mycur%NOTFOUND; end loop; close mycur; end; Cursor FOR loops Syntax FOR record_name IN Cursor_name LOOP Statement 1 Statement 2 Statement 3 END LOOP;  The Cursor FOR loop is a shortcut to process explicit cursors.  Implicit open, fetch , exit and close cursor.  The record is implicitly declared. Example declare cursor emp_cursor is select ename,deptno from emp; begin for emp_record in emp_cursor Loop if emp_record.deptno=20 then dbms_output.put_line(' Employee '|| emp_record.ename|| 'work in software dept.'); end if ; end loop; end; Cursor FOR loops Using Subqueries When you use a subquery in a FOR loop, you do not need to declare a cursor. begin for emp_record in (select ename,deptno from emp) Loop if emp_record.deptno=20 then dbms_output.put_line(' Employee '|| emp_record.ename|| 'work in software dept.'); 75
  • 76. end if; end loop; end; Cursor with Parameters You can pass parameters to the cursor in a cursor FOR loop. This means that you can open and close an explicit cursor several times in a block, returning a different active set on each occasion. For each execution, the previous cursor is closed and re-opened with a new set of parameters. Syntax CURSOR cursor_name [ (parameter_name datatype, …)] IS Select Statement ; OPEN cursor_name (parameter_value,….); Example declare v_no number; v_name varchar2(30); cursor emp_cur (p_no number) is select no, name from employe where no=p_no; begin open emp_cur(102); loop fetch emp_cur into v_no,v_name; exit when emp_cur%NOTFOUND; dbms_output.put_line('No : '||v_no || 'Name : '||v_name); end loop; close emp_cur; end; Cursor with For update clause FOR UPDATE The FOR UPDATE clause identifies the rows that will be updated or deleted, and then locks the rows in the result set. Syntax 76
  • 77. Select … from tablename FOR UPDATE [OF column _reference][NOWAIT] WHERE CURRENT OF clause Syntax WHERE CURRENT OF cursorname (i.e) When referencing the current row from an explicit cursor, use WHERE CURRENT OF clause. This allows you to apply updates and deletes to the row currently being addressed, without the need to explicitly reference the ROWID. Example declare cursor c1 is select * from emp for update; cursor c2 is select * from emp; begin for emp_rec in c1 loop if emp_rec.job='MANAGER' then update emp set sal=sal+500 where current of c1; update emp set sal=sal+500 where empno=emp_rec.empno; elsif emp_rec.job='CLERK' then update emp set sal=sal+200 where current of c1; end if; end loop; for erec in c2 loop dbms_output.put_line(erec.ename || ' Now earns '||erec.sal); end loop; end; SUBPROGRAMS Subprograms are named PL/SQL blocks that can take parameters and be invoked. PL/SQL has two types of subprograms called procedures and functions Benefits of Subprograms - Easy maintenance that enables you to modify:  Routines online without interfering with other users  One routine to affect multiple applications  One routine to eliminate duplicate testing. - Improved data security and integrity by doing the following: 77
  • 78.  Control indirect access to database objects from nonprivileged users with security privileges.  Ensure that related actions are performed together , or not at all, by funneling activity for related tables through a single path. - Improved performance that allows you to do the following  Avoid reparsing for multiple users by exploiting the shared SQL area.  Avoid PL/SQL parsing at run time by parsing at compilation time.  Reduce the number of calls to the database and decrease network traffic by bundling commands. - Improved code clarity:  Using appropriate identifier names to describe the action of the routines reduces the need for comments and enhances the clarity of the code. PROCEDURES  Procedure is a subprogram that performs a specific action.  A procedure is named PL/SQL block that can accept parameters and perform an action Advantages  Reusability: it is enough to just revoke the appropriate procedure or function whenever required. We need not write the entire coding.  Modularity: Using procedures and functions are program can be divided into small manageable sub programs.  Performance: Since the procedures and functions are stored along with the server, the performance is improved.  Modify one routine to affect multiple applications  As a subprogram is executed with its definer’s right by default, it is easy to restrict the access privilege by granting a privilege only to execute the subprogram to a user.  After a subprogram is compiled, the parsed code is available in the shared SQL area of the server and subsequent calls to the subprogram use this parsed code. This avoids reparsing for multiple users. Syntax CREATE OR REPLACE PROCEDURE <procedurename> [(argument [IN| OUT|INOUT] datatype [,(argument [IN| OUT|INOUT] datatype] … { IS | AS } 78
  • 79. variable datatype; begin PL/SQL coding (executing part) exception exception part end; where CREATE OR REPLACE PROCEDURE -- creates new procedure or replace exist procedure argument -- Variable used to input and retrieve parameters. IN - Specifies that a value for the argument must be given when the procedure is invoked OUT -- Specifies that a value is passed to this argument and we can get the values through this argument. INOUT -- Specifies that a value for the argument must be given when invoking the procedure and procedure passes a value for the argument. datatype -- it is datatype for argument Example number, varchar2 note 1) IN , OUT , INPUT are called qualifiers of the arguments . The default qualifier is IN. 2) A procedure may have no argument execute a procedure exec procedurename(argumentvalue) Example create or replace procedure dispe (eno in number default 7499) is mn varchar2(20); begin select ename into mn from emp where empno=eno; dbms_output.put_line(‘The name is ‘||mn); end; Example exec dispe(7698) 79
  • 80. exec dispe() here the procedure take default argument as input.(i.e 7499). invoke procedure in another PL/SQL program declare en number:=&en; begin dispe(en); end; / Example - out parameter create or replace procedure disps(eno in number,sal out number) as mn varchar2(20); begin select sal,ename into sal,mn from emp where empno=eno; dbms_output.put_line(‘the employee name is ‘||mn); end; accessing the previous procedure declare sa number; begin disps(7698,sa); dbms_output.put_line(‘the salary of the person ‘||sa); end; / Example of IN OUT parameter create or replace procedure espn(num IN OUT number) as begin select sal into num from new1 where no=num; end; accessing in IN OUT declare num number:=&no; begin espn(num); 80
  • 81. dbms_output.put_line (‘the result is’||num); End; Nested Procedure and Exception handling create or replace procedure proc1 is procedure proc2 is v_a number :=10; v_b number :=0; begin dbms_output.put_line('This is inner procedure'); dbms_output.put_line('the result ' || v_a/v_b); exception when zero_divide then -- inner proc2 handles the exception if suppose it will not handle this error in prco2, it will be handled in proc1 exception block dbms_output.put_line(' exception in proc2 inner'); end proc2; begin dbms_output.put_line('this is outer procedure'); proc2; exception when ZERO_DIVIDE then dbms_output.put_line('exception in proc1 outer'); end proc1; Drop procedure Drop procedure procedurename; Example Drop procedure espn; Functions • A function is a subprogram that computes a value. • A function is a named PL/SQL block that can accept argument and return a value to the caller. The value is returned using keyword RETURN with in the function. • A function can return only one value while a procedure can return any number of values through OUT parameters. 81
  • 82. Advantages of functions  It promotes security  It improves the performance of the database  It minimizes the use of system resources (memory)  It increases the productivity of application program  It enhances the integrity of programs Security Users may be permitted to access data only through functions and not permitted to access the table. Performance Since functions are loaded in the shared pool of the System Global Area(SGA). They are not retrieved from the list and hence the speed of the execution is very fast. note : function cannot be called using EXEC statement. Example create or replace function getname(eno in number) return varchar2 is name varchar2(20); begin select ename into name from emp where empno=eno; return name; end; Calling function select getname(7698) from dual; Calling a function in PL/SQL program declare no number:=&no; v_name varchar2(200); begin dbms_output.put_line(‘the name of the person is’||getname(no)); --function 82
  • 83. v_name := getname(no); calling end; Normally a function is used to compute specific values. They are not meant to perform any DML operations on the table. For Example if a function tries to insert a record onto a table, Oracle throws an error. The function has to satisfy some purity levels for performing any DML operations. Purity Level determines to what extent the function does not do any alterations to the database object. The four levels of purity levels are shown in the following table. Purity Level Expansion Description WNDS Write No Database State Function does not perform any DML operations on tables. RNDS Read No Database State Reading is restricted from any table. RNPS Read No Package State Functions must not alter any packaged variables WNPS Write No Package State Function cannot write onto any package variable. Depending on the purity level, a function is restricted to the following restrictions 1. A function callable from a SELECT statement must not perform any operation to any tables. 2. Functions can take only IN parameter and not OUT and IN OUT . 3. Return type of a function must be a database type. Notations When calling a subprogram, the actual parameters are written using either positional or named notation. That is , the association between an actual and formal parameter can be indicated by position or name. for Example , given the declarations Example 83
  • 84. create or replace function getsal(fno number,fname varchar2) return number is saly number; begin select sal into saly from sala where no=fno and name=fname; return saly; end; select getsal(12,’praveen’) from dual; Positional notation The function call uses positional notation. The PL/SQL compiler associates the first actual parameter, no with the first formal parameter fno. And, the compiler associates the second actual parameter, na with the second formal parameter, fname declare no number:=&no; na varchar2(30):=‘&name’; begin dbms_output.put_line(‘the salary of the person is’||getsal(no,na)); end; Named notation This function uses the named notation. The arrow (called an association operator) associates the formal parameter to the left of the arrow with the actual parameter to the right of the arrow. declare no number:=&no; na varchar2(30):=‘&name’; begin dbms_output.put_line(‘the salary of the person is’|| getsal (fno=>no, fname=>na)); end; Mixed notation declare 84
  • 85. no number:=&no; na varchar2(30):=‘&name’; begin dbms_output.put_line(‘the salary of the person is’||getsal(no,fname=>na)); end; dbms_output.put_line(‘the salary of the person is’||getsal(fno=>no,na)); --illegal Viewing Procedures and functions Procedures and functions are viewed using the data_dictionary views: SELECT *FROM USER_SOURCE; Drop function Drop function functionname; Example Drop function getsal; TRIGGERS A stored procedure that is fired implicitly whenever the data in the associated table are changed is called a trigger. Introduction Oracle enables us to define triggers that are executed automatically whenever a row is inserted into a table or an existing row updated or deleted. while other procedures are to be called explicitly for execution , triggers are executed implicitly by Oracle. Use of Database Triggers  A trigger can be used to avoid invalid transaction  A trigger can be used to keep duplicate data.  A trigger can be used to audit changes to data in table. (i.e store the particulars of the modified and deleted rows in a separate table).  A trigger can be used to enforce additional referential integrity.  A trigger can be used to enforce complex business rules. 85
  • 86. Parts of Triggers A database trigger has three parts. They are 1. Triggering statement 2. Trigger restriction 3. Trigger action Triggering statement The SQL statement that includes the trigger is called the triggering statement. it may be any DML statement (INSERT , UPDATE or DELETE). Trigger Restriction This is optional.This is available for triggers that are fired for each row. The trigger is fired only if this condition is true. Trigger Action The PL/SQL block executed when a trigger is fired is called trigger action. here triggering restriction is true. Types of Triggers Triggers are classified into different types depending on when the trigger is to be fired. They are • Before • After • INSTEAD OF BEFORE / AFTER The BEFORE option of a trigger is used to specify when the trigger must be fired. if the option BEFORE is chosen. The trigger is fired before the triggering statement is executed. In case of AFTER the trigger is fired after executing the statement. BEFORE  Before triggers are used when the triggering action determines whether the triggering statement must be allowed to be completed or not.  To derive the values of a specific column before the execution of the triggering statement(INSERT or UPDATE). 86
  • 87. AFTER  AFTER triggers execute the trigger action after the execution of the triggering statement.  To perform the trigger action immediately after the execution of triggering statement.  if there is already a BEFORE trigger, we can use the AFTER trigger to perform a different action. Based on how many records are to be affected by the trigger, triggers can be classified as : o ROW level o Statement level Row level triggers These types of triggers are fired for each row that I affected by the triggering statement. for example UPDATE statement for multiple rows of a table. In this case , the ROW level triggers are executed for every row that is affected by the UPDATE statement. Statement level triggers A trigger that is fired only once for the execution of the triggering statement is called a statement trigger. Syntax for creating triggers CREATE OR REPLACE TRIGGER <trigger_name> [BEFORE / AFTER] [INSERT/DELETE/UPDATE] ON <tablename> [FOR EACH ROW] [WHEN <condition>] keywords and parameters CREATE OR REPLACE -- create new one or replacing existing one. <trigger_name> -- name of the trigger BEFORE -- indicates that Oracle fires the triggers before the execution of the triggering statement 87
  • 88. AFTER -- indicates that Oracle fires the triggers after the execution of the triggering statement [INSERT/DELETE/UPDATE] – when the trigger fires i.e which statement <tablename> -- specifies the name of the table FOR EACH ROW – specifies that the trigger fires at row level. WHEN -- Restricts the trigger to fire when the condition true. Example1 create or replace trigger insdept before insert on dept begin dbms_output.put_line(‘inserting records’); end; example2 create or replace trigger insemp before insert on sales declare x number; begin select count(*) into x from sales; dbms_output.put_line(x+1 ||’Number of records are available’); end; Accessing column values When a trigger action or the trigger body contains statements that require access to the table values or for checking the new value with the old value. Two correlation names are used  :new , :old :new  refers to the new values entered in the trigger statement :old  refers to the old existing values in the table. These are also called as pseudorecords since they do not contain any permanent record. Statement :new :old Insert New values entered in the Insert command Null Update New values entered in Old values available in 88
  • 89. Update statement the table Delete Null Old Values in the table example3 create or replace trigger insdep after insert on dept for each row BEGIN DBMS_OUTPUT.PUT_LINE(:new.deptno || ‘ ‘ || :new.dname || ‘ ‘ ||:new.loc); End; Insert into dept values (12, ‘sales’, ‘chennai’); This trigger when sal exceed create or replace trigger chksal after insert on emp1 for each row begin if not(:new.job='MANAGER' AND (:new.sal>4000 and :new.sal<6000)) then raise_application_error(-20000,'manager salary cannot exceed 8000 and cannot be less than 4000'); end if; end; / example the number less than 100 trigger executed no insert ,update create or replace trigger checkn before insert or update on trigg for each row when (new.num<100) begin raise_application_error(-20001,'sorry number not a valid'); end; / Here set trigger in particular column (no in g4 table) create or replace trigger chekno before insert or update of no on g4 for each row when (new.no<100) begin raise_application_error(-20002,'number not a valid'); end; / Packages A package is a schema object that groups logically PL/SQL types, items and sub programs. 89
  • 90. Understanding packages Packages are usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification is the interface to your applications: it declares the types, variables, constants, exceptions cursors and subprograms available for use.the body fully defines cursors and subprograms, and so implements the specification Package specification The package specification contains public declarations. The scope of these declarations is local to the database schema and global to the package. So, the declared items are accessible from the application and from anywhere in the package. The specification lists the package resources available to applications. All the information that the application needs to use is in the specification. Format of package CREATE OR REPLACE PACKAGE package_name IS | AS Public type and item declarations Sub program specifications END package_name; The following points needs to be noted about the above syntax • REPLACE keyword which is optional drops or recreates the package specification. • All the constructs declared in a package specification are visible to users who are granted privileges on the package. • Variables declared in the package specification are initialized to NULL by default. The package specification can be divided into three parts. They are • Package_name – declares the name of the package • Public type and item declarations – declares variables, constants,cursors,exception of types. • Subprogram specifications – declare the PL/SQL subprograms Example 90
  • 91. This is example creates a package specification create or replace package packdemo is message varchar2(25) := ‘Divide by zero’; end; example – using procedure we access the package message create or replace procedure packproc(x number, y number, c char) is begin if c=‘+’ then dbms_output.put_line(‘Added :’ ||to_char(x+y)); elsif c=‘-’ then dbms_output.put_line(‘Sub :’ ||to_char(x-y)); elsif c=‘/’ then dbms_output.put_line(‘division :’ ||x/y); end if; exception when ZERO_DIVIDE then dbms_output.put_line(packdemo.message); end; / Package Body The package body implements the package specification. That is the package body contains the definition of every cursor and sub programs declared in the package specification. The package body can also contain private declarations. Which define types and items necessary for the internal workings of the package. The scope of these declarations is local to the package body. example SQL> create or replace package gppdemo is 2 procedure getdetails(enos number); 3 end gppdemo; 4 / Package created. Package Body 91
  • 92. SQL> create or replace package body gppdemo is 2 procedure getdetails(enos number) is 3 eno number(4); 4 empname varchar2(50); 5 jobs varchar2(50); 6 mgrs varchar2(25); 7 hdate date; 8 sals number(12,2); 9 comms number(12,2); 10 dno number(5); 11 begin 12 select empno,ename,job,mgr,hiredate,sal,comm,deptno into 13 eno,empname,jobs,mgrs,hdate,sals,comms,dno from emp where empno=enos; 14 dbms_output.put_line(‘Ename: ‘||empname); 15 dbms_output.put_line(‘Job : ‘||jobs); 16 dbms_output.put_line(‘Mgr : ‘||mgrs); 17 dbms_output.put_line(‘HireDate: ‘||hdate); 18 dbms_output.put_line(‘Salary :’||sals); 19 if comms is null then 20 dbms_output.put_line(‘Commission : NULL’); 21 else 22 dbms_output.put_line(‘Commission :’||comms); 23 end if; 24 dbms_output.put_line(‘Deptno :’||dno); 25 exception 26 when no_data_found then 27 dbms_output.put_line(‘Data Not found’); 28 when others then 29 dbms_output.put_line(‘Some Error’); 30 end getdetails; 31 end ; 32 / Package body created. 92
  • 93. SQL> exec gppdemo.getdetails(7566); Ename: JONES Job : MANAGER Mgr : 7839 HireDate: 02-APR-81 Salary :2975 Commission : NULL Deptno :20 PL/SQL procedure successfully completed. Ex 2 create or replace package billdata is procedure billinsert(bn number,bna varchar2,bpr number); procedure billdelete(bn number); end; create or replace package body billdata is message varchar2(50) := ‘The given number is not found’; procedure billinsert(bn number,bna varchar2,bpr number) is begin insert into bill values(bn,bna,bpr); end; procedure billdelete(bn number) is begin delete from bill where bno=bn; exception when NO_DATA_FOUND then dbms_output.put_line(message); end; end; / SQL> exec billdata.billinsert(12,’gff’,67); PL/SQL procedure successfully completed. SQL> exec billdata.billdelete(1076); PL/SQL procedure successfully completed. 93
  • 94. Create or replace package hrpackage is Procedure getname(eno number); Function gettotalpay(eno number); Procedure getdetails(eno number); End hrpackage; create or replace package body hrpackage1 is procedure getname(eno number) is empname varchar2(25); begin select ename into empname from emp where empno=eno; exception when no_data_found then dbms_output.put_line(‘Data Not found’); when others then dbms_output.put_line(‘Some Error’); end; function gettotalpay(empnos number) return number is totals number; begin select sal+nvl(comm,0) into totals from emp where empno=empnos; return totals; exception when no_data_found then dbms_output.put_line(‘Data Not found’); when others then dbms_output.put_line(‘Some Error’); end; procedure getdetails(enos number) is eno number(5); empname varchar2(50); jobs varchar2(50); mgrs varchar2(25); hdate date; sals number(12,2); comms number(12,2); dno number(5); begin select empno,ename,job,mgr,hiredate,sal,comm,deptno into eno,empname,jobs,mgrs,hdate,sals,comms,dno from emp where wmpno=enos; dbms_output.put_line(‘Ename: ‘||empname); 94
  • 95. dbms_output.put_line(‘Job : ‘||jobs); dbms_output.put_line(‘Mgr : ‘||mgrs); dbms_output.put_line(‘HireDate: ‘||hdate); dbms_output.put_line(‘Salary :’||sals); if comms is null then dbms_output.put_line(‘Commission : NULL’); else dbms_output.put_line(‘Commission :’||comms); end if; dbms_output.put_line(‘Deptno :’||dno); exception when no_data_found then dbms_output.put_line(‘Data Not found’); when others then dbms_output.put_line(‘Some Error’); end; end; / 95
  • 96. REF Cursors A REF Cursor is a datatype that holds a cursor value in the same way that a VARCHAR2 variable will hold a string value. A REF Cursor can be opened on the server and passed to the client as a unit rather than fetching one row at a time. One can use a Ref Cursor as target of an assignment, and it can be passed as parameter to other program units. Ref Cursors are opened with an OPEN FOR statement. In most other ways they behave similar to normal cursors. -- Strongly typed REF CURSOR. DECLARE TYPE t_ref_cursor IS REF CURSOR RETURN cursor_variable_test%ROWTYPE; c_cursor t_ref_cursor; l_row cursor_variable_test%ROWTYPE; BEGIN DBMS_OUTPUT.put_line('Strongly typed REF CURSOR'); OPEN c_cursor FOR SELECT * FROM cursor_variable_test; LOOP FETCH c_cursor INTO l_row; EXIT WHEN c_cursor%NOTFOUND; DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description); END LOOP; CLOSE c_cursor; END; / -- Weakly typed REF CURSOR. DECLARE TYPE t_ref_cursor IS REF CURSOR; c_cursor t_ref_cursor; l_row cursor_variable_test%ROWTYPE; BEGIN DBMS_OUTPUT.put_line('Weakly typed REF CURSOR'); OPEN c_cursor FOR SELECT * FROM cursor_variable_test; LOOP FETCH c_cursor INTO l_row; EXIT WHEN c_cursor%NOTFOUND; 96
  • 97. DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description); END LOOP; CLOSE c_cursor; OPEN c_cursor FOR SELECT * FROM emp; LOOP FETCH c_cursor INTO l_row; EXIT WHEN c_cursor%NOTFOUND; DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description); END LOOP; CLOSE c_cursor; END; / ++++++++++++++ Table Type – Sample Package Package Spec create or replace package xxgp_type_test_pkg is TYPE t_gptest_rec_type IS RECORD ( EMPNO NUMBER(4) , ENAME VARCHAR2(10 BYTE), JOB VARCHAR2(9 BYTE), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER(7,2), DEPTNO NUMBER(2) ); TYPE t_gptest_tab IS TABLE OF t_gptest_rec_type; procedure p_emp_insert ( p_gptest_tab IN t_gptest_tab); end xxgp_type_test_pkg; Package Body create or replace package body xxgp_type_test_pkg is 97
  • 98. procedure p_emp_insert ( p_gptest_tab IN t_gptest_tab) is begin for i in p_gptest_tab.FIRST..p_gptest_tab.LAST LOOP insert into empgp (EMPNO , ENAME , JOB , MGR , HIREDATE , SAL , COMM , DEPTNO ) values ( p_gptest_tab(i).EMPNO, p_gptest_tab(i).ENAME , p_gptest_tab(i).JOB , p_gptest_tab(i).MGR , p_gptest_tab(i).HIREDATE , p_gptest_tab(i).SAL , p_gptest_tab(i).COMM , p_gptest_tab(i).DEPTNO ); commit; END LOOP; end p_emp_insert; end xxgp_type_test_pkg; Sample Execution Script declare l_gptest_tab apps.xxgp_type_test_pkg.t_gptest_tab; begin -- Value Passing to Table Type l_gptest_tab := apps.xxgp_type_test_pkg.t_gptest_tab(); l_gptest_tab.extend(3); -- To Mention How many records going to insert l_gptest_tab(1).empno := 8000 ; l_gptest_tab(1).ename := 'Praveen'; l_gptest_tab(1).job := 'Job'; l_gptest_tab(1).mgr := NULL; l_gptest_tab(1).hiredate := TRUNC(SYSDATE); l_gptest_tab(1).sal := 10000; 98
  • 99. l_gptest_tab(1).comm := NULL; l_gptest_tab(1).deptno := 20; l_gptest_tab(2).empno := 8001 ; l_gptest_tab(2).ename := 'Rahul'; l_gptest_tab(2).job := 'Job'; l_gptest_tab(2).mgr := NULL; l_gptest_tab(2).hiredate := TRUNC(SYSDATE); l_gptest_tab(2).sal := 12000; l_gptest_tab(2).comm := NULL; l_gptest_tab(2).deptno := 20; l_gptest_tab(3).empno := 8002 ; l_gptest_tab(3).ename := 'Vasanth'; l_gptest_tab(3).job := 'Job'; l_gptest_tab(3).mgr := NULL; l_gptest_tab(3).hiredate := TRUNC(SYSDATE); l_gptest_tab(3).sal := 11000; l_gptest_tab(3).comm := NULL; l_gptest_tab(3).deptno := 30; -- Here l_gptest_tab contains 3 records. It passed as parameter to store in table apps.xxgp_type_test_pkg.p_emp_insert ( l_gptest_tab ); commit; end; 99
  • 100. Sample Example Type and Bulk Collect INTO DECLARE TYPE t_gptest_rec_type IS RECORD ( EMPNO NUMBER(4) , ENAME VARCHAR2(10 BYTE), JOB VARCHAR2(9 BYTE), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER(7,2), DEPTNO NUMBER(2) ); TYPE t_gptest_tab IS TABLE OF t_gptest_rec_type; TYPE t_gptest_rec_type1 IS TABLE OF empgp%ROWTYPE; l_gptest_tab t_gptest_tab ; l_start NUMBER; BEGIN SELECT * BULK COLLECT INTO l_gptest_tab FROM empgp; DBMS_OUTPUT.put_line('Total Records :' || l_gptest_tab.count ) ; FOR i IN l_gptest_tab.FIRST..l_gptest_tab.LAST LOOP DBMS_OUTPUT.put_line(i||'- Employee Details :'|| l_gptest_tab(i).empno ||' - '||l_gptest_tab(i).ename); END LOOP; END; / 100
  • 101. Introduction to iSQL iSQL * Plus is an Oracle tool that recognizes and submits SQL statement to the Oracle server for execution. iSQL * Plus contains its own language. Following are features of iSQL * Plus : • The database is accessed from the browser • It provides online editing for modifying SQL Statements • It controls environmental settings • It formats query results into a basic report • Local as well as remote databases can be accessed. The iSQL Interface The following figure illustrates SQL and iSQL * Plus Interaction SQL Statements Using iSQL * Plus the user can perform the following tasks:  Retrieve, Modify , Insert and Delete data by executing SQL statements  Script files can be created to store SQL statements that can be run later  Store the output of a query in a file  Print query results in the form of reports, perform formatting and calculation on query results Formatted Reports Client iSQL Plus Query Results 101 iSQL * Plus Internet Browser Oracle Server