R20 DBMS Lab Manual Master
R20 DBMS Lab Manual Master
(AUTONOMOUS)
(Approved By AICTE, Affiliated By JNTUK, Kakinada, Accredited with ‘A’ Grade by NAAC and NBA)
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
Prepared by
1
CONTENTS OF LAB MANUAL
6. CO’s 9
7. CO/ PO/ PSO Mapping 9
8. CO-PO mapping with reasons 10
Details of Experiments
Working with ER Diagram
9 11
● To produce eminent and ethical Engineers and Managers for society by imparting
quality professional education with emphasis on human values and holistic
excellence.
MISSION
3
DEPARTMENT VISION AND MISSION
To become a reputed center in computer Science and systems engineering for quality,
competency and social responsibility.
Mission of the Department:
DM2 Providing additional skills and training to meet the current needs of the industry.
DM3 Inculcating ethical values to meet the challenges of life with courage and confidence.
4
PROGRAM OUTCOMES (PO’S)
1. Engineering knowledge:
Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
2. Problem analysis:
Identify, formulate, research literature, and analyze complex engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions:
Design solutions for complex engineering problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural, societal, and environmental considerations.
8. Ethics:
Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice.
10. Communication:
Communicate effectively on complex engineering activities with the engineering community and with society at large, such
as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance:
Demonstrate knowledge and understanding of the engineering and management principles and apply these to one’s own
work, as a member and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning:
Recognize the need for, and have the preparation and ability to engage in independent and life-long learning in the broadest
context of technological change.
5
PROGRAM SPECIFIC OUTCOME (PSO’S)
6
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
(Autonomous)
Accredited by NBA & NAAC with Grade “A” and Affiliated to JNTUK-Kakinada
Vinjanampadu, Vatticherukuru Mandal, Guntur, Andhra Pradesh522017
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course Code Course Name LTPC
20CS4L01 Database Management Systems Lab 0 0 3 1.5
Course Outcomes:
At the end of the course, the students will be able to:
CO1: Demonstrate the database design using ER Diagrams.
CO2: Develop SQL Queries to manipulate the data in the database.
CO3: Inspect and handle errors using exception handling mechanism.
CO4: Apply Procedural Language constructs to execute block of SQL statements.
List of Experiments:
Experiment 1: Working with ER Diagram
Example: ER Diagram for Sailors Database
Entities:1 Sailor 2. Boat
Relationship: Reserves
Primary Key Attributes:
1. SID (Sailor Entity)
2. BID (Boat Entity)
Experiment 2: Working with DDL, DML, DCL and Key Constraints
Creating, Altering and Dropping of Tables and Inserting Rows into a Table (Use Constraints
While Creating Tables), Examples using Select command.
Experiment 3: Working with Queries and Nested Queries
Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSECT and Constraints.
Experiment 4: Working with Queries using Aggregate Operators & Views
Queries using Aggregate Functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING, Creation and Dropping of Views.
7
Experiment 5: Working with Conversion Functions & String Functions
Queries using Conversion Functions (to_char, to_number and to_date), String Functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), Date
Functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc,
round, to_char, to_date).
Experiment 6: Working with Triggers using PL/SQL
Develop programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers.
Experiment 7: Working with PL/SQL Procedures
Develop programs using Procedures, passing Parameters IN and OUT of Procedures.
Experiment 8: Working with Loops using PL/SQL and Exception Handling
Develop programs using WHILE loops, FOR loops, Nested loops using ERROR handling,
BUILTIN Exceptions, USER defined Exceptions, and RAISE_APPLICATION_ERROR.
Experiment 9: Working with Functions using PL/SQL
Develop programs using stored Functions, invoke Functions in SQL statements and write
complex Functions.
Experiment 10: Working with Cursors using PL/SQL
Develop programs using Cursors, parameters in a Cursor, FOR UPDATE Cursor, WHERE
CURRENT OF clause and Cursor variables.
TEXT BOOKS:
1. Benjamin Rosenzweig, Elena Silvestrova Rakhimov, Oracle PL/SQL by Example,
3rdEdition,Pearson Education.
2. Scott Urman, Ron Hardman,MichaelMclaughlin, Oracle Database 10G PL/SQL
Programming,
Tata Mc-Graw Hill.
3. Dr .P.S. Deshpande,SQL and PL/SQL for Oracle 11g, Black Book.
8
COURSE OUTCOMES:
Course Course Outcome Taxonomy Level
Code
C2206.1 Demonstrate the database design using ER Diagrams. Knowledge
C2206.2 Develop SQL Queries to manipulate the data in the database. Apply
C2206.3 Inspect and handle errors using exception handling mechanism. Apply
CO-PO MAPPING
PO PO PO PO PO1
PO/CO NO: PO2 PO3 PO5 PO8 PO9 PO10 PO11
1 4 6 7 2
C2206.1 3 2
C2206.2 1
C2206.3 2 3
C2206.4 2
9
CO-PO mapping Reasons
10
Experiment 1: Working with ER Diagram
Basic notations used in E-R model:-
Strong entity
An entity that exists independently of the other entity types is called strong entity.
Weak entity
An entity that is always dependent on the other entity is called weak entity.
Relationship
A meaningful association between or among the entity types is called relationship.
Identifying relationship
The relationship between the weak entity and strong entity or its owner is called identifying
relationship.
Attribute
A property or characteristic of an entity type is called attribute.
11
Simple attribute
An attribute that cannot be broken into smaller components that are meaningful to the
organization is called simple attribute.
Composite attribute
An attribute that can be broken into number of smaller components is called composite
attribute.
For example,
address
Multivalued attribute
An attribute that may take more than one value for a given entity instance is called
multivalued attribute.
For example,
address
12
Derived attribute
An attribute whose value can be calculated from the related attribute value of the same
entity is called derived attribute.
For example,
Relationship
A meaningful association between or among the entity types is called relationship.
Degree of relationship
The number of entity types that participate in a relationship is called degree of relationship.
-> There are three types of relationships. They are
1. Unary relationship or Recursive relationship.
2. Binary relationship.
3. Ternary relationship.
13
Unary relationship
The relationship between the instances of a single entity type is called unary relationship or
recursive relationship.
Example:
Binary relationship
The relationship between the instances of two entity types is called binary relationship.
Example:
14
Ternary relationship
A simultaneous relationship among the instances of three entity types is called ternary
relationship.
Example:
M N
SAILOR reserves BOAT
bname
15
Experiment 2: Working with DDL, DML, DCL and Key Constraints.
Creating, Altering and Dropping of Tables and Inserting Rows into a Table (Use Constraints
While Creating Tables), Examples using Select command.
ALTERING TABLE
1. ALTER TABLE STUDENT
ADD PHNO NUMBER(10) NOT NULL;
INSERTION OF ROWS
INSERT INTO STUDENT VALUES
(&RNO,'&NAME',&AGE,'&BRANCH',&PHNO);
16
RNO NAME AGE BRANCH PHNO
1 ABC 20 CSE 123
2 XYZ 20 CSE 456
3 PQR 18 IT 234
4 ABC 18 IT 567
5 DEF 19 CAI 1234
6 PQRS 19 CAI 5678
7 ABCD 21 CSD 789
8 WXYZ 21 CSD 6789
9 MNOP 17 ECE 12345
10 DEFG 17 ECE 56789
QUERIES
1. DISPLAY ALL THE RECORDS IN STUDENT TABLE
SELECT * FROM STUDENT;
17
2. DISPLAY NAME,PHNO IN STUDENT TABLE
SELECT NAME,PHNO FROM STUDENT;
NAME PHNO
ABC 123
XYZ 456
PQR 234
ABC 567
DEF 1234
PQRS 5678
ABCD 789
WXYZ 6789
MNOP 12345
DEFG 56789
BRANCH COUNT(*)
CSE 2
IT 2
CAI 2
CSD 2
ECE 2
19
Experiment 3: Working with Queries and Nested Queries.
Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSECT and Constraints.
1. ANY
This will return TRUE if any of the sub query value meet the condition
2. ALL
This will return TRUE if all of the sub query values meet the condition
3. IN
This will return TRUE if operand is equal to one of the list of values
4. EXISTS
This will return TRUE if sub query returns one or more records
5. NOT EXISTS
This will return TRUE if sub query not returns one or more records
6. SET OPERATORS
1. UNION
This will combine the result of two or more SELECT statements. It avoids duplication.
SYN:
SELECT statement1
UNION
SELECT statement2;
2. INTERSECT
This will return only common records returned by two or more SELECT statement.
SYN:
SELECT STATEMENT1
INTERSECT
SELECT STATEMENT2;
20
3. MINUS
This will return records from the set which does not exists in another set.
SYN:
SELECT STATEMENT1
MINUS
SELECT STATEMENT2;
4. UNION ALL
This will combine the result of two or more SELECT statements including duplication.
SYN:
SELECT statement1
UNION ALL
SELECT statement2;
EXAMPLE QUERIES
1. Write a query to get empno, ename, job and deptno of managers.
SELECT EMPNO,ENAME,JOB,DEPTNO FROM EMP E
WHERE EXISTS(SELECT EMPNO FROM EMP WHERE EMP.MGR=E.EMPNO);
21
ENAME JOB
TURNER SALESMAN
WARD SALESMAN
MARTIN SALESMAN
ALLEN SALESMAN
MILLER CLERK
SMITH CLERK
ADEMS CLERK
JAMES CLERK
3. Write a query to get employee names who are getting any salary of employees
working in the department 20.
SELECT ENAME FROM EMP WHERE SAL =ANY(SELECT SAL FROM EMP WHERE
DEPTNO=20);
ENAME
SMITH
JONES
FORD
SCOTT
ADEMS
4. Write a query to get employee names who are getting less salary of any employees
working in the department 20.
SELECT ENAME FROM EMP WHERE SAL <ANY(SELECT SAL FROM EMP WHERE
DEPTNO=20);
22
ENAME
SMITH
JAMES
ADEMS
WARD
MARTIN
MILLER
ALLEN
CLARK
BLAKE
JONES
5. Write a query to get employee names who are belonging to departments 10,20,30.
SELECT ENAME FROM EMP WHERE DEPTNO IN (10,20,30);
ENAME
SMITH
JONES
FORD
SCOTT
ADEMS
6. SET OPERATORS
1. Display different designations in the departments 20 and 30
23
JOB
CLERK
SALESMAN
MANAGER
ANALYST
JOB
CLERK
MANAGER
JOB
ANALYST
24
JOB
MANAGER
ANALYST
ANALYST
CLERK
CLERK
MANAGER
SALESMAN
SALESMAN
SALESMAN
SALESMAN
CLERK
25
Experiment 4: Working with Queries using Aggregate Operators & Views
Queries using Aggregate Functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING, Creation and Dropping of Views.
26
View Creation
create or replace view viewaggregate
as
select
job,
sum(sal) "sum",
count(*) "count",
avg(sal) "average",
max(sal) "max",
min(sal) "min"
from emp
group by job;
View created.
SQL> select * from viewaggregate;
JOB sum count average max min
CLERK 4150 4 1037.5 1300 800
SALESMAN 5600 4 1400 1600 1250
PRESIDENT 5000 1 5000 5000 5000
MANAGER 8275 3 2758.33333 2975 2450
ANALYST 6000 2 3000 3000 3000
VIEW deletion
SYN:
DROP VIEW VNAME;
EG: DROP VIEW VIEWAGGREGATE;
27
Experiment 5: Working with Conversion Functions & String Functions
Queries using Conversion Functions (to_char, to_number and to_date),
String Functions (Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length,
substr)
Date Functions (Sysdate, next_day, add_months, last_day, months_between, least,
greatest, trunc, round, to_char, to_date).
Conversion functions:
These functions are to convert the one data type to another data type.
a) TO_CHAR(‘date’, format ) : it is used to convert the date into the specified character
format.
Syntax:
Select TO_CHAR(‘Date specification’, ‘DDTH-MMTH-YYTH’) from DUAL;
SPECIAL DATE FORMATS :
DEFAULT FORMAT - DD:MON:YY;
DAY:
D - DAY OF WEEK(1 TO 7)
DD - DAY OF THE MONTH(1 TO 31)
DDD - DAY OF THE YEAR(1 TO 365)
DY - NAME OF THE DAY,THREE LETTER ABBRIVITAION SUN,MON,THU
DAY - NAME OF THE DAY(MONDAY,SUNDAY etc)
MONTH:
MM - MONTH OF NUMBER( 1 TO 12)
MON - NAME OF THE MONTH WITH THREE LETTERS(JAN,FEB,MAR )
MONTH - FULL NAME OF THE MONTH.
YEAR :
Y - LAST DIGIT OF THE YEAR(2000-0)
YY - TWO DIGITS OF THE YEAR(2000-00)
YYY - THREE DIGITS OF THE YEAR(2000-000)
YYYY – FULL DIGITS OF THE YEAR
Y,YYY - 2,000
28
1. SELECT to_char(sysdate, 'mm-dd-yyyy') from dual
TO_CHAR(SYSDATE)
04-18-2022
29
b) TO_DATE(‘char’ , format) : it is used to convert the character into specified date
format;
Syntax: Select TO_DATE(‘date in character’ , ‘date’) from dual;
String functions
lower( ) – This function returns the string in lower case.
1. SELECT lower(ename) from emp;
2. SELECT * FROM emp WHERE JOB = lower('MANAGER')
Initcap( ) – This function returns the string with first letter as capital.
SELECT initcap('hello my name is Imtiaz') as sentence from dual;
Substr – This function returns the sub string of the given string.
1. select substr('hello', 2, 2) from dual;
2. select 'hello', substr('hello', 2, 2) from dual;
3. select 'hello', substr('hello', 2) from dual;
4. select 'Hello my name is', substr('Hello my name is', 10) from dual;
5. select 'Hello my name is', substr('Hello my name is', 10, 5) from dual;
6. select 'Hello my name is', length(substr('Hello my name is', 10, 5)) from dual;
30
LPAD – This function adds the symbol in the left side of the string.
1. select LPAD('hello', 10, '&') from dual;
2. select LPAD('hello', 100, '&') from dual;
RPAD – This function adds the symbol in the right side of the string.
select RPAD('hello', 100, '&') from dual;
LTRIM – This function trimming the left side of the string.
select LTRIM('hello', 'h') from dual;
Date functions
1) SYSDATE: it returns the system date.
Syntax: Select SYSDATE from DUAL;
select SYSDATE from dual;
SYSDATE
17-MAY-22
2) NEXT_DAY(‘date’,’day name’) : it returns the date of next specified day of the week
after the date.
Syntax: Select NEXT_DAY(‘date’, ‘day name’) from DUAL;
select SYSDATE, NEXT_DAY(SYSDATE,'WEDNESDAY') from dual;
SYSDATE NEXT_DAY(SYSDATE,'
13-AUG-15 19-AUG-15
31
HIREDDATE ADD_MONTHS(HIREDDA ADD_MONTHS(HIREDDA
09-JUN-81 09-OCT-81 09-FEB-81
17-NOV-81 17-MAR-82 17-JUL-81
23-JAN-82 23-MAY-82 23-SEP-81
5) ROUND(m,n): It is used to round the n specify number of digits after the decimal.
Syntax: Select ROUND(M,n) from DUAL;
select ROUND(TO_DATE('12-apr-71'),'MM') "Nearest month"
from dual;
Nearest month
01-APR-71
6) TRUNC(m,n): It is used to Truncates the n specify number of digits after the decimal.
Syntax: Select ROUND(M,n) from DUAL;
1.SELECT hiredate, trunc(hiredate, 'MONTH') from emp
32
7. GREATEST(list of values): It returns greatest value in given list of values.
Syntax: Select GREATEST(v1,v2,v3,….) from dual;
select GREATEST(10,'7',-1) from dual;
GREATEST(10,'7',-1)
10
33
What is PL/SQL?
PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of
SQL along with the procedural features of programming languages. It was developed by
Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any variables, constants, records and cursors,
which are used to manipulate data in the execution section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and
ends with END. This is a mandatory section and is the section where the program logic is
written to perform any task. The programmatic constructs like loops, conditional statement
and SQL statements form the part of execution section.
Exception Section:
Exception section starts with EXCEPTION keyword. This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions can be
handled in this section.
34
Every statement in the above three sections must end with a semicolon; and PL/SQL
blocks can be nested within other PL/SQL blocks. Comments can be used to document
code.
Comments:
1) Single line Comments: --(double hyphen) is used for single line comments
2) Multiple line Comments: /*…*/ symbols are used for multi line comments
PL/SQL Variables
These are placeholders that store the values that can change through the PL/SQL Block.
The General Syntax to declare a variable is:
vname datatype := value;
Each variable declaration is a separate statement and must be terminated by a semicolon.
35
Experiment 6: Working with Triggers using PL/SQL
Develop programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers.
Def:
Trigger is a stored procedure that initiates an action when an event(insert/delete/update)
occurs. They are stored and managed by DBMS. The DBMS automatically fires the trigger
as a result of a data modification to the associated table. Its syntax is
Syntax
CREATE [OR REPLACE ] TRIGGER tname
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
36
This clause determines the triggering event. More than one triggering events can be used
together separated by OR keyword. The trigger gets fired at all the specified triggering
event.
[OF col_name] -:
This clause is used with update triggers. This clause is used when you want to trigger an
event only when a specific column is updated.
[ON table_name] :
- This clause identifies the name of the table or view to which the trigger is associated.
[REFERENCING OLD AS o NEW AS n] :-
This clause is used to reference the old and new values of the data being changed. By
default, you reference the values as :old.column_name or :new.column_name. The
reference names can also be changed from old (or new) to any other user-defined name.
You cannot reference old values when inserting a record, or new values when deleting a
record, because they do not exist.
[FOR EACH ROW] :-
This clause is used to determine whether a trigger must fire when each row gets affected (
i.e. a Row Level Trigger) or just once when the entire sql statement is executed(i.e.
Statement Level Trigger).
WHEN (condition) :-
This clause is valid only for row level triggers. The trigger is fired only for rows that
satisfy the condition specified.
Types of PL/SQL Triggers
There are two types of triggers based on the which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.
37
These events will alternates between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.
Example:
SQL>CREATE TABLE EMPLOYEE1(EMPNO NUMBER(10), ENAME
VARCHAR(20),
ADDRESS VARCHAR(20));
SQL> INSERT INTO EMPLOYEE2 VALUES(600,’Rama Rao’,’GUNTUR’);
SQL> INSERT INTO EMPLOYEE2 VALUES(700,’Chandra’’,’VIJAYAWAD’);
SQL> INSERT INTO EMPLOYEE2 VALUES(800,’Kumar’,’NARSAPUR’);
TRIGGER CREATION:
SQL> CREATE OR REPLACE TRIGGER EMP_TRIGG
AFTER UPDATE OR DELETE ON EMPLOYEE1
FOR EACH ROW
BEGIN
INSERT INTO EMP1 VALUES(:OLD.EMPNO, :OLD.ENAME, :OLD.ADDRESS);
END;
38
SQL> SELECT * FROM EMP1;
no rows selected
39
EMPNO ENAME ADDRESS
700 Chandra VIJAYAWADA
40
if Day_of_month BETWEEN 28 AND 31 then
RAISE excep;
end if;
EXCEPTION WHEN excep THEN
Dbms_output.put_line(‘Can not update between 28 and 31 dates of month’);
END;
41
Experiment 7: Working with PL/SQL Procedures
Develop programs using Procedures, passing Parameters IN and OUT of Procedures.
Definition
A Procedure is a subprogram unit that consists of a group of PL/SQL statements.
Each procedure in Oracle has its own unique name by which it can be referred. This
subprogram unit is stored as a database object.
These subprograms do not return a value directly; mainly used to perform an action.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
--> procedure-name specifies the name of the procedure.
-> [OR REPLACE] option allows the modification of an existing procedure.
-> The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter that
will be used to return a value outside of the procedure.
-> procedure-body contains the executable part.
-> The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example program-1
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
42
/
OUTPUT
Procedure created.
43
Example program-2 ----> IN and OUT example
This program finds the minimum of two values. Here, the procedure takes two
numbers using the IN mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result -
44
Example program-3 IN OUT example
This procedure computes the square of value of a passed value. This example shows how we
can use the same parameter to accept a value and then return another result.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result -
45
Experiment 8: Working with Loops using PL/SQL and Exception Handling
Develop programs using WHILE loops, FOR loops, Nested loops using ERROR
handling, BUILTIN Exceptions, USER defined Exceptions, and
RAISE_APPLICATION_ERROR.
1) Simple Loop: In this loop structure, sequence of statements is enclosed between the
LOOP and the END LOOP statements. At each iteration, the sequence of statements is
executed and then control resumes at the top of the loop. It requires EXIT statement within
the body to terminate the loop.
Syntax:
LOOP
Execute Commands/Statements
END LOOP;
Example: Write a program to display numbers from 1 to 5 along with their square values.
Declare
n number(3):=1;
begin
LOOP
Exit when n>=6;
Dbms_output.put_line(‘the square of ||n|| ’ is ‘||n*n);
n:=n+1;
END LOOP;
End;
Output:
46
Statement processed. the square of 1 is 1 the square of 2 is 4 the square of 3 is 9 the square
of 4 is 16 the square of 5 is 25
47
When zero_divide then
dbms_output.put_line(‘Division with zero ‘);
End;
Output:
Statement processed. The given number is not palindrome
3) FOR LOOP: Execute a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
Syntax:
FOR variable IN [Reverser] Start…end
LOOP
Execute Commands/Statement;
END LOOP;
Important steps to follow when executing a for loop:
1) The counter variable is implicitly declared in the declaration section, so it's not necessary
to
declare it explicitly. 2) The counter variable is incremented by 1 and does not need to be
incremented explicitly. 3) EXIT WHEN statement and EXIT statements can be used in FOR
loops but it's not done
oftenly.
Example: Program to check whether the given value is prime of not.
Declare
n number(5);
nof number:=0;
exp exception;
begin
n:=23;
if n<0 then
raise exp;
end if;
FOR i in 1..n
48
LOOP
if mod(n,i)=0 then
nof:=nof+1;
end if;
END LOOP;
if nof=2 then
dbms_output.put_line('The given number is prime');
else
dbms_output.put_line('The given number is not prime');
end if;
Exception
When zero_divide then
dbms_output.put_line('The value is too large to assign');
When exp then
dbms_output.put_line('The given value is negative');
End;
Output:
Statement processed. The given number is prime
Nested Loops: PL/SQL allows using one loop inside another loop. Such loops are called as
nested loops. We can use any loop in any other loop.
Example: Program to print Prime numbers upto 50.
Declare
nof number;
k number;
begin
dbms_output.put_line('The Prime numbers are given as ');
FOR n in 1..50 LOOP
nof:=0;
k:=floor(n/2);
FOR i in 2..k LOOP
49
if (mod(n,i)=0) then
nof:=1;
end if;
END LOOP;
if(nof=0) then
dbms_output.put_line(n);
End if;
END LOOP;
End;
Output:
Statement processed. The Prime numbers are given as 1 2 3 5 7 11 13 17 19 23 29 31 37 41
43 47
Types of Exception
There are two types of Exceptions in Pl/SQL.
1. Predefined Exceptions
2. User-defined Exception
Predefined Exceptions:
Oracle has predefined some common exceptions. These exceptions have a unique exception
name and error number. These exceptions are already defined in the 'STANDARD' package
in Oracle. In code, we can directly use these predefined exception name to handle them.
User-defined Exception
In Oracle, other than the above-predefined exceptions, the programmer can create their own
exception and handle them. They can be created at a subprogram level in the declaration
part. These exceptions are visible only in that subprogram. The exception that is defined in
the package specification is public exception, and it is visible wherever the package is
accessible.
Syntax: At Subprogram level
DECLARE
<exception_name> EXCEPTION;
50
BEGIN
<Execution block>
EXCEPTION
WHEN <exception_name> THEN
<Handler>
END;
Syntax: At Package specification level
CREATE PACKAGE <package_name>
IS
<exception_name> EXCEPTION;
.
.
END <package_name>;
All the predefined exceptions are raised implicitly whenever the error occurs. But the user-
defined exceptions needs to be raised explicitly. This can be achieved using the keyword
'RAISE'.
Syntax: RAISE <exception name>;
RAISE_APPLICATION_ERROR:
It is a built-in procedure in oracle which is used to display the user-defined error messages
along with the error number whose range is in between -20000 and -20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous
transactions which are not committed within the PL/SQL Block are rolled back
automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.
RAISE_APPLICATION_ERROR is used for the following reasons, a) to create a unique id
for an user-defined exception. b) to make the user-defined exception look like an Oracle
error.
Syntax:
raise_application_error( error_number, message[, {TRUE | FALSE}]);
51
The final parameter passed to the procedure is a Boolean(true/false) that tells the procedure
to add this error to the error stack or replace all errors in the stack with this error. Passing the
value of 'True' adds the error to the current stack, while the default is 'False'.
Steps to be folowed to use RAISE_APPLICATION_ERROR procedure: 1. Declare a user-
defined exception in the declaration section. 2. Raise the user-defined exception based on a
specific business rule in the execution section. 3. Finally, catch the exception and link the
exception to a user-defined error number in
RAISE_APPLICATION_ERROR
Example: Raise an error when balance of bank account is too low.
DECLARE
bal NUMBER;
low_bal exception;
pragma exception_init(low_bal, -20201);
BEGIN
SELECT balance INTO bal FROM CUSTOMER WHERE empid=125;
IF bal < 500 THEN
/* Issue your own error code( ORA-20201) with your own error message.*/
RAISE_APPLICATION_ERROR(-20201, ‘The Balance is too low’);
END IF
EXCEPTION
WHEN low_bal THEN
Dbms_output.put_line(SQLCODE);
Dbms_output.put_line(sqlerrm);
END;
Output:
-20201
ORA-20201: The Balance is too low
52
Experiment 9: Working with Functions using PL/SQL
Develop programs using stored Functions, invoke Functions in SQL statements and
write
complex Functions.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement.
syntax:
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
->function-name specifies the name of the function.
-> [OR REPLACE] option allows the modification of an existing function.
-> The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter that
will be used to return a value outside of the procedure.
-> The function must contain a return statement.
-> The RETURN clause specifies the data type you are going to return from the function.
-> function-body contains the executable part.
-> The AS keyword is used instead of the IS keyword for creating a standalone function.
53
Example program -1
The following example illustrates how to create and call a standalone function. This function
returns the total number of employees in the EMP table.
CREATE OR REPLACE FUNCTION totalEmployees
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total FROM emp;
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result
-
Function created.
Calling a Function
To call a function, we simply need to pass the required parameters along with the function
name and if the function returns a value, then we can store the returned value.
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result -
Total no. of Employees: 14
54
Example program -2 ---> Recursive functions
DECLARE
num number;
factorial number;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result -
Factorial 6 is 720
PL/SQL procedure successfully completed.
55
Experiment 10: Working with Cursors using PL/SQL
Develop programs using Cursors, parameters in a Cursor, FOR UPDATE Cursor,
WHERE CURRENT OF clause and Cursor variables
What is Cursor?
A cursor is a temporary work area created in the system memory when a SQL
statement is executed. A cursor contains information on a select statement and the rows of
data accessed by it.
This temporary work area is used to store the data retrieved from the database, and
manipulate this data. A cursor can hold more than one row, but can process only one row at
a time. The set of rows the cursor holds is called the active set.
There are two types of cursors in PL/SQL:
A) Implicit cursors
These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed. They are also created when a SELECT statement that
returns just one row is executed.
Implicit cursor Attributes
1. SQL%FOUND
The return value is TRUE, if the DML statements like INSERT, DELETE and
UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.
The return value is FALSE, if DML statements like INSERT, DELETE and
UPDATE do not affect row and if SELECT….INTO statement do not return a row.
2. SQL%NOTFOUND
The return value is FALSE, if DML statements like INSERT, DELETE and
UPDATE at least one row and if SELECT ….INTO statement return at least one row.
The return value is TRUE, if a DML statement like INSERT, DELETE and
UPDATE do not affect even one row and if SELECT ….INTO statement does not return a
row.
3. %ROWCOUNT
Return the number of rows affected by the DML operations INSERT, DELETE,
UPDATE, SELECT
56
Example program to demonstrate implicit cursors
Update EMP table and increase the salary of each employee by 500 and use the
SQL%ROWCOUNT attribute to determine the number of rows affected.
DECLARE
total_rows number(2);
BEGIN
UPDATE EMP SET sal = sal + 500;
IF sql%notfound THEN
dbms_output.put_line('no employees are selected for updation');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' employees are updated ');
END IF;
END;
/
OUTPUT
14 employees are updated
B) Explicit cursors
They must be created when you are executing a SELECT statement that returns more
than one row. Even though the cursor stores multiple records, only one record can be
processed at a time, which is called as current row. When you fetch a row the current row
position moves to next row.
Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the PL/SQL
Block. It is created on a SELECT Statement which returns more than one row.
Syntax
CURSOR cursor_name IS select_statement;
57
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example - CURSOR c1 IS SELECT empno, ename, sal FROM emp;
Opening the Cursor
Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it.
For example, we will open the above defined cursor as follows -
OPEN c1;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time.
For example, we will fetch rows from the above-opened cursor as follows -
FETCH c1 INTO c1_id, c1_name, c1_sal;
Closing the Cursor
Closing the cursor means releasing the allocated memory.
For example, we will close the above-opened cursor as follows -
CLOSE c1;
Example program to demonstrate Explicit cursors
DECLARE
CURSOR RES IS SELECT *FROM EMPO3;
R EMPO3%ROWTYPE;
BEGIN
OPEN RES;
LOOP
FETCH RES INTO R;
EXIT WHEN RES%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(R.ENO||R.ENAME);
END LOOP;
CLOSE RES;
END;
/
OUTPUT - PL/SQL procedure successfully completed.
58
WHERE CURRENT OF & FOR UPDATE
The WHERE CURRENT OF clause is used in some UPDATE and DELETE statements.
The WHERE CURRENT OF clause in an UPDATE or DELETE statement states that the
most recent row fetched from the table should be updated or deleted. We must declare the
cursor with the FOR UPDATE clause to use this feature. Inside a cursor loop, WHERE
CURRENT OF allows the current row to be directly updated. When the session opens a
cursor with the FOR UPDATE clause, all rows in the return set will hold row-level
exclusive locks. Other sessions can only query the rows, but they cannot update, delete, or
select with FOR UPDATE. Oracle provides the FOR UPDATE clause in SQL syntax to
allow the developer to lock a set of Oracle rows for the duration of a transaction. The syntax
of using the WHERE CURRENT OF clause in UPDATE and DELETE statements follows:
WHERE [CURRENT OF cursor_name | search_condition]
Example 1: The following example opens a cursor for employees and updates the
commission, if there is no commission then assigned based on the salary level.
DECLARE
CURSOR C1 IS select empno, ename, salary from emp
WHERE comm IS NULL FOR UPDATE OF comm;
Var_comm number(10,2);
BEGIN
FOR R1 IN C1 LOOP
if R1.salary<=5000 then
Var_comm := R1.salary*0.25;
elsif R1.salaray<=10000 then
Var_comm:=R1.salaray*0.20;
elsif R1.salary<=30000 then
Var_comm:=R1.salary*0.15;
else
Var_comm:=R1.salary*0.12;
end if;
UPDATE emp SET comm=var_comm WHERE CURRENT OF C1;
END LOOP;
END;
59
ADDITIONAL EXPERIMENTS
11. Queries on relational operators
1. Display the name and salary of all employees whose salary is more than 1000.
Select ename, sal from emp where sal>2500;
ENAME SAL
JONES 2975
BLAKE 2850
SCOTT 3000
KING 5000
FORD 3000
2. Display the name and salary of all employees whose salary is less than 1000.
Select ename, sal from emp where sal<1000;
ENAME SAL
SMITH 800
JAMES 950
3. Display the name and salary of all employees whose salary is more than or equal
to 3000.
Select ename, sal from emp where sal>=3000;
ENAME SAL
SCOTT 3000
KING 5000
FORD 3000
60
12. Queries on logical operators
1. Display the names of clerks working in the department 20.
Select ename,job,deptno from emp where job=’CLERK’ and deptno=20;
ENAME JOB DEPTNO
SMITH CLERK 20
ADAMS CLERK 20
ENAME JOB
SMITH CLERK
ALLEN SALESMAN
WARD SALESMAN
MARTIN SALESMAN
SCOTT ANALYST
KING PRESIDENT
TURNER SALESMAN
ADAMS CLERK
JAMES CLERK
FORD ANALYST
MILLER CLERK
61
13. Queries based on special operator “BETWEEN”
1. Display employee names and salary whose salary is between 1000 and 2000.
Select ename, sal from emp where sal between 1000 and 2000;
ENAME SAL
ALLEN 1600
WARD 1250
MARTIN 1250
TURNER 1500
ADAMS 11000
MILLER 1300
2. List employee names who have joined before 30th june ’81 and after December ’81
Select ename from emp where hiredate between ’30-JUN-81’ and ’31-DEC-81’;
ENAME HIREDATE
MARTIN 28-SEP-81
KING 17-NOV-81
TURNER 08-SEP-81
JAMES 03-DEC-81
FORD 04-DEC-81
62
14. Queries based DISTINCT clause with SELECT
1. Display different jobs available in emp table.
Select distinct job from emp;
JOB
CLERK
SALESMAN
MANAGER
ANALYST
PRESIDENT
ENAME COMM
ALLEN 300
WARD 500
MARTIN 1400
TURNER 0
63
16. Queries about Matching pattern with a column from a table
1. Display employee name whose names start with “S”.
Select ename from emp where ename like ‘S%’;
ENAME
SMITH
SCOTT
ENAME
JONES
ADAMS
JAMES
ENAME
SMITH
ALLEN
JONES
BLAKE
CLARK
SCOTT
ADAMS
JAMES
ENAME
KING
MILLER
64