Date post: | 02-Apr-2018 |
Category: |
Documents |
Upload: | rukmini-vegesna |
View: | 259 times |
Download: | 1 times |
of 99
7/27/2019 SQL Plsql Material
1/99
SQL
SQL is divided into the following
Data Definition Language (DDL)
Data Manipulation Language (DML)
Data Retrieval Language (DRL)
Transaction Control Language (TCL)
Data Control Language (DCL)
DDL Data Definition Language (DDL) statements are used to define the database structure or
schema. Some examples:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
DRL Data Retrieval Language:
SELECT - retrieve data from the a database
Page 1
7/27/2019 SQL Plsql Material
2/99
7/27/2019 SQL Plsql Material
3/99
SELECT:
SELECT *
FROM emp;
SELECT emno,ename,sal,deptno
FROM emp;
SELECT *
FROM emp
WHERE deptno = 10;
SELECT empno,ename,sal,deptno
FROM emp
WHERE deptno = 10;
SELECT *
FROM emp
WHERE job = manager;
SELECT *
FROM emp
WHERE job = MANAGER;
Page 3
7/27/2019 SQL Plsql Material
4/99
SELECT *
FROM emp
WHERE deptno = 10 AND job = MANAGER;
SELECT *
FROM emp
WHERE deptno = 10 OR job = MANAGER;
OPERATORS:
The following are the different types of operators used in where clause.
Arithmetic operators
Comparison operators
Logical operators
Arithmetic operators: +, -, *, /
Comparison operators
=, !=, >, =,
7/27/2019 SQL Plsql Material
5/99
Or -- lowest precedence
Not
IN: This will gives the output based on the column and its list of values specified.
SELECT *
FROM emp
WHERE deptno IN(10,30)
SELECT *
FROM emp
WHERE deptno NOT IN(10,30);
BETWEEN AND : This will gives the output based on the column and its lower bound,
upperbound.
SELECT *
FROM emp
WHERE depno BETWEEN 10 AND 30;
SELECT *
FROM emp
WHERE depno NOT BETWEEN 10 AND 30;
IS NULL : This will gives the output based on the null values in the specified column.
SELECT *
Page 5
7/27/2019 SQL Plsql Material
6/99
FROM emp
WHERE comm IS NULL;
SELECT *
FROM emp
WHERE comm IS NOT NULL;
SELECT *
FROM emp
WHERE sal > 5000 AND comm IS NULL;
SELECT *
FROM emp
WHERE deptno= 10 AND comm IS NULL;
LIKE: This will be used to search through the rows of database column based on the pattern
you specify.
SELECT *
FROM emp
WHERE name LIKE S%
SELECT *
Page 6
7/27/2019 SQL Plsql Material
7/99
FROM emp
WHERE name LIKE _O%;
SELECT *
FROM emp
WHERE name LIKE %S%;
ORDER BY : This will be used to ordering the columns data (ascending or descending).
By default oracle will use ascending order. If you want output in descending order you have to
use desc keyword after the column.
SELECT *
FROM emp
ORDER BY deptno;
SELECT *
FROM emp
WHERE job = SALESMAN
ORDER BY deptno;
SELECT *
FROM emp
WHERE job = SALESMAN
Page 7
7/27/2019 SQL Plsql Material
8/99
ORDER BY ename;
Comparison operators:
a) USING =, >, =, select * from student where no = 2;
SQL> select * from student where no < 2;
SQL> select * from student where no > 2;
SQL> select * from student where no select * from student where no >= 2;
SQL> select * from student where no != 2;
SQL> select * from student where no 2;
CASE :Case is similar to decode but easier to understand while going through coding
Ex: SQL> Select sal,
Case sal
When 500 then low
When 5000 then high
Else medium
End case
From emp;
Page 8
7/27/2019 SQL Plsql Material
9/99
SQL FUNCTIONS
Functions can be categorized as follows.
Single Row Functions
Group Functions
Single Row Functions:
Number Functions
Character Functions
Date Functions
Analytical Functions
Miscellaneous Functions
Conversion Functions
Multi Row Functions
Aggregate Function
Aggregate Function
SUM
COUNT
MAX
Page 9
7/27/2019 SQL Plsql Material
10/99
MIN
AVG
Single Row Functions:
Number Functions
ROUND
TRUNCATE
CEIL
FLOOR
MODULUS
POWER SQRT
ABS
SIGN
Character Functions
Character Functions
_____________________
lower()-- converting into lower case
upper()-- converting into upper case
initcap() ---- converting into initial letters as capital
ltrim() -- cut leftside gaps
rtirm() -- cut rightside gaps
trim() -- cut bothside gaps
**lpad() -- attach special characters at leftside of string
**rpad() -- attach special characters at rightside of string
Page 10
7/27/2019 SQL Plsql Material
11/99
**substr() -- to fetch part of String
**instring() -- to fetch position of required string
diff b/w substr and instr ????
LOWER
UPPER
INITCAP
CONCAT SUBSTRING:
Substr(colname,x,y)
If m is +ve then its forwarded
If m is ve then its backwarded
If n is not given ,then it returns from mth position to end of string
If n
7/27/2019 SQL Plsql Material
12/99
SYSDATE
MONTHS_BETWEEN
ADD_MONTH
NEXT_DAY LAST_DAY
ROUND(DATE,FORMAT)
TRUNC(DATE,FORMAT)
Analytical Functions:
RANK
DENSE_RANK
LEAD
LAG
ROW_NUM
RANK:
SELECT EMPNO,ENAME,JOB,SAL,RANK()
OVER(ORDER BY SAL)
FROM EMP
SELECT EMPNO,ENAME,JOB,SAL,RANK()
OVER(ORDER BY SAL NULLS FIRST)
FROM EMP
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO,RANK()
OVER(PARTITION BY DEPTNO ORDER BY SAL NULLS FIRST)
FROM EMP
Page 12
7/27/2019 SQL Plsql Material
13/99
DENSE_RANK():
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO,DENSE_RANK()
OVER(ORDER BY SAL)
FROM EMP
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO,DENSE_RANK()
OVER(PARTITION BY DEPTNO ORDER BY SAL)
FROM EMP
LEAD:
SELECT EMPNO,ENAME,SAL,DEPTNO,
LEAD(SAL,1,0) OVER(ORDER BY SAL)
FROM EMP
SELECT EMPNO,ENAME,SAL,DEPTNO,
LEAD(SAL,1,0) OVER(PARTITION BY DEPTNO ORDER BY SAL)
FROM EMP
LAG:
SELECT EMPNO,ENAME,SAL,DEPTNO,
LAG(SAL,1,0) OVER(ORDER BY SAL)
Page 13
7/27/2019 SQL Plsql Material
14/99
FROM EMP
SELECT EMPNO,ENAME,SAL,DEPTNO,
LAG(SAL,1,0) OVER(PARTITION BY DEPTNO ORDER BY SAL NULLS FIRST)
FROM EMP
ROW_NUMBER:
SELECT EMPNO,ENAME,SAL,DEPTNO,
ROW_NUMBER() OVER(ORDER BY SAL NULLS FIRST) "SEQ NUMBER"
FROM EMP
MISCELLANEOUS FUNCTIONS:
UID
USER
VSIZE
CONVERSION FUNCTIONS
TO_CHAR
TO_DATE
TO_NUM
Page 14
7/27/2019 SQL Plsql Material
15/99
INSERT
This will be used to insert the records into table. We have two methods to insert.
By value method
By address method
A) Using Value Method
INSERT INTO emp
VALUES (1122,SATEESH,ANALYST,7902,24-JUN-10,3000,200,10);
INSERT INTO emp(empno,ename,sal,hiredate,deptno)
VALUES (1123,HEMA,5000,22-JAN-10,10);
INSERT INTO emp(empno,ename ,hiredate)
VALUES (1123,RAMU,4-DEC-10);
INSERT INTO emp(hiredate ,ename ,empno)
VALUES (4-DEC-10,RAMU, 1123);
Page 15
7/27/2019 SQL Plsql Material
16/99
To insert a new record again you have to type entire insert command, if there are lot of
records this will be difficult. This will be avoided by using address method.
B) Using Address Method
This will prompt you for the values but for every insert you have to use forward slash.
INSERT INTO emp(empno,ename ,job,mgr,hiredate,sal,comm,deptno)
VALUES (&empno,&ename,&job,&mgr,&hiredate,&sal,&comm,&deptno);
INSERT INTO emp(empno,ename ,hiredate)
VALUES (&empno,&ename ,&hiredate);
UPDATE
This can be used to modify the table data.
Ex: SQL> update student set marks = 500;
If you are not specifying any condition this will update entire table.
SQL> update student set marks = 500 where no = 2;
SQL> update student set marks = 500, name = 'sateesh' where no = 1;
DELETE
This can be used to delete the table data temporarily.
This can be used to delete specific row/s from the table using the condition.
Page 16
7/27/2019 SQL Plsql Material
17/99
SQL> delete student;
If you are not specifying any condition this will delete entire table.
SQL> delete student where no = 2;
Page 17
7/27/2019 SQL Plsql Material
18/99
DDL
CREATE TABLE:
SQL> create table student
(
no number (2),
name varchar (10),
marks number (3)
);
ALTER:
This can be used to add or remove columns and to modify the precision of the datatype.
a) ADDING COLUMN:
SQL> ALTER TABLE student
ADD sdob date;
b) REMOVING COLUMN
SQL> ALTER TABLE student
DROP COLUMN sdob;
c) MODIFY COLUMN
SQL> ALTER TABLE student
MODIFY marks number (5);
* To decrease precision the column should be empty.
* Or we can decrease the precision if length of the datatype is greater than the
Column value.
Page 18
7/27/2019 SQL Plsql Material
19/99
d) RENAMING COLUMN
Ex: SQL> ALTER TABLE student
RENAME COLUMN marks to smarks;
TRUNCATE:
This can be used to delete the entire table data permanently.
But table structure is available in the database.
Here (after truncate ) we can re enter the values into table.
SQL> TRUNCATE TABLE student;
DROP :
This will be used to drop the database object.
Here entire data and structure of the table will lose from the database.
SQL> DROP TABLE student;
RENAME:
This will be used to rename the database object;
SQL> RENAME student TO stud;
TCL
COMMIT:
This will be used to save the work.
Commit is of two types.
Page 19
7/27/2019 SQL Plsql Material
20/99
Implicit
Explicit
a) IMPLICIT:
This will be issued by oracle internally in two situations.
When any DDL operation is performed.
When you are exiting from SQL * PLUS.
b) EXPLICIT:
This will be issued by the user.
Syntax: Commit or commit work;
* When ever you committed then the transaction was completed.
ROLLBACK:
This will undo the operation.
This will be applied in two methods.
Upto previous commit
Upto previous rollback
Syntax: Roll or roll work; Or Rollback or rollback work;
* While process is going on, if suddenly power goes then oracle will rollback the transaction.
SAVEPOINT:
You can use savepoints to rollback portions of your current set of transactions.
Syntax: Savepoint < savepoint_name >;
Ex: SQL> savepoint s1;
Page 20
7/27/2019 SQL Plsql Material
21/99
SQL> insert into student values(1, a, 100);
SQL> savepoint s2;
SQL> insert into student values(2, b, 200);
SQL> savepoint s3;
SQL> insert into student values(3, c, 300);
SQL> savepoint s4;
SQL> insert into student values(4, d, 400);
Before rollback
SQL> select * from student;
SQL> rollback to savepoint s3;
Or
SQL> rollback to s3;
This will rollback last two records.
SQL> select * from student;
Page 21
7/27/2019 SQL Plsql Material
22/99
DCL
DCL commands are used to granting and revoking the permissions.
GRANT:
This is used to grant the privileges to other users.
Syntax: Grant < privileges > on < object_name > to < user_name > [with grant option];
SQL> grant select on student to Sateesh; -- you can give individual privilege
SQL> grant select,insert on student to Sateesh; -- you can give set of privileges
SQL> grant all on student to Sateesh; -- you can give all privileges
The Sateesh user has to use dot method to access the object.
SQL> select * from scott.student;
The Sateesh user can not grant permission on student table to other users. To get this type of option use the following.
SQL> grant all on student to Sateesh with grant option;
Now Sateesh user also has the grant permissions on student table.
Page 22
7/27/2019 SQL Plsql Material
23/99
REVOKE:
This is used to revoke the privileges from the users to which you granted the privileges.
Syntax: Revoke < privileges > on < object_name > from < user_name >;
SQL> revoke select on student form Sateesh;-- you can revoke individual privilege
SQL> revoke select, insert on student from Sateesh; -- you can revoke set of privileges
SQL> revoke all on student from Sateesh; -- you can revoke all privileges
PARTITIONS
A single logical table can be split into a number of physically separate pieces based on ranges of key values. Each of the parts of the table is called a partition.
A non-partitioned table can not be partitioned later.
TYPES:
Page 23
7/27/2019 SQL Plsql Material
24/99
Range partitions
List partitions
ADVANTAGES:
Reducing downtime for scheduled maintenance, which allows maintenance operations to
be carried out on selected partitions while other partitions are available to users.
Reducing downtime due to data failure, failure of a particular partition will no way affect
other partitions.
Partition independence allows for concurrent use of the various partitions for various
purposes.
ADVANTAGES OF PARTITIONS BY STORING THEM IN DIFFERENT TABLESPACES
Reduces the possibility of data corruption in multiple partitions.
Back up and recovery of each partition can be done independently.
DISADVANTAGES
Partitioned tables cannot contain any columns with long or long raw datatypes, LOB
types or object types.
RANGE PARTITIONS: Creating range partitioned table
Page 24
7/27/2019 SQL Plsql Material
25/99
SQL> CREATE TABLE student_rpd
(
no number(2),
name varchar(10)
)
partition by range(no)
(
partition p1 values less than(10),
partition p2 values less than(20),
partition p3 values less than(30),
partition p4 values less than(maxvalue)
);
Note: If you are using maxvalue for the last partition, you can not add a partition.
b) Inserting records into range partitioned table
SQL> Insert into student values(1,a); -- this will go to p1
SQL> Insert into student values(11,b); -- this will go to p2
SQL> Insert into student values(21,c); -- this will go to p3
SQL> Insert into student values(31,d); -- this will go to p4
c) Retrieving records from range partitioned table
SQL> Select *from student;
SQL> Select *from student partition(p1);
d) Possible operations with range partitions
Add
Drop
Page 25
7/27/2019 SQL Plsql Material
26/99
Truncate
Rename
e) Adding a partition
SQL> ALTER TABLE student
ADD PARTITION p5 VALUES LESS THAN (40);
f) Dropping a partition
SQL> ALTER TABLE student
DROP PARTITION p4;
g) Renaming a partition
SQL> ALTER TABLE student
RENAME PARTITION p3 TO p6;
h) Truncate a partition
SQL> ALTER TABLE student
TRUNCATE PARTITION p6;
LIST PARTITION: Creating list partitioned table
SQL> CREATE TABLE student_lpd
(
no NUMBER(4),
Page 26
7/27/2019 SQL Plsql Material
27/99
name VARCHAR(10),
branch VARCHAR2(10)
)
PARTITION BY LIST(branch)
(
PARTITION p1 VALUES ('ece','eee'),
PARTITION p2 VALUES ('cse','it'),
PARTITION p3 VALUES ('civil','mechanical')
);
c) Retrieving records from list partitioned table
d) Possible operations with list partitions
Add
Drop
Truncate
Rename
GROUP BY
HAVING
ROLL UP
CUBE
1 select deptno,job,sum(sal)
2 from emp
3* group by deptno,job
DEPTNO JOB SUM(SAL)
30 SALESMAN 1965.15
20 MANAGER 6218.92
select deptno,job,sum(sal)
from emp
* group by rollup(deptno,job)
DEPTNO JOB SUM(SAL)
10 MGR 24675
10 CLERK 1729.91
Page 27
7/27/2019 SQL Plsql Material
28/99
20 CLERK 3971.74
30 CLERK 1094.5
10 PRESIDENT 6653.45
30 MANAGER 3283.52
10 CLERK 1729.91
10 MANAGER 34760.19
20 ANALYST 6271.19
10 MGR 24675
0 rows selected.
10 MANAGER 34760.19
10 PRESIDENT 6653.45
10 67818.55
20 CLERK 3971.74
20 ANALYST 6271.19
20 MANAGER 6218.92
20 16461.85
30 CLERK 1094.5
30 MANAGER 3283.52
30 SALESMAN 1965.15
30 6343.17
90623.57
CONSTRAINTS
Constraints are categorized as follows.
Domain integrity constraints
Not null
Check
Entity integrity constraints
Unique
Primary key
Referential integrity constraints
Page 28
7/27/2019 SQL Plsql Material
29/99
7/27/2019 SQL Plsql Material
30/99
SQL> create table student(no number(2) , name varchar(10), marks number(3), check
(marks > 300));
SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint ch
check(marks > 300));
ALTER LEVEL
SQL> alter table student add check(marks>300);
SQL> alter table student add constraint ch check(marks>300);
UNIQUE:
This is used to avoid duplicates but it allows nulls.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) unique, name varchar(10), marks number(3));
SQL> create table student(no number(2) constraint un unique, name varchar(10), marks
number(3));
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10), marks number(3),
unique(no));
SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint un
unique(no));
Page 30
7/27/2019 SQL Plsql Material
31/99
ALTER LEVEL
SQL> alter table student add unique(no);
SQL> alter table student add constraint un unique(no);
PRIMARY KEY:
This is used to avoid duplicates and nulls. This will work as combination of unique and not null.
Primary key always attached to the parent table.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) primary key, name varchar(10), marks number(3));
SQL> create table student(no number(2) constraint pk primary key, name varchar(10),
marks number(3));
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10), marks number(3),
primary key(no));
SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint pk
primary key(no));
Page 31
7/27/2019 SQL Plsql Material
32/99
ALTER LEVEL
SQL> alter table student add primary key(no);
SQL> alter table student add constraint pk primary key(no);
FOREIGN KEY:
This is used to reference the parent table primary key column which allows duplicates.
Foreign key always attached to the child table.
We can add this constraint in table and alter levels only.
Ex:
TABLE LEVEL
SQL> create table emp(empno number(2), ename varchar(10), deptno number(2),
primary key(empno), foreign key(deptno) references dept(deptno));
SQL> create table emp(empno number(2), ename varchar(10), deptno number(2),
constraint pk primary key(empno), constraint fk foreign key(deptno) references
dept(deptno));
ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references dept(deptno);
SQL> alter table emp add constraint fk foreign key(deptno) references dept(deptno);
Once the primary key and foreign key relationship has been created then you can not remove any
parent record if the dependent Childs exist.
Page 32
7/27/2019 SQL Plsql Material
33/99
ON DELTE CASCADE:
By using this clause you can remove the parent record even it Childs exists.
Because when ever you remove parent record oracle automatically removes all its dependent
records from child table, if this clause is present while creating foreign key constraint.
TABLE LEVEL
SQL> create table emp(empno number(2), ename varchar(10), deptno number(2),
primary key(empno), foreign key(deptno) references dept(deptno) on delete cascade);
SQL> create table emp(empno number(2), ename varchar(10), deptno number(2),
constraint pk primary key(empno), constraint fk foreign key(deptno) references
dept(deptno) on delete cascade);
ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references dept(deptno) on delete cascade;
SQL> alter table emp add constraint fk foreign key(deptno) references dept(deptno) on
delete cascade;
COMPOSITE KEYS:
A composite key can be defined on a combination of columns.
We can define composite keys on entity integrity and referential integrity constraints.
Composite key can be defined in table and alter levels only.
UNIQUE (TABLE LEVEL)
SQL> create table student(no number(2) , name varchar(10), marks number(3),
Page 33
7/27/2019 SQL Plsql Material
34/99
unique(no,name));
SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint
un unique(no,name));
UNIQUE (ALTER LEVEL)
SQL> alter table student add unique(no,name);
SQL> alter table student add constraint un unique(no,name);
PRIMARY KEY (TABLE LEVEL)
SQL> create table student(no number(2) , name varchar(10), marks number(3),
primary key(no,name));
SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint pk
primary key(no,name));
PRIMARY KEY (ALTER LEVEL)
SQL> alter table student add primary key(no,anme);
SQL> alter table student add constraint pk primary key(no,name);
FOREIGN KEY (TABLE LEVEL)
SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), dnamevarchar(10), primary key(empno), foreign key(deptno,dname) references dept(deptno,dname));
SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), dname
varchar(10), constraint pk primary key(empno), constraint fk foreign key(deptno,dname)
references dept(deptno,dname));
Page 34
7/27/2019 SQL Plsql Material
35/99
FOREIGN KEY (ALTER LEVEL)
SQL> alter table emp add foreign key(deptno,dname) references dept(deptno,dname);
SQL> alter table emp add constraint fk foreign key(deptno,dname) references
dept(deptno,dname);
OPERATIONS WITH CONSTRAINTS:
Possible operations with constraints as follows.
Enable
Disable
Drop
ENABLE:
This will enable the constraint. Before enable, the constraint will check the existing data.
Ex: SQL> ALTER TABLE student
ENABLE CONSTRAINT un;
DISABLE:
This will disable the constraint.
Ex: SQL> ALTER TABLE student
DISABLE CONSTRAINT un;
Page 35
7/27/2019 SQL Plsql Material
36/99
DROP:
This will remove the constraint.
Ex: SQL> ALTER TABLE student
DROP CONSTRAINT un;
Once the table is dropped, constraints automatically will drop.
SET OPERATORS
TYPES
Union
Union all
Intersect
Page 36
7/27/2019 SQL Plsql Material
37/99
Minus
UNION:
This will combine the records of multiple tables having the same structure.
Ex: SQL> SELECT * FROM student1
UNION
SELECT * FROM student2;
UNION ALL:
This will combine the records of multiple tables having the same structure but including
duplicates.
Ex: SQL> SELECT * FROM student1
UNION ALL
SELECT * FROM student2;
INTERSECT:
This will give the common records of multiple tables having the same structure.
Ex: SQL> SELECT * FROM student1
INTERSECT
SELECT * FROM student2;
MINUS:
This will give the records of a table whose records are not in other tables having the same
structure.
Ex: SQL> SELECT * FROM student1
MINUS
Page 37
7/27/2019 SQL Plsql Material
38/99
SELECT * FROM student2;
JOINS
The purpose of a join is to combine the data across tables.
A join is actually performed by the where clause which combines the specified rows of
tables.
If a join involves in more than two tables then oracle joins first two tables based on the
joins condition and then compares the result with the next table and so on.
CATEGORIES OF JOINS:
1) ANSI SQL JOINS (works in all RDBMS environments)
2) ORACLE PROPRIETARY JOINS (works in only ORACLE environment)
TYPES OF JOINS:
Inner joins (reality)
Outer joins (reality & virtuality)
Inner Joins:
Displays result only when matched records are found.
Equi join
Non eqvi join
Self join , Natural joins are extended joins of Inner joins
Page 38
7/27/2019 SQL Plsql Material
39/99
Self join : works on same table but different columns
Natural join : system automatically applies join condition
Both result set should have same column to perform natural join
Outer Joins:
Left outer join
Right outer join
Full outer join
Inner joins:
Equi join:
When tables are joined based on common column, then it is called as equi join
SQL> select empno,ename,sal,dept.deptno,dname,job
from emp,dept
where emp.deptno=dept.deptno
SQL> select empno,ename,sal,d.deptno,dname,job
from dept d inner join emp e
on d.deptno=e.deptno
Non equi join:
Page 39
7/27/2019 SQL Plsql Material
40/99
When table are joined without any common columns then it is called as non equi join.
SQL> select empno,ename,grade,sal,lsal,hsal
from emp,salgrade
where sal between lsal and hsal
write a query to fetch all the employees along with their deptname and grade
SQL> select ename,dname,grade
from emp e,dept d,salgrade s
where e.deptno=d.deptno and
e.sal between lsal and hsal
Self Join:
When a table is joined to itself is called self join.
In self join , we will create two table aliases for same table.
SQL> select e.ename,m.ename
from emp e,emp m
where e.mgr= m.empno;
Natural Join:
SQL> select *
from emp natural join dept
where dname=accounting;
VIEWS
Page 40
7/27/2019 SQL Plsql Material
41/99
A view is a database object that is a logical representation of a table. It is delivered from a table
but has no storage of its own and often may be used in the same manner as a table.
A view takes the output of the query and treats it as a table, therefore a view can be thought of as
a stored query or a virtual table.
TYPES:
Simple view
Complex view
Simple view can be created from one table where as complex view can be created from multiple
tables.
WHY VIEWS ?
Provides additional level of security by restricting access to a predetermined set of rows
and/or columns of a table.
Hide the data complexity.
Simplify commands for the user.
VIEWS WITHOUT DML:
Read only view
View with group by
View with rownum
View with aggregate functions
Partition view
View with distinct
Ex:
SQL> Create view dept_v as select *from dept with read only;
SQL> Create view dept_v as select deptno, sum(sal) t_sal from emp group by deptno;
SQL> Create view stud as select rownum no, name, marks from student;
Page 41
7/27/2019 SQL Plsql Material
42/99
SQL> Create view student as select *from student1 union select *from student2;
SQL> Create view stud as select distinct no,name from student;
VIEWS WITH DML
View with not null column -- insert with out not null column not possible
-- update not null column to null is not possible
-- delete possible
View with out not null column which was in base table -- insert not possible
-- update, delete possible
View with expression -- insert , update not possible
-- delete possible
View with functions (except aggregate) -- insert, update not possible-- delete possible
View was created but the underlying table was dropped then we will get the message like
view has errors.
View was created but the base table has been altered but still the view was with the initial
definition, we have to replace the view to affect the changes.
Complex view (view with more than one table)
-- insert not possible
-- update, delete possible (not always)
CREATING VIEW WITHOUT HAVING THE BASE TABLE
Page 42
7/27/2019 SQL Plsql Material
43/99
SQL> Create force view stud as select * from student;
-- Once the base table was created then the view is validated.
VIEW WITH CHECK OPTION CONSTRAINT
SQL> Create view stud as select *from student where marks = 500 with check option constraint
Ck;
- Insert possible with marks value as 500
- Update possible excluding marks column
- Delete possible
DROPPING VIEWS
SQL> drop view dept_v;
SEQUENCE
Its a sql objects to genereate unique sequential numbers
Its used as primary key ,unique key purpose
Syntax:
CREATE SEQUENCE seq_name
INCREMENT BY integer
START WITH integer
MAXVAL integer
MINVAL integer
Page 43
7/27/2019 SQL Plsql Material
44/99
CYCLE/NOCYCLE
CACHE integer/NO CHACHE
INCREMENT BY:
Interval between serial numbers
Can be +ve or ve but not zero.
If not mention default is 1.
MIN VALUE:
Represents min value of sequence.
MAX VALUE:
Represents max value can be generated.
CYCLE:
Represents sequence will continue to generate values after reaching max value or min value also
NOCYCLE:
Represents sequence should stop generating new numbers once it reaches to targeted limits.
CACHE:
Represents pre allocation of sequence numbers
NOCYCLE:
Represents value of sequence are not pre allocated.
ALTER OPTIONS
The alter option is available here to alter sequences
Only upcoming values are effected due to these alterations.
Page 44
7/27/2019 SQL Plsql Material
45/99
START WITH option cannot be changed by using ALTER option.
To change the START WITH option , drop the sequence and then recreate the sequence.
While altering MAXVALUE we cannot give lower than currvalue.
DICTIONARY TABLES:
User_objects
User_sequences catalog.
Page 45
7/27/2019 SQL Plsql Material
46/99
MATERIALIZED VIEWS
Materialized view contains image of dat a from base tables in client system memory
location
Hence select statements on materialized view run faster than normal views.
In order to create materialized view on a base table table should have primary keyMaterialized views purpose is read only.
Advantages:
You can use materialized views to achieve one or more of the following goals:
Ease Network LoadsCreate a Mass Deployment Environment
Enable Data Subsetting
Enable Disconnected Computing
Creating of materialized views
Page 46
http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25283http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25286http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25288http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25290http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25286http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25288http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#25290http://download.oracle.com/docs/cd/B10500_01/server.920/a96567/repmview.htm#252837/27/2019 SQL Plsql Material
47/99
There are series of steps to create materialized views.
1) Grant permissions like create materialized view , create database link ur target
account.
2) Create database link to source account/login to access objects3) Make sure that our source table must have primary key .
4) Create log table to our source table. Which consist of all updations done to source table
5) Create materialized view to source table here.
Step1:
Login as system/manager:
SQL >Grant create materialized view to sateesh34;
SQL>Grant create database link to sateesh34;
Step -2
Login into source table account:
o Create primary key
o Create log table
SQL > CREATE MATERIALIZED VIEW LOG ON EMP;
Step3:
Page 47
7/27/2019 SQL Plsql Material
48/99
Login as sateesh34/sateesh34:
SQL> create database link www.scott.com
connect to scott
identified by tiger
using 'prod';
SQL> create materialized view mv_com
refresh fast with primary key
start with sysdate
next sysdate+1/(24*60)
as
Select * from [email protected]
SYNONYM
A synonym is a database object, which is used as an alias for a table, view or sequence.
A synonym is an alias for one of the following objects:
table
view
stored procedure
stored function
package
java class
used defined object object type
another synonym etc
Page 48
http://www.scott.com/http://www.scott.com/7/27/2019 SQL Plsql Material
49/99
TYPES:
Private
Public
Private synonym is available to the particular user who creates.
Public synonym is created by DBA which is available to all the users.
ADVANTAGES:
Hide the name and owner of the object.
Provides location transparency for remote objects of a distributed database.
CREATE AND DROP:
Syx1: CREATE SYNONYM synonym-name FOR OBJECT_NAME;
Syx1: CREATE PUBLIC SYNONYM synonym-name FOR OBJECT_NAME;
SQL> create synonym s1 for emp;
SQL> create public synonym s2 for emp;
SQL> drop synonym s1;
SUBQUERIES AND EXISTS
SUBQUERIES
Nesting of queries, one within the other is termed as a subquery.
A statement containing a subquery is called a parent query.
Subqueries are used to retrieve data from tables that depend on the values in the table itself.
TYPES
Page 49
7/27/2019 SQL Plsql Material
50/99
Single row subqueries
Multi row subqueries
Multiple subqueries
Correlated subqueries
SINGLE ROW SUBQUERIES:
In single row subquery, it will return one value.
Ex:
SQL> select * from emp where sal > (select sal from emp where empno = 7566);
MULTI ROW SUBQUERIES:
In multi row subquery, it will return more than one value. In such cases we should include
operators like any, all, in, not in, between, the comparision operator and the subquery.
Ex:/
SQL> select * from emp where sal > any (select sal from emp where sal between 2500 and
4000);
SQL> select * from emp where sal > all (select sal from emp where sal between 2500 and
4000);
MULTIPLE SUBQUERIES:
There is no limit on the number of subqueries included in a where clause. It allows nesting of a
query within a subquery.
Page 50
7/27/2019 SQL Plsql Material
51/99
SQL> select * from emp where sal = (select max(sal) from emp where sal < (select
max(sal) from emp));
CORRELATED SUBQUERIES:
A subquery is evaluated once for the entire parent statement where as a correlated subquery is
evaluated once for every row processed by the parent statement.
SQL> select distinct deptno from emp e where 5 select deptno,count(*) from emp group by deptno having count(*) > 4;
From the above query can you want to display the names of employees?
SQL> select deptno,ename, count(*) from emp group by deptno,ename having count(*) > 4;
no rows selected
The above query returns nothing because combination of deptno and ename never return more
than one count.
The solution is to use exists which follows.
SQL> select deptno,ename from emp e1 where exists (select * from emp e2
where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4) order
by deptno,ename;
NOT EXISTS:
Page 51
7/27/2019 SQL Plsql Material
52/99
SQL> select deptno,ename from emp e1 where not exists (select * from emp e2
where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4) order by
deptno,ename;
WALKUP TREES AND INLINE VIEW
WALKUP TREES:
Using hierarchical queries, you can retrieve data based on a natural hierarchical relationship
between rows in a table. However, where a hierarchical relationship exists between the rows of atable, a process called tree walking enables the hierarchy to be constructed.
SQL> select ename || '==>' || prior ename, level from emp start with ename = 'KING'
connect by prior empno=mgr;
In the above
Start with clause specifies the root row of the table.
Level pseudo column gives the 1 for root , 2 for child and so on.
Connect by prior clause specifies the columns which has parent-child relationship.
INLINE VIEW OR TOP-N ANALYSIS:
In the select statement instead of table name, replacing the select statement is known as inline
view.
Ex:
SQL> Select ename, sal, rownum rank from (select *from emp order by sal);
INDEXES
Page 52
7/27/2019 SQL Plsql Material
53/99
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because theindexes also need an update). So you should only create indexes on columns (and tables) that
will be frequently searched against.
Index is typically a listing of keywords accompanied by the location of information on a subject.
We can create indexes explicitly to speed up SQL statement execution on a table. The index
points directly to the location of the rows containing the value.
WHY INDEXES?
Indexes are most useful on larger tables, on columns that are likely to appear in where
clauses as simple equality.
TYPES
Unique index
Non-unique index
Btree index
Bitmap index
Composite index
Reverse key index
Index organized table
UNIQUE INDEX:
Unique indexes guarantee that no two rows of a table have duplicate values in the columns that
define the index. Unique index is automatically created when primary key or unique constraint is
created.
Page 53
7/27/2019 SQL Plsql Material
54/99
Ex: SQL> create unique index stud_ind on student(sno);
NON-UNIQUE INDEX:
Non-Unique indexes do not impose the above restriction on the column values.
Ex: SQL> create index stud_ind on student(sno);
BTREE INDEX:
The default type of index used in an oracle database is the btree index. A btree index is designed
to provide both rapid access to individual rows and quick access to groups of rows within a
range. The btree index does this by performing a succession of value comparisons. Each
comparison eliminates many of the rows.
Ex: SQL> create index stud_ind on student(sno);
BITMAP INDEX:
This can be used for low cardinality columns: that is columns in which the number of distinct
values is small when compared to the number of the rows in the table.
Ex:
SQL> create bitmap index stud_ind on student(sex);
COMPOSITE INDEX:
A composite index also called a concatenated index is an index created on multiple columns of a
table. Columns in a composite index can appear in any order and need not be adjacent columns
of the table.
Ex: SQL> create bitmap index stud_ind on student(sno, sname);
Page 54
7/27/2019 SQL Plsql Material
55/99
REVERSE KEY INDEX:
A reverse key index when compared to standard index reverses each byte of the column being
indexed while keeping the column order. Such an arrangement can help avoid performance
degradations in indexes.
Ex: SQL> create index stud_ind on student(sno, reverse);
We can rebuild a reverse key index into normal index using the noreverse keyword.
Ex: SQL> alter index stud_ind rebuild noreverse;
FUNCTION BASED INDEX:
This will use result of the function as key instead of using column as the value for the key.
Ex: SQL> create index stud_ind on student(upper(sname));
INDEX-ORGANIZED TABLE:
An index-organized table keeps its data sorted according to the primary key column values for
the table. Index-organized tables store their data as if the entire table was stored in an index.
An index-organized table allows you to store the entire tables data in an index.
Ex: SQL> create table student (sno number(2),sname varchar(10),smarks number(3) constraint
pk primary key(sno) organization index;
Page 55
7/27/2019 SQL Plsql Material
56/99
---------------------------------------case statements------------------------------------------
select empno,ename,deptno,
case deptno
when 10 then 'accounts'
when 20 then 'sales'
when 30 then 'purchase'
else 'raw material'
end
from emp
order by deptno
/
-----------------------------------------------------------
select ename,sal,
case
when sal>800 and sal=3000 and sal=6000 and sal
7/27/2019 SQL Plsql Material
57/99
else 'grade 4'
end
from emp
order by deptno
/
------------------------------------pseudo columns--------------------------------------------------
Pseudo column behave like a table column, but not actually stored in a table
Against pseudo column only SELECT will work
Against pseudo column INSERT, DELETE,UPDATE(DML) cannot work
CASE AND DEFAULT
CASE:
Case is similar to decode but easier to understand while going through coding
Ex : SQL> Select sal,
Case sal
When 500 then low
When 5000 then high
Else medium
End case
From emp;
Page 57
7/27/2019 SQL Plsql Material
58/99
Ex: select empno,ename,deptno,
case deptno
when 10 then 'accounts'
when 20 then 'sales'
when 30 then 'purchase'
else 'raw material'
end
from emp
order by deptno
/
Ex: select ename,sal,
case
when sal>800 and sal=3000 and sal=6000 and sal
7/27/2019 SQL Plsql Material
59/99
Default can be considered as a substitute behavior of not null constraint when applied to new
rows being entered into the table.
When you define a column with the default keyword followed by a value, you are actually telling
the database that, on insert if a row was not assigned a value for this column, use the defaultvalue that you have specified.
Default is applied only during insertion of new rows.
Ex: SQL> create table student(no number(2) default 11,name varchar(2));
SQL> insert into student values(1,'a');
SQL> insert into student(name) values('b');
SQL> select * from student;
SQL> insert into student values(null, c);
SQL> select * from student;
- Default can not override nulls.
DECODE:
In oracle PL/SQL, The decode function has the functionality of an IF-THEN-ELSE Statement.
SYNTAX:-
Decode(expression,
Search_1,result_1,
Search_2,result_2,
Default
Page 59
7/27/2019 SQL Plsql Material
60/99
)
Here
Expression is the Value to Compare.
Search is the value that is compared against expression.
Result is the Value Returned if the Expression is equal to search.
Default is optional. if no matches are found then decode will return default.If Default is
omitted then the decode statement will return null value.(IF NO MATCHES ARE FOUND).
Increment the salaries with decode operator
select empno,ename,deptno,
sal old_sal,
sum(decode(deptno,
10,sal+(sal*(10/100)),
20,sal+(sal*(20/100)),
30,sal+(sal*(30/100)),
Page 60
7/27/2019 SQL Plsql Material
61/99
'0000') )newsal
from vamsi_emp
/
With out default value in synatax:
select empno,ename,deptno,
sal old_sal,
decode(deptno,
10,sal+(sal*(10/100)),
20,sal+(sal*(20/100)),
30,sal+(sal*(30/100))
) newsal
from vamsi_emp
/
Sum of new salaries incremented by decode
select
sum(decode(deptno,
Page 61
7/27/2019 SQL Plsql Material
62/99
10,sal+(sal*(10/100)),
20,sal+(sal*(20/100)),
30,sal+(sal*(30/100)),
'0000')) newsal
from vamsi_emp
/
Using decode multiple times in query:
select empno,ename,deptno,
decode(deptno,10,'ece',
20,'cse',
30,'eee',
40,'it'
) dname,
decode(deptno,10,sal+(sal*(10/100)),
20,sal+(sal*(20/100)),
30,sal+(sal*(30/100))
) newsal
from vamsi_emp
Page 62
7/27/2019 SQL Plsql Material
63/99
INTRODUCTION
What is PL/SQL?
SQL statements operate independently, having little effect on one another. This is of limited usefor writing programs, where you must create a body of code that is going to vary its behavior
according to the data and to user or other input.
Advantages of PL/SQL
These are the advantages of PL/SQL.
Block Structures
Better Performance
Higher Productivity
Full Portability
Tight Security
Error Handling:
Access to Pre-defined Packages
Support for Object-Oriented Programming
Support for Developing Web Applications and Pages
The basic unit in any PL/SQL program is block. All PL/SQL programs are composed of blocks
which can occur sequentially or nested.
BLOCK STRUCTURE
Declare
Page 63
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAHAGEF%23CJAHAGEFhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJABDHHJ%23CJABDHHJhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJADFBDD%23CJADFBDDhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAFDGHC%23CJAFDGHChttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAJDHCF%23CJAJDHCFhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAFFJDB%23CJAFFJDBhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAIEIJA%23CJAIEIJAhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAHAGEF%23CJAHAGEFhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJABDHHJ%23CJABDHHJhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJADFBDD%23CJADFBDDhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAFDGHC%23CJAFDGHChttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAJDHCF%23CJAJDHCFhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAFFJDB%23CJAFFJDBhttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm#CJAIEIJA%23CJAIEIJA7/27/2019 SQL Plsql Material
64/99
7/27/2019 SQL Plsql Material
65/99
MULTILINE COMMENTS:
Multiline comments start with the /* delimiter and ends with */ delimiter.
Ex: BEGIN
Dbms_output.put_line(hello); /* sample program */
END;
VARIABLE DECLERATIONS
Variables can be declared in declarative section of the block;
Ex:
DECLAREa number;
b number := 5;
c number default 6;
d number constant := 7;
ANCHORED DECLERATIONS
PL/SQL offers two kinds of achoring.
Scalar anchoring
Record anchoring
SCALAR ANCHORING:
Use the %TYPE attribute to define your variable based on tables column of some other PL/SQL
scalar variable.
Ex:
DECLARE
dno dept.deptno%type;
RECORD ANCHORING:
Use the %ROWTYPE attribute to define your record structure based on a table.
Ex:
DECLARE
V_dept dept%rowtype;
Page 65
7/27/2019 SQL Plsql Material
66/99
PL/SQL CONTROL STRUCTURES :
PL/SQL has a variety of control structures that allow you to control the behaviour of the block as
it runs. These structures include conditional statements and loops.
Syntax:1
If < condition1 > then
Sequence of statements;
Elsif < condition1 > then
Sequence of statements;
Else
Sequence of statements;
End if;
Ex:
DECLARE
dno number(2);BEGIN
select deptno into dno from dept where dname = 'ACCOUNTING';
if dno = 10 then
dbms_output.put_line('Location is NEW YORK');
elsif dno = 20 then
dbms_output.put_line('Location is DALLAS');
Page 66
7/27/2019 SQL Plsql Material
67/99
elsif dno = 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end if;
END;
Output: Location is NEW YORK
SIMPLE LOOP:
Syntax:
LoopSequence of statements;
Exit when < condition >;
End loop;
In the syntax exit when < condition > is equivalent to
If < condition > then
Exit;
End if;
Ex:
DECLARE
i number := 1;
BEGIN
loop
dbms_output.put_line('i = ' || i);
i := i + 1;
exit when i > 5;
end loop;
END;
Output: i = 1
Page 67
7/27/2019 SQL Plsql Material
68/99
i = 2
i = 3
i = 4
i = 5
WHILE LOOP:
Syntax:
While loop
Sequence of statements;End loop;
Ex:
DECLARE
i number := 1;
BEGIN
While i in low_bound ..high_bound loop
Sequence of statements;
Page 68
7/27/2019 SQL Plsql Material
69/99
End loop;
Ex1:
BEGIN
For i in 1..5 loop
dbms_output.put_line('i = ' || i);
end loop;
END;
Output: i = 1
i = 2
i = 3
i = 4i = 5
Ex2:
BEGIN
For i in reverse 1..5 loop
dbms_output.put_line('i = ' || i);
end loop;
END;
Output: i = 5
i = 4
i = 3
i = 2
i = 1
Page 69
7/27/2019 SQL Plsql Material
70/99
CURSORS
Introduction:
Cursor is a pointer to memory location(RAM) called as context area whichcontains the information necessary for row by row processing, including the number of rows
processed by the statement, a pointer to the parsed representation of the statement, and the active
set which is the set of rows returned by the query.
Cursor contains two parts
Header
Body
Header includes cursor name, any parameters and the type of data being loaded.Body includes the select statement.
Ex:
Cursor c(dno in number) return dept%rowtype is select *from dept;
In the above
Header cursor c(dno in number) return dept%rowtype
Body select *from dept
CURSOR TYPES
Implicit (SQL)
Explicit
Parameterized cursors
Nested Cursors
REF cursors
Page 70
7/27/2019 SQL Plsql Material
71/99
CURSOR STAGES
Declare
Open
Fetch
Close
CURSOR ATTRIBUTES
%found
%notfound
%rowcount %isopen
%bulk_rowcount
%bulk_exceptions
CURSOR DECLERATION
Syntax:
Cursor < cursor_name > is select statement ;Ex:
Cursor c is select *from dept;
CURSOR LOOPS:
Simple loop
While loop
For loop
SIMPLE LOOP:
Syntax:
Loop
Fetch < cursor_name > into < record_variable >;
Exit when < cursor_name > % notfound;
Page 71
7/27/2019 SQL Plsql Material
72/99
< statements >;
End loop;
Ex:
DECLARE
cursor c1 is select * from emp;
v_data c1%rowtype;
begin
open c1;
fetch c1 into v_data;
while c1%found
loop
dbms_output.put_line(v_data.empno);fetch c1 into v_data;
end loop;
close c1;
END;
SQL> /
2233
7369
7499
7521
PL/SQL procedure successfully completed.
WHILE LOOP:
Syntax:
While < cursor_name > % found loop
Fetch < cursor_name > into < record_variable >;
< statements >;
End loop;
Ex:
DECLARE
cursor c1 is select * from emp;
Page 72
7/27/2019 SQL Plsql Material
73/99
v_data c1%rowtype;
begin
open c1;
fetch c1 into v_data;
while c1%found
loop
dbms_output.put_line('record number'||c1%rowcount||' is '||v_data.empno
||' with '||v_data.ename);
fetch c1 into v_data;
end loop;
close c1;
END;SQL> /
record number1 is 2233 with SURESH
record number2 is 7369 with SMITH
record number3 is 7499 with ALLEN
record number4 is 7521 with WARD
record number5 is 7566 with JONES
PL/SQL procedure successfully completed.
FOR LOOP:
Syntax:
for < record_variable > in < cursor_name > loop
< statements >;
End loop;
Ex:
DECLARE
cursor c1 is select * from emp;
v_data c1%rowtype;
begin
for v1 in c1 loop
Page 73
7/27/2019 SQL Plsql Material
74/99
dbms_output.put_line(v1.empno);
end loop;
END;
SQL> /
2233
7369
7499
7521
7566
PL/SQL procedure successfully completed.
Ex:
DECLARE
cursor c1 is select * from emp;
v_data c1%rowtype;
begin
open c1;
fetch c1 into v_data;
while c1%found
loop
dbms_output.put_line('recordnumber'||c1%rowcount||' '||v_data.empno);
fetch c1 into v_data;
end loop;
close c1;
END;
SQL> /
record number1 2233
record number2 7369
record number3 7499
record number4 7521
record number5 7566
Page 74
7/27/2019 SQL Plsql Material
75/99
PL/SQL procedure successfully completed.
Ex:
SQL>
DECLARE
v_deptno emp.deptno%type :=&deptno;
begin
update emp set sal=1500 where deptno = v_deptno;
--dbms_output.put_line('1 row has been updated');
dbms_output.put_line(sql%rowcount||'rows are updated');
if sql%notfound thendbms_output.put_line('data not found... updation abruptly terminated');
end if;
END
PARAMETARIZED CURSORS:
This was used when you are going to use the cursor in more than one place with different
values for the same where clause. Cursor parameters must be in mode.
Cursor parameters may have default values.
The scope of cursor parameter is within the select statement.
Ex:
DECLARE
cursor c(dno in number) is select * from dept where deptno = dno;v_dept dept%rowtype;
BEGIN
open c(20);
loop
fetch c into v_dept;
exit when c%notfound;
Page 75
7/27/2019 SQL Plsql Material
76/99
dbms_output.put_line('Dname = ' || v_dept.dname || ' Loc = ' ||
dept.loc);
end loop;
close c;
END;
Output:
Dname = RESEARCH Loc = DALLAS
NESTED CURSORS:
EX:
DECLARE
cursor c1 is select * from dept;
cursor c2(a number) is select * from emp where deptno=a;
v_data c1%rowtype;
v_data2 c2%rowtype;
begin
for v1 in c1 loop
dbms_output.put_line(v1.deptno||' '||v1.dname);
for v2 in c2(v1.deptno) loop
dbms_output.put_line(v2.empno||' '||v2.ename||' '||v2.sal);
exit when c2%notfound;
end loop;
exit when c1%notfound;
end loop;
END;
/
Output:
20 SALES
Page 76
7/27/2019 SQL Plsql Material
77/99
7566 JONES 6218.92
7876 ADAMS 2299.43
7369 SMITH 1672.31
30 HR
7499 ALLEN 20000
7698 BLAKE 3283.52
7900 JAMES 1094.5
10 accounting
7782 CLARK 3104.94
7839 ssssssssss 6336.62
4477 MUNE 23500
7934 MILLER 1647.53
REF cursor:
A ref cursor in Oracle PL/SQL is much like an ordinary PL/SQL cursor in that it
acts as a pointer to the result set of the cursor with which it is associated. However, the
difference is that a ref cursor can be assigned to different result sets whereas a cursor is always
associated with the same result set. Cursors and ref cursors are not interchangeable.
The real purpose of ref cursors is to be able to share cursors and result sets
between the client and the Oracle server or between different subroutines
There are two steps required to create a cursor variable.
define a ref cursor TYPE.
declare cursor variable(s) of that type.
Ex:
Create or replace procedure proc123 is
Type ty_dt is ref cursor;
C_V ty_dt;
v_data emp%rowtype;
Page 77
7/27/2019 SQL Plsql Material
78/99
Begin
Open C_V for select * from emp;
loop
Fetch C_V into v_data;
Dbms_output.put_line(v_data.empno|| v_data.ename|| v_data.sal);
Exit when C_V%notfound;
End loop;
Close C_V;
END;
EXCEPTIONS
Introduction:
PL/SQL implements error handling with exceptions and exception handlers.
Exceptions can be associated with oracle errors or with your own user-defined errors. By using
exceptions and exception handlers, you can make your PL/SQL programs robust and able to deal
with both unexpected and expected errors during execution.
ERROR TYPES:
Compile-time errors
Runtime errors
Errors that occur during the compilation phase are detected by the PL/SQL engine and reported
back to the user, we have to correct them.
Runtime errors are detected by the PL/SQL runtime engine which can programmatically raise
and caught by exception handlers.Exceptions are designed for run-time error handling, rather than compile-time error handling.
HANDLING EXCEPTIONS:
When exception is raised, control passes to the exception section of the block. The exception
section consists of handlers for some or all of the exceptions. An exception handler contains the
Page 78
7/27/2019 SQL Plsql Material
79/99
code that is executed when the error associated with the exception occurs, and the exception is
raised.
Syntax:
EXCEPTION
When exception_name then
Sequence_of_statements;
When exception_name then
Sequence_of_statements;
When others then
Sequence_of_statements;
END;
EXCEPTION TYPES
Predefined exceptions
User-defined exceptions
PREDEFINED EXCEPTIONS:
Oracle has predefined several exceptions that corresponds to the most common oracle errors.
Like the predefined types, the identifiers of these exceptions are defined in the STANDARD package. Because of this, they are already available to the program, it is not necessary to declare
them in the declarative secion.
EX:1
DECLARE
a number :=&A_Number_is;
b number :=&B_Number_is;
c number;
begin
c:=a/b;
dbms_output.put_line('the value for c is'||c);
exception
when zero_divide then
Page 79
7/27/2019 SQL Plsql Material
80/99
dbms_output.put_line('plz enter non zero value for b ');
END;
/
EX:2
DECLARE
v_empno varchar2(20):='&empno';
v_ename varchar2(20):='&ename';
begin
insert into emp(empno,ename) values(v_empno,v_ename);
exception
when invalid_number thendbms_output.put_line('sorry this is invalid number format');
when dup_val_on_index then
dbms_output.put_line('duplicate index is comming');
when no_data_found then
dbms_output.put_line('sorry this number is not available');
END;
/
EX:3
DECLARE
cursor c1 is select * from emp;
v_data c1%rowtype;
begin
open c1;
fetch c1 into v_data;
dbms_output.put_line(v_data.empno);
open c1;
--close c1;
close c1;
exception
Page 80
7/27/2019 SQL Plsql Material
81/99
when invalid_cursor then
dbms_output.put_line('this is invalid cursor');
when cursor_already_open then
dbms_output.put_line('the cursor alredy is open');
END;
/
EX:4.
declare
v_grade varchar2(10):='&entergrade';begin
case v_grade
when 'a' then
dbms_output.put_line('excellent');
when 'b' then
dbms_output.put_line('good');
when 'c' then
dbms_output.put_line('average');
when 'd' then
dbms_output.put_line('poor');
end case;
exception
when case_not_found then
dbms_output.put_line('sorry u entered invalid grade');
end;
/
USER-DEFINED EXCEPTIONS:
A user-defined exception is an error that is defined by the programmer. User-defined exceptions
are declared in the declarative secion of a PL/SQL block. Just like variables, exeptions have a
Page 81
7/27/2019 SQL Plsql Material
82/99
type EXCEPTION and scope.
RAISING EXCEPTIONS
User-defined exceptions are raised explicitly via the RAISE statement.
Ex_1:
DECLARE
e exception;
BEGIN
If then
Statement1;
else
raise e;
End if;
EXCEPTION
when e then
dbms_output.put_line('e is raised');
END;
Output:
e is raised
Ex_2:
DECLARE
e1 exception;
e2 exception;
Page 82
7/27/2019 SQL Plsql Material
83/99
BEGIN
BEGIN
raise e1;
EXCEPTION
when e1 then
dbms_output.put_line('e1 is raised');
raise e2;
when e2 then
dbms_output.put_line('e2 is raised');
END;
EXCEPTION
when e2 thendbms_output.put_line('From outer block: e2 is raised');
END;
Output:
e1 is raised
From outer block: e2 is raised
RAISE_APPLICATION_ERROR:
You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.
Syntax:
RAISE_APPLICATION_ERROR( error_number , error_message ,, [keep_errors_flag ]);
The Boolean parameter keep_errors_flag is optional. If it is TRUE, the new error is added to the
list of errors already raised. If it is FALSE, which is default, the new error will replace the
current list of errors.
Page 83
7/27/2019 SQL Plsql Material
84/99
PROCEDURES
Introduction:
Procedure is a subprogram used to perform a specific action. A procedure
contains two parts specification and the body. Procedure specification begins with CREATE and
ends with procedure name or parameters list. Procedures that do not take parameters are written
without a parenthesis. The body of the procedure starts after the keyword IS or AS and ends with
keyword END.
Advantages:
Stored Procedures are precompiled one.
It is the group of sql statements.
Stored procedure is a fast one because it is already precompiled.
stored procedure is the one ie easy to maintain.
Syntax:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
Page 84
7/27/2019 SQL Plsql Material
85/99
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
CREATE TABLE T2 (a INTEGER, b CHAR(10));
Ex1:
CREATE OR REPLACE PROCEDURE insert_record(p_no IN NUMBER,
p_name IN varchar2)
IS
BEGIN
INSERT INTO T2 VALUES(p_no,'p_name');
dbms_output.put_line('one row is inserted');
END;
/
Ex2: (out parameter)
create or replace procedure outpa(a in number,
b out varchar2,
c out number,
d out number)
is
begin
select ename,sal,comm
into b,c,d
from emp
where empno=a;
Page 85
7/27/2019 SQL Plsql Material
86/99
end;
/
Procedure created.
SQL> var x varchar2(10)
SQL> var y number
SQL> var z number
SQL> exec outpa( 7934,:x,:y,:z);
PL/SQL procedure successfully completed.
SQL> print x;
X
--------------------------------MILLER
SQL> print y;
Y
----------
1647.53
SQL> print z;
Z
----------
Ex:(inout parameter)
Create procedure proc123(x in out number) is
Begin
X:=x+1; --x acts like out
Dbms_output.put_line(x);
End;
Declare
Page 86
7/27/2019 SQL Plsql Material
87/99
i NUMBER:=10;
BEGIN
Proc123(i); -- passing value in mode
END;
Ex1:
CREATE OR REPLACE PROCEDURE salary_increment(p_deptno IN NUMBER)
IS
BEGIN
if p_deptno=10 then
update emp set sal=sal+sal*(10/100) where deptno=p_deptno;
elsif p_deptno=20 thenupdate emp set sal=sal+sal*(15/100) where deptno=p_deptno;
elsif p_deptno=30 then
update emp set sal=sal+sal*(20/100) where deptno=p_deptno;
else
update emp set sal=sal+sal*(25/100) where deptno=p_deptno;
end if;
commit;
dbms_output.put_line('updation is over||thank you');
END;
Page 87
7/27/2019 SQL Plsql Material
88/99
FUNCTION
Introduction:
A function is a named PL/SQL Block which is similar to a procedure. The major
difference between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.
PROCEDURES VERSES FUNCTIONS:
Procedures may return through out and in out parameters where as function must
return.
Procedures can not have return clause where as functions must.
Page 88
7/27/2019 SQL Plsql Material
89/99
We can use call statement directly for executing procedure where as we need to
declare a variable in case of functions.
Functions can use in select statements where as procedures can not.
Functions can call from reports environment where as procedures can not.
We can use exec for executing procedures where as functions can not.
Function can be used in dbms_output where as procedure can not .
The General Syntax to create a function is:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
Exception section
Return return_variable;END;
EX:
CREATE or REPLACE function
ITAX(num number)
RETURN number
IS
t number(9,2);
BEGIN
t:=num*(2/100);
RETURN t;
Page 89
7/27/2019 SQL Plsql Material
90/99
END
EX:
CREATE or REPLACE FUNCTION PExp(V_Empno NUMBER)
RETURN number
IS
V_HireDate Emp.HireDate%TYPE;
V_Exp number(4,2):=1;
BEGIN
SELECT HireDate INTO V_HireDate
FROM Emp
WHERE Empno=V_Empno;V_Exp:=MONTHS_BETWEEN(SYSDATE,V_HireDate)/12;
RETURN V_Exp;
END;
How to execute functions (Three ways)
1.select from dual;
2.begin
Dbms_output.put_line(functionname);
end;
3.declare
X number;
Begin
X := functionname;
End;
Calling Procedures From Functions:
CREATE or REPLACE function calpro(num number)
RETURN number
IS
t number(9,2);
Page 90
7/27/2019 SQL Plsql Material
91/99
BEGIN
t:=num*(2/100);
msg_display(); -- we are calling this procedure from function
RETURN t;
END;
PACKAGES
Introduction:
Packages shows you how to bundle related PL/SQL programming resources into
a package. The resources might include a collection of procedures and functions.
A package is a schema object that groups logically related PL/SQL types, items, and
subprograms. Packages usually have two parts, a specification and a body, although sometimes
the body is unnecessary. The specification (spec for short) 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 spec.
The first time a packaged subprogram is called or any reference to a packaged variable or
type is made, the package is instantiated.
Each session will have its own copy of packaged variables, ensuring that two sessions
executing subprograms in the same package use different memory locations.
In many cases initialization needs to be run the first time the package is instantiated
within a session. This can be done by adding initialization section to the package body after all
the objects.
Packages are stored in the data dictionary and can not be local.
Packaged subprograms has an advantage over stand alone subprogram.
When ever any reference to package, the whole package p-code was stored in shared poolof SGA.
Package may have local subprograms.
Page 91
7/27/2019 SQL Plsql Material
92/99
Advantages of PL/SQL Packages:
Modularity
Easier Application Design
Information Hiding
Added Functionality
Better Performance
Package Specification:
CREATE OR REPLACE PACKAGE UD_Pkg
IS
FUNCTION ITAX(Num NUMBER) RETURN NUMBER;
FUNCTION PExp(V_Empno NUMBER) RETURN NUMBER;
PROCEDURE insert_record(p_no IN NUMBER,p_name IN varchar2);
PROCEDURE salary_increment(p_deptno IN NUMBER);
END UD_Pkg;
Package Body:
CREATE or REPLACE PACKAGE UD_Pkg
AS
FUNCTION ITAX(Num NUMBER) RETURN NUMBER
IS
Page 92
7/27/2019 SQL Plsql Material
93/99
t number(9,2);
BEGIN
t:=Num*(2/100);
RETURN t;
END ITAX;
FUNCTION PEXP(V_Empno NUMBER) RETURN NUMBER
IS
V_HireDate Emp.HireDate%TYPE;
V_Exp number(4,2):=1;
BEGIN
SELECT HireDate INTO V_HireDate
FROM Emp
WHERE Empno=V_Empno;
V_Exp:=MONTHS_BETWEEN(SYSDATE,V_HireDate)/12;
RETURN V_Exp;
END PEXP;
PROCEDURE insert_record(p_no IN NUMBER, p_name IN varchar2)
IS
BEGIN
INSERT INTO T2 VALUES(p_no,'p_name');
dbms_output.put_line('one row is inserted');
END insert_record;
Page 93
7/27/2019 SQL Plsql Material
94/99
PROCEDURE salary_increment(p_deptno IN NUMBER)
IS
BEGIN
if p_deptno=10 then
update emp set sal=sal+sal*(10/100) where deptno=p_deptno;
elsif p_deptno=20 then
update emp set sal=sal+sal*(15/100) where deptno=p_deptno;
elsif p_deptno=30 then
update emp set sal=sal+sal*(20/100) where deptno=p_deptno;
else
update emp set sal=sal+sal*(25/100) where deptno=p_deptno;
end if;
commit;
dbms_output.put_line('updation is over||thank you');
END salary_increment;
END UD_Pkg;
PRAGMA Autonomous Transactions:
PRAGMA's are directives for the Oracle PL/SQL compiler. The
AUTONOMOUS_TRANSACTION pragma instructs the compiler to treat the following pl/sql
block as autonomous (independent) from whatever transaction calls it. This means that any
changes made to the database in the autonomous transaction are independent of the main
transaction and are either committed or rolled back without affecting the main transaction.
Oracle pl/sql autonomous transactions must explicitly either roll back or commit any changes
before exiting and can be:- stand alone procedures or functions
Page 94
7/27/2019 SQL Plsql Material
95/99
procedures/functions defined in a package (but not nested)
triggers
schema-level anonymous pl/sql blocks
Example.
First we declare an anonymous transaction
CREATE OR REPLACE PROCEDURE log_details
(msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION
BEGIN
INSERT INTO log(msg_id ,log_msg,time_of_msg)
VALUES (log_seq.NEXTVAL,msg,SYSDATE);
COMMIT; -- must commit or rollback
END;
Next, we have another transaction that calls this procedure.
BEGIN
DELETE employees;
log_msg('Deleting all employees');
ROLLBACK;
log_msg('after rollback of delete employees');
END;
Page 95
7/27/2019 SQL Plsql Material
96/99
TRIGGERS
Introduction:
Triggers are similar to stored procedures. A trigger stored in the database can
include SQL and PL/SQL or Java statements to run as a unit and can invoke stored procedures.
However, procedures and triggers differ in the way that they are invoked. A procedure is
explicitly run by a user, application, or trigger. Triggers are implicitly fired by Oracle when a
triggering event occurs, no matter which user is connected or which application is being used.
Advantages:
Triggers is a special kind of procedure.
the Main advantage of the trigger is automatic.
whenever the table affected by insert update or delete
query that time the triggers will implicitely call.
You can write triggers that fire whenever one of the following operations occurs:
1. DML statements (INSERT, UPDATE, DELETE) on a particular table or view, issued byany user
2. DDL statements (CREATE or ALTER primarily) issued either by a particular
schema/user or by any schema/user in the database
3. Database events, such as logon/logoff, errors, or startup/shutdown, also issued either by a
particular schema/user or by any schema/user in the database
Page 96
7/27/2019 SQL Plsql Material
97/99
Parts of a Trigger:
A trigger has three basic parts:
A triggering event or statement
A trigger restriction
A trigger action
Types of Triggers:
This section describes the different types of triggers:
Row Triggers and Statement Triggers
BEFORE and AFTER Triggers
INSTEAD OF Triggers
Triggers on System Events and User Events
Trigger Execution:
A trigger is in either of two distinct modes:
Trigger
Mode DefinitionEnabled An enabled trigger runs its trigger action if a triggering statement is issued and the
trigger restriction (if any) evaluates to true.
Disabled A disabled trigger does not run its trigger action, even if a triggering statement is
issued and the trigger restriction (if any) would evaluate to true.
Page 97
http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i6047http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i6052http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i10900http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i6061http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i6047http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i6052http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i10900http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#i60617/27/2019 SQL Plsql Material
98/99
EX :
create or replace trigger aft_ins
after insert or update or delete
on emp
declare
v_day varchar2(10);
begin
v_day:=to_char(sysdate,'dy');
dbms_output.put_line('you are inserting rows at '||v_day||' day ');
end;
/
EX:
create or replace trigger bef_ins
before insert or update or delete
on emp
declare
v_day varchar2(5);
begin
v_day:=to_char(sysdate,'dy');
IF v_day is 'SAT' or v_day is 'SUN' then
dbms_output.put_line('server not allowing week end transactions');
end if;
end;
/
Co-Relation Identifiers in Row Level:
Two co-relation identifiers provided by pl/sql are :OLD & :NEW.
These are special kind of bind variables.
EX:
create or replace trigger deptrbin
before delete on dept
Page 98
7/27/2019 SQL Plsql Material
99/99
for each row
begin
insert into recyclebin values(:OLD.deptno,:OLD.dname,:OLD.loc);
end;
EX:
create or replace trigger aft_ins_fe
after delete on emp
for each row
begin
dbms_output.put_line('you are deleting rows');
end;/
Ex:
create or replace trigger non_working_hours
before insert or update or delete
on emp
for each row
begin
if(to_char(sysdate,'hh24')17 or
to_char(sysdate,'dy')='sat' or
to_char(sysdate,'dy')='sun' ) then