DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Data Base Management System lab manual
CONTENTS1. 2. Creating tables for various relations.
Implementing the queries in SQL for a) Insertion. b) Retrieval. c)
Updation. d) Deletion. SQL Reporting. Creating views. Introduction
to pl/sql Implementing operations on relations. Writing Cursors.
Exception handling. Writing function. Writing procedure Writing
package. Writing Triggers. Creating Forms and Generating
Reports
3. 4. 5. 6. 7. 8. 9. 10. 11. 12.
1
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Introduction to Database Management SystemAll database
management systems (oracle is a DBMS) allows users to create
containers for data storage and management. These containers are
called cells. The minimum information that has to be given to
oracle for suitable container to be constructed which can hold free
form human data is The cell/field name The cell/field length The
type of data that can be placed in to the cell. We imagine that
each field was an object created for us by oracle. Then number of
fields created in same horizontal plane would be another object
created for us by oracle. Multiple fields placed in the same
horizontal plane is an object called a Record by oracle. Several
Records, of equal length, placed one below the other to enable
users to continue to store data is called a Table(consists of rows
and columns used for storing data). The table therefore becomes the
third object after fields and rows. A GROUP of Tables with related
data in them is called a database. Relational data base management
system Relational data base management system uses only its
relational capabilities to manage the information stored in its
database.
2
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Introduction to SQL SQL stands for Structured Query Language.
Oracle provides many extensions to ANSI SQL.SQL is standard
language for interfacing with a relational database. A table is
primary database object of SQL ,which is used to store the data in
the form of rows and columns. SQL developed by IBM is used as
standard language to access data from database. In order to
communicate with database SQL has been divided into three sub
languages and each sub language consists of different commands,
they are
a) Data Definition Language DDL COMMANDS: CREATE ALTER DROP b)
Data Manipulation Language DML COMMANDS: SELECT INSERT UPDATE
DELETE c) Transaction Commit Language TCL COMMANDS: COMMIT ROLLBACK
SAVEPOINT
3
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
EXERCISE -1DATA TYPESIn order to create a data base object
(table) we need to specify a data type of that particular columns
while creation of that table itself. Oracle mainly supports two
types of data types. 1. 2. Internal data type. Composite data
type.
A data type associates a fixed set of properties with the values
that can be used in a column of a table or in an argument of a
procedure or function. These properties cause oracle to treat
values of one data type different from values of another data type.
Oracle supplies the following built-in data types:
CHARACTER DATATYPES Char(size) Fixed-length character data of
length size bytes(maximum 2000 bytes per row ,default size is 1
byte per row). Varchar2(size) variable length character data.
NUMBER DATATYPE Number(p,s)Variable-length numeric data (fixed
or floating point).
4
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
DATE DATATYPE DateFixed length date and time date. The standard
format is dd-mon-yy. To enter dates other than standard format ,use
the appropriate functions.
LONG DATATYPE LongCell/field defined as LONG can store variable
length character strings containing upto 65,535 characters.
USER DEFINE DATATYPES:Like the oracle internal data types that
are already present the user can create new data type.
When we define the data type we use create or replace command.
SYNTAX: for creating a table create table (columnname data
type(size),columnname datatype(size));
5
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
For example: create a table which describes employee
particulars.
Column cccccccolname empname emp no. Address Pin code Salary
data type varchar2 varchar2 varchar number number
size 20 6 30 6 10,2
Its code is as followed
SQL> CREATE TABLE employee (empname varchar2(20),emp no.
varchar2(6),address varchar2(30),pin code number(6),salary
number(10,2));
6
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
CONSTRAINTSConstrains are the mechanism used in oracle in order
to prevent invalid data or to avoid the duplicacy of the data being
entered by the user.
Integrity constraints:An integrity constraint is the rule that
restricts the values for one or more columns in a table. Constraint
clauses can appear in either CREATE TABLE or ALTER TABLE
commands.
SYNTAX to define an integrity constraint , Table_constraint::=
create table (column_name datatype , column_name datatype
,constraint constraint_name constraint_definition (column_names));
NOTE: This syntax can define any type of integrity constraint
except a NOT NULL constraint. Column_constraint::= create table
(column_name datatype , constraint constraint_specification); NOTE:
Column_constraint table that appears in an ALTER Table statement
can only define or remove a NOT NULL constraint.
7
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
There are three types of constraints 1. Domain Integrity
Constraint.
Not Null Constraint Syntax: create table (column_name datatype
Not Null); Check constraint Syntax: create table (column_name
datatype check ); 2. Entity Integrity Constraint. Unique_constrain
syntax: create table (column definitions ,constraint
[constraintname] unique); Primary key syntax: create table (column
definitons , [constraint-name] primary key); Note: The DISABLE
option oracle to define the constraint but not enforce it.
8
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
3. Referential Integrity Constraint. Syntax: create table
(column definitons , [constraintname] reference <
column_name>); 4. Foreign key
This identifies the column or combination of columns in the
child table that makes up of the foreign key .
On Delete Cascade Allows deletion of referenced key values in
the parent table that have dependent rows in the child table and
causes oracle to automatically delete dependent rows from the child
table to maintain referential integrity.Syntax: create table
(column definitons , [constraintname] reference <
column_name>);
create the following tables with the help of above
example..9
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
TABLE STRUCTURE FOR DBMS LAB I DEPARTMENT: DCODE number DNAME
varchar2 EMPLOYEE: ECODE number ENAME varchar2 GCODE varchar2 DOB
date DOJ date DCODE number SEX char BASIC number REPORTTO number
(Same as ecode) PROGRAME: PCODE varchar2 ECODE number PROGSEC:
PCODE PNAME DURATION DESCRIPTION GRADE: GCODE GNAME MAXBASIC
MINBASIC RAISE varchar2 varchar2 number varchar2 varchar2 varchar2
number number number
II
III
IV
V
10
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise -2BASIC CLAUSES IN SQL: SELECT
colum1,colum2[,column3,....] this clause is used to diplay selected
columns. FROM table1[,table2,....] this clause is used to select
the source tables. OPTIONAL CLAUSES: WHERE condition1 [and
condition2 [or condition3]] this clause is used to give some
condition which can be imposed on selected columns. ORDER BY
column1[,column2,...] [desc] this clause is used to get the result
in sorting order of columns specified in the same clause. GROUP BY
column1,column2 Whenever you want to select column name along with
group funcitons you should include those columns in group by
clause. group by clause can also have not selected columns.
11
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
HAVING
condition.
This cluase should preceded by group by clause. We use this to
give column selection conditions which cannot be achieved by where
clause(row selection condition).
The following in built functions in oracle are just a few
selected from many functions that are most commonly used in
commercial application development. DUAL is a table which consists
single column and single row.using this usually we will check the
funcitons.
PSEUDO COLUMNS: ROWNUM, ROWID, LEVEL, SYSDATE AGGREGATE OR GROUP
FUNCTIONS : AVG, MAX, MIN, SUM, COUNT NUMBER FUNCTIONS :
ABS,POWER,ROUND,SQRT. STRING FUNCTIONS: LOWER, UPPER, INITCAP,
SUBSTR, LENGTH, LTRIM, RTRIM,LPAD, RPAD DATE FUNCTIONS :
ADD_MONTHS, MONTHS_BETWEEN, NEXT_DAY, LAST_DAY12
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
CONVERSION FUNCTIONS: TO_CHAR, TO_DATE, TO_NUMBER MISLENIOUS
FUNCITONS: DECODE, TRANSLATE.
Note: For the detailed information of above mentioned functions
refer to complete reference Or sql/pl/sql by Oracle press write the
following queries 1. 2. 3. Exercise-2(A) Insert values into your
table for specific columns. Insert values into your table for all
columns. Insert values into one table using other table.
Exercise-2(B) 1. 2. 3. 4. 1. 2. Select specific columns from a
table. Select distinct columns from a table. Select specific
columns by changing column headings. Select today's date using dual
table. Exercise-2(C) Update a single column value in a table.
Update more than one column value in a table.
Exercise-2(D) 1. 2. Delete all rows from a table. Delete
specific rows from a table.
13
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
JOINSIntroduction to Joins different or same tables(is done
using concept called JOINS): Examples are shown below which covers
different types of joins. 1. NORMAL JOIN CARTISIAN PRODUCT SELECT *
FROM EMP,DEPT 2. EQUI JOIN & NON EQUI JOIN SELECT * FROM EMP,
DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO SELECT * FROM EMP, DEPT WHERE
EMP.DEPTNODEPT.DEPTNO 3. SELF JOIN SELECT EMPNO,MGR FROM EMP A, EMP
B WHERE A.EMPNO=B.MGR
14
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
4.
OUTER JOIN LEFT OUTER JOIN RIGHT INNER JOIN
SELECT EMPNO,ENAME FROM EMP, DEPT WHERE
EMP.DEPTNO(+)=DEPT.DEPTNO SELECT EMPNO,ENAME FROM EMP, DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO(+) Write the following queries. 1. Get a
list of all employees in a particular department along with their
gradecode, grade description, current basic and maximum basic in
current grade.apply lpad to gcode to get like
g1--------------------- in total 35 characters along with gcode.
lpad(string,total no of characters,format) 2. 3. 4. Get list of all
employees who had attended a particular training program. Get the
program code at runtime. Get list of all employees in a particular
age group. Specify the age group like 22-30 yrs
(hint:months_between). Get the list of all employees whose first
letters of the names have been specified. Get the number of
employees,and average basic in each department for every grade.
5.
15
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exerice:3 SQL REPORTING: EXAMPLE: Q: To get the list of all
employees in their of order of employee names REM first programe.
SET HEADSEP * SET FEEDBACK off SET NEWPAGE 2 TTITLE 'Solution to
the first query * list of all employees' BTITLE 'CMRCET' COLUMN
ename HEADING 'Employees * Name' format a10 SET PAGESIZE 24 select
ename from emp order by ename desc; SET PAUSE 'more...' set pause
on Output: Solution to the first query list of all employees
Employees Name ... ... CMRCET
16
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Generate SQL Report for the following queries using above sql
report commands 1. Get the list of all employees in reverse order
of employee code, display ecode as Employee ,dcode as Employee ,
ename as Employee Code Department Name Get the gname at runtime and
give the following report rem set headsep set feedback ttitle
btitle column ename column dname accept gname prompt like enter
grade name break on department name duplicate skip set pause
Employee Name 3. Department Name
2.
Get the details of employee number, employee name, employee's
department name, employee grade name using above sql reporting
commands Get the departments which do not have employees. Get the
following report on emp table where paydate(first salary taken
date) should be the last friday of the month if employee's hiredate
is before 15th of that month otherwise first friday of next month.
empno ename hiredate paydate
4. 5.
17
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise -4INTRODUCTION TO SIMPLE VIEWS: VIEW is a logical
object. this will be created by using other tables with select
statement. We use views to hide the table names and query coplexity
from user. We can rename the base table column in our view with
column alias in the select query. Example: create view dsk as
select empno eno from emp; UPDATABLE VIEWS: This View should
contain the mandatory columns of base tables, should not have
aggregate functions,distinct clause,group by or having clause.
Using drop view we can destroy a view. Write queries for following
. 1. 2. 3. 4. 5. Create a view to get a list of training programs
attended by employee 'CMRCET' or another with ecode 2. To create a
view to get the current grade, current basic, increment step,
maximum basic for ecode 3 and ename='CMRCET'. Create views which
should contain odd, even numbered rows of employee table. Create a
view with ename,dname,gname. Delete duplicate rows from a table
except last occurrence.
18
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise -5 Introduction to PL/SQL:Pl/sql is a completely
portable ,high performance transaction processing language .
DATA TYPES BUILT-IN DATA TYPES1. Number Float Integer character
type char varchar2 Boolean Date
2.
3. 4.
The basic pl/sql program structure is as followingDeclare Begin
(%TYPE,%ROWTYPE)
Exception End;
19
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Control Structures:1. If then End if; If then elsif then else
End if;
2.
Loops:1. GOTO: go to lablename;
2. Simple loop: loop exit end loop 3. For loop: for in .. loop
end loop 4. While loop: While loop end loop;20
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Write the following specified programs 1. 2. 3. 4. 5. To find
whether the given number is palindrome or not ? To find all
Armstrong number below given number. To count the words, vowels,
consonants and length of the given string (Hint: substr). To handle
zero_divide,value_error and your exceptions. To print prime numbers
between 100 and 500.
21
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise 6 ExceptionsIn pl/sql ,a warning or error condition is
called an exception. Exceptions can be internally defined (by the
runtime system) Or user defined .Unlike internal exceptions, user
defined exceptions must be given names. When an error occurs ,
exception is raised. That is, normal execution stops and control
transfers to the exception-handling part of that pl/sql block or
subprogram. Internal exceptions are raised implicitly
(automatically) by runtime system. User-defined exceptions must be
raised explicitly by RAISE statements, which can also predefined
exceptions. Few of the pre defined oracle errors are 1.
dup_val_on_index: Try to store duplicate values in a database
column that is constrained by a unique index. 2. 3. 4. 5. 6. 7.
Ect.. Invalid_number Login_denined No_data_found Not_logged_on
Program_error Zero_divide
22
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
USER_DEFINED EXCEPTION A USER_DEFINED EXCEPTION should be
declared and raised explicitly by a raise statement. It can be
declared only in the declarative part of the pl/sql block. The
syntax is as follows: exception; The syntax for raise statement
follows. Raise; 1.write a pl/sql block to raise an exception if
employee number read is not found when employee details are
displayed. 2. Write a program to implement Not_logged_on
exception.
23
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise 7
CURSORSOracle uses work areas to execute SQL statements and
store processing information. A PL/SQL construct called cursor lets
us you name a work area and access its stored information. There
are 2 types of cursors. IMPLICIT CURSOR: Is the cursor which is
always generated Implicitly by the oracle. We can use the Implicit
cursor as SQL ,which is its name. EXPLICIT CURSORS These cursors
are always defined by the user in PL/SQL block with the following
syntax. DECLARE CURSOR IS ; BEGIN < Select statements>;
END;
PARAMETRIC CURSORS: Parameterized cursors is used to give
parameters while opening the cursor. These parameters are to
substitute in cursor declaration. We use OPEN, FETCH, CLOSE
statements to control a Cursor.
24
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
CURSOR ATTRIBUTES: %FOUND %NOTFOUND %ISOPEN %ROWCOUNT Using the
above attributes we can Know the different states of cursor. CURSOR
FOR LOOP: FOR VARIABLE IN CURSOR LOOP END LOOP; FOR UPDATE CLAUSE:
Is used to restrict update on particular columns by selecting those
columns in for update clause. CURRENT OF Is used in where clause to
update the current record of cursor but cursor should have for
update clause.
25
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
EXERCISE1 2 3 4 Write a program to display employee table using
cursor also handle cursor exceptions. Write a program to display
employee name and department name using one cursor. Write a program
to find experience of each employee using parameterized cursor.
Write a program to update the database using cursors based on the
following conditions handling exceptions. 1. If Basic is greater
than Rs.1500.00 then give increment of Rs.200.00. 2. If Basic is
between Rs.1501.00 and Rs.3000.00 then give increment of Rs.500.00.
3. If Basic is greater than Rs.3000.00 then give increment of
Rs.750.00. 5 6 Write a program to delete a particular row using
cursor. Write a program to print rows from last to first using
cursor.
26
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise-8SUBPROGRAMSA subprogram is used to reduce the program
in size. we use the same set of statements to be executed for the
different values, so we write the same set of statements as a
subprogram. A subprogram can be a function or procedure in PL/SQL
which has to be created separately as a database object.
FUNCTIONBasically function is to return a value of various data
types available. To get the function result we have to assign
function to returntype variable. Function can't return more than
one value. Example: Create or replace function add(a number, b
number)return number is C number; Begin C:=a+b; Return C; End;
Exercise: 1. 2. Write a function to get the factorial of given
number. Write a function to check the existing of employee for
given employee number.
27
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise-9 PROCEDUREBasically a procedure is used to perform
some task which may return one value or more than one value or no
value. we use parameters to get the result of procedures. MODES OF
PARAMETER: IN Read only value Right side of :=
literal,expression,variable OUT IN OUT Example: Create or
replace procedure add(a in number, b in number, c out number) is
Begin C:=a+b; End; Exercise: 1. 2. Write a procedure to insert a
row into your table. Write a procedure to insert a particular
record in some other table while deleting from a table. Write only
value Left side of := Only Un initialized variable. Read&Write
Value Left & Right side of := Only Initialized variable
28
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise -10 PACKAGE:Package is used to group the related
functions and procedures of a database. A Package will be created
as 2 different objects package specification and package body. The
functions and procedures in that packages are treated as members of
that package object but not as database objects. Before creating
the package body there should be package specification for that
package. PACKAGE SPECIFICATION: create or replace package as
variable that you want to include in this package; cursors that are
common for the entire package; function prototype declaration of a
function with return type; procedure prototype declaration of a
procedure; end PACKAGE BODY: create or replace package body as body
of a function ; (by discarding create or replace as in ordinary
function); body of a procedure ; (by discarding create or replace
as in ordinary procedure); end
29
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise: 1. Write a package with functions isprime,
isarmstrong, ispositive, isnegative to check whether the given
number is prime, Armstrong, positive, negative respectively.
Include following procedures, variables in the above package. a)
Procedure that displays a number in words for a given integer. b)
Procedure that deletes the records in a table based on the
parameter. variables: a)Pi value b)e value cusors: a)cursor that
with all the columns of employee table. b)cursor that can have only
department 10 employee details.
2.
30
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise-11 TRIGGERA Trigger is PL/SQL block which can be
executed without explicit calling at the time of DML operations on
a table. Types of Triggers: Triggers are categorized base on when
they are fired: Before After For each row For each
statement(default)
Syntax: create or replace trigger {before/after/instead of}
{insert/delete/update[of column1[,column2..]]} on [for each
statement/ row] [when ] DECLARE BEGIN END; INSTEAD OF trigger is
only for views.
31
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Note: 1) A Database trigger can also have declarative and
exception Handling parts. 2) A sub query cannot be included in when
clause.
Enable/Disable: Alter trigger enable/disable; Alter table
disable all;
EXERCISETABLES FOR NEXT EXERCISE employee(empno, hiredate, dob,
sal, appno). personal(empno, address, phno, email). selected(appno,
dateofInterview). application(appno, ename, address, phno, enmail,
qualification, dob, designation). 1. 2. 3. create necessary
triggers which insert employees personal details in personal table
after inserting in employee table. Create a trigger before
insert/update/delete of employee details to stop the transactions
on Saturdays and Sundays. Create a trigger to check detail records
while deleting or updating master records at master table.
32
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Exercise-12
FORMSDeveloper 2000 Forms is used to develop Client/Server
applications by which can be used to enter, access, change or
delete data from oracle database in A form based environment.
FormA Form module is nothing but collection of objects such as
windows, Block , canvas, items, event based PL/SQL Code blocks
called Form Triggers Menu Collection of Objects such as menu items,
submenus, submenu items And PL/SQL Code blocks. PL/SQL Libraries
Collection of PL/SQL functions and procedures stored in a single
Library file. This library file is then attached to a form/menu.
Item These are objects contained in blocks, that present data
values to the user depending upon the item type(text, checkbox,
list ,radio group, button...). Block A block is group of related
items. They can be span over many canvases. Data block: Is
associated with data(tables) with in the database Control block: Is
not associated with any of the data in the database.
33
DBMS
Department of Computer Science Data Base Management Systems
Laboratory Manual
Canvasview A canvasview is a "surface" where visual objects are
arranged. Window window is similar to an empty picture frame, which
can hold the canavasview and allows to resize, move the
canvaseview. Trigger A forms object it associates a Pl/SQL block
with an event.
REPORTSData model which is used to give the query and Data
model-> editor -> SQL -> click in the editor: Q1 ->
properties Select the necessary columns from tables to get the
report. Exercise 1. 2. 3. 4. Develop a form to contain 3 different
blocks on emp, dept, salgrade tables. Enforce the constraints on
this Develop a form to display the time and college name in a form
using control block. Develop a master detail blocks form for dept,
emp tables along with navigation items. Create simple report in
tabuler model with the details of employee ename, department name,
salary, next increment date ( assume that every year from the
joining date each employee get increment). Generate a master
details report with the department name and total no.of employees
and total salary of that department.
5.
34