Sei sulla pagina 1di 34

DBMS Department of Computer Science

Data Base Management Systems Laboratory Manual

Data Base Management System lab manual

CONTENTS
1. Creating tables for various relations.

2. Implementing the queries in SQL for


a) Insertion.
b) Retrieval.
c) Updation.
d) Deletion.

3. SQL Reporting.

4. Creating views.

5. Introduction to pl/sql
Implementing operations on relations.

6. Writing Cursors.

7. Exception handling.

8. Writing function.

9. Writing procedure

10. Writing package.

11. Writing Triggers.

12. Creating Forms and Generating Reports

1
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Introduction to Database Management System

All 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 -1

DATA TYPES

In 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. Internal data type.


2. 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

 Date
Fixed 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

 Long

Cell/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 <table name>(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 name
cccccccol data type size

empname varchar2 20
emp no. varchar2 6
Address varchar 30
Pin code number 6
Salary number 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

CONSTRAINTS

Constrains 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 <table_name>(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 <table_name>(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 <table_name>
(column_name datatype Not Null);

 Check constraint

Syntax:
create table <table_name>
(column_name datatype check <condition>);

2. Entity Integrity Constraint.

 Unique_constrain

syntax:

create table <table_name>(column definitions ,constraint [constraint-


name] unique);

 Primary key

syntax:

create table <table_name>(column definitons ,<constraint>


[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 <table_name>(column definitons ,<constraint> [constraint-


name] reference <parents table_name>< 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 <table_name>(column definitons ,<constraint> [constraint-


name] reference <parents table_name>< 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

II EMPLOYEE:
ECODE number
ENAME varchar2
GCODE varchar2
DOB date
DOJ date
DCODE number
SEX char
BASIC number
REPORTTO number (Same as ecode)

III PROGRAME:
PCODE varchar2
ECODE number

IV PROGSEC:
PCODE varchar2
PNAME varchar2
DURATION number
DESCRIPTION varchar2

V GRADE:
GCODE varchar2
GNAME varchar2
MAXBASIC number
MINBASIC number
RAISE number

10
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Exercise -2

BASIC 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_DAY

12
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

Exercise-2(A)
1. Insert values into your table for specific columns.
2. Insert values into your table for all columns.
3. Insert values into one table using other table.

Exercise-2(B)

1. Select specific columns from a table.


2. Select distinct columns from a table.
3. Select specific columns by changing column headings.
4. Select today's date using dual table.

Exercise-2(C)
1. Update a single column value in a table.
2. Update more than one column value in a table.

Exercise-2(D)

1. Delete all rows from a table.


2. Delete specific rows from a table.

13
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

JOINS
Introduction 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.DEPTNO<>DEPT.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. Get list of all employees who had attended a particular training


program. Get the program code at runtime.

3. Get list of all employees in a particular age group. Specify the age
group like 22-30 yrs (hint:months_between).

4. Get the list of all employees whose first letters of the names have been
specified.

5. Get the number of employees,and average basic in each department


for every grade.

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

2. 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 Department
Name Name

3. Get the details of employee number, employee name, employee's


department name, employee grade name using above sql reporting
commands

4. Get the departments which do not have employees.

5. 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

17
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Exercise -4

INTRODUCTION 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 <viewname> we can destroy a view.


Write queries for following .

1. Create a view to get a list of training programs attended by employee


'CMRCET' or another with ecode 2.

2. To create a view to get the current grade, current basic, increment


step, maximum basic for ecode 3 and ename='CMRCET'.

3. Create views which should contain odd, even numbered rows of


employee table.

4. Create a view with ename,dname,gname.

5. 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 TYPES

1. Number

 Float
 Integer
2. character type
 char
 varchar2
3. Boolean
4. Date

The basic pl/sql program structure is as following

Declare
<All declarations> (%TYPE,%ROWTYPE)
Begin

<Executable statements>

Exception
<Exception handling>
End;

19
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Control Structures:

1. If <condition> then
<statements>
End if;

2. If <condition> then
<statements>
elsif <condition> then
<statements>
else
<statements>
End if;

Loops:
1. GOTO:
<<lablename>>
<statements>
go to lablename;

2. Simple loop:
loop
<statements>
exit <condition>
end loop

3. For loop:
for <counter> in <startvalue> .. <end value>
loop
<statements>
end loop

4. While loop:
While <condition>
loop
<statements>
end loop;

20
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Write the following specified programs

1. To find whether the given number is palindrome or not ?

2. To find all Armstrong number below given number.

3. To count the words, vowels, consonants and length of the given string
(Hint: substr).

4. To handle zero_divide,value_error and your exceptions.

5. To print prime numbers between 100 and 500.

21
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Exercise –6

Exceptions

In 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. Invalid_number

3. Login_denined

4. No_data_found

5. Not_logged_on

6. Program_error

7. Zero_divide

Ect..

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_name> exception;

The syntax for ‘raise’ statement follows.

Raise<exception_name>;

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

CURSORS

Oracle 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 <Cursorname> IS <Select statement>;
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
<statements>
END LOOP;

FOR UPDATE CLAUSE:


Is used to restrict update on particular columns by selecting
those columns in for update clause.

CURRENT OF <cursorname>

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

EXERCISE

1 Write a program to display employee table using cursor also handle


cursor exceptions.
2 Write a program to display employee name and department name
using one cursor.
3 Write a program to find experience of each employee using
parameterized cursor.

4 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 Write a program to delete a particular row using cursor.

6 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-8

SUBPROGRAMS

A 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.

FUNCTION

Basically 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. Write a function to get the factorial of given number.


2. 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

PROCEDURE

Basically 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 Write only value Left side of :=

Only Un initialized variable.


IN OUT Read&Write Value Left & Right side of :=
Only Initialized variable

Example:

Create or replace procedure add(a in number, b in


number, c out number) is
Begin
C:=a+b;
End;

Exercise:

1. Write a procedure to insert a row into your table.


2. Write a procedure to insert a particular record in some other table
while deleting from a table.

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 <packagename> 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 <packagename>

PACKAGE BODY:
create or replace package body <packagename> 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 <packagename>

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.

2. 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.

30
DBMS Department of Computer Science
Data Base Management Systems Laboratory Manual

Exercise-11

TRIGGER

A 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 <triggername>
{before/after/instead of}
{insert/delete/update[of column1[,column2..]]} on
<table name/view name > [for each statement/
row] [when <condition>]

DECLARE
<declarations>
BEGIN
<executable statements>
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 <triggername> enable/disable;

Alter table <tablename> disable all;

EXERCISE

TABLES 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. create necessary triggers which insert employees personal details in


personal table after inserting in employee table.

2. Create a trigger before insert/update/delete of employee details to stop


the transactions on Saturdays and Sundays.

3. 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

FORMS
Developer 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.

Form

A 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.

REPORTS

Data 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. Develop a form to contain 3 different blocks on emp, dept,


salgrade tables. Enforce the constraints on this
2. Develop a form to display the time and college name in a form using
control block.
3. Develop a master detail blocks form for dept, emp tables along with
navigation items.
4. 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).

5. Generate a master details report with the department name and total
no.of employees and total salary of that department.

34

Potrebbero piacerti anche