Dbms Manual
Dbms Manual
Lab Manual(AR20)
in
Database Management Systems
II B.TECH - II Semester
Prepared by
Dr. S Vishnu Murthy
Associate Professor
Department of CSE
AR20
(i) CO-Statement
S. No CO-Statement
CO1• Create tables Relational database
CO2• Manipulate data in the Database using SQL
CO3• Compose Queries to retrieve required data from the database.
CO4 Use aggregate functions
•
CO5 Develop programs using triggers and cursors
CO6 Design Procedures, Functions and Packages for required Database tasks.
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
DBMSLAB.CO1 3 - 3 - 2 - - - - - - 2 3 - 1
DBMSLAB.CO2 2 - 3 - 3 - - - - - - 2 3 - 1
DBMSLAB.CO3 3 - 3 - 3 - - - - - - 2 3 - 1
DBMSLAB.CO4 2 - 3 - 2 - - - - - - 2 3 - 1
DBMSLAB..CO5 3 - 3 - 3 - - - - - - 2 3 - 1
DBMSLAB..CO6 3 - 3 - 3 - - - - - - 2 3 - 1
DBMS.TOT 16 - 18 - 16 - - - - - - 12 18 - 6
…
DBMS
1 - 3 - 3 - - - - - - 2 3 - 2
LAB
…
...
AR20
Additional Experiments
DDL commands:
The Create Table Command: - it defines each column of the table uniquely. Each column has
minimum of three attributes, a name , data type and size.
Syntax:
Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>));
Ex:
create table emp(empno number(4) primary key, ename char(10));
2. Modifying the structure of tables.
a)add new columns
Syntax:
Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size));
Example
alter table emp add(sal number(7,2));
3. Dropping a column from a table.
Syntax:
Alter table <tablename> drop column <col>;
Page No.1
Example
alter table emp drop column sal;
4. Modifying existing columns.
Syntax:
Alter table <table name> modify(<col><newdatatype>(<newsize>));
Ex:
alter table emp modify(ename varchar2(15));
Syntax:
insert into <table name> (<col1>,<col2>) values(<exp>,<exp>);
9. Delete operations.
a) Remove all rows
Page No.2
Syntax:
Update <table name> set <col>=<exp>,<col>=<exp>
where <condition>;
11. Types of integrity constrains.
a) Not null constraint at column level.
Syntax:
<Column><data type>(size)not null
b) Unique contraint
Syntax:
Unique constraint at column level.
<col><data type>(size)unique;
12. Viewing data in the tables: - once data has been inserted into a table, the next most logical
operation would be to view what has been inserted.
Page No.3
Select <column> to <column> from table name;
Select * from table name;
13. Filtering data from table- while viewing data from a table, it is rare that all the data from
table will be required each time. Hence, sql must give us a method of filtering out data that is not
required data.
a) Selected columns and all rows:
Syntax: Select <col1>,<col2> from <table name>;
b) Selected rows and all columns:
Syntax: Select * from <table name> where <condition>;
c) Selected columns and selected rows
Syntax: select <col1>,<col2> from <tablename> where<condition>;
Syntax:
GRANT <object privileges> ON <object name> TO<username>
[WITH GRANT OPTION];
b) Revoke permissions using the REVOKE statement:
The REVOKE statement is used to deny the Grant given on an object.
Syntax:
REVOKE<object privilege> ON FROM<user name>;
Page No.4
Experiment-01
Aim :
a) Execute single line and group functions on a table.
b) Create tables for various relations in SQL with necessary integrity constraints, keys,
data types.Verify messages by violating the constraints.
Single-row functions return a single result row for every row of a queried table or view.
They are numeric functions,character functions,datetime functions and conversion
functions
SELECT POWER(3,2) "Raised" FROM DUAL;
Raised
----------
9
Square root
-----------
5.09901951
COUNT(*)
----------
24
SELECT AVG(Salary) average_sal FROM employees;
AVERAGE_SAL
-----------
15694
SELECT SUM(Salary) total_sal FROM employees;
TOTAL_SAL
---------
87472
Page No.5
Select job, sum(sal) from emp group by job;
Select job,sum(sal) from emp group by job having (sal>10000);
Select min(salary) from emp;
Select max(sal) from employee;
b)Description:-
integrity constraints allows us to preserve the integrity of the database.
Integrity constraints disallow wrong/invalid data into the database.
Solution:
Create table emp(empno number(3) primary key,
empname varchar2(20) not null,
dept varchar2(12) default ‘admin’,
phone number(10) unique,
salary number(8,2) check(salary between 3000 and 30000));
Page No.6
Experiment -02
a) Implement the Queries in SQL for a) insertion b) retrieval c) updating d) deletion
b) Perform various join operations like Equi and non-equi ,outer join, self join
on two tables and show the results
a) Create table emp(empno number(3),ename varchar2(15),job varchar2(15),salary
number(3),deptno number(3));
Insert into emp values(&empno,’&ename’,’&job’,&salary,&deptno);
Select * from emp;
Update emp set salary=35000 where empno=109;
Delete from emp where ename=‘Rupesh’;
b) First create two tables with required attribute
Create table dept(depid number(5),depno number(3),pno number(3));
Insert into dept values(&depid,&depno,&pno);
Create table project(pno number(3),pname varchar2(34));
insert into project values(&pno,’&pname’);
Select dept.*,project.* from dept join project on dept.pno=project.pno;
Select dept.*,project.* from dept left outer join project on dept.pno=project.pno;
Select dept.*,project.* from dept right outer join project on dept.pno=project.pno;
Select dept.*,project.* from dept full outer join project on dept.pno=project.pno;
Select * from dept inner join project on dept.pno=project.pno and dept.pno!=4
Page No.7
Experiment -03
Page No.8
Experiment -04
a)Write a PL/SQL program to find the largest of three integers.
b) Write a PL/SQL program to find the factorial of a given integer and store the integer with it’s
factorial in a table .
Set serveroutput on
Declare
X number(3):=&x;
Y number(3):=&y;
Z number(3):=&z;
Big number(3);
Begin
Big:=X;
If(Y>Big) then Big:=Y;
Endif;
If(Z>Big) then Big:=Z;
Endif;
Dbms_output.put_line(to_char(Big)||’is largest’);
End;
/
b)
Create table fac(n number(3),f number(8));
Set serverouput on
Declare
N number(3):=&N;
F number(8):=1;
Begin
For I in 1..n loop
F=f*I;
END LOOP;
Dbms_output.put_line(‘FACTORIAL IS’||to_char(f));
Insert into fac values(N,F);
End;
/
Page No.9
Experiment -05
a)Write a PL/SQL program to display the sum of digits of given number.
b)Write a PL/SQL program to display the reverse of given number.
AIM: Write a PL/SQL program to display the sum of digits of a given number.
a)Set serveroutput on
N number(3):=&N;
S number(3):=0;
Begin
While(N>0) loop
S=S+mod(N,10);
N:=trunc(N/10);
End loop;
Dbms_output.put_line(‘sum is’||to_char(S));
End;/
b) Write a PL/SQL program to display reverse of a given number.
DBMS CODE:
Set serveroutput on
N number(3):=&N;
S number(3):=0;
Begin
While(N>0) loop
S=S*10+mod(N,10);
N:=trunc(N/10);
End loop;
Dbms_output.put_line(‘sum is’||to_char(S));
Page No.10
Experiment -6
Write a PL/SQL program to accept two numbers N1 and N2 and perform division operation.
And also handle the exception “Divide by zero “when N2 is zero.
Set serveroutput on
Declare
A number(3):=&a;
B number(3):=&b;
C number(3);
Begin
If(b=0) then raise zero_divide;
Else
C:=a/b;
Dbms_output.put_line(‘result is’||to_char(C));
Endif;
Exception
When zero_divide then
Dbms_output.put_line(‘b cannot be zero’);
End;
/
Write a PL/SQL program to accept the customer id from the user and display the corresponding
customer name and address from customer table. Raise user defined exception “invalid- id”
when customer id is <=0 and catch built in exceptions “no data found “ and display suitable
messages for each exception.
Set serveroutput on
Create table employee(empno number(5),ename varchar2(35),salary number(8,2));
Insert into employee values(&empno,’&ename’,&salary)
Declare
C_no employee.empno%type:=&c_id;
C_name employee.ename%type;
C_salary employee.salary%type;
Ex_invalid_id exception;
Begin
If(c_no<=0) then raise ex_invalid_id;
Else
Select ename,salary into c_name,c_salary from employee where empno=c_no;
Dbms_output.put_line(‘employee name:’||c_name);
Dbms_output.put_line(‘employee salary:’||c_salary);
End if;
Exception
When ex_invalid_id then
Dbms_output.put_line(‘id must be greater than zero’);
When no_data_found then
Dbms_output.put_line(‘No such customer’);
When others then
Dbms_output.put_line(‘Error’);
End;/
Page No.11
Experiment -07
Write a PL/SQL program using cursors to update the salaries of employees as follows and
also count and display the no of records have been updated.
if sal<10000 then update salary to 15000
If sal>=10000 and <20000 then update salary to 25000
If sal>=20000 and <=30000 then update salary to 40000
Description: Oracle uses a work area to execute SQL commands and processed information.
This area can be accessed using cursors. Cursor is a database object used by applications to
manipulate data in a set on a row-by-row basis. Example:If you need to insert/update/delete
bunch of data one by one, you have to use a cursor with a while loop
Cursors can be used when the user wants to process data one row at a time.
Cursors can be implicit or explicit.
Oracle automatically creates an implicit cursor for each SQL statement..
It has 4 attributes
SQL%ROWCOUNT,
SQL%FOUND,
SQL%NOTFOUND,
SQL%ISOPEN.
EXPLICIT cursors are created & managed by the programmer. It needs every
time explicit open,fetch . The data that is stored in the cursor is called active data set. We can
open,fetch and close a cursor.
Life cycle of a cursor:
1.Open cursor :
1) Server-side private memory of the server process is UGA(user global area).
2) A memory structure for the cursor is allocated in UGA.
3) Just a portion of memory is allocated for the cursor and SQL statement is not associated with
the memory structure.
2.Parse cursor :
1)An SQL statement is associated with the cursor.
3.Bind input variables: If the SQL statement uses bind variables, their values must be provided.
4.Execute cursor: The SQL statement is executed.
5.Fetch cursor: If the SQL statement returns data, this step retrieves it. Especially for queries,this
step is where most of the processing is performed. In the case of queries, rows might be partially
fetched. In other words, the cursor might be closed before fetching all the rows.
6.Close cursor: The resources associated with the cursor in the UGA are freed and consequently
made available for other cursors.
Solution :
Set serveroutput on
Create table employee(empno number(3),ename varchar2(35), salary number(8,2));
Insert into employee values(&empno,’&ename’,&salary);
Declare
Cursor my_cur is select empno,salary from employee;
Page No.12
Xno employee.empno%type;
Xsal employee.salary%type;
C number(3);
Begin
Open my_cur;
C:=0;
Loop
Fetch my_cur into xno,xsal;
Exit when my_cur%notfound;
If(Xsal<10000) then
Update employee set salary=15000 where empno=Xno;
C:=C+1;
else
If(Xsal<20000) then
Update employee set salary=25000 where empno=Xno;
C:=C+1;
Else
If(Xsal<30000) then
update employee set salary=40000 where empno=Xno;
C:=C+1;
End if;
End if;
End if;
End loop;
Close my_cur;
Dbms_output.put_line(c||’record has been completely updated’);
End;
/
Page No.13
Addional example program:
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Page No.14
Experiment-08
Aim: Write a PL/SQL program using triggers to automatically store all the deleted
records from employee table in a separate table called “employees history “ along with
date of deletion,user-id of the person who deleted
Description: A trigger is a PL/SQL program associated with a specific database table.
Triggers are fired/executed automatically whenever a given SQL operation affects the
table. The SQL operations may be insert,update,delete etc.
Advantages./uses of triggers
▪ Automatically generate derived column values
▪ Prevent invalid transactions
▪ Gather statistics on table access
▪ Maintain synchronous table replicates
Types of triggers
▪ Statement triggers
▪ Row triggers
▪ Before triggers
▪ After triggers
Row Trigger(Example)
Create or replace trigger del_info after delete on student for each row
Begin
Insert into del_dummy values (:old.name, :old.rollno,sysdate);
End;
/
Statement level trigger(Example)
create trigger stmt_level_trigger
after update on emp
begin
update emp
set grade = NULL
where grade = 13;
end;
/
Solution
Set serveroutput on
Create table employee(empno number(3) not null,ename varchar2(30));
Insert into employee values(&empno,’&ename’);
Select * from employee;
Create table employee_history(empno number(3) not null,ename varchar2(30),dob date);
Create or replace trigger del_info after delete on employee for each row
Begin
Insert into employee_history values(:old.empno,:old.ename,sysdate);
End;
/
Delete from employee where empno=507;
Select * from employee;
Select * from employee_history;
Page No.15
Experiment-09
a) Write a PL/SQL program to which computes and returns the maximum of two values using a
function.
DBMS CODE:
Set serverouput on
Declare
A number(5);
B number(5);
C number(5);
Function findmax(x in number, y in number) return number is
Z number(5);
Begin
If(X>Y) then Z:=X;
Else
Z:=Y;
End if;
Return Z;
End;
Begin
A:=&A;
B:=&B;
C:=findmax(A,B);
Dbms_output.put_line(‘Max is’||to_char(C));
End;
/
b)Write a PL/SQL procedure to display all the records of employee table in a neat format.
DBMS CODE:(You should create a emp table before this code)
Set serveroutput on
Declare
Emp_rec emp%rowtype;
Begin
Select * into emp_rec from emp where empno=&empno;
Dbms_output.put_line(‘emp no is ‘||emp_rec.empno);
Dbms_output.put_line(‘emp name is ‘||emp_rec.ename);
Dbms_output.put_line(‘emp job is ‘||emp_rec.jobs);
Dbms_output.put_line(‘emp salary is ‘||emp_rec.salary);
End;
/
Page No.16
Experiment -10
Write a PL/SQL program to create a Package to group logically related variables,types and sub
programs and use the package elements later.
Description : Packages are schema objects that groups logically related PL/SQL types, variables
and subprograms.
A package will have two mandatory parts:
• Package specification
• Package body or definition
Package Specification
The specification is the interface to the package. It just DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced from outside the package.
In other words, it contains all information about the content of the package, but excludes the
code for the subprograms.
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.
REATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
Package Body
The package body has the codes for various methods declared in the package specification and
other private declarations, which are hidden from code outside the package.
Sample Program :
CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
Using the Package Elements
ECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/
Solution to Experiment:
Page No.17
Set serveroutput on
Create table employee(empno number(5),ename varchar2(45),salary number(8,2));
Insert into employee values(&empno,’&ename’,&salary);
Create or replace package cust_sal as
Procedure find_sal(c_id in employee.empno%type) is
C_sal employee.salary%type;
Begin
Select salary into c_sal from employee where empno=c_id;
Dbms_output.put_line(‘salary:’||c_sal);
End find_sal;
End cust_sal;
/
Declare
Id employee.empno%type:=&id;
Begin
Cust_sal.find_sal(id);
End;
/
Page No.18
Additional Experiments
Experiment-01
Aim : Program using CASE with Exception statement in PL/SQL
Solution :
DECLARE
2 grade CHAR(1);
3 BEGIN
4 grade := 'B';
5
6 CASE
7 WHEN grade = 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
8 WHEN grade = 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');
9 WHEN grade = 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');
10 WHEN grade = 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');
11 WHEN grade = 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');
12 END CASE;
13
14 EXCEPTION
15 WHEN CASE_NOT_FOUND THEN
16 DBMS_OUTPUT.PUT_LINE('No such grade');
17 END;
18 /
Expected output
Very Good
Page No.19
Experiment-02
Page No.20
Experiment-03
Aim : PL/SQL Function that computes and returns the maximum of two values.
Description:-It uses a function with two IN paramaters of number type and compares the two
using if statement and returns the maximum out of two.
Solution :
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
Expected output:
Maximum of (23,45): 45
Page No.21