Dbms Lab Manual MR21 Syllabus Final (1)
Dbms Lab Manual MR21 Syllabus Final (1)
Prepared by
1
PROGRAM OUTCOMES
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
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.
2
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.
3
CS453PC: DATABASE MANAGEMENT SYSTEMS LAB
Course Objectives:
• Understand and apply the principles of data modelling using Entity Relationship
and develop a good database design.
• Understand the use of Structured Query Language (SQL) and its syntax.
• Apply Normalization techniques to normalize a database.
Course Outcomes:
LIST OF EXPERIMENTS:
1. Database Design with E-R Model ( Ex: Company Database, Sailors database)
2. Relational Model (Practicing DDL,DML, DCL commands) (Ex: Employee data base, sailors
database)
3. Applying constraints on Relations
4. Queries using - Aggregate functions, Order By, GROUP BY, HAVING Clause
5. Number Functions, String Functions, Date Functions
6. Nested Queries, Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT etc.)
4
7. Creation and dropping of Views.
8. Working with Join operations ( Inner join, equi join, natural join, outer joins)
9. Procedures and Functions in PL/SQL
10. Triggers (Creation of trigger, delete trigger, update trigger)
11. Usage of Cursor (Implicit and Explicit)
TEXT BOOKS:
REFERENCES BOOKS:
1. Database Systems design, Implementation, and Management, Peter Rob & Carlos
Coronel 7th Edition.
2. Fundamentals of Database Systems, Elmasri Navrate, Pearson Education
3. Introduction to Database Systems, C.J. Date, Pearson Education
4. Oracle for Professionals, The X Team, S. Shah and V. Shah, SPD.
5. Database Systems Using Oracle: A Simplified guide to SQL and PL/SQL, Shah, PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley Student
Edition.
5
INDEX
6
Exp.No Name of the Experiment Page.No
12 Functions 96
a) Write a function to find number of employees in an
organization
b) Function to find maximum of two numbers
c) Function to find Factorial of a number
d) Function to reverse the given number
e) Write a function to get total salary payable to employees.
13 Triggers 103
a) Write a trigger that doesnot allow a sal to be updates if
employee commission is null.
b) Write a trigger that inserts or updates values of ename and
job as UPPER case strings, if we give lower case strings
c) Write a trigger to ensure that department table doesnot
contain duplicate or null values in deptno coloumn.
14 CURSORS 106
a) Update students marks using implicit cursors.
b) Write a program to print names of all employees using
cursors
c) Write a cursor to find employee with given job and dno.
7
Experiment No: 1
An entity can be a real-world object, either animate or inanimate, that can be easily identifiable.
For example, in a school database, students, teachers, classes, and courses offered can be
considered as entities. All these entities have some attributes or properties that give them their
identity.
An entity set is a collection of similar types of entities. An entity set may contain entities with
attribute sharing similar values. For example, a Students set may contain all the students of a
school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity
sets need not be disjoint.
Entities are represented by means of rectangles. Rectangles are named with the entity set they
represent.
Attributes
Entities are represented by means of their properties, called attributes. All attributes have
values. For example, a student entity may have name, class, and age as attributes.
There exists a domain or range of values that can be assigned to attributes. For example, a
student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be
negative, etc.
Types of Attributes
• Simple attribute − Simple attributes are atomic values, which cannot be divided further.
For example, a student's phone number is an atomic value of 10 digits.
8
• Composite attribute − Composite attributes are made of more than one simple attribute.
For example, a student's complete name may have first_name and last_name.
• Derived attribute − Derived attributes are the attributes that do not exist in the physical
database, but their values are derived from other attributes present in the database. For
example, average_salary in a department should not be saved directly in the database,
instead it can be derived. For another example, age can be derived from data_of_birth.
9
Relationship
The association among entities is called a relationship. For example, an employee works_at a
department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.
Relationship Set
A set of relationships of similar type is called a relationship set. Like entities, a relationship too
can have attributes. These attributes are called descriptive attributes.
Degree of Relationship
The number of participating entities in a relationship defines the degree of the relationship.
• Binary = degree 2
• Ternary = degree 3
• n-ary = degree
Mapping Cardinalities
Cardinality is the number of instance of an entity from a relation that can be associated with the
relation.
• One-to-one − When only one instance of an entity is associated with the relationship, it
is marked as '1:1'. The following image reflects that only one instance of each entity
should be associated with the relationship. It depicts one-to-one relationship.
10
• One-to-many − When more than one instance of an entity is associated with a
relationship, it is marked as '1:N'. The following image reflects that only one instance of
entity on the left and more than one instance of an entity on the right can be associated
with the relationship. It depicts one-to-many relationship.
• Many-to-many − The following image reflects that more than one instance of an entity
on the left and more than one instance of an entity on the right can be associated with the
relationship. It depicts many-to-many relationship.
Participation Constraints
11
Generalization
As mentioned above, the process of generalizing entities, where the generalized entities contain
the properties of all the generalized entities, is called generalization. In generalization, a number
of entities are brought together into one generalized entity based on their similar characteristics.
For example, pigeon, house sparrow, crow and dove can all be generalized as Birds.
Specialization
12
Similarly, in a school database, persons can be specialized as teacher, student, or a staff, based
on what role they play in school as entities.
Inheritance
We use all the above features of ER-Model in order to create classes of objects in object-oriented
programming. The details of entities are generally hidden from the user; this process known as
abstraction.
For example, the attributes of a Person class such as name, age, and gender can be inherited by
lower-level entities such as Student or Teacher.
13
Types of Keys
Candidate key
A candidate key is a simple or composite key that is unique and minimal. It is unique because no
two rows in a table may have the same value at any time. It is minimal because every column is
necessary in order to attain uniqueness.
From our COMPANY database example, if the entity is Employee(EID, First Name, Last Name,
SIN, Address, Phone, BirthDate, Salary, DepartmentID), possible candidate keys are:
• EID, SIN
• First Name and Last Name – assuming there is no one else in the company with the same
name
• Last Name and DepartmentID – assuming two people with the same last name don’t
work in the same department
Composite key
Using the example from the candidate key section, possible composite keys are:
• First Name and Last Name – assuming there is no one else in the company with the same
name
• Last Name and Department ID – assuming two people with the same last name don’t
work in the same department
Primary key
The primary key is a candidate key that is selected by the database designer to be used as an
identifying mechanism for the whole entity set. It must uniquely identify tuples in a table and not
be null. The primary key is indicated in the ER model by underlining the attribute.
• A candidate key is selected by the designer to uniquely identify tuples in a table. It must
not be null.
• A key is chosen by the database designer to be used as an identifying mechanism for the
whole entity set. This is referred to as the primary key. This key is indicated by
underlining the attribute in the ER model.
Employee(EID, First Name, Last Name, SIN, Address, Phone, BirthDate, Salary,
DepartmentID)
14
Secondary key
A secondary key is an attribute used strictly for retrieval purposes (can be composite), for
example: Phone and Last Name.
Alternate key
Alternate keys are all candidate keys not chosen as the primary key.
Foreign key
A foreign key (FK) is an attribute in a table that references the primary key in another table OR it
can be null. Both foreign and primary keys must be of the same data type.
Employee(EID, First Name, Last Name, SIN, Address, Phone, BirthDate, Salary,
DepartmentID)
15
Example:
Viva Questions
17
Experiment 2: Relational Model
AIM: Represent all entities in a tabular fashion. Represent all relationships in a tabular
fashion.
Relational Model was proposed by E.F. Codd to model data in the form of relations or
tables. After designing the conceptual model of Database using ER diagram, we need to convert
the conceptual model in the relational model which can be implemented using any RDMBS
languages like Oracle SQL, MySQL etc
18
Data Type Max Size
Explanation (if applicable)
Syntax
The precision p
Where p is a precision value; s is a scale value. For
can range from 1
example, numeric(6,2) is a number that has 4
numeric(p,s) to 38. The scale s
digits before the decimal and 2 digits after the
can range from -
decimal.
84 to 127.
Storage size is
Where x is the number of bits to store.
bit(x) 1 bit.
Integer data with a value of either 1 or 0.
from January 1,
4712 BC to
date Stores year, month, and day values.
December 31,
9999 AD.
19
Differences between CHAR, VARCHAR and VARCHAR2 one by one:-
1) CHAR: – We can use the CHAR data types for storing the fix length character strings. These
string values may be Space/Blank before going to store in the memory. We cannot use this data
type to store the variable length strings, because it will waste space on the disc memory.
2) VARCHAR: – These data types like VARCHAR & VARCHAR2 are similar to each other in
the behavior. This type of the data type is used to reserve the space for future usage.
3) VARCHAR2:- VARCHAR2 is also used to store the variable length character strings. The
length of the variable string values are stored within the values itself on the disc.
1) ORACLE suggested the new data type VARCHAR2, which is going to replace the
VARCHAR.
2) VARCHAR can stores up to 2000 bytes of characters and on the other hand VARCHAR2 can
stores the 4000 bytes of characters.
3) VARCHAR occupy space for the NULL values and on the other hand VARCHAR2 not
occupy the space.
4) VARCHAR is ANSI standard, where VARCHAR2 is Oracle standard
Here is the difference between CHAR and VARCHAR:-
1) VARCHAR is used to store variable length character string values up to 2000 bytes of
characters. So that’s why it quite slow. On the other hand CHAR is faster than the VARCHAR.
Sometime twice faster than the VARCHAR.
2) CHAR is fixed length, right padded with spaces and VARCHAR is fixed length, right padded
NULL and more over the VARCHAR2 is variable length.
3) Searching with the CHAR is easy because every single string is stored at the specified location
from each other. So, that’s why system does not need to find the end of the string. But on the
other hand in VARCHAR system has to look for the end of the each string.
20
We also have some other data types like nCHAR and nVARCHAR data types. These are
classified as UNICODE characters, whereas CHAR and VARCHAR are called the Non-
UNICODE characters.
We can use VARCHAR when strings do not have a fixed length (e.g. Names, States, etc.)
We can use CHAR when strings are always going to be the same length (e.g. SSN, License
Number, etc.)
Viva Questions:
2. What is SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987
21
Experiment : 3 DDL Commands
DDL
These SQL commands are mainly categorized into four categories as discussed below:
1. DDL(Data Definition Language) : DDL or Data Definition Language actually consists of
the SQL commands that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the structure of
database objects in database.
Examples of DDL commands:
• CREATE – is used to create the database or its objects (like table, index, function,
views, store procedure and triggers).
CREATE TABLE table_name
(
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);
Ex:
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);
• TRUNCATE–is used to remove all records from a table, including all spaces
allocated for the records are removed.
TRUNCATE TABLE table_name;
Viva Questions:
23
Experiment : 4- DML, DCL, TCL
DML(Data Manipulation Language) : The SQL commands that deals with the manipulation of
data present in database belong to DML or Data Manipulation Language and this includes most
of the SQL statements.
Examples of DML:
• SELECT – is used to retrieve data from the a database.
SELECT column1,column2 FROM table_name
SELECT * FROM table_name;
DCL(Data Control Language) : DCL includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions and other controls of the database system.
• GRANT-gives user’s access privileges to database.
• REVOKE-withdraw user’s access privileges given by using the GRANT command.
Example:
SQL> connect system/root;
Connected.
SQL> create user cse identified by cse;
24
User created.
Grant succeeded.
Revoke succeeded.
TCL(transaction Control Language) : TCL commands deals with the transaction within
the database.
Examples of TCL commands:
• COMMIT– commits a Transaction.
• ROLLBACK– rollbacks a transaction in case of any error occurs.
ROLLBACK;
• SAVEPOINT–sets a savepoint within a transaction.
A SAVEPOINT is a point in a transaction in which you can roll the transaction back
to a certain point without rolling back the entire transaction.
25
SAVEPOINT SAVEPOINT_NAME;
ROLLBACK TO SAVEPOINT_NAME;
RELEASE SAVEPOINT:- This command is used to remove a SAVEPOINT that
you have created.
Syntax:
RELEASE SAVEPOINT SAVEPOINT_NAME
student table,
Viva Questions:
Department Table:
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
27
Empno Empname Job MGR Hiredate Sal Comm Did
EMPLOYEE TABLE:
28
7934 MILLER CLERK 7782 23-JAN-82 1300 10
2)DESC EMP;
ENAME VARCHAR2(15)
JOB VARCHAR2(10)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(10,2)
COMM NUMBER( 3)
DID NUMBER(2)
29
Basic SQL Queries:
30
2) DISPLAY ALL THE INFORMATION ABOUT DEPARTMENT TABLE.
DNAME LOC
ACCOUNTING NEW
YORK
RESEARCH DALLAS
SALES CHICAGO
OPERATIONS BOSTON
31
QUERIES USING RELATIONAL OPERATOTRS (=,<,<=,>,>=,!=,<>)
AND LOGICAL OPERATORS (AND,OR,NOT,ANY , EXISTS, BETWEEN)
EMPNAME
1) LIST EMPLOYEE NAMES WHO ARE WORKING
CLARK FOR DEPT NUMBER 10;
KING SELECT EMPNAME FROM EMP WHERE DEPTNO=10;
MILLER
EMPNAME
WARD
SCOTT
FORD
32
MILLER
EMPNAME
5)LIST THE NAME SOF EMPLOYEES WHO ARE NOT
CLARK
MANAGERS.
KING
MILLER SELECT EMPNAME FROM EMP WHERE JOB!=’MANAGER’;
EMPNAME
WARD
SCOTT
KING
JAMES
MILLER
FORD
EMPNAME
WARD
SCOTT
SMITH
MILLER
33
EMPNO EMPNAME SAL
7698 BLAKE 2850 6) LIST THE FIRST three EMPLOYEE
DETAILS.
SELECT * FROM EMP WHERE
ROWNUM<=3;
EMPNAME SAL
SMITH 1800
WARD 1250
MILLER 1300
9)LIST THE EMPLOYEES WHO HAVE JOINED IN THE MONTH OF SEPTEMBER 1981
SELECT EMPNAME FROM EMP WHERE HIREDATE BETWEEN ’01 SEP1981’ AND
‘30SEP1981’;
EMPNAME
SMITH
MILLER
11) LIST THE EMPLOYEE NUMBER, NAME, SALARY OF ALL EMPLOYEES WHO ARE
WORKING FOR MANAGER 7839.
34
7782 CLARK 2450 QUERIES USING DISTINCT AND NULL:
DISTINCT:
• DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all
the duplicate records and fetching only unique records. There may be a situation when
you have multiple duplicate records in a table. While fetching such records, it makes
more sens
NULL:
• It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
2) LIST THE EMPLOYEE NAMES WHO ARE NOT ELIGIBLE FOR COMMISSION.
SELECT EMPNAME FROMM EMP WHERE COMM IS NULL;
EMPNAME
SMITH
BLAKE
CLARK
SCOTT
KING
JAMES
FORD
MILLER
3) LIST THE NAME AND JOBS OF EMPLOYEES WHO DONOT REPORT TO
ANYONE.
SELECT EMPNAME , JOB FROM EMP WHERE MGR is NULL;
EMPNAME JOB
KING PRESIDENT
4) LIST THE EMPLOYEE NAMES WHO ARE ELIGIBLE FOR COMMISSION.
SELECT EMPNAME FROM EMP WHERE COMM IS NOTNULL;
EMPNAME
35
WARD
• The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
EMPNAME
WARD
FORD
3) LIST THE FIVE CHATACTER NAMES STARTING WITH “S” AND ENDING WITH
LETTER “H”;
SELECT EMPNAME FROM EMP WHERE EMPNMAE LIKE ‘S _ _ _ H% ’;
EMPNAME
SMITH
36
4)LIST THE EMPLOYEE NAMES WHO ARE HAVING second CHARACTER AS “A“
and maximum size is 3 characters;
37
QUERIES USING ARITHMETIC OPERATORS: +, - ,*, /, mod
2) LIST THE EMPNAMES,SALARY ,PF, HRA, DA AND GROSS SALARY OF ALL THE
EMPLOYEES (PF=10% OF SALARY, HRA=50% OF SALARY, DA=30% OF SALARY,
GROSS=PF+DA+HRA +SALARY);
38
QUERIES USING ORDER BY CLAUSE:
• The ORDER BY command is used to sort the result set in ascending or descending order.
• The ORDER BY command sorts the result set in ascending order by default. To sort the
records in descending order, use the DESC keyword.
39
3) LIST THE EMPLOYEES WHO ARE EITHER CLERK OR ANALYST IN THE
DESCENDING ORDER.
SELECT * FROM EMP WHERE JOB=’CLERK’ OR JOB=’ANALYST’ ORDER BY
JOB DESC;
EMPNO EMPNAME JOB MGR HIREDATE SAL COMM DEPTNO
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7782 SCOTT ANALYST 7566 09-DEC-82 3000 20
5) LIST THE EMPNAMES,SALARY ,PF, HRA, DA AND GROSS SALARY OF ALL THE
EMPLOYEES in the ASCENDING ORDER OF GROSS. (PF=10% OF SALARY, HRA=50%
OF SALARY, DA=30% OF SALARY, GROSS=PF+DA+HRA +SALARY)
41
QUERIES USING AGGREGATE FUNCTIONS:
TOTAL_SAL
8750
6) FIND THE NO. OF EMPLOYEES WORKING IN A COMPANY
SELECT COUNT(*) FROM EMP;
COUNT(*)
9
42
8) FIND THE TOTAL SALARY GIVEN TO MANAGER.
Viva Questions:
43
Experiment : 6 QUERIES USING “ GROUP BY” ,
DEPTNO NO_OF_EMP
30 4
20 2
10 3
2) LIST THE TOTAL SALARY,MINIMUM SAL, AVERAGE SALARY,MAXIMUMU
SALARY OF EMPLOYEES JOB WISE.
DEPTNO TOTAL
30 6850
20 6000 4) LIST THE NUMBER OF EMPLOYEES IN EACH
10 8750 JOB.
SELECT JOB,COUNT(*) NO_OF_EMP FROM EMP
GROUP BY JOB;
JOB NO_OF_EMP
SALESMAN 1
CLERK 2
PRESIDENT 1
44
MANAGER 3
ANALYST 2
45
2) LIST THE JOBS OF ALL EMPLOYEES WHERE THE MA SAL>=5000
SELECT JOB,MAX(SAL) FROM EMP GROUP BY JOB HAVING
MAX(SAL)>=5000;
JOB MAX(SAL)
PRESIDENT 5000
Viva Questions:
46
Experiment 7: Nested Queries and Corelated nested Quesries
Create Sailors table, Boats table and reserves table
Sailors table
Boats
47
Reserves
• SQL> /
Enter value for sid: 29
Enter value for sname: brutus
Enter value for rating: 1
48
Enter value for age: 33
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(29,'brutus',1,33)
1 row created.
• SQL> /
Enter value for sid: 31
Enter value for sname: lubber
Enter value for rating: 8
Enter value for age: 55.5
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(31,'lubber',8,55.5)
1 row created.
• SQL> /
Enter value for sid: 32
Enter value for sname: andy
Enter value for rating: 8
Enter value for age: 25.5
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(32,'andy',8,25.5)
1 row created.
• SQL> /
Enter value for sid: 58
Enter value for sname: rusty
Enter value for rating: 10
Enter value for age: 35
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(58,'rusty',10,35)
1 row created.
• SQL> /
Enter value for sid: 64
Enter value for sname: horatio
Enter value for rating: 7
Enter value for age: 35.0
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(64,'horatio',7,35.0)
1 row created.
49
• SQL> /
Enter value for sid: 71
Enter value for sname: zorka
Enter value for rating: 10
Enter value for age: 16.0
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(71,'zorka',10,16.0)
1 row created.
• SQL> /
Enter value for sid: 74
Enter value for sname: horatio
Enter value for rating: 9
Enter value for age: 35.0
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(74,'horatio',9,35.0)
1 row created.
• SQL> /
Enter value for sid: 85
Enter value for sname: art
Enter value for rating: 3
Enter value for age: 23.5
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(85 ,'art',3,23.5)
1 row created.
• SQL> /
Enter value for sid: 95
Enter value for sname: bob
Enter value for rating: 3
Enter value for age: 63.5
old 1: insert into sailors values(&sid,'&sname',&rating,&age)
new 1: insert into sailors values(95,'bob',3,63.5)
1 row created.
boats table creation:
• SQL> create table boats(bid number(3),bname varchar2(12),color
varchar2(10),primary key(bid));
Table created.
inserting values into boats table:
50
• SQL> insert into boats values(&bid,'&bname','&color');
Enter value for bid: 101
Enter value for bname: interlake
Enter value for color: blue
old 1: insert into boats values(&bid,'&bname','&color')
new 1: insert into boats values(101,'interlake','blue')
1 row created.
• SQL> /
Enter value for bid: 102
Enter value for bname: interlake
Enter value for color: red
old 1: insert into boats values(&bid,'&bname','&color')
new 1: insert into boats values(102,'interlake','red')
1 row created.
• SQL> /
Enter value for bid: 103
Enter value for bname: clipper
Enter value for color: green
old 1: insert into boats values(&bid,'&bname','&color')
new 1: insert into boats values(103,'clipper','green')
1 row created.
• SQL> /
Enter value for bid: 104
Enter value for bname: marine
Enter value for color: red
old 1: insert into boats values(&bid,'&bname','&color')
new 1: insert into boats values(104,'marine','red')
1 row created.
reserves table creation:
• SQL> /
Enter value for sid: 22
Enter value for bid: 102
Enter value for day: 10oct98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(22,102,'10oct98')
1 row created.
• SQL> /
Enter value for sid: 22
Enter value for bid: 103
Enter value for day: 10aug98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(22,103,'10aug98')
1 row created.
• SQL> /
Enter value for sid: 22
Enter value for bid: 104
Enter value for day: 10july98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(22,104,'10july98')
1 row created.
• SQL> /
Enter value for sid: 31
Enter value for bid: 102
Enter value for day: 11oct98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(31,102,'11oct98')
1 row created.
• SQL> /
Enter value for sid: 31
Enter value for bid: 103
Enter value for day: 11june98
52
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(31,103,'11june98')
1 row created.
• SQL> /
Enter value for sid: 31
Enter value for bid: 104
Enter value for day: 11dec98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(31,104,'11dec98')
1 row created.
• SQL> /
Enter value for sid: 64
Enter value for bid: 101
Enter value for day: 9may98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(64,101,'9may98')
1 row created.
• SQL> /
Enter value for sid: 64
Enter value for bid: 102
Enter value for day: 9aug98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(64,102,'9aug98')
1 row created.
• SQL> /
Enter value for sid: 74
Enter value for bid: 103
Enter value for day: 9aug98
old 1: insert into reserves values(&sid,&bid,'&day')
new 1: insert into reserves values(74,103,'9aug98')
1 row created.
tables information:
SQL> select * from sailors;
10 rows selected.
basic queries:
1.find the distinct names and ages of sailors?
• SQL> select distinct s.sname ,s.age from sailors s;
SNAME AGE
---------- ----------
dustin 45
zorka 16
brutus 33
andy 25.5
rusty 35
bob 63.5
54
lubber 55.5
horatio 35
art 23.5
9 rows selected.
4.find the sids of sailors who have reserved red colour boat?
• SQL> select s.sid from sailors s,boats b,reserves r where s.sid=r.sid and
b.color='red' and b.bid=r.bid;
SID
----------
22
22
31
31
64
5.find colours and names of boats reserved by lubber?
• SQL> select b.color,b.bname from boats b,reserves r,sailors s where
s.sname='lubber'and s.sid=r.sid and r.bid=b.bid;
COLOR BNAME
---------- ------------
red interlake
green clipper
red marine
6.find the distinct names of sailors who have reserved atleast one boat?
55
• SQL> select distinct s.sname from sailors s ,reserves r where s.sid=r.sid;
SNAME
----------
lubber
dustin
horatio
7.compute incriments for the rating for the person who have sailed two different boats on same
day?
• SQL> select s.sname,s.rating+1 inc from sailors s,reserves r1,reserves r2 where
s.sid=r1.sid and s.sid=r2.sid and r1.bid!=r2.bid and r1.day=r2.day;
SNAME INC
---------- ----------
dustin 8
dustin 8
8.find names and ages of sailors whose name begins and ends with the letter b and has atleast 3
characters?
• SQL> select s.sname,s.age from sailors s where s.sname like 'b_%b';
SNAME AGE
---------- ----------
bob 63.5
9.list the sailors names,ratings who age is greter than 35?
• SQL> select s.sname,s.rating from sailors s where s.age>35;
SNAME RATING
---------- ----------
dustin 7
lubber 8
bob 3
10.find the silors names whose rating>8 and age<35?
• SQL> select s.sname from sailors s where s.age <35 and s.rating>8;
SNAME
----------
zorka
56
o In the union operation, all the number of datatype and columns must be same in both the
tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
4. Minus or EXCEPT
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
57
o It has no duplicates and data arranged in ascending order by default.
Syntax
1.find the sids of sailors who have reserved red or a green boat?
• SQL> select s.sid from sailors s ,reserves r,boats b where s.sid=r.sid and r.bid=b.bid
and b.color='red' union select s1.sid from sailors s1,reserves r1,boats b1 where
s1.sid=r1.sid and r1.bid=b1.bid and b1.color='green';
SID
----------
22
31
64
74
3.find the sids of sailors who have reserved a red boat but not a green boat?
• SQL> select s.sid from sailors s ,reserves r,boats b where s.sid=r.sid and r.bid=b.bid
and b.color='red' minus select s1.sid from sailors s1,reserves r1,boats b1
where s1.sid=r1.sid and r1.bid=b1.bid and b1.color='green';
SID
----------
64
4.find the sids of sailors who have rating equal to 10 or who have reserved boat no 104?
• SQL> select s.sid from sailors s where s.rating=10 union select r1.sid from sailors
s1,reserves r1 where s1.sid=r1.sid and r1.bid=104;
SID
----------
22
31
58
71
set compartions operations and nested queries:
Set Comparison Operators
There are different types of set comparison operators like EXISTS, IN , NOT IN and UNIQUE.
SQL also supports op ANY and op ALL, where op means arithmetic comparison operators such
as <, <=, =, <>, >=, >. SOME are also one of the set comparison operators but it is similar to
ANY.
ANY means that the condition will be true if the operation is true for any of the values in the
range.
In short, ANY (or SOME) allows you to specify the comparison you want in each predicate,
such as X<ANY (A1, A2, A3) is translated to X < A1 OR X < A2 OR X < A3.
59
Sal<ANY(2000,3000,4000) sal<2000 or sal<3000 or sal<4000
ALL means that the condition will be true only if the operation is true for all values in the range.
For illustrative purposes, X != ALL (A1, A2, A3) is translated to X != A1 AND X != A2 AND X
!= A3.
Nested Query:
In nested queries, a query is written inside a query. The result of inner query is used in
execution of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in
writing independent nested queries.
60
• SQL> select s.sname from sailors s where s.sid in(select r.bid from reserves r where
r.bid not in(select b.bid from boats b where b.color='red'));
no rows selected
4.find sialors names and ids whose rating is better than some sailors called horatio?
• SQL> select s.sid,s.sname from sailors s where not exists((select b.bid from boats
b)minus(select r.bid from reserves r where r.sid=s.sid));
SID SNAME
---------- ----------
22 dustin
queries using aggregate functions:
1.find the average of age of all the sailors?
• SQL> select avg(s.age) from sailors s;
AVG(S.AGE)
----------
36.7
2.find the average of age of sailors with rating 10?
• SQL> select avg(s.age) from sailors s where s.rating=10;
AVG(S.AGE)
----------
25.5
3.find the name and age of the oldest sailor?
• SQL> select s.sname ,s.age from sailors s where s.age=(select max(s1.age) from
sailors s1);
SNAME AGE
---------- ----------
bob 63.5
4. count the no of sialors in sialors relation?
• SQL> select count(*) from sailors s;
COUNT(*)
----------
10
5.count the no of distinct sailor names?
62
• SQL> select count(distinct(s.sname)) from sailors s;
COUNT(DISTINCT(S.SNAME))
------------------------
9
6.find the names of sailor who are older than oldest sailors with rating of 10?
• SQL> select s.sname from sailors s where s.age>(select max(s1.age) from sailors s1
where s1.rating=10);
SNAME
----------
dustin
lubber
bob
7.find the max age from sailors relation?
• SQL> select min(s.age) from sailors s;
MIN(S.AGE)
----------
16
queries using groupby and having clause:
1.find the age of the youngest sailor for each rating level?
• SQL> select min(s.age),s.rating from sailors s group by s.rating;
MIN(S.AGE) RATING
---------- ----------
33 1
25.5 8
35 7
23.5 3
16 10
35 9
6 rows selected.
2.find the age of the youngest sailor who is eligible to vote for each rating level with atleast 2
sailors?
• SQL> select min(s.age),s.rating from sailors s where s.age>=18 group by s.rating
having count(s.rating)>=2;
MIN(S.AGE) RATING
---------- ----------
25.5 8
35 7
23.5 3
63
Viva Questions:
In Correlated query, a query is nested inside another query and inner query uses values from
outer query. Inner query is dependent on Outer query.
64
Experiment : 8 –
a) Queries using number functions
71
Experiment 9: JOINS
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
• cross join: CROSS JOIN produces a result set which is the number of rows in the first
table multiplied by the number of rows in the second table if no WHERE clause is used
along with CROSS JOIN.This kind of result is called as Cartesian Product.
• equi join (or) inner join: Returns records that have matching values in both tables
• natural join: NATURAL JOIN is a type of EQUI JOIN and is structured in such a way
that, columns with the same name of associated tables will appear once only.
• outer join
i. left outer join: This join returns all the rows of the table on the left side of the
join and matching rows for the table on the right side of join. The rows for
which there is no matching row on right side, the result-set will contain null.
ii. right outer join: RIGHT JOIN is similar to LEFT JOIN. This join returns all the
rows of the table on the right side of the join and matching rows for the table on
the left side of join. The rows for which there is no matching row on left side,
the result-set will contain null.
iii. full outer join: FULL JOIN creates the result-set by combining result of both
LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from
both the tables. The rows for which there is no matching, the result-set will
contain NULL values.
72
class relation
SID SNAME
1 JOHN
2 Paul
4 Akhil
class_info relation
SID ADDR
1 DELHI
2 BOMBAY
3 CHENNAI
1) CROSS JOIN:
select * from class_info cross join class;
73
3) NATURAL JOIN:
select * from class_info natural join class ;
74
Viva Questions:
75
Experiment 10: Views
A view is a virtual table , created to reduce the redundancy. .It will not create a separate table but
only takes a few columns from the existing parent table.
SYNTAX:
create view view_name as (select col1, col2, col3,…….. from table_name where <condition>
group by col1 having <condition>);
QUERIES:
1) To create a view:
create view emp_v1 as (select empno, empname from emp);
76
5) To create view on two tables:
create view emp_v3 as (select e.empno, e.deptno, d.dname from emp e , dept d where
e.deptno = d.deptno);
Viva Questions:
77
Experiment 11: PL/SQL
What is PL/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.
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.
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 placeholders like variables, constants, records and
cursors, which are used to manipulate data in the execution section. Placeholders may be any of
Variables, Constants and Records, which stores data temporarily. Cursors are also declared in
this 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:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This
section is optional. Any errors in the program can be handled in this section, so that the PL/SQL
Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled,
the Block terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be
nested within other PL/SQL blocks. Comments can be used to document code.
78
How a Sample PL/SQL Block Looks
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
If Statement:
The IF statement associates a condition with a sequence of statements enclosed by the keywords
THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition
is FALSE or NULL, then the IF statement does nothing.
Syntax:
IF condition THEN
S;
ELSE
STMTS;
END IF;
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause
lets you add additional conditions.
Syntax:
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
the CASE statement selects one sequence of statements to execute. However, to select the
sequence, the CASE statement uses a selector rather than multiple Boolean expressions. A
selector is an expression, whose value is used to select one of several alternatives.
79
Syntax:
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;
Loop
Stmts;
Exit when(condition);
End loop;
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
80
a) To print hello world message
declare
msg varchar(15):='hello world';
begin
dbms_output.put_line('message is'||msg);
end;
Statement processed.
a is small
Statement processed.
d ) greatest of 3 numbers
declare
a integer;
81
b integer;
c integer;
begin
a:=:a;
b:=:b;
c:=:c;
if(a>b and a>c) then
dbms_output.put_line('a is greatest num');
elsif(b>a and b>c) then
dbms_output.put_line('b is greatest num');
else
dbms_output.put_line('c is greatest num');
end if;
end;
input:
a: 10
b: 2
c: 3
a is greatest num
Statement processed.
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('verygood');
when 'C' then dbms_output.put_line('well done');
when 'D' then dbms_output.put_line('passed');
when 'F' then dbms_output.put_line('better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
Excellent
Statement processed.
f)
--Here, sequence of statement(s) may be a single statement or a block of statements. An
--EXIT statement or an EXIT WHEN statement is required to break the loop.
--Example:
DECLARE
x number := 10;
BEGIN
82
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
10
20
30
40
50
After Exit x is: 60
Statement processed.
factorial of n is 120
Statement processed.
Statement processed.
84
i) To write a PL/SQL block to Generate Fibonacci Series
DECLARE
num number(5);
f1 number(5):=0;
f2 number(5):=1;
f3 number(5);
i number(5):=3;
BEGIN
num:=:num;
dbms_output.put_line('THE FIBONACCI SERIES IS:');
dbms_output.put_line(f1);
dbms_output.put_line(f2);
while(i<=num) loop
f3:=f1+f2;
dbms_output.put_line(f3);
f1:=f2;
f2:=f3;
i:=i+1;
end loop;
END;
THE FIBONACCI SERIES IS:
0
1
1
2
3
5
8
13
21
34
k) MULTIPLICATION TABLE
declare
i number(2);
n number(2);
begin
n:=:n;
for i in 1..10 loop
dbms_output.put_line( n || ' * ' || i || ' = ' || n*i);
end loop;
end;
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Statement processed.
l) Print 1 to n prime numbers
declare
i integer;
n integer;
c integer;
begin
n:=:n;
for i in 2..n loop
c:=0;
for j in 1..i loop
if(mod(i,j)=0) then
c:=c+1;
end if;
end loop;
if (c=2) then
86
dbms_output.put_line(i);
end if;
end loop;
end;
2
3
5
7
Statement processed.
A GOTO statement in PL/SQL programming language provides an unconditional jump from the
GOTO to a labeled statement in the same subprogram.
Syntax
The syntax for a GOTO statement in PL/SQL is as follows −
GOTO label;
..
..
<< label >>
statement;
m) Illustrate go to statement
DECLARE
a number(2) := 1;
BEGIN
<<loopstart>>
WHILE a <= 5 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 3 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
value of a: 1
value of a: 2
value of a: 4
value of a: 5
Statement processed.
n) Update the sal of the emp , for manager – 20%, salesman 15%, others 10%
87
declare
ejob emp.job%type;
esal emp.sal%type;
eid emp.empno%type;
inc number(7,2);
begin
eid:=:empno;
if ejob='MANAGER' then
inc:=0.2;
inc:=0.15;
else
inc:=0.1;
end if;
end;
-----
o) Find out whether the commission is NULL or not for the given eid
declare
88
eid emp.empno % type;
begin
eid:=:empno;
dbms_output.put_line('comm is null');
else
end if;
end;
PROCEDURES:
A Procedure in PL/SQL is a subprogram unit that consists of a group of PL/SQL
statements that can be called by name. Each procedure in PL/SQL has its own unique name by
which it can be referred to and called. This subprogram unit in the Oracle database is stored as
a database object.
Syntax:
CREATE OR REPLACE PROCEDURE
<procedure_name>
(
<parameterl IN/OUT <datatype>
..
.
)
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;
IN Parameter:
OUT Parameter:
IN OUT Parameter:
• This parameter is used for both giving input and for getting output from the subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
• In the calling statement, these parameters should always be a variable to hold the value
from the subprograms.
Note: RETURN statement to return the control to the calling block, but it cannot return any
values through the RETURN statement.
Procedures cannot be called directly from SELECT statements. They can be called from another
block or through EXEC keyword.
a number:=0;
b number:=1;
c number;
i number;
begin
dbms_output.put_line(a);
90
dbms_output.put_line(b);
c:=a+b;
a:=b;
b:=c;
dbms_output.put_line(c);
end loop;
end;
Procedure created.
declare
n number(10);
begin
n:=:n;
fib(n);
end;
input: 5
output:
Statement processed.
q) Write a procedure for finding out whether the given number is prime or not
91
create or replace procedure isprime(n number) as
c integer:=0;
i integer;
begin
if(mod(n,i)=0) then
c:=c+1;
end if;
end loop;
if(c=2) then
dbms_output.put_line('prime');
else
dbms_output.put_line('not prime');
end if;
end;
declare
n integer;
begin
n:=:n;
isprime(n);
end;
---
r) Write a procedure for finding out whether the given number is palindrome or not
t number;
begin
rev:=0;
t:=n;
rev:=(rev*10)+mod(t,10);
t:=trunc(t/10);
end loop;
if n=rev then
dbms_output.put_line('Palindrome');
else
dbms_output.put_line('notPalindrome');
end if;
end;
declare
n number:=:n;
begin
palindrome(n);
end;
begin
93
commit;
dbms_output.put_line('update successfully');
end;
declare
eno emp.empno%type;
inc number;
begin
eno:=:eno;
inc:=:inc;
empupdate(eno,inc);
end;
t number;
begin
t:=a;
a:=b;
b:=t;
end;
declare
a number:=:a;
b number:=:b;
begin
dbms_output.put_line('before swapping'||a||','||b);
94
swap(a,b);
dbms_output.put_line('after swapping'||a||','||b);
end;
95
Experiment 12: Functions
Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique
name by which it can be referred. These are stored as PL/SQL database objects.
• Function use RETURN keyword to return the value, and the datatype of this is defined at
the time of creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in
functions.
96
Procedure Function
• RETURN will simply exit the • RETURN will exit the control from
control from subprogram. subprogram and also returns the value
RETURN number IS
total number(2) := 0;
BEGIN
FROM emp;
RETURN total;
END;
DECLARE
c number(2);
BEGIN
c := totalemps();
END;
output:
97
Total no. of emps: 16
Statement processed.
DECLARE
a number;
b number;
c number;
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:=:a;
b:=:b;
98
c := findMax(a, b);
END;
---
DECLARE
num number;
factorial number;
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:=:num;
factorial := fact(num);
99
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
----
declare
a int;
c int;
n int;
rev int:=0;
r int;
return int
as
z int;
begin
n := x;
while (n > 0)
loop
r := mod(n, 10);
n := trunc(n / 10);
end loop;
z := rev;
100
return z;
end ;
BEGIN
a := 123456789;
c := reverse_it(a);
END;
-----
RETURN NUMBER
IS
totalsal NUMBER := 0;
BEGIN
FROM emp;
RETURN totalsal;
END;
declare
sal NUMBER := 0;
BEGIN
101
sal := get_total_sal ();
END;
Sal: 35740
Statement processed.
Viva Questions:
SQL is a natural language which is very PL/SQL is a procedural extension of Oracle - SQL.
useful for interactive processing.
All SQL statements are executed by the PL/SQL statements send the entire block of
database server one at a time, thus it is a statements to the database server at the same time,
time-consuming process. thus network traffic is reduced considerably.
No error handling procedures are there in PL/SQL supports customized error handling.
SQL.
2. Explain the purpose of %TYPE and %ROWTYPE data types with the
example?
• Answer: PL/SQL uses the %TYPE declaration attribute for anchoring. This attribute
provides the datatype of a variable, constant or column. %TYPE attribute is useful while
declaring a variable that has the same datatype as a table column.
• For example, the variable m_empno has the same data type and size as the
column empno in table emp.
m_empno emp.empno%TYPE;
• %ROWTYPE attribute is used to declare a variable to be a record having the same
structure as a row in a table. The row is defined as a record and its fields have the same
names and data types as the columns in the table or view.
• For example:
dept_rec dept%ROWTYPE;
• This declares a record that can store an entire row for the DEPT table.
102
Experiment 13: Triggers- Triggers are stored programs which are automatically executed
or fired when some events occur.
Triggers are, in fact, written to be executed in response to any of the following events −
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{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)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
103
a) trigger that doesn’t allow a salary to be updated if the employee commission is null.
begin
end if;
end;
----
b) To write a trigger that inserts or updates values of ename and job as uppercase strings
even if we give lowercase strings.
BEFORE
begin
:new.ename:=upper(:new.ename);
:new.job:=upper(:new.job);
end;
------
104
c) To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate or null
values in DEPTNO column.
BEFORE
insert on "DEPT"
declare
a number;
begin
else
if(a=1) then
end if;
end if;
end;
105
Experiment 14: PL/SQL Cursor
When an SQL statement is processed, Oracle creates a memory area known as context area. A
cursor is a pointer to this context area. It contains all information needed for processing the
statement. In PL/SQL, the context area is controlled by Cursor. A cursor contains information
on a select statement and the rows of data accessed by it.
A cursor is used to referred to a program to fetch and process the rows returned by the SQL
statement, one at a time. There are two types of cursors:
o Implicit Cursors
o Explicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is executed,
if you don't use an explicit cursor for the statement.
These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect at least one row or more rows or a SELECT INTO
statement returned one or more rows. Otherwise it returns FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect no row, or a SELECT INTO statement return no rows.
Otherwise it returns FALSE. It is a just opposite of %FOUND.
106
a) Update the students marks using implicit cursors
DECLARE
total_rows number(2);
BEGIN
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
The Explicit cursors are defined by the programmers to gain more control over the context area.
These cursors 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.
You must follow these steps while working with an explicit cursor.
107
1) Declare the cursor:
It defines the cursor with a name and the associated SELECT statement.
It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
SQL statements into it.
1. OPEN cursor_name;
3) Fetch the cursor:
It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:
It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.
1. Close cursor_name;
b) Write a program to print emp number, name, sal, dno of all employees from emp using
cursors.
DECLARE
i emp.empno%type;
j emp.ename%type;
k emp.deptno%type;
l emp.sal%type;
108
BEGIN
open c;
loop
fetch c into i, j, k, l;
end loop;
close c;
END;
output:
109
7521 WARD 30 1250
Statement processed.
-----
DECLARE
cursor c1(j varchar2, dn number) is select empno, ename from emp where job=j and
deptno=dn;
row1 emp%rowtype;
jb emp.job%type;
d emp.deptno%type;
BEGIN
jb:=:jb;
d:=:dno;
open c1(jb,d);
if c1%notfound then
else
end if;
close c1;
110
end;
input:
job: manager
depno:10
output:
Statement processed.
Viva Question:
1. What is a Trigger.
2. Difference between row level and coloumn level trigger
3. Define a Cursor
4. Explain Implicit cursor and explicit cursor.
111
Experiment 15: Exception Handling
An exception is an error which disrupts the normal flow of program instructions. PL/SQL
provides us the exception block which raises the exception thus helping the programmer to find
out the fault and resolve it.
DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
END;
DECLARE
temp varchar(20);
ename varchar2(20);
BEGIN
ename:=:ename;
dbms_output.put_line('ERROR');
dbms_output.put_line(ename);
end;
input: smith
output:
ERROR
there is no name as
smith
Statement processed.
DECLARE
temp varchar(20);
BEGIN
dbms_output.put_line(temp);
113
EXCEPTION
end;
output:
Statement processed.
114
c) Raise an exception when data type is changed
DECLARE
temp number;
BEGIN
EXCEPTION
dbms_output.put_line('Error');
END; -----
Error
Statement processed
115
d) Divide by zero exception
DECLARE
a int;
b int;
answer int;
BEGIN
a:=:a;
b:=:b;
answer:=a/b;
exception
END;
a: 10
b: 0
the value of a is 10
the value of b is 0
116
User Defined Exception:
DECLARE
x int;
y int;
exp1 EXCEPTION;
BEGIN
x:=:x;
y:=:y;
IF y=0 then
raise exp1;
ELSE
END IF;
EXCEPTION
dbms_output.put_line('Error');
END;
Viva Questions:
Packages:
PL/SQL package is a logical grouping of a related subprogram
(procedure/function) into a single element. A Package is compiled and
stored as a database object that can be used later. PL/SQL package has
two components.
• Package Specification
• Package Body
Package Specification
Package specification consists of a declaration of all the public variables,
cursors, objects, procedures, functions, and exception.
All objects placed in the specification are
called public objects. Any subprogram not in the package
specification but coded in the package body is called
a private object.
Syntax
CREATE [OR REPLACE] PACKAGE <package_name>
IS
<sub_program and public element declaration>
.
.
END <package name>
Syntax
CREATE [OR REPLACE] PACKAGE <package_name>
IS
<sub_program and public element declaration>
.
.
118
END <package name>
Package Body
It consists of the definition of all the elements that are present in the
package specification. It can also have a definition of elements that are
not declared in the specification, these elements are called private
elements and can be called only from inside the package.
Syntax:
CREATE [OR REPLACE] PACKAGE BODY <package_name>
IS
<global_declaration part>
<Private element definition>
<sub_program and public element definition>
.
<Package Initialization>
END <package_name>
Ex:
CREATE or replace PACKAGE math AS
FUNCTION fact RETURN int;
END math;
BEGIN
DBMS_OUTPUT.PUT_LINE (math.fact);
END;
119