dbms lab
dbms lab
(Autonomous)
Dundigal, Hyderabad - 500 043
Lab Manual:
Prepared by
Y MANOHAR REDDY(IARE10857)
Lab 6 -Triggers 37
Lab 7 - Procedures 42
Lab 8- Cursors 44
Page 2
Course Information
1 Introduction
The requirement of modern days is to have an automated system that manages, modifies and updates
data accurately. This is achieved by a DBMS in robust, correct and non-redundant way. DBMS lab
aims at practicing and achieving this aim by using various software’s such as SQL, ORACLE, and MS
– Access etc. It provides practice on built-in SQL functions using languages like DDL, DCL, DML
and TCL to create and manage database systems. This is essential for mobile and web application
development for business, scientific and engineering applications.
The student is expected to be prepared for each lab.Lab preparation includes reading the labexperi-
ment and related textbook material. If you have questions or problems with the preparation, contact
your Laboratory Teaching faculty, but in a timely manner. Do not wait until an hour or two befor
the lab and then expect the lab faculty to be immediately available.
Active participation by each student in lab activities is expected. The student is expected to askthe
laboratory faculty any questions they may have.
A large portion of the student’s grade is determined in the comprehensive final exam, resulting in a
requirement of understanding the concepts and procedure of each lab experiment for the successful-
completion of the lab class. The student should remain alert and use common sense while performing
a lab experiment. They are also responsible for keeping a professional and accurate record of the
labexperiments in the lab manual wherever tables are provided. Students should report any errors in
the lab manual to the teaching assistant.
TThe laboratory faculty shall be completely familiar with each lab prior to class. The laboratory
faculty shall provide the students with a syllabus and safety review during the first class. The syllabus
shall include the laboratory faculty office hours, telephone number, and the name of the faculty coor-
dinator. The laboratory faculty is responsible for ensuring that all the necessary equipment and/or
preparations for the lab are available and in working condition. Lab experiments should be checked
in advance to make sure everything is in working order. The laboratory faculty should fully answer
any questions posed by the students and supervise the students performing the lab experiments. The
laboratory faculty is expected to grade the lab notebooks and reports in a fair and timely manner.
The reports should be returned to the students in the next lab period following submission. The
laboratory faculty should report any errors in the lab manual to the faculty coordinator.
The faculty coordinator should ensure that the laboratory is properly equipped, i.e., that the teaching
assistants receive any equipment necessary to perform the experiments. The coordinator is responsible
for supervising the teaching assistants and resolving any questions or problems that are identified by
the teaching assistants or the students. The coordinator may supervise the format of the final exam for
the lab. They are also responsible for making any necessary corrections to this manual and ensuring
that it is continually updated and available.
Page 3
1.4 Lab Policy and Grading
Attendance
Attendance is mandatory and any absence must be for a valid excuse and must be documented.If the
instructor is more than 15 minutes late, students may consider lab for the day cancelled.
Lab Records
Grading Policy
The final grade of this course is determined using the criterion detailed in the syllabus.
Instructions to Students
• Before entering the lab the student should carry the following things (MANDATORY)
o Identity card issued by the college.
o Work Sheets
• Student must sign in and sign out in the register provided when attending the lab session without
fail.
• Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed to
attend the lab.
• Students need to maintain 100% attendance in lab if not a strict action will be taken.
• All students must follow a Dress Code while in the laboratory
• Foods, drinks are NOT allowed.
• All bags must be left at the indicated place.
• Refer to the lab staff if you need any help in using the lab.
• Respect the laboratory and its other users.
• Workspace must be kept clean and tidy after experiment is completed.
• Read the Manual carefully before coming to the laboratory and be sure about what you are sup-
posed to do.
• Do the experiments as per the instructions given in the manual.
• Copy all the programs to observation which are taught in class before attending the lab session.
• Students are not supposed to use floppy disks, pen drives without permission of lab- incharge.
• Lab records need to be submitted on or before the date of submission.
• Computer labs are established with sophisticated and high end branded systems, which should be
utilized properly.
• Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab ses-
sions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe
punishment.
• Students must take the permission of the faculty in case of any urgency to go out; if anybody found
loitering outside the lab / class without permission during working hours will be treated seriously and
punished appropriately.
• Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly.
Page 4
1.5 Course Goals and Objectives
Goal:
The goal of the laboratory course is to present an introduction to database management systems, with
an emphasis on how to organize, maintain and retrieve - efficiently, and effectively - information from
a DBMS.
Objectives:
• The SQL commands for data definition, manipulation, control and perform transactions in database
systems.
• The procedural language for implementation of functions, procedures, cursors and triggers using
PL/SQL programs.
• The logical design of a real time database system with the help of Entity Relationship diagrams.
Students must write their experimental outputs in the provided tables in this laboratory manual and
reproduce them in the lab reports. Reports are integral to recording the methodology and results
of an experiment. In engineering practice, the laboratory notebook serves as an invaluable reference
to the technique used in the lab and is essential when trying to duplicate a result or write a report.
Therefore, it is important to learn to keep accurate data. Make plots of data and sketches when these
are appropriate in the recording and analysis of observations. Note that the data collected will be an
accurate and permanent record of the data obtained during the experiment and the analysis of the
results. You will need this record when you are ready to prepare a lab report.
Reports are the primary means of communicating your experience and conclusions to other profes-
sionals. In this course you will use the lab report to inform your laboratory faculty about what you
did and what youhave learned from the experience.Engineering results are meaningless unless they can
be communicated to others. You will be directed by your laboratory facultyto prepare a lab report on
a few selected lab experiments during the semester.Your assignment might be different from your lab
partner’s assignment.
Your laboratory report should be clear and concise.The lab report shall be typed on a word proces-
sor.As a guide,use the format on the next page.Use tables,diagrams, sketches, as necessaryto show
what you did, what was observed, and what conclusions you can draw from this. Even thoughyou will
work with one or more lab partners, your report will be the result of your individual effort in order to
provide you with practice in technical communication.
Page 5
• All page margins must be 1.25 inches. All content (including text, figures, tables, etc.) must fit
within the margins.
• All the tables should have titles and should be numbered. Tables should be labeled numerically as
Table 1, Table 2, etc. Table captions appear above the table. The column headings should be labeled
with the units specified.
• Use MS-Word equation (under Insert Equation menu), MathType, or a similar tool to type formulas.
• If you need to copy a schematic or figure from the lab manual to your report, use Copy and Paste
function or take a screenshot by using Snipping Tool in MS-Windows.
• Do not place screenshots of your lab notebook in the report! Diagrams, tables, calculations, etc.
must be generated using the existing tools in the word processor.
Coverpage
Cover page must include lab nameand number,your name,yourlab partner’s name,and the date the
lab was performed.
Objective
Software Needed
• Write the lab’s part number and title in bold font. Firstly, describe the problem that you studied
in this part, give an introduction of the theory, and explain why you did this experiment.Do not lift
the text from the lab manual; use your ownwords.
•Secondly,describe the experimental setup and procedures.Do not follow the lab manual in listing out
individual pieces of equipment and assembly instructions.That is not relevant information in a lab
report! Your description should take the form of a narrative, and include information notpresent in
the manual,such as descriptions of what happened during intermediate steps of the experiment.
•Thirdly,explain your findings. This is the most important part of your report,because here,you show
that you understand the experiment beyond the simple level of completing it. Explain(compare ex-
pected results with those obtained). Analyse (analyze experimental error). Interpret(explain your
Page 6
results in terms of theoretical issues and relate to your experimental objectives).All the results should
be presented even if there is any inconsistency with the theory. It should be possible to understand
what is going onby just reading through the text paragraphs, without looking at the figures.
•Finally, provide a summary of what was learned from this part of the laboratory experiment.If the
results seem unexpected or unreliable,discuss them and give possible explanations.
Conclusion
The conclusion section should provide a take-home message summing up what has been learned from
the experiment:
• Briefly restate the purpose of the experiment (the question it was seeking to answer)
• Note the main limitations that are relevant to the interpretation of the results
• Summarize what the experiment has contributed to your understanding of the problem.
Questions pertaining to this lab must be answered at the end of laboratory report.
Page 7
Lab-Orientation
Introduction
The students should become familiar with the oracle software in the lab, the course requirements, and
the teaching instructor. Students should also make sure that they have all of the co-requisites and
pre-requisites for the course at this time.
Objective
To familiarize the students with the introduction of oracle database management system and instal-
lation of oracle database management system software.
Software Needed
Oracle Database
Oracle database (Oracle DB) is a relational database management system (RDBMS) from the Oracle
Corporation. Originally developed in 1977 by Lawrence Ellison and other developers, Oracle DB is
one of the most trusted and widely-used relational database engines.
The system is built around a relational database framework in which data objects may be directly
accessed by users (or an application front end) through structured query language (SQL). Oracle is a
fully scalable relational database architecture and is often used by global enterprises, which manage
and process data across wide and local area networks. The Oracle database has its own network
component to allow communications across networks.
Oracle Database (known as Oracle RDBMS) is a Database Management System produced and mar-
keted by Oracle Corporation.The Most Fundamental and common usage of Oracle Database is to store
a Pre-Defined type of Data. It supports the Structured Query language (SQL) to Manage and Manip-
ulate the Data that it has. It is one of the most Reliable and highly used Relational Database Engines.
There are many versions of Oracle Database like Oracle Database 10g, Oracle Database 11g, Oracle
Database 12c, Oracle Database 19c, etc. from which Oracle 19c is the Latest Version. In this article,
we will learn how to Install version 11g on Windows.
Step 2: Click the Download Button and Scroll Down to Database Section.
Step 3: Click Database 11g Enterprise/Standard Editions, after which you’ll find different versions of
Oracle for different OS. Download the Files according to your OS.
Step 4: After Clicking the Download Button, the page will be directed to Login Screen where you’ll
need to Sign In in Oracle Account. If you don’t have one, then you must Sign Up, because without
that you won’t be able to download the Files.
Step 5: Repeat the same steps for both the Files and Download them.
Page 8
Extraction of Downloaded Files:
Step 1: Extract both the files with the use of WinRAR or any other extraction tool of your choice in
the same directory.
Step 2: Go to Folder database -> Stage -> Components Copy all the content of this Folder
Step 3: Go to Main Database -> Stage Paste the copied content in Components Folder
Step 1: Go to Main Database Folder where you’ll find Setup. Right click the setup.exe file and choose
Run as Administrator.
Step 2: Click Yes to continue. This will start Oracle Universal Installer.
Step 3: Select any of the three different Installation Options according to your needs.
• Option 1 – If you want to Install Oracle Server Software and want to Create Database also.
• Option 2 – If you want to Install Oracle Server only.
• Option 3 – If you want to Upgrade your Existing Database.
Step 4: Choose between Server Class and Desktop Class as per your requirement and click on Next.
Step 5: Configure the basic settings and create a Password for your database. Once the configuration
is done click on Next to continue.
Step 6: Oracle Universal Installer(OUI) will check for the Prerequisites such as Hardware compatibility.
Step 7: Click on Finish to start the Installation process. This installation might take some time
depending on your Hardware.
Step 9: Copy the localhost link provided to open your Enterprise Manager.
Step 10: Click the Close Button and you are done with the Installation Process.
Go to Start Menu and
• Search Oracle Folder
• Click on Database Control – Oracle (Your Global Database Name)
• This will take you to the Login Screen of your Oracle Enterprise Manager.
Page 9
Lab-1 CREATION OF TABLES
Introduction
Structure Query Language (SQL) is a database query language used for storing and managing data
in Relational DBMS. In RDBMS the data is stored in the form of tables. The create table state-
ment is used to create a table for the database. This table can have n rows and m columns based
on the requirement. So, with the help of this query, we can store data in the form of rows and columns.
Objective
By the end of this lab, the student should learn how to create the tables, inserting values into the
tables and updating the tables.
PreLab:
Prior coming to the lab, students should have knowledge on DDL commands and DML commands.
Software Needed
Background
SQL Commands
DDL: Data Definition Language (DDL) statements are used to define the database structure or schema.
DDL Commands: Create, Alter, Drop, Rename, Truncate CREATE - to create objects in the database.
ALTER - alters the structure of the database DROP - delete objects from the database.
TRUNCATE - remove all records from a table, including all spaces allocated for the records are re-
moved RENAME - rename an object.
DML: Data Manipulation Language (DML) statements are used for managing data within schema
objects and to manipulate data of a database objects.
DML Commands: Insert, Update, Delete, Select INSERT - insert data into a table
DELETE - deletes all records from a table, the space for the records remain.
Procedure
Page 10
Step 3: Create table and update the table by using DDL and DML commands
Program:
name type
Empno Number
Empname Varchar2(10)
Job Varchar2(10)
Mgr Number
Sal Number
Solution
SQL> create table employee(empno number,ename varchar2(10),job varchar2(10),mgr number,sal
number);
Table created.
SQL> desc employee;
Name Null? Type
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
COMMISSION NUMBER
Page 11
old 1: insert into employee values(&empno,’&ename’,’&job’,&mgr,&sal,’&commission’)
new 1: insert into employee values(101,’abhi’,’manager’,1234,10000,’70’)
1 row created.
SQL> /
Enter value for empno: 102 Enter value for ename: rohith Enter value for job: analyst
Enter value for mgr: 2345 Enter value for sal: 9000
Enter value for commission: 65
old 1: insert into employee values(&empno,’&ename’,’&job’,&mgr,&sal,’&commission’)
new 1: insert into employee values(102,’rohith’,’analyst’,2345,9000,’65’)
1 row created.
Table altered.
Name Type
Deptno Number
Deptname Varchar2(10)
location Varchar2(10)
Page 12
e. Delete any column data from the table.
SOLUTION:
Table created.
DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)
Table altered.
DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)
DESIGNATION VARCHAR2(10)
1 row created.
SQL> /
1 row created.
Page 13
DEPTNO DEPTNAME
9 accounting
12 operations
10 research
11 sales
2 rows updated.
Table altered.
Name Type
Cust name Varchar2(20)
Cust street Varchar2(20)
Cust city Varchar2(20)
Name Type
Branch name Varchar2(20)
Branch city Varchar2(20)
Asserts Number
Viva Questions
1) What is DBMS?
2) What is a database?
Page 14
3) What is a database system?
Page 15
Lab 2 - QUERIES USING DDL AND DML
Introduction
DDL is short name of Data Definition Language, which deals with database schemas and descriptions,
of how the data should reside in the database. And DML is short name of Data Manipulation Lan-
guage which deals with data manipulation and includes most common SQL statements such SELECT,
INSERT, UPDATE, DELETE, etc., and it is used to store, modify, retrieve, delete and update data
in a database.
Objective
By the end of this lab, the student should learn how to grant permissions, create the tables, inserting
values into the tables and updating the tables.
PreLab
• Prior coming to the lab, student should come have knowledge on DDL commands, DML commands
and TCL Commands.
Software Needed
Background
SQL Commands
DDL: Data Definition Language (DDL) statements are used to define the database structure or schema.
DML: Data Manipulation Language (DML) statements are used for managing data within schema
objects and to manipulate data of a database objects.
Page 16
2. Column Level Constraints.
1. NOT NULL:
Syntax:
<col><datatype>(size)not null
SQL > create table emp(e_id varchar(5) NOT NULL,e_name varchar(10), e_design varchar(10),dept
varchar(10),mgr varchar(10),salary number(10));
2. UNIQUE :
Ex:- SQL > create table depositor(customer_name varchar(10),acc_no number(15) UNIQUE, brach_name
varchar(10));
Syntax:
Ex:-
3. PRIMARY KEY:
Syntax:
<col><datatype>(size)primary key;
Ex:-
SQL> create table customer(customer_id number (5) PRIMARY KEY, customer_name varchar(10),cus-
tomer_street varchar(10),brach_name varchar(10));
Syntax:
Ex:-
Page 17
SQL > create table customer1(customer_id number (5),customer_name varchar(10),customer_street
varchar(10),brach_name varchar(10),PRIMARY KEY(customer_id));
4. CHECK:
Ex:- create table loan1(loan_no varchar(10),customer_name varchar(10), balance number (10), CHECK(bal-
ance>1000));
5. FOREIGN KEY:
Syntax:
Syntax:
Procedure
Page 18
SOLUTION:
–Provide roles
–Assigning privileges
b) Insert the any three records in the employee table and use rollback. Check the result.
1 row created.
Page 19
SQL> rollback;
Rollback complete.
c) Add primary key constraint and not null constraint to the employee table.
SQL> alter table employee modify(empno number primary key, ename varchar2(10) not null);
Table altered.
d) Insert null values to the employee table and verify the result.
Page 20
SOLUTION:
–Provide roles
–Assigning privileges
GRANT CREATE SESSION GRANT ANY PRIVILEGE TO <USER NAME>; GRANT UNLIM-
ITED TABLESPACE TO <USER NAME>;
1 row created.
SQL> commit;
Commit complete.
9 accounting Hyderabad
10 research Chennai
11 sales Banglore
12 operations Mumbai
9 accounting Chennai
13 sales Delhi
Page 21
6 rows selected.
c) Add constraints like unique and not null to the department table.
Table altered.
Table altered.
DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION NOT NULL VARCHAR2(10)
Page 22
c. Add save point after insertion of records and verify save point.
d. Add constraints not null and primary key to the sailor table.
Viva Questions
4. What is RDBMS?
Page 23
Lab 3 – QUERIES USING AGGREGATE FUNCTIONS
Introduction
In database management an aggregate function is a function where the values of multiple rows are
grouped together as input on certain criteria to form a single value of more significant meaning. Var-
ious Aggregate Functions are there such as count, sum, avg, min, max.
Objectives
By the end of this lab, the student should learn how various aggregate functions works and advantages
of using aggregate functions.
Prelab
Prior coming to the lab, student should come have knowledge on Aggregate Functions and syntax of
Aggregate Functions.
Software Needed
Background
An SQL aggregate function calculates on a set of values and returns a single value. For example, the
average function ( AVG) takes a list of values and returns the average.
Because an aggregate function operates on a set of values, it is often used with the GROUP BY clause
of the SELECT statement. The GROUP BY clause divides the result set into groups of values and
the aggregate function returns a single value for each group.
Procedure
Table created.
Page 24
SQL> desc emp;
EID NUMBER
ENAME VARCHAR2(10)
AGE NUMBER
SALARY NUMBER
44
22
220
31.4285714
SQL> create or replace view A as select age from emp where age<30;
View created.
Page 25
AGE
22
29
27
29
SALARY
9000
10000
8000
6000
7000
ENAME SALARY
rohan 6000
Alex 7000
shane 8000
abhi 8000
tiger 8000
Anu 9000
scott 10000
7 rows selected.
ENAME SALARY
scott 10000
anu 9000
shane 8000
Abhi 8000
Tiger 8000
Alex 7000
Rohan 6000
7 rows selected.
Page 26
SQL> select ename,salary from emp where age<29 group by ename,salary having salary<10000;
ENAME SALARY
alex 7000
anu 9000
1:
a) By using the group by clause, display the enames who belongs to deptno 10 along with average
salary.
b) Display lowest paid employee details under each department.
c) Display number of employees working in each department and their department number.
d) Using built in functions, display number of employees working in each department and their de-
partment name from dept table. Insert deptname to dept table and insert deptname for each row, do
the required thing specified above.
e) List all employees which start with either B or C.
f) Display only these ename of employees where the maximum salary is greater than or equal to 5000.
2:
a) Calculate the average salary for each different job.
b) Show the average salary of each job excluding manager.
c) Show the average salary for all departments employing more than three people.
d) Display employees who earn more than the lowest salary in department 30
e) Show that value returned by sign (n) function.
f) How many days between day of birth to current date.
3:
a) Show that two substring as single string.
b) List all employee names, salary and 15c) Display lowest paid emp details under each manager
d) Display the average monthly salary bill for each deptno.
e) Show the average salary for all departments employing more than two people.
f) By using the group by clause, display the eid who belongs to deptno 05 along with average salary.
4:
a) Count the number of employees in department 20
b) Find the minimum salary earned by clerk.
c) Find minimum, maximum, average salary of all employees.
d) List the minimum and maximum salaries for each job type
e) List the employee names in descending order.
f) List the employee id, names in ascending order by empid.
5:
a) Find the sids ,names of sailors who have reserved all boats called “INTERLAKE
b) Find the age of youngest sailor who is eligible to vote for each rating level with at least two such
sailors.
c) Find the sname , bid and reservation date for each reservation.
d) Find the ages of sailors whose name begin and end with B and has at least 3 characters.
e) List in alphabetic order all sailors who have reserved red boat.
Page 27
f) Find the age of youngest sailor for each rating level.
Viva Questions
Page 28
LAB 4-PROGRAMS ON PL/SQL
Introduction
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. PL/SQL is one
of three key programming languages embedded in the Oracle Database, along with SQL itself and Java.
Objective
By the end of this lab, the student should learn how to write programs by using PL/SQL.
Prelab
Prior coming to the lab, student should have a basic understanding of SQL Commands.
Software Needed
Background
SQL Commands
DDL: Data Definition Language (DDL) statements are used to define the database structure or schema.
DML: Data Manipulation Language (DML) statements are used for managing data within schema
objects and to manipulate data of a database objects.
Procedure
Page 29
1 a) Write a PL/SQL block to find the maximum number from given three numbers.
declare
a number; b number; c number;
begin
a:=&a;
b:=&b;
c:=&c;
if (a>b and a>c) then
dbms_output.put_line(’a is maximum ’ || a); elsif (b>a and b>c) then
dbms_output.put_line(’b is maximum ’ || b);
else
end if;
end;
/
dbms_output
declare
a number(3); b number(3);
begin
a:=&a;
b:=&b;
dbms_output.put_line(Before swapping a= ||a|| and b= ||b);
a:=a+b;
b:=a-b;
a:=a-b;
dbms_output.put_line(After swapping a= ||a|| and b= ||b);
end;
/
2 a) Write a PL/SQL program to find the total and average of 4 subjects and display
the grade
declare
java number(10); dbms number(10); co number(10); mfcs number(10); total number(10); avgs num-
ber(10); per number(10);
begin
dbms_output.put_line(’ENTER THE MARKS’);
java:=&java; dbms:=&dbms; co:=&co; mfcs:=&mfcsl;
total:=(java+dbms+co+mfcs); per:=(total/600)*100;
if java<40 or dbms<40 or co<40 or mfcs<40 then dbms_output.put_line(’FAIL’);
if per>75 then dbms_output.put_line(’GRADE A’);
elsif per>65 and per<75 then dbms_output.put_line(’GRADE B’);
elsif per>55 and per<65 then dbms_output.put_line(’GRADE C’);
else
dbms_output.put_line(’INVALID INPUT’);
end if;
dbms_output.put_line(’PERCENTAGE IS ’||per);
end;
/
Page 30
2 b) Write a program to accept a number and find the sum of the digits
declare
n number(5):=&n; s number:=0;
r number(2):=0;
begin
while n !=0 loop r:=mod(n,10); s:=s+r; n:=trunc(n/10);
end loop;
dbms_output.put_line(’sum of digits of given number is ’||s);
end;
/
3 a) PL/SQL Program to accept a number from user and print number in reverse order.
declare
num1 number(5); num2 number(5); rev number(5); begin num1:=&num1; rev:=0;
while num1>0 loop
num2:=num1 mod 10; rev:=num2+(rev*10); num1:=floor(num1/10);
end loop;
dbms_output.put_line(’Reverse number is: ’||rev);
end;
/
3b) Write a PL / SQL program to check whether the given number is prime or not.
declare
num number; i number:=1; c number:=0;
begin
num:=# for i in 1..num loop
if((mod(num,i))=0) then
c:=c+1;
end if;
end loop;
if(c>2) then
dbms_output.put_line(num||’ not a prime’);
else
dbms_output.put_line(num||’ is prime’);
end if;
end;
/
declare
i number(4):=1;
n number(4):=&n; f number(4):=1;
begin
for i in 1..n loop
f:=f*i;
end loop;
Dbms_output.put_line(’the factorial of ’||n||’ is:’||f);
Page 31
end;
/
4 b) calculate the area of a circle for a value of radius varying from 3 to 7. Store the
radius and the corresponding values of calculated area in table areas. Consisting of two
columns radius and area
Declare
pi constant number(4,2) := 3.14; radius number(5);
area number(14,2);
Begin radius := 3;
While radius <=7 Loop
area := pi* power(radius,2);
Insert into areas values (radius, area);
radius:= radius+1;
end loop;
end;
/
5a) Write a PL/SQL program to accept a string and remove the vowels from the string.
(When ‘hello’ passed to the program it should display ‘Hll’ removing e and o from the
world Hello).
set serveroutput on
set verify off
accept vstring prompt ”Please enter your string: ”;
declare
vnewstring varchar2(100);
begin
vnewstring := regexp_replace(’&vstring’, ’[aeiouAEIOU]’,”);
dbms_output.put_line(’The new string is: ’ || vnewstring);
end;
/
1. Write a PL/SQL program to accept a number and a divisor. Make sure the divisor is less than or
equal to 10. Else display an error message. Otherwise Display the remainder
VIiva Questions
Page 32
Lab 5 - PROCEDURES AND FUNCTIONS
Introduction
A procudure is a named PL/SQL block which performs one or more specific task. This is similar to
a procedure in other programming languages. A procedure has a header and a body.The header con-
sists of the name of the procedure and the parameters or variables passed to the procedure. The body
consists or declaration section, execution section and exception section similar to a general PL/SQL
Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.
A function is a named PL/SQL Block which is similar to a procedure. The major difference between
a procedure and a function is, a function must always return a value, but a procedure may or may
not return a value.
Objective
By the end of this lab, the student should learn how to write and execute Procedures and Functions
related programs by using PL/SQL .
PreLab
Prior coming to the lab, student should have strong knowledge on procedures and function concepts.
Software Needed
Background
Students should have knowledge on procedures and functions concepts and syntax’s for creating pro-
cedure and function.
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows –
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.
Page 33
{Syntax to create a function:}
Procedure
1) calculate the net salary and year salary if da is 30% of basic, hra is 10% of basic and
pf is 7% if basic salary is less than 8000, pf is 10% if basic sal between 8000 to 160000.
declare
ename varchar2(15); basic number;
da number; hra number; pf number;
netsalary number; yearsalary number;
begin
ename:=’&ename’; basic:=&basic; da:=basic * (30/100); hra:=basic * (10/100);
if (basic < 8000) then
pf:=basic * (8/100);
elsif (basic >= 8000 and basic <= 16000) then
pf:=basic * (10/100);
end if;
netsalary:=basic + da + hra - pf; yearsalary := netsalary*12;
dbms_output.put_line(’Employee name : ’ || ename);
dbms_output.put_line(’Providend Fund : ’ || pf); dbms_output.put_line(’Net salary : ’ || netsalary);
dbms_output.put_line(’Year salary : ’|| yearsalary); end;
/
2) Create a function to find the factorial of a given number and hence find NCR.
SQL> create or replace function fact(n number) return number is a number:=n; f number:=1; i num-
ber;
begin
for i in 1..n loop f:=f*a; a:=a-1;
end loop;
return f;
end;
/
Page 34
is
n1 number:=fact(n);
r1 number:=fact(r);
nr1 number:=fact(n-r);
result number;
begin result:=(n1)/(r1*nr1);
return result;
end;
/
4) write a pl/sql function accept date of birth as ”dd-mm-yyyy” and sum all digits till
you get single digit number to show as he lucky number.
Page 35
Probing Further Experiments
1.Write the PL/SQL programs to create the procedure to find sum of N natural number.
2.Write the PL/SQL programs to create the procedure to find Fibonacci series.
3.Write the PL/SQL programs to create the procedure to check the given number is perfect or not.
Viva Questions
5. What is normalization?
Page 36
Lab-6 - TRIGGERS
Introduction
A trigger is a set of SQL statements that reside in system memory with unique names. It is a special-
ized category of stored procedure that is called automatically when a database server event occurs.
Each trigger is always associated with a table.
A trigger is called a special procedure because it cannot be called directly like a stored procedure.
The key distinction between the trigger and procedure is that a trigger is called automatically when
a data modification event occurs against a table. A stored procedure, on the other hand, must be
invoked directly.
Objective
By the end of this lab, the student should learn how to create triggers and when to use triggers.
Prelab
Prior coming to the lab, student should have a basic understanding of DML, TCL languages and
triggers.
Software Needed
Background
Syntax:
Procedure
1. Create a row level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger
will display the salary difference between the old values and new values:
Page 37
WHEN (NEW.ID > 0) DECLARE
sal_diff number; BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line(’Old salary: ’ || :OLD.salary);
dbms_output.put_line(’New salary: ’ || :NEW.salary); dbms_output.put_line(’Salary difference: ’
|| sal_diff);
END;
/
Trigger created.
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table:
When a record is created in CUSTOMERS table, above create trigger display_salary_changes will
be fired and it will display the following result:
Old salary:
New salary: 7500 Salary difference:
Table created.
Trigger created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
Page 38
2 values (’01’,’Jason’, ’Martin’, to_date(’19960725’,’YYYYMMDD’), to_date(’20060725’,’YYYYM-
MDD’), 1234.56, ’Toronto’, ’Programmer’)
3/
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’02’,’Alison’, ’Mathews’, to_date(’19760321’,’YYYYMMDD’), to_date(’19860221’,’YYYYM-
MDD’), 6661.78, ’Vancouver’,’Tester’)
3/
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’03’,’James’, ’Smith’, to_date(’19781212’,’YYYYMMDD’), to_date(’19900315’,’YYYYM-
MDD’), 6544.78, ’Vancouver’,’Tester’)
3/
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’04’,’Celia’, ’Rice’, to_date(’19821024’,’YYYYMMDD’), to_date(’19990421’,’YYYYMMDD’),
2344.78, ’Vancouver’,’Manager’)
3/
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’05’,’Robert’, ’Black’, to_date(’19840115’,’YYYYMMDD’), to_date(’19980808’,’YYYYM-
MDD’), 2334.78, ’Vancouver’,’Tester’)
3/
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’06’,’Linda’, ’Green’, to_date(’19870730’,’YYYYMMDD’), to_date(’19960104’,’YYYYMMDD’),
4322.78,’New York’, ’Tester’)
3/
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’07’,’David’, ’Larry’, to_date(’19901231’,’YYYYMMDD’), to_date(’19980212’,’YYYYMMDD’),
7897.78,’New York’, ’Manager’)
3/
Page 39
1 row created.
SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’08’,’James’, ’Cat’, to_date(’19960917’,’YYYYMMDD’), to_date(’20020415’,’YYYYMMDD’),
1232.78,’Vancouver’, ’Tester’)
3/
1 row created.
8 rows selected.
Table dropped.
3) Trigger before deleting a record from emp table. Trigger will insert the row to be
deleted into another table and also record the user who has deleted the record.
Trigger created.
Page 40
8 rows deleted.
8 rows selected.
Table dropped.
1. Creation of insert trigger, delete trigger, update trigger practice triggers using the passenger
database. Passenger( Passport_ id INTEGER PRIMARY KEY, Name VARCHAR (50) Not NULL,
Age Integer Not NULL, Sex Char, Address VARCHAR (50) Not NULL); Write a Insert Trigger to
check the Passport_id is exactly six digits or not. Write a trigger on passenger to display messages „1
Record is inserted�, „1 record is deleted�, „1 record is updated� when insertion, deletion and updation
are done on passenger respectively.
2. Insert row in employee table using Triggers. Every trigger is created with name any trigger have
same name must be replaced by new name. These triggers can raised before insert, update or delete
rows on data base. The main difference between a trigger and a stored procedure is that the former
is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs.
3. Create a transparent audit system for a table CUST_MSTR. The system must keep track of the
records that are being deleted or updated.
Viva Questions:
1 What is Denormalization?
4 What is an entity?
Page 41
Lab 7 - PROCEDURES
Introduction
A procudure is a named PL/SQL block which performs one or more specific task. This is similar to
a procedure in other programming languages. A procedure has a header and a body The header con-
sists of the name of the procedure and the parameters or variables passed to the procedure. The body
consists or declaration section, execution section and exception section similar to a general PL/SQL
Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.
Objective
By the end of this lab, the student should learn how to write and execute Procedures and Functions
related programs by using PL/SQL .
Prelab
Prior coming to the lab, student should have strong knowledge on procedures and function concepts.
Software Needed
Background
Students should have knowledge on procedures and functions concepts and syntax’s for creating pro-
cedure and function. A procedure is created with the CREATE OR REPLACE PROCEDURE state-
ment. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows –
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.
Procedure
Page 42
Step 2: Connect to the database using username and password
Step 3: Write a pl/sql procedure/function program.
Step 4: Execute the procedure/function.
2. Create the procedure for GCD: Program should load two registers with two Numbers and then
apply the logic for GCD of two numbers. GCD of two numbers is performed by dividing the greater
number by the smaller number till the remainder is zero. If it is zero, the divisor is the GCD if not
the remainder and the divisors of the previous division are the new set of two numbers. The process
is repeated by dividing greater of the two numbers by the smaller number till the remainder is zero
and GCD is found.
3. Write the PL/SQL programs to create the procedure for factorial of given number.
Viva Questions
4. What is an attribute?
Page 43
Lab 8-CURSORS
Introduction
The ‘Cursor’ is the PL/SQL construct that allows the user to name the work area and access the stored
information in it. Cursors are used when the user needs to update records in a singleton fashion or in
a row by row manner, in a database table.
The Data that is stored in the Cursor is called the Active Data Set. Oracle DBMS has another pre-
defined area in the main memory Set, within which the cursors are opened.
Objective
By the end of this lab, the student should learn how to write and execute programs by using Cursors.
Prelab
Prior coming to the lab, student should have a basic understanding of DML, TCL languages and
triggers.
Software Needed
Background
Syntax:
Procedure
1.
declare
cursor xx is select empno,ename,sal from emp26; a_empno emp26.empno%type;
a_ename emp26.ename%type; a_sal emp26.sal%type;
begin open xx;
loop
fetch xx into a_empno,a_ename,a_sal;
Page 44
exit when xx% not found;
dbms_output.put_line(a_empno||’ ’||a_ename||’ ’||a_sal);
end loop;
close xx;
end;
SQL> /
1. Write a PL/SQL block that will display the name, dept no, salary of fist highest paid employees.
2. Update the balance stock in the item master table each time a transaction takes place in the item
transaction table. The change in item master table depends on the item id is already present in the
item master then update operation is performed to decrease the balance stock by the quantity specified
in the item transaction in case the item id is not present in the item master table then the record is
inserted in the item master table.
3. Write a PL/SQL block that will display the employee details along with salary using cursors.
4. To write a Cursor to display the list of employees who are working as a Managers or Analyst.
6. Write a PL/SQL block using implicit cursor that will display message, the salaries of all the em-
ployees in the „employee� table are updated. If none of the employee�s salary are updated we get a
message ’None of the salaries were updated’. Else we get a message like for example, ’Salaries for 1000
employees are updated’ if there are 1000 rows in „employee� table.
Viva Questions
4. What is Join?
5. What is 1NF?
Page 45
Lab 9 - CASE STUDY: BOOK PUBLISHING COMPANY
Introduction
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.
Objective
By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.
Background
1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.
Procedure
A publishing company produces scientific books on various subjects. The books are written by authors
who specialize in one particular subject. The company employs editors who, not necessarily being
specialists in a particular area, each take sole responsibility for editing one or more publications.A
publication covers essentially one of the specialist subjects and is normally written by a single author.
When writing a particular book, each author works with on editor, but may submit another work for
publication to be supervised by other editors. To improve their competitiveness, the company tries to
employ a variety of authors, more than one author being a specialist in a particular subject.
Page 46
Viva Questions
1. What is 2NF?
2. What is 3NF?
3. What is BCNF?
Page 47
Lab 10 -CASE STUDY: GENERAL HOSPITAL
Introduction
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.
Objective
By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.
Background
1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.
Procedure
A General Hospital consists of a number of specialized wards (such as Maternity, Paediatry, Oncology,
etc). Each ward hosts a number of patients, who were admitted on the recommendation of their own
GP and confirmed by a consultant employed by the Hospital. On admission, the personal details of
every patient are recorded. A separate register is to be held to store the information of the tests
undertaken and the results of a prescribed treatment. A number of tests may be conducted for each
patient. Each patient is assigned to one leading consultant but may be examined by another doctor,
if required. Doctors are specialists in some branch of medicine and may be leading consultants for a
number of patients, not necessarily from the same ward.
Page 48
3. Create the logical data model using E-R diagram
Viva Questions
Page 49
Lab 11 - CASE STUDY: CAR RENTAL COMPANY
Introduction
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.
Objective
By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.
Background
1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.
Procedure
A database is to be designed for a Car Rental Co. (CRC). The information required includes a descrip-
tion of cars, subcontractors (i.e. garages), company expenditures, company revenues and customers.
Cars are to be described by such data as: make, model, year of production, engine size, and fuel type,
number of passengers, registration number, purchase price, purchase date, rent price and insurance
details. It is the company policy not to keep any car for a period exceeding one year. All major repairs
and maintenance are done by subcontractors (i.e. franchised garages), with whom CRC has long-term
agreements. Therefore the data about garages to be kept in the database includes garage names,
addresses, range of services and the like. Some garages require payments immediately after a repair
has been made; with others CRC has made arrangements for credit facilities. Company expenditures
are to be registered for all outgoings connected with purchases, repairs, maintenance, insurance etc.
Similarly the cash inflow coming from all sources - car hire, car sales, insurance claims - must be
kept of file. CRC maintains a reasonably stable client base. For this privileged category of customers
special credit card facilities are provided. These customers may also book in advance a particular car.
These reservations can be made for any period of time up to one month. Casual customers must pay a
deposit for an estimated time of rental, unless they wish to pay by credit card. All major credit cards
are accepted. Personal details (such as name, address, telephone number, driving license, number)
about each customer are kept in the database.
Page 50
Probing Further Experiments
Viva Questions
1. What is SQL?
Page 51
Lab 12 -CASE STUDY: STUDENT PROGRESS MONITORING SYSTEM
Introduction
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.
Objective
By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.
Background
1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.
Procedure
A database is to be designed for a college to monitor students’ progress throughout their course of
study. The students are reading for a degree (such as BA, BA(Hons) MSc, etc) within the framework
of the modular system. The college provides a number of module, each being characterised by its code,
title, credit value, module leader, teaching staff and the department they come from. A module is co-
ordinated by a module leader who shares teaching duties with one or more lecturers. A lecturer may
teach (and be a module leader for) more than one module. Students are free to choose any module
they wish but the following rules must be observed: some modules require pre-requisites modules and
some degree programmes have compulsory modules. The database is also to contain some informa-
tion about students including their numbers, names, addresses, degrees they read for, and their past
performance (i.e. modules taken and examination results).
Page 52
Probing Further Experiments
Viva Questions
1. What is ER Diagram?
2. What is ER Model?
3. What is Entity?
4. What is relationship?
Page 53