You are on page 1of 95

FRANCIS XAVIER ENGINEERING COLLEGE

TIRUNELVELI - 627003

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS6312 DATABASE MANAGEMENT


SYSTEMS LABORATORY

PREPARED BY
S. N. ANANTHI AP/CSE
M. JENIGA GEMSY THEPORA AP/CSE

http://www.francisxavier.ac.in

Page 1

Ex. No

Name of the Experiment


Creation of a Database and writing SQL queries to retrieve information from the
database
Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing
records based on conditions

Creation of Views, Synonyms, Sequence, Indexes , Save point

Creating an Employee Database to set various constraints

Creating relationship between the databases

Study of PL/SQL block

Write a PL/SQL block to satisfy some conditions by accepting input from the
user.

Write a PL/SQL block that handles all types of exceptions

Creation of Procedures

10

Creation of database triggers and Functions


Mini Project (Application Development Using Oracle/

11

Mysql)

http://www.francisxavier.ac.in

Page 2

INTRODUCTION TO DBMS

OVERVIEW OF RDBMS:
RDBMS is the acronym for Relational Data Base Management System.
The concept of relational database is known since 1980s but the idea of Data Base Management
System is definitely old. The most famous RDBMS packages are Oracle, Sybase, and Informix.
What is DBMS?
A Data Base Management System is essentially a collection of interrelated data and a set
of programs to access this data. This collection of data is called the Database. The Primary
objective of a DBMS is to provide a convenient environment to retrieve and store database
information. Database systems support single user and multiuser environment. While on one
hand DBMS permits only one person to access the database at a given time, on the other
RDBMS allows many users simultaneous access to the database.
A Database System consists of two Parts namely, DBMS and Database Application.
DBMS is the program that organizes and maintains the information whereas the Database
Application is the program that lets us view, retrieve and update information stored in the
DBMS.
DBMS has to protect against unintentional changes that could be caused by users and
applications. In case of multi user system, it must be capable of notifying any database change to
the other user.
DBMS offers following services:
Data Definition
Data maintenance
Data Manipulation
Data display
Data Integrity
http://www.francisxavier.ac.in

Page 3

INTRODUCTION TO ORACLE

Every business enterprise maintains large volumes of data for its operations. With
more and more people accessing this data for their work the need to maintain its integrity and
relevance increases. Normally, with the traditional methods of storing data and information in
files, the chance that the data loses its integrity and validity are very high.
Oracle 8 is an Object Relational Database Management System (ORDBMS). It
offers capabilities of both relational and object oriented data base systems. In general, objects
can be defined as reusable software codes which are location independent and perform a specific
task on any application environment with little or no change to the code.
Oracle products are based on a concept known as the client/Server Technology.
This concept involves segregating the processing of an application between two systems. One
performs all activities related to the database (server) and the other performs activities that help
the user to interact with the application (client).
A Client or front-end database application also interacts with the database by
requesting and receiving information from the database server. It acts as an interface between the
user and the database. Further, it also checks for validation against the data entered by the user.
The commonly used front end tools of oracle are SQL * Plus V 8, Oracle forms 5.0 and Reports
3.0.
The database server or backend is used to manage the database tables optimally
among multiple clients who concurrently request the server for the sane data. It also enforces
data integrity across all client applications and controls database access and other security
requirements.
Tools of Oracle:
The tools provided by Oracle are so user friendly that a person with minimum
skillls in the field of computer can access them with ease. The main tools are
SQL * Plus

http://www.francisxavier.ac.in

Page 4

PL/SQL
Forms
Reports
SQL * Plus:
SQL * Plus is a Structered Query Language supported by Oracle. Through SQl*
Plus we can store, retrieve, edit, enter and run SQL commands and PL/SQL blocks. Using SQl *
Plus we can perform calculations, list column definitions for any table and can format query
results in the form of a report.
PL/SQL:
PL/SQL is an extension of SQL. PL./SQL statements can contain any number of
SQL statements integrated with flow of control statements. Thus PL/SQL combines the data
manipulating power of SQL with data processing power of procedural languages.
Forms:
This is a graphical tool used for generating and executing form-based aplications.
A form basically comprises blocks and fields. Multiple tables can be accessed over a single form,
based on the application with the help of transaction commands. Oracle Forms Buildet is the
design componennt of Oracle forms. We can build, generate and run an Oracle forms application
from the builder.
Reports:
It is an application development tool of Oracle for developing, executing,
displaying and printing reports. We can create a wide variety of reports, which have various
modes. Oracle reports are powerful, yet easy to use.
The reasons for choosing Oracle 8 as the RDBMS for effectively managing the data are
Ability to retrieve data spread across multiple tables.
Oracle specific SQL *Plus functions used when required to query the database
http://www.francisxavier.ac.in

Page 5

especially to decide future course of action.


Provisions to maintain integrity of the database to avois data duplication and have
constant checks on the validity of data.
Ability to break the most frequently used object, the table into smaller units thereby
reducing the risk to loss of data.
With a number of clients accessing the database, Oracle allows explicit locking of
data. Concurrent access of data for manipulation can be prevented in this way.
Storing of information out-of-line with the table is also a major advantage. This
allows unstructured information to be stored in a different location with the pointers
to the location present in the table.
It supports OOPs concepts, making it a powerful object oriented database.

http://www.francisxavier.ac.in

Page 6

INTRODUCTION TO SQL

SQL was invented and developed by IBM in early 1970s. SQL stands for
Structured Query Language. IBM was able to demonstrate how to control relational database
using SQL. The SQL implemented by ORACLE CORPORATION is 100% compliant with the
ANSI/ ISO standard SQL data language. Oracles database language is SQL, which is used for
storing and retrieving information in Oracle. A table is a Primary database object of SQL that is
used to store data. A table that holds data in the form of rows and columns.
In order to communicate with the database, SQL supports the following categories
of commands: Data Definition Language

- create, alter and drop commands.

Data Manipulation Language - insert, select, delete and update commands.


Transaction Control Language - commit, savepoint and rollback commands.
Data control Language

- grant and revoke commands.

Data Definition Language:


DDL is used to create an object ( table ), alter the structure of an object
and also to drop the object created. A table is a unit of storage that holds data in the form of rows
and columns. DDL is used for table definition.
Data Manipulation Language:
DML commands are most frequently used SQL commands. They are used
to query and manipulate existing objects like tables.
Transaction Control Language:
A transaction is a logical unit of work. All changes made to the database
can be referred to as a transaction. Transaction changes can be made permanent to a database
only if they are committed. A transaction begins with an executable SQL statement ends
explicitly with either rollback or commit commands and implicitly i.e., automatically, when a
http://www.francisxavier.ac.in

Page 7

DDL statement is used.


The following are the benefits of SQL:

Non-procedural Language, because more than one record can be accessed rather
than one record at a time.

It is the common language for all relational databases. In other words it is portable
and it requires very few modifications so that it can work on other databases.

Very simple commands for Querying, inserting, deleting and modifying data and
objects.

SQL Vs SQL *Plus:


SQL is a standard language common to all relational databases. SQL is a database
language used for storing and retrieving data from the database. Most relational Database
Management Systems provide extensions to SQL to make it easier for application developers.
SQL *Plus is an Oracle specific Program which accepts SQL commands and
PL/SQL blocks and executes them. SQL *Plus enables manipulation of SQL commands and
PL/SQL blocks. It also performs many additional tasks as well. Through SQL *Plus we can

enter, edit, store, retrieve and run SQL commands and PL/SQL blocks.

format, perform calculations, store and print query results in the form of reports.

list column definitions for any table.

Access and copy data between SQL databases.

Send messages to and accept responses from an end user.

http://www.francisxavier.ac.in

Page 8

Ex.No:1.

CREATION OF A DATABASE AND WRITING SQL QUERIES TO


RETRIEVE INFORMATION FROM THE DATABASE.

AIM:
To create a database and write SQL queries to retrieve information from the database.
DESCRIPTION:
Data Definition Language:
DDL (Data Definition Language) statements are used to create, change the objects of a
database. Typically a database administrator is responsible for using DDL statements or
production databases in a large database system.
The commands used are:
Create - It is used to create a table.
Alter - This command is used to add a new column, modify the existing column
definition and to include or drop integrity constraint.
Drop - It will delete the table structure provided the table should be empty.
Truncate - If there is no further use of records stored in a table and the structure has to
be retained, and then the records alone can be deleted.
Desc - This is used to view the structure of the table.
SYNTAX:
CREATE TABLE:
create table <table name> (fieldname-1 data type constraints if any,fieldname-2
data type constraints if any,. fieldname-n data type constraints if any);
create table <table name> as (select(attribute-list) from <existing table name>);
ALTER TABLE:
alter table <table name> add/modify (fieldname-1 datatype,fieldname-2 data type,..
fieldname-n data type );
alter table drop column column name;
Table altered.
DESCRIBING TABLE:
desc <table name>;

http://www.francisxavier.ac.in

Page 9

CHANGING NAME OF AN OBJECT:


To change the name of a table, view, sequence, or synonym, execute the rename
statement.
Syntax: rename old name to new name;
TRUNCATE:
The truncate table statement
removes all rows from a table
Release the storage space used by that table
Syntax: truncate table <table name>;
DROP TABLE:
1. All data and structure in the table is deleted
2. Any pending transactions are committed.
3. All indexes are dropped.
Syntax: drop table <table name>;
Table dropped.

http://www.francisxavier.ac.in

Page 10

SAMPLE OUTPUT:
SQL> create table tbl03 (sno number (2), regno number (12), name varchar2 (10), age number
(2), marks number (2));
Table created.
SQL> desc tbl03;
Name

Null?

Type

-------------------- ---------------------- -------------------------SNO

NUMBER (2)

REGNO

NUMBER (12)

NAME

VARCHAR2 (10)

AGE

NUMBER (2)

MARKS

NUMBER (2)

SQL> alter table tbl03 add (total number (3));


Table altered.
SQL> desc tbl03;
Name

Null?

-------------------- ---------------------

Type
--------------------

SNO

NUMBER (2)

REGNO

NUMBER (12)

NAME

VARCHAR2 (10)

AGE

NUMBER (2)

MARKS

NUMBER (2)

TOTAL

NUMBER (3)

SQL> insert into tbl03 values (&sno, &regno,'&name', &age, &marks, &total);
Enter value for sno: 02

http://www.francisxavier.ac.in

Page 11

Enter value for regno: 003


Enter value for name: Abishek
Enter value for age: 18
Enter value for marks: 99
Enter value for total: 599
old 1: insert into tbl03 values (&sno, &regno,'&name', &age, &marks, &total)
new 1: insert into tbl03 values (02, 003,'Abishek', 18, 99,599)
1 row created.
SQL> insert into tbl03 values (22, 023,'Isai', 18, 98,598);
1 row created.
SQL> select * from tbl03;
SNO

REGNO

---------- -------------

NAME

AGE

MARKS

TOTAL

-------------------- ---------- ---------------- --------------

003

Abishek

18

99

599

22

023

Iasi

18

98

598

AGE

MARKS

SQL> select name from tbl03;


NAME
---------Abishek
Isai
SQL> select * from tbl03 where total=599;
SNO

REGNO

---------- ------------2

003

NAME

TOTAL

----------------- ---------- ---------------- -------------Abishek

http://www.francisxavier.ac.in

18

99

599

Page 12

SQL> update tbl03 set age=20 where age=18;


2 rows updated.
SQL> select * from tbl03;
SNO

REGNO

NAME

AGE

MARKS

TOTAL

---------- ------------- -------------------- ---------- ---------------- -------------2

003

Abishek

18

99

599

22

023

Isai

20

98

598

MARKS

TOTAL

SQL> update tbl03 set total=95 where name='Isai';


1 row updated.
SQL> delete from tbl03 where sno=22;
1 row deleted.
SQL> select * from tbl03;
SNO

REGNO

NAME

AGE

---------- ------------- -------------------- ---------- ---------------- -------------2 003

Abishek

18

99

599

SQL> truncate table tbl03;


Table truncated.
SQL>rename tbl03 to tbl03z;
Table renamed.
SQL> drop table tbl03z;
Table dropped.
SQL> select * from tbl03z;
select * from tbl03z
*
ERROR at line 1:
http://www.francisxavier.ac.in

Page 13

ORA-00942: table or view does not exist


SQL> desc tbl03z;
*
ERROR:
ORA-04043: object tbl03z does not exist

RESULT:
Thus the creation of a database and writing SQL queries to retrieve information from the
database was implemented.

http://www.francisxavier.ac.in

Page 14

Ex.No.2. PERFORMING INSERTION, DELETION, MODIFYING,


UPDATING AND VIEWING RECORDS BASED ON CONDITIONS

ALTERING,

AIM:
To Perform Insertion, Deletion, Modifying, Altering, Updating and Viewing records
based on conditions in RDBMS.
DESCRIPTION:
Data Manipulation Language
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are
1. Insert
2. Select
3. Update
4. Delete
SYNTAX :
INSERT: This is used to add one or more rows to a table. The values are separated by commas
and the data types char and date are enclosed in apostrophes. The values must br entered in the
same order as they are defined.
Inserting a single row into a table:
insert into <table name> values(fieldvalue-1,fieldvalue-2,,fieldvalue-n);
Inserting more than one record using a single insert command:
insert into <table name> values(&fieldname-1,&fieldname-2,&fieldname-n);
Skipping the fields while inserting:
insert into <tablename(coln names to which datas to b inserted)> values (list of values);
Other way is to give null while passing the values.
insert into <table name>(select(att_list) from <existing table name>);
SELECT: - It is used to retrieve information from the table.it is generally refered to as querying
the table. We can either display all columns in a table or only specify column from the table.
SELECT(att_list) FROM <table name> [WHERE <condition/expression>];
Retrieval of all columns from a table:
Select * from tablename; // This query selects all rows from the table.
Retrieval of specific columns from a table:It retrieves the specified columns from the table.
Select column_name1, ..,column_namen from table name;
Elimination of duplicates from the select clause: It prevents retriving the duplicated values
.Distinct keyword is to be used.
Select DISTINCT col1, col2 from table name;
http://www.francisxavier.ac.in

Page 15

Select command with where clause: To select specific rows from a table we include where
clause in the select command. It can appear only after the from clause.
Syntax: Select column_name1, ..,column_namen from table name where condition;
Select command with order by clause:
Syntax: Select column_name1, ..,column_namen from table name where condition order
by colmnname;
Select command to create a table:
Syntax: create table tablename as select * from existing_tablename;
Select command to insert records:
Syntax: insert into tablename ( select columns from existing_tablename);
UPDATE - It is used to alter the column values in a table. A single column may be updated or
more than one column could be updated.
update <table name> set (fieldname-1 = value, fieldname-2 = value,,fieldname-n =
value) [WHERE <condition/expression>];
DELETE - After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional where clause.
delete from <table name> [where <condition/expression>];
ALTER TABLE
alter table table_name add column_name datatype
alter table <table name> add (fieldname-1 datatype,fieldname-2 datatype,..
fieldname-n datatype );
alter table <table name> modify (fieldname-1 data type (new size));
alter table drop column column name;
Table altered.

http://www.francisxavier.ac.in

Page 16

SAMPLE OUTPUT:
INSERT, SELECT, UPDATE AND DELETE COMMANDS
SQL> create table person(pid int, lastname varchar2(10),firstname varchar(10),
address varchar2(20),age number);
Table created.
INSERTING A SINGLE ROW INTO A TABLE
SQL> insert into person values(1,'Prettina','Anne','Bangalore',14);
1 row created.
SQL> insert into person values(2,'Benitto','Anish','Trichy',24);
1 row created.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
INSERTING MORE THAN ONE ROW USING A SINGLE INSERT COMMAND
SQL> insert into person values(&pid,'&lastname','&firstname','&address',&age);
Enter value for pid: 3
Enter value for lastname: Raj
Enter value for firstname: Anita
Enter value for address: Chennai
Enter value for age: 27
old 1: insert into person values(&pid,'&lastname','&firstname','&address',&age)
new 1: insert into person values(3,'Raj','Anita','Chennai',27)
1 row created.
SQL> /
Enter value for pid: 4
Enter value for lastname: kumar
Enter value for firstname: Ashok
Enter value for address: Coimbatore
Enter value for age: 30
old 1: insert into person values(&pid,'&lastname','&firstname','&address',&age)
new 1: insert into person values(4,'kumar','Ashok','Coimbatore',30)
1 row created.
SQL> select * from person;

http://www.francisxavier.ac.in

Page 17

PID LASTNAME FIRSTNAME ADDRESS AGE


---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 kumar Ashok Coimbatore 30
SKIPPING THE FIELDS WHILE INSERTING
SQL> insert into person(pid,lastname,firstname) values(5,Hinn,Benny);
insert into person(pid,lastname,firstname) values(5,'Hinn','Benny')
1 row created.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 kumar Ashok Coimbatore 30
5 Hinn Benny
INSERT VALUES USING MEANINGFUL FIELD NAMES
SQL> insert into person values(&personid,'&lastname','&firstname','&personaddress',&age);
Enter value for personid: 6
Enter value for lastname: Prakash
Enter value for firstname: Bhaskar
Enter value for personaddress: Andhra
Enter value for age: 40
old 1: insert into person values(&personid,'&lastname','&firstname','&personaddress',&age)
new 1: insert into person values(6,'Prakash','Bhaskar','Andhra',40)
1 row created.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 kumar Ashok Coimbatore 30
5 Hinn Benny
6 Prakash Bhaskar Andhra 40
6 rows selected.
UPDATE VALUES USING CONDITION
SQL> update person set address='United States'where pid=5;
http://www.francisxavier.ac.in

Page 18

1 row updated.
UPDATE VALUES USING &
SQL> update person set address ='&address',age=&age where pid=&pid;
Enter value for address: Assam
Enter value for age: 40
Enter value for pid: 6
old 1: update person set address ='&address',age=&age where pid=&pid
new 1: update person set address ='Assam',age=40 where pid=6
1 row updated.
SQL> /
Enter value for address: Britain
Enter value for age: 55
Enter value for pid: 5
old 1: update person set address ='&address',age=&age where pid=&pid
new 1: update person set address ='Britain',age=55 where pid=5
1 row updated.
SELECT COMMAND TO RETRIEVE THE ENTIRE INFORMATION FROM THE TABLE
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
6 rows selected.
SELECT COMMAND USING 'WHERE' CLAUSE
SQL>select * from person where lastname= 'Kumar' and address='Coimbatore';
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------4 Kumar Ashok Coimbatore 30
7 Kumar Chander Coimbatore 45
SELECT COMMAND TO RETRIEVE THE TOP VALUES
SQL> select * from person where rownum<=3;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
http://www.francisxavier.ac.in

Page 19

SELECT COMMAND WITH LIKE OPERATOR


SQL> select * from person where address like 'C%';
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------3 Raj Anita Chennai 27
4 kumar Ashok Coimbatore 30
SQL> select * from person where address like '%i%';
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------2 Benitto Anish richy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
SELECT COMMAND USING IN OPERATOR
SQL> select * from person where lastname in('Prettina');
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
SELECT COMMAND USING BETWEEN OPERATOR
SQL> insert into person values(7,'Kumar','Chander','Coimbatore',45);
1 row created.
SQL> select * from person where lastname between 'Kumar' and 'Kumar';
PID LASTNAME FIRSTNAME ADDRESS AGE
--------- ---------- ---------- -------------------- ---------6 Kumar Ashok Coimbatore 30
7 Kumar Chander Coimbatore 45
SELECT COMMAND TO ELIMINATE DUPLICATES
SQL> select DISTINCT lastname from person;
LASTNAME
---------Benitto
Hinn
Kumar
Prakash
Prettina
Raj
6 rows selected.
SELECT COMMAND WITH ORDER BY CLAUSE
SQL> select pid, firstname,age from person order by age;

http://www.francisxavier.ac.in

Page 20

PID FIRSTNAME AGE


---------- ---------- ---------1 Anne 14
2 Anish 24
3 Anita 27
4 Ashok 30
6 Bhaskar 40
7 Chander 45
5 Benny 55
7 rows selected.
SELECT COMMAND TO CREATE A TABLE
SQL> create table individual as select * from person;
Table created.
SQL> select * from individual;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- ------------ -------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SELECT COMMAND TO INSERT RECORDS
SQL> insert into individual(select * from person);
7 rows created.
SELECT COMMAND WITH FUNCTIONS
SQL> select count(*) as pid from person;
PID
---------7
SQL> select count(distinct lastname) as pid from person;
PID
---------6
SQL> select max(age) from person;
MAX(AGE)
---------55
http://www.francisxavier.ac.in

Page 21

SQL> select min(age) from person;


MIN(AGE)
---------14
SQL> select sum(age) from person;
SUM(AGE)
---------235
DATA CONTROL LANGUAGE (DCL) COMMANDS
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ -------1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> commit;
Commit complete.
DELETE COMMAND
SQL> delete from person where lastname='Kumar';
2 rows deleted.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------ -------1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
SQL> rollback;
Rollback complete.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ ------1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
http://www.francisxavier.ac.in

Page 22

3 Raj Anita Chennai 27


4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> savepoint s1;
Savepoint created.
SQL> delete from person;
7 rows deleted.
SQL> select * from person;
no rows selected
SQL> rollback to savepoint s1;
Rollback complete.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------- ------1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.

RESULT:
Thus the Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on
conditions in RDBMS were executed and verified.

http://www.francisxavier.ac.in

Page 23

Ex.No.3

CREATION OF VIEWS, SYNONYMS, SEQUENCE, INDEXES, SAVE POINT

AIM:
To create Views, Sequence, Indexes, Save point and Synonyms in SQL.

DESCRIPTION:
VIEWS
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.
A view is an object that gives the user the logical view of data from the underlying table.
Any relation that is not part of the logical model but is made visible to the user as a virtual
relation is called a view. They are generally used to avoid duplication of data.
Views are created for the following reasons,

Data simplicity

To provide data security

Structural simplicity (because view contains only limited number of rows and columns)

TYPES OF VIEWS

Updatable views Allow data manipulation

Read only views Do not allow data manipulation

SQL create view


CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE
condition
SQL updating a view
Update view name set field name=value where condition
SQL create or replace view
CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM
table_name WHERE condition.
SQL drop view
DROP VIEW view-name;
http://www.francisxavier.ac.in

Page 24

INDEXES
Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. An index is a pointer to data in a table. An index in a database is very similar to an
index in the back of a book. An index helps speed up SELECT queries and WHERE clauses, but
it slows down data input, with UPDATE and INSERT statements. Indexes can be created or
dropped with no effect on the data. Index in sql is created on existing tables to retrieve the rows
quickly. When there are thousands of records in a table, retrieving information will take a long
time. Therefore indexes are created on columns which are accessed frequently, so that the
information can be retrieved quickly. Indexes can be created on a single column or a group of
columns. When an index is created, it first sorts the data and then it assigns a ROWID for each
row.

An index can be created in a table to find data more quickly and efficiently.

The users cannot see the indexes, they are just used to speed up searches/queries

Syntax to create Index


CREATE INDEX index_name ON table_name (column_name1,column_name2...);
Syntax to create SQL unique index
CREATE UNIQUE INDEX index_name ON table_name (column_name1,
column_name2...);

index_name is the name of the INDEX.

table_name is the name of the table to which the indexed column belongs.

column_name1, column_name2.. is the list of columns which make up the INDEX.

The Drop Index Command


An index can be dropped using SQL DROP command. Care should be taken when
dropping an index because performance may be slowed or improved.
DROP INDEX index_name;

SEQUENCE
A sequence is a user-defined schema bound object that generates a sequence of numeric
values according to the specification with which the sequence was created. The sequence of
numeric values is generated in an ascending or descending order at a defined interval and can be
configured to restart (cycle) when exhausted. Sequences, unlike identity columns, are not
http://www.francisxavier.ac.in

Page 25

associated with specific tables. Applications refer to a sequence object to retrieve its next value.
The relationship between sequences and tables is controlled by the application. User applications
can reference a sequence object and coordinate the values across multiple rows and tables.
SYNTAX
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
Drop Sequence: Syntax: DROP SEQUENCE sequence_name

TRANSACTION CONTROL LANGUAGE


There are following commands used to control transactions:

COMMIT: to save the changes.

ROLLBACK: to rollback the changes.

SAVEPOINT: creates points within groups of transactions in which to ROLLBACK

SET TRANSACTION: Places a name on a transaction.

Transactional control commands are only used with the DML commands INSERT, UPDATE
and DELETE only. They cannot be used while creating tables or dropping them because these
operations are automatically committed in the database.
The COMMIT Command
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all transactions to the database since
the last COMMIT or ROLLBACK command.
Syntax: COMMIT;
The ROLLBACK Command
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. The ROLLBACK command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was issued.
Syntax: ROLLBACK;
http://www.francisxavier.ac.in

Page 26

The SAVEPOINT Command


A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain
point without rolling back the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements.
The ROLLBACK command is used to undo a group of transactions.
Syntax:

ROLLBACK TO SAVEPOINT_NAME;

Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state:
The RELEASE SAVEPOINT Command
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.
Syntax: RELEASE SAVEPOINT SAVEPOINT_NAME;
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undo transactions performed since the SAVEPOINT.
undo transactions performed since the SAVEPOINT.

SYNONYMS
Synonym is an alternative name for a table, view, sequence, operator, procedure, stored
function, package, materialized view, Java class schema object, user-defined object type, or
another synonym. A synonym places a dependency on its target object and becomes invalid if the
target object is changed or dropped.
CREATE SYNONYM offices
FOR hr.locations;

http://www.francisxavier.ac.in

Page 27

SAMPLE OUTPUT:
VIEWS
SQL>create table kavi1(name varchar(20),rno number(5),marks number(5),primary key
(rno));
Table created.
SQL> desc kavi1;
NAME

NULL?

TYPE

------------------------------------------------------------------------------------------------NAME
RNO

VARCHAR (20)
NOTNULL

MARKS

NUMBER (5)
NUMBER (5)

SQL> insert into kavi1 values (prami, 1001, 350);


1 row created.
SQL> insert into kavi1 values (kavi, 1002, 298);
1 row created.
SQL> insert into kavi1 values (indhu, 1003, 375);
1 row created.
SQL> select * from kavi1;
NAME

RNO

MARKS

-----------------------------------------------------------------------------------------prami

1001

350

kavi

1002

298

indhu

1003

375

SQL> create table kavi2 (rollno number (5), attendance number (5), primary key (roll no));
Table created.
SQL> desc kavi2;
NAME

NULL?

TYPE

----------------------------------------------------------------------------------ROLLNO

NOTNULL

ATTENDENCE

NUMBER (5)
NUMBER (5)

SQL> insert into kavi2 values (1001, 90);


http://www.francisxavier.ac.in

Page 28

1 row created.
SQL> insert into kavi2 values (1002, 75);
1 row created.
SQL> insert into kavi2 values (1003, 85);
1 row created.
SQL> select * from kavi2;
ROLLNO

ATTENDENCE

----------------------------------------------------------------------------------------1001

90

1002

75

1003

85

SQL> create view kaviview as select name, rno, marks, attendance from kavi1, kavi2

where

rollno=rno;
view created.
SQL> select * from kaviview;
NAME

RNO

MARKS

ATTENDENCE

--------------------------------------------------------------------------------------------------------------------prami

1001

350

90

kavi

1002

298

75

indhu

1003

375

85

SQL> update kaviview

set

name=kavi where name=priya;

1 row updated.
SQL> update kaviview

set marks=352 where name=prami;

1 row updated;
SQL> select * from kaviview;
NAME

RNO

MARKS

ATTENDENCE

--------------------------------------------------------------------------------------------------------------------prami

1001

352

90

priya

1002

298

75

indhu

1003

375

85

http://www.francisxavier.ac.in

Page 29

INDEX
SQL> create table persons (first name varchar (20), last name varchar(10));
Table created;
SQL> create index plndex on persons (last name);
Index created.
SQL> select * from persons;
No rows selected.
SQL> drop plndex on persons;
Drop index plndex on persons
*
ERROR at line1:
ORA_00950: Invalid DROP option.

SEQUENCE
SQL> create table supplier2 (supplierid number (10), supplier name varchar (20));
Table created.
SQL>insert into supplier2 values (10,ganesh);
1 row created.
SQL> select * from supplier2;
SUPPLIER ID

SUPPLIERNAME

-------------------------------------------------------------------------------10

ganesh

SQL> create sequence supplier2_seq2


2

MINVALUE 1

STARTWITH 1

INCREMENT BY 1

CACHE 20

Sequence created.
SQL> insert into supplier2 (supplier id, supplier name) values
(supplier2_seq.NEXTVAL,Kraftfoods);
1 row created.
http://www.francisxavier.ac.in

Page 30

SQL> select*from supplier2;


SUPPLIERID

SUPPLIERNAME

---------------------------------------------------------------------------------------10

ganesh

Kraftfoods

SQL> insert into supplier2 (supplier id, supplier name) values


(supplier2_seq.NEXTVAL,parle);
1 row created.
SQL> select*from supplier2;
SUPPLIERID

SUPPLIERNAME

-----------------------------------------------------------------------------------10

ganesh

Kraft foods

Parley

SQL> select*from supplier2_seq2*;


Error at line1:
ORA-00942: table or view does not exist;

SYNONYMS
create public synonym suppliers for app.suppliers;
Synonym created.

TCL COMMANDS
SQL> create table tb43 (rno number(2),name varchar(10));
Table created;
SQL>insert into tb43 values(2,kavi);
1 row created.
SQL>insert into tb43 values(3,prami);
1 row created.
SQL>insert into tb43 values(4,geetha);
1 row created.
http://www.francisxavier.ac.in

Page 31

SQL> select * from tb43;


RNO

NAME

--------------------------------------------------2

kavi

prami

geetha

SQL> commit;
Commit complete.
SQL>insert into tb43 values(5,indhu);
1 row created.
SQL> select * from tb43;
RNO

NAME

----------------------------------------------------------2

kavi

prami

geetha

indhu

SQL>rollback;
Rollback complete;
SQL> select * from tb43;
RNO

NAME

----------------------------------------------------2

kavi

prami

geetha

SQL>save point s1;


Save point created;
SQL> delete * from tb43 where rno=3;
1 row deleted.
SQL> select * from tb43;

http://www.francisxavier.ac.in

Page 32

RNO

NAME

-------------------------------------------------------2

kavi

prami

SQL> insert into tb43 values(7,balu);


1 row created.
SQL> select * from tb43;
RNO

NAME

-----------------------------------------------------2

kavi

prami

balu

SQL> rollback to s1;


Rollback complete;
SQL> select * from tb43;
RNO

NAME

-----------------------------------------------------2

kavi

prami

RESULT:
Thus the Views, Sequence, Indexes, Save point and Synonyms are implemented
in SQL.

http://www.francisxavier.ac.in

Page 33

Ex. No. 4.

CREATING AN EMPLOYEE DATABASE TO SET VARIOUS


CONSTRAINTS

AIM
To create an Employee database with various constraints.

DESCRIPTION:
SQL CONSTRAINTS
Constraints are the rules enforced on data columns on table. These are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in the
database.
Constraints could be column level or table level. Column level constraints are applied
only to one column, whereas table level constraints are applied to the whole table.
Following are commonly used constraints available in SQL.

NOT NULL Constraint: Ensures that a column cannot have NULL value.

UNIQUE Constraint: Ensures that all values in a column are different.

PRIMARY Key: Uniquely identified each rows/records in a database table.

FOREIGN Key: Uniquely identified a rows/records in any another database table.

CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.

http://www.francisxavier.ac.in

Page 34

SAMPLE OUTPUT:
NOT NULL
SQL>

CREATE

TABLE

EMPLOYEE

(EMP_NO

NUMBER(6)NOT

NULL,NAME

VARCHAR2(10),BRANCH VARCHAR2(6));
Table created.
SQL> DESC EMPLOYEE;
Name

Null?

Type

----------------------------------------- -------- ---------------------------EMP_NO

NOT NULL

NUMBER(6)

NAME

VARCHAR2(10)

BRANCH

VARCHAR2(6)

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');


Enter value for emp_no: 501
Enter value for name: ABHILASH
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(501,'ABHILASH', CHENNAI)
1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no: 502
Enter value for name: ABI
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(502,'ABI', CHENNAI)
1 row created.
SQL> SELECT * FROM EMPLOYEE;
EMP_NO

NAME

BRANCH

--------------

-------------- -------------

501

ABHILASH CHENNAI

502

ABI

CHENNAI

http://www.francisxavier.ac.in

Page 35

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');


Enter value for emp_no:
Enter value for name: BHAVYA
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(,'BHAVYA', CHENNAI)
INSERT INTO EMPLOYEE VALUES(,'BHAVYA', CHENNAI)
*
ERROR:CANNOT INSERT NULL INTO("SCOTT", EMPLOYEE,EMP_NO)

UNIQUE
SQL>

CREATE

TABLE

EMPLOYEE

(EMP_NO

NUMBER(6)

UNIQUE

,NAME

VARCHAR2(10),BRANCH VARCHAR2(6));
Table created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: chennai
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(501,'abhilash', CHENNAI)
1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no: 502
Enter value for name: ABI
Enter value for branch: chennai
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(502,'ABI',' CHENNAI ')
1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no: 502
Enter value for name: BHAVYA
http://www.francisxavier.ac.in

Page 36

Enter value for branch: chennai


old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(502,'BHAVYA','CSE')
INSERT INTO EMPLOYEE VALUES(502,'BHAVYA', CHENNAI)*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated

PRIMARY KEY
SQL> CREATE TABLE EMPLOYEE (EMP_NO NUMBER(6) PRIMARY KEY ,NAME
VARCHAR2(10),BRANCH VARCHAR2(6));
Table created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no: 501
Enter value for name: abhilash
Enter value for branch: chennai
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(501,'abhilash', chennai)
1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no: 502
Enter value for name: ABI
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(502,'ABI','CHENNAI')
1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no: 502
Enter value for name: BHAVYA
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(502,'BHAVYA', 'CHENNAI')
http://www.francisxavier.ac.in

Page 37

INSERT INTO EMPLOYEE VALUES(502,'BHAVYA', 'CHENNAI')


*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for emp_no:
Enter value for name: BHAVYA
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(,'BHAVYA', 'CHENNAI')
INSERT INTO EMPLOYEE VALUES(,'BHAVYA', 'CHENNAI')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT", EMPLOYEE,EMP_NO)
SQL> SELECT * FROM EMPLOYEE;
ROLLNO

NAME

BRANCH

----------

----------

-----------

501

ABHILASH CHENNAI

502

ABI

CHENNAI

CHECK
SQL>

create table EMPLOYEE (emp_no number(5),name varchar2(10),sal number(10)

constraint no_ck check(sal between 10000 and 30000));


Table created.
SQL> insert into EMPLOYEE values(&emp_no,'&name',&sal);
Enter value for rno: 567
Enter value for name: sachin
Enter value for sal: 29000
old 1: insert into EMPLOYEE values(&emp_no,'&name',&sal)
new 1: insert into EMPLOYEE values(567,'sachin',29000)
1 row created.
SQL> insert into EMPLOYEE values(&emp_no,'&name',&sal);
http://www.francisxavier.ac.in

Page 38

Enter value for emp_no: 565


Enter value for name: rohit
Enter value for sal: 35000
old 1: insert into EMPLOYEE values(&emp_no,'&name',&sal)
new 1: insert into EMPLOYEE values(565,'rohit',35000)
insert into EMPLOYEE values(565,'rohit',35000)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.NO_CK) violated

FOREIGN KEY
SOL>create table adm(emp_id number(6) constraint emp_id_pk primary key,ename
varchar2(15),per number(5));
Table created.
SQL> insert into adm values(&emp_id,'&ename',&per);
Enter value for emp_id: 1
Enter value for ename: abi
Enter value for per: 80
old 1: insert into adm values(&emp_id,'&ename',&per)
new 1: insert into adm values(1,'abi',80)
1 row created.
SQL> insert into adm values(&emp_id,'&ename',&per);
Enter value for emp_id: 2
Enter value for ename: rohit
Enter value for per: 89
old 1: insert into adm values(&emp_id,'&ename',&per)
new 1: insert into adm values(2,'rohit',89)
1 row created.
SQL> insert into adm values(&emp_id,'&ename',&per);
Enter value for emp_id: 3
Enter value for ename: sachin
http://www.francisxavier.ac.in

Page 39

Enter value for per: 99


old 1: insert into adm values(&emp_id,'&ename',&per)
new 1: insert into adm values(3,'sachin',99)
1 row created.
SQL> insert into adm values(&emp_id,'&ename',&per);
Enter value for emp_id: 4
Enter value for ename: naveen
Enter value for per: 70
old 1: insert into adm values(&emp_id,'&ename',&per)
new 1: insert into adm values(4,'naveen',70)
1 row created.
SQL> select * from adm;
EMP_ID
----------

ENAME

PER

--------------- ----------

abi

80

rohit

89

sachin

99

naveen

70

SQL> create table department(emp_id number(6) constraint sid_fk references


adm(emp_id),branch varchar2(5),post_name varchar2(10));
Table created.
SQL> insert into department values(&emp_id,'&branch','&post_name);
Enter value for emp_id: 1
Enter value for branch: cse
Enter value for post_name: a
old 1: insert into department values(&emp_id,'&branch','&post_name)
new 1: insert into department values(1,'cse','a')
1 row created.
SQL> insert into department values(&emp_id,'&branch','&post_name);
Enter value for emp_id: 5
Enter value for branch: cse
http://www.francisxavier.ac.in

Page 40

Enter value for post_name: b


old 1: insert into department values(&emp_id,'&branch','&post_name)
new 1: insert into department values(5,'cse','b')
insert into department values(5,'cse','b')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SID_FK) violated - parent key not found
SQL> delete from adm where emp_id=1;
*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.SID_FK) violated - child record found
SQL> delete from department where emp_id=1;
1 row deleted.
SQL> delete from adm where emp_id=1;
1 row deleted.
SQL>select * from adm;
EMP_ID ENAME

PER

----- --------------- - ---------2

rohit

89

sachin

99

naveen

70

RESULT :
Thus an Employee database with various constraints was created and the output was
verified.

http://www.francisxavier.ac.in

Page 41

Ex.No.5

CREATING RELATIONSHIP BETWEEN THE DATABASES

AIM:
To create relationship between the databases in Oracle using Structured Query Language
commands.

DESCRIPTION:

PRIMARY KEY: Uniquely identified each rows/records in a database table.

FOREIGN KEY: Uniquely identified a rows/records in any another database table

PRIMARY KEY

The primary key constraint uniquely identifies each record in a database table.

Primary keys must contain unquie values

A primary keys column cannot contain NULL values.

Most tables should have a primary key, and each table can have only ONE
primary key.

SYNTAX:
create table<table name>(fieldname1 datatatype (size) primary key);
FOREIGNKEY

The table containing the foreign key is called the referencing or child table and
the table containing the candidate key is called the referenced or parent table

A foreign key is a key used to link two tables together. This sometimes called
referencing key.

Foreign key is a column or a combination whose values match primary key in


a different table.

The relationship between two tables matches the primary key in one of the
tables with a foreign key in the second table.

If a table has a primary key defined on any fields, then you cannot have two
records having the same value of those fields.

SYNTAX:

create table<table name>(fieldname1 data type(size) constraint first table primary key);
http://www.francisxavier.ac.in

Page 42

SAMPLE OUTPUT:
Table name: Branch
SQL>Create table branch(branch_name varchar2(30) primary key, branch_city varchar2(20),
assets number);
Table created.
SQL>desc branch;
Name

Null?

Type

--------------------------------------------------------------------BRANCH_NAME

NOT NULL VARCHAR2(30)

BRANCH_CITY

VARCHAR2(20)

ASSETS

NUMBER

=====================================================================
Table name: Customer
SQL>create table customer(customer_id varchar2(10) primary key, customer_name
varchar2(20), customer_Street varchar2(15), customer_City varchar2(15));
Table created.
SQL>desc customer;
Name

Null?

Type

-------------------------------------------------------------------CUSTOMER_ID

NOT NULL VARCHAR2(10)

CUSTOMER_NAME

VARCHAR2(20)

CUSTOMER_STREET

VARCHAR2(15)

CUSTOMER_CITY

VARCHAR2(15)

=====================================================================
Table name: Account
SQL>create table account(account_no varchar2(10) primary key, branch_name varchar2(30)
REFERENCES BRANCH(BRANCH_NAME), balance number);
Table created.
SQL>desc account;

http://www.francisxavier.ac.in

Page 43

Name

Null?

Type

-------------------------------------------------------------------ACCOUNT_NO

NOT NULL VARCHAR2(10)

BRANCH_NAME

VARCHAR2(30)

BALANCE

NUMBER

Table name: Loan


SQL>create table loan(loan_no varchar2(20) primary key, branch_name varchar2(20)
REFERENCES BRANCH(BRANCH_NAME), amount number);
Table created.
SQL>desc loan;
Name

Null?

Type

-------------------------------------------------------------------LOAN_NO

NOT NULL VARCHAR2(4)

BRANCH_NAME

VARCHAR2(20)

AMOUNT

NUMBER

====================================================================
Table name: borrower
SQL>create table borrower (customer_id varchar2(11) references
customer(customer_id),loan_no varchar2(4) references loan(loan_no))
SQL> desc borrower;
Name

Null?

Type

----------------------------------------- -------- ---------------------------CUSTOMER_ID

VARCHAR2(11)

LOAN_NO

VARCHAR2(4)

Table name: depositor


SQL>create table depositor(customer_id varchar2(11) references customer(customer_id),
account_no varchar2(11) references account(account_no))

http://www.francisxavier.ac.in

Page 44

SQL> desc depositor;


Name

Null?

Type

----------------------------------------- -------- ---------------------------CUSTOMER_ID

VARCHAR2(11)

ACCOUNT_NO

VARCHAR2(11)

=====================================================================
INSERTING RECORDS IN ALL THE SIX CREATED TABLES:
SQL> insert into branch values ('tambaram','chennai-45', 50000)
SQL>insert into customer values ('cus_109','mohammed','southeast_masi','chennai-32')
SQL>insert into account values ('735_105','chrompet', 5000)

SQL>insert into loan values ('ln_106','saidapet', 2000)


SQL>insert into borrower values ('cus_101','ln_101')
SQL>insert into depositor values ('cus_108','735_102')
=====================================================================
1. For all customers who have loan from the bank find their IDs, loan number and loan amount.
(Join)
SQL> select borrower.CUSTOMER_ID, loan.LOAN_NO, loan.AMOUNT from loan, borrower
where loan. LOAN_NO=borrower. LOAN_NO
CUSTOMER_ID LOAN_NO

AMOUNT

----------- -------------------- ----------------------------------------------cus_101

ln_101

900

cus_101

ln_106

2000

cus_103

ln_107

500

cus_105

ln_105

1000

cus_103

ln_104

1300

cus_105

ln_102

1500

6 rows selected.

http://www.francisxavier.ac.in

Page 45

2. For all customers who have loan at tambaram branch find their IDs,loan ID,loan
amount.(Join)
SQL> select borrower.CUSTOMER_ID,loan.LOAN_NO,loan.AMOUNT from loan, borrower
where loan. LOAN_NO=borrower. LOAN_NO and loan. BRANCH_NAME='tambaram'

CUSTOMER_ID

LOAN_NO

AMOUNT

----------- -------------------- -------------------------------------------------------------cus_103

ln_104

1300

3. Find the number of depositor at each branch.(Join)


SQL> select account.BRANCH_NAME,count(account.BRANCH_NAME) as No_of_Depositor
from account,depositor where account.ACCOUNT_NO=depositor.ACCOUNT_NO group by
account.BRANCH_NAME
BRANCH_NAME

NO_OF_DEPOSITOR

------------------------------ ----------------------------------------------adayar

chrompet

guindy

saidapet

tnagar

RESULT:
Thus, relationship between the databases in Oracle using Structured Query Language
commands was created successfully.

http://www.francisxavier.ac.in

Page 46

Ex.No .6

STUDY OF PL/SQL BLOCK

AIM:
To Study about PL/SQL block.

DESCRIPTION:
PL/SQL

PL/SQL stands for Procedural Language extension of SQL.

PL/SQL is a combination of SQL along with the procedural features of programming


languages.

It was developed by Oracle Corporation in the early 90s to enhance the capabilities of
SQL.

A Simple PL/SQL Block


Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL
block.
PL/SQL Block consists of three sections

The Declaration section (optional).

The Execution section (mandatory).

The Exception (or Error) Handling section (optional).

Declaration Section
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants, records
and cursors, which are used to manipulate data in the execution section. Placeholders may be any
of Variables, Constants and Records, which stores data temporarily. Cursors are also declared in
this section.
Execution Section
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and
ends with END. This is a mandatory section and is the section where the program logic is written
to perform any task. The programmatic constructs like loops, conditional statement and SQL
statements from the part of execution section.

http://www.francisxavier.ac.in

Page 47

Exception Section
The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in this section,
so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that
cannot be handled, the Block terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks
can be nested within other PL/SQL blocks. Comments can be used to document code.
A Sample PL/SQL Block Looks like:
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/SQL Block Structure:
DECLARE
v_variable VARCHAR2(5);
BEGIN
SELECT column_name
INTO v_variable
FROM table_name;
EXCEPTION
WHEN exception_name THEN
...
END;
Block Types
1. Anonymous
[DECLARE]
BEGIN
http://www.francisxavier.ac.in

Page 48

--statements
[EXCEPTION]
END;
2. Procedure
PROCEDURE name
IS
BEGIN
--statements
[EXCEPTION]
END;
PROCEDURE name
3. Function
FUNCTION name
RETURN datatype
IS
BEGIN
--statements
RETURN value;
[EXCEPTION]
END;

RESULT:
Thus the PL/SQL blocks are studied.

http://www.francisxavier.ac.in

Page 49

Ex.No.7

WRITE A PL/SQL BLOCK TO SATISFY SOME CONDITIONS BY


ACCEPTING INPUT FROM THE USER.

AIM:
To write a PL/SQL block to satisfy some conditions by accepting input from the user
using oracle.

DESCRIPTION:
PL/SQL Control Structure provides conditional tests, loops, flow control and branches
that let to produce well-structured programs.

SYNTAX:
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/ SQL GENERAL SYNTAX
SQL> declare
<variable declaration>;
begin
<executable statement >;
end;
PL/ SQL GENERAL SYNTAX FOR IF CONDITION
SQL> declare
<variable declaration>;
begin
if(condition) then
<executable statement >;
end;
http://www.francisxavier.ac.in

Page 50

PL/ SQL GENERAL SYNTAX FOR IF AND ELSECONDITION


SQL> declare
<variable declaration>;
begin
if (test condition) then
<statements>;
else
<statements>;
end if;
end;
PL/ SQL GENERAL SYNTAX FOR NESTED IF CONDITION
SQL> declare
<variable declaration>;
begin
if (test condition) then
<statements>;
else if (test condition) then
<statements>;
else
<statements>;
end if;
end;
PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT
SQL> declare
<variable declaration>;
begin
loop
<statement>;
end loop;
<executable statement>;
end;
http://www.francisxavier.ac.in

Page 51

PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT


SQL> declare
<variable declaration>;
begin
while <condition>
loop
<statement>;
end loop;
<executable statement>;
end;
PL/SQL CODING FOR ADDITION OF TWO NUMBERS
(Write a PL/SQL Program for Addition of Two numbers)
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: Develop the set of statements with the essential operational parameters.
STEP 4: Specify the Individual operation to be carried out.
STEP 5: Execute the statements.
STEP 6: Stop.
PROGRAM
SQL>set serveroutput on
SQL>declare
1 a number;
2 b number;
3 c number;
4 begin
5 a: =&a;
6 b: =&b;
7 c: =a+b;
8 dbms_output.put_line ('sum of'||a||'and'||b||'is'||c);

http://www.francisxavier.ac.in

Page 52

9 end;
10 /
INPUT
Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
Enter value for b: 12
old 7: b:=&b;
new 7: b:=12;
OUTPUT
sum of23and12is35
PL/SQL procedure successfully completed.

PL/ SQL PROGRAM FOR IF CONDITION


( Write a PL/SQL Program to find out the maximum value using if condition)
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: invoke the if condition.
STEP 4: Execute the statements.
STEP 5: Stop.
PROGRAM
SQL>set serveroutput on
SQL> declare
2 b number;
3 c number;
4 BEGIN
5 B:=10;
6 C:=20;
7 if(C>B) THEN
8 dbms_output.put_line('C is maximum');
http://www.francisxavier.ac.in

Page 53

9 end if;
10 end;
11 /
OUTPUT
C is maximum
PL/SQL procedure successfully completed.

PL/ SQL PROGRAM FOR IF ELSE CONDITION


( Write a PL/SQL Program to check whether the value is less than or greater than 5 using if else
condition)
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: invoke the if else condition.
STEP 4: Execute the statements.
STEP 5: Stop.
PROGRAM
SQL>set serveroutput on
SQL> declare
2 n number;
3 begin
4 dbms_output. put_line('enter a number');
5 n:=&number;
6 if n<5 then
7 dbms_output.put_line('entered number is less than 5');
8 else
9 dbms_output.put_line('entered number is greater than 5');
10 end if;
11 end;
12 /

http://www.francisxavier.ac.in

Page 54

INPUT
Enter value for number: 2
old 5: n:=&number;
new 5: n:=2;
OUTPUT
entered number is less than 5
PL/SQL procedure successfully completed.
PL/ SQL PROGRAM FOR IF ELSE IF CONDITION
( Write a PL/SQL Program to find the greatest of three numbers using if else if )
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: invoke the if else if condition.
STEP 4: Execute the statements.
STEP 5: Stop.
PROGRAM
SQL>set server output on
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 if(a>b)and(a>c) then
10 dbms_output.put_line('A is maximum');
11 else if(b>a)and(b>c)then
12 dbms_output.put_line('B is maximum');
13 else
14 dbms_output.put_line('C is maximum');
http://www.francisxavier.ac.in

Page 55

15 end if;
16 end;
17 /
INPUT
Enter value for a: 21
old 7: a:=&a;
new 7: a:=21;
Enter value for b: 12
old 8: b:=&b;
new 8: b:=12;
Enter value for b: 45
old 9: c:=&b;
new 9: c:=45;
OUTPUT
C is maximum
PL/SQL procedure successfully completed.

PL/ SQL PROGRAM FOR LOOPING STATEMENT


( Write a PL/SQL Program to find the summation of odd numbers using for loop)
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: invoke the for loop condition.
STEP 4: Execute the statements.
STEP 5: Stop.
PROGRAM
SQL>set server output on
SQL> declare
2 n number;
3 sum1 number default 0;
4 end value number;
http://www.francisxavier.ac.in

Page 56

5 begin
6 end value:=&end value;
7 n:=1;
8 for n in 1..endvalue
9 loop
10 if mod(n,2)=1
11 then
12 sum1:=sum1+n;
13 end if;
14 end loop;
15 dbms_output.put_line('sum ='||sum1);
16 end;
17 /
INPUT
Enter value for end value: 4
old 6: end value:=&end value;
new 6: end value:=4;
OUTPUT
sum =4
PL/SQL procedure successfully completed.

PL/ SQL PROGRAM FOR LOOPING STATEMENT


(Write a PL/SQL Program to find the factorial of given number using for loop)
PROCEDURE:
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: invoke the for loop condition.
STEP 4: Execute the statements.
STEP 5: Stop.

http://www.francisxavier.ac.in

Page 57

PROGRAM
SQL>set server output on
SQL>1 declare
2 n number;
3 i number;
4 p number:=1;
5 begin
6 n:=&n;
7 for i in 1..n loop
8 p:=p*i;
9 end loop;
10 dbms_output.put_line(n ||' ! = '||p);
11* end;
Enter value for n: 5
old 6: n:=&n;
new 6: n:=5;
5 ! = 120
PL/SQL procedure successfully completed.

RESULT:
Thus a PL/SQL block to satisfy some conditions by accepting input from the user was
created using oracle.
http://www.francisxavier.ac.in

Page 58

Ex.No.8

WRITE A PL/SQL BLOCK THAT HANDLES ALL TYPES OF


EXCEPTIONS

AIM:
To implement and execute PL/SQL Block that handles all types of exceptions in Oracle
Database using Procedural Language concepts.

DESCRIPTION:
EXCEPTIONS
In PL/SQL, the user can catch certain runtime errors. Exceptions can be internally
defined by Oracle or the user. Exceptions are used to handle errors that occur in your PL/SQL
code. A PL/SQL block contains an EXCEPTION block to handle exception.
There are three types of exceptions:
1. Predefined Oracle errors
2. Undefined Oracle errors
3. User-defined errors
The different parts of the exception.
1. Declare the exception.
2. Raise an exception.
3. Handle the exception.
An exception has four attributes:
1. Name provides a short description of the problem.
2. Type identifies the area of the error.
3. Exception Code gives a numeric representation of the exception.
4. Error message provides additional information about the exception.
The predefined divide-by-zero exception has the following values for the attributes:
1. Name = ZERO_DIVIDE
2. Type = ORA (from the Oracle engine)
3. Exception Code = C01476
Error message = divisor is equal to zero

http://www.francisxavier.ac.in

Page 59

EXCEPTION HANDLING
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block
known as exception Handling. Using Exception Handling we can test the code and avoid it from
exiting abruptly.When an exception occurs messages which explains its cause is received.
PL/SQL Exception message consists of three parts.
Type of Exception
An Error Code
A message
STRUCTURE OF EXCEPTION HANDLING
GENERAL SYNTAX FOR CODING THE EXCEPTION SECTION
DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;
Types of Exception
There are 2 types of Exceptions.
a) System Exceptions
b) User-defined Exceptions
a) System Exceptions
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule.
There are some system exceptions which are raised frequently, so they are pre-defined and given
a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
http://www.francisxavier.ac.in

Page 60

For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a


code to handle the exception as given below.
BEGIN
Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any row.');
END;
b) User-defined Exceptions
PL/SQL allows us to define our own exceptions according to the need of our program. A
user-defined exception must be declared and then raised explicitly, using a RAISE statement.
To define an exception we use EXCEPTION keyword as below:
EXCEPTION_NAME EXCEPTION;
To raise exception that weve defined to use the RAISE statement as follows:
RAISE EXCEPTION_NAME
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the command
RAISE. Following is the simple syntax of raising an exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

http://www.francisxavier.ac.in

Page 61

TYPES OF MORE COMMONLY USED EXCEPTIONS


NO_DATA_FOUND
TOO_MANY_ROWS

Singleton SELECT statement returned no data.


Singleton SELECT statement returned more than one row of
data.

INVALID_CURSOR

Illegal cursor operation occurred.

VALUE_ERROR

Arithmetic, conversion, or truncation error occurred.

INVALID_NUMBER

Conversion of a number to a character string failed.

ZERO_DIVIDE

Attempted to divide by zero.

DUP_VAL_ON_INDEX

Attempted to insert a duplicate value into a column that has a


unique index.

CURSOR_ALREADY_OPEN

Attempted to open a cursor that was previously opened.

NOT_LOGGED_ON

A database call was made without being logged into Oracle.

TRANSACTION_BACKED_OUT

Usually raised when a remote portion of a transaction is


rolled back.

LOGIN_DENIED

Login to Oracle failed.

PROGRAM_ERROR

If PL/SQL encounters an internal problem.

STORAGE_ERROR

If PL/SQL runs out of memory or if memory is corrupted.

TIMEOUT_ON_RESOURCE

Timeout occurred while Oracle was waiting for a resource.

OTHERS

For all of the rest.

PROGRAM
ZERO_DIVIDE EXCEPTION
SQL> BEGIN
2

DBMS_OUTPUT.PUT_LINE(1 / 0);

3 END;
4 /
OUTPUT
begin
*
ERROR at line 1:
http://www.francisxavier.ac.in

Page 62

ORA-01476: divisor is equal to zero


ORA-06512: at line 2
-----------------------------------------------------BEGIN
2 DBMS_OUTPUT.PUT_LINE(1 / 0);
3 EXCEPTION
4 WHEN ZERO_DIVIDE THEN
5 DBMS_OUTPUT.PUT_LINE('Division by zero');
6 END;
7 /
Division by zero:
PL/SQL procedure successfully completed.
INVALID_NUMBER EXCEPTION
1 BEGIN
2 INSERT INTO employees(DEPARTMENT_ID)VALUES('101x');
3 EXCEPTION
4 WHEN INVALID_NUMBER THEN
5 DBMS_OUTPUT.PUT_LINE('Conversion of string to number failed');
6* end;
SQL> /
Conversion of string to number failed
PL/SQL procedure successfully completed.
OTHERS EXCEPTION
1

BEGIN

DBMS_OUTPUT.PUT_LINE(1 / 0);

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('An exception occurred');

6* END;
7 /
An exception occurred
http://www.francisxavier.ac.in

Page 63

PL/SQL procedure successfully completed.


FIRST CREATE A TABLE NAMED CUSTOMERSS WTH ATTRIBUTE ID, NAME,
ADDRESS AND THEN IMPLEMENT THE FOLLOWING CODE:
SQL>declare
c_id customerss.id%type;
c_name customerss.name%type;
c_addr customerss.address%type;
begin
SELECT name,address INTO c_name,c_addr FROM customerss WHERE id=c_id;
dbms_output.put_line('Name: '|| c_name);
dbms_output.put_line('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
OUTPUT:
'No such customer
PROGRAM:
(The following example illustrates the programmer-defined exceptions. Get the salary of an
employee and check it with the jobs salary range. If the salary is below the range, an exception
BELOW_SALARY_RANGE is raised. If the salary is above the range, exception
ABOVE_SALARY_RANGE is raised)
SET SERVEROUTPUT ON SIZE 100000;
DECLARE
-- define exceptions
BELOW_SALARY_RANGE EXCEPTION;
ABOVE_SALARY_RANGE EXCEPTION;
-- salary variables
n_salary employees.salary%TYPE;
n_min_salary employees.salary%TYPE;
n_max_salary employees.salary%TYPE;
-- input employee id
http://www.francisxavier.ac.in

Page 64

n_emp_id employees.employee_id%TYPE := &emp_id;


BEGIN
SELECT salary, min_salary max_salary INTO n_salary, n_min_salary, n_max_salary
FROM employees
INNER JOIN jobs ON jobs.job_id = employees.job_id
WHERE employee_id = n_emp_id;
IF n_salary < n_min_salary THEN
RAISE BELOW_SALARY_RANGE;
ELSIF n_salary > n_max_salary THEN
RAISE ABOVE_SALARY_RANGE;
END IF;
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary $' || n_salary );
EXCEPTION WHEN BELOW_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary below the salary range');
WHEN ABOVE_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary above the salary range');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ' || n_emp_id || ' not found');
END;
/

RESULT:
Thus a PL/SQL block that handles all type of exceptions was written, executed and
verified successfully.

http://www.francisxavier.ac.in

Page 65

Ex.No.9

CREATION OF PROCEDURES

AIM:
To implement and execute Procedures in Oracle Database using Procedural Language
concepts.

DESCRIPTION:
PROCEDURES
1) Procedure is a sub program used to perform an action.
2) Replace-recreates the procedure if it already exists.
3 MODES
1) IN Means you must specify a value for the argument at the time execution of the
procedure.
2) OUT-passes back a value to its calling program.
3) INOUT When calling the procedure, yu must specify the value and that procedures
passes value back to the calling procedure.
SYNTAX
Create or replace procedure <procedure_name> (argument {in, out, in out} data type) {is, as}
Variable declaration
Begin
Pl/SQL Subprogram body.
Exception
Exception PL/SQL Block.
End;

http://www.francisxavier.ac.in

Page 66

I) PROCEDURE USING POSITIONAL PARAMETERS:


SQL> set serveroutput on
SQL> create or replace procedure proc1 as
2 begin
3 dbms_output.put_line('hello from procedure...');
4 end;
5/
OUTPUT
Procedure created.
SQL> EXECUTE proc1
Hello from procedure...
PL/SQL procedure successfully completed.

II) PROCEDURE USING NOTATIONAL PARAMETERS:


SQL> create or replace procedure proc2
2 (n1 in number,n2 in number,tot out number) is
3 begin
4 tot := n1 + n2;
5 end;
6/
OUTPUT
Procedure created.
SQL> variable t number
SQL> EXEC proc2(33,66,:T)
PL/SQL procedure successfully completed.
SQL> PRINT T
T
---------99

http://www.francisxavier.ac.in

Page 67

III) PROCEDURE TO WRITE PL/SQL PROCEDURE TO REVERSE A NUMBER.


ALGORITHM
Step 1: Start the program
Step 2: Declare the variables n, temp, rem and rev =0
Step 3: Prompt the user to enter the value for n
Step 4: Assign the value of temp as n
Step 5: Check if n > 0. If so, start the while loop for temp > 0
Step 6: rem:=mod(temp,10);
Step 7: rev:=rev*10+rem;
Step 8: temp:=floor(temp/10);
Step 9: Exit the while loop
Step 10: Display the reversed number
Step 11: Exit the if loop
Step 12: Stop the program.
PROCEDURE FOR REVERSING A NUMBER
SQL>set server output on
SQL>create or replace procedure rev(n number) is
2 temp number;
3 rem number;
4 rev number=0;
5 begin
6 temp=n;
7 if n>0 then
8 while temp>0
9 loop
10 rem:=mod(temp,10);
11 rev:=rev*10+rem;
12 temp:=floor(temp/10);
13 end loop;
14 dbms_output.put_line(the reversed number is||rev);
15 else
http://www.francisxavier.ac.in

Page 68

16 dbms_output.put_line(invalid);
17 end if;
18 end
19 /
Procedure created
SQL>declare
2 n number;
3 begin
4 n:=&n;
5 rev(n);
6 end;
7/
OUTPUT
Enter value for n:876
The reversed number is 678
PL/SQL procedure successfully completed.
IV) PROCEDURE FOR GCD OF NUMBERS
SQL> create or replace procedure pro is
a number(3);
b number(3);
c number(3);
d number(3);
begin
a:=&a;
b:=&b;
if(a>b) then
c:=mod(a,b);
if(c=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(b);
else
http://www.francisxavier.ac.in

Page 69

dbms_output.put_line('GCD is');
dbms_output.put_line(c);
end if;
else
d:=mod(b,a);
if(d=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(a);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(d);
end if;
end if;
end;
/
Enter value for a: 8
old 8: a:=&a;
new 8: a:=8;
Enter value for b: 16
old 9: b:=&b;
new 9: b:=16;
Procedure created.
SQL> set serveroutput on;
SQL> execute pro;
GCD is
8
PL/SQL procedure successfully completed.
V) PROCEDURE FOR CURSOR IMPLEMENATION
create table st13(regno number(4),name varchar2(20),mark1 number(3),mark2 number(3),mark3
numbe r(3),mark4 number(3),mark5 number(3));
insert into st13 values(101,'raji',100,90,97,89,91);
http://www.francisxavier.ac.in

Page 70

insert into a13 values(102,'kali');


insert into a13 values(103,'jaya');
select * from st13;

REGNO

NAME

------

--------

MARK1
------------

MARK2
----------

101 raji

100

90

102 kali

99

77

103 jaya

78

88

MARK3

MARK4 MARK5

---------- ---------97

-------

89

91

69

81

99

77

60

89

SQL>set server output on


declare
ave number(5,2);
tot number(3);
cursor c_mark is select * from st13 where mark1>=40 and mark2>=40 and mark3>=40 and
mark4>=40 and mark5>=40;
begin
dbms_output.put_line('regno name mark1 mark2 mark3 mark4 mark5 total average');
dbms_output.put_line('------------------------------------------------------');
for student in c_mark
loop
tot:=st13.mark1+st13.mark2+st13.mark3+st13.mark4+st13.mark5;
ave:=tot/5;
dbms_output.put_line(st13.regno||rpad(st13.name,15)||rpad(st13.mark1,6)||rpad(st13.mark2,6)||rp
ad(st13.mark3,6)||rpad(st13.mark4,6)||rpad(st13.mark5,6)||rpad(tot,8)||rpad(ave,5));
end loop;
end;
/

http://www.francisxavier.ac.in

Page 71

regno name mark1 mark2 mark3 mark4 mark5 total average


-----------------------------------------------------101raji

100 90 97 89 91 467

93.4

102kali

99 77 69 81 99 425

85

103jaya

78 88 77 60 89 392

78.4

PL/SQL procedure successfully completed.

VI) PROCEDURE FOR EXPLICIT CURSORS AND EXPLICIT CURSORS


IMPLEMENTATION
CREATING A TABLE EMP IN ORACLE
SQL> select * from EMP;
EMPNO ENAME JOB
----------

MGR

HIREDATE

---------- --------- ---------- ---------

SAL COMM DEPTNO


---------- ---------- ----------

7369 SMITH CLERK 7902 17-DEC-80 800 400 20


7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000
7839 KING PRESIDENT 17-NOV-81 5000 10
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100
7900 JAMES CLERK 7698 03-DEC-81 950 20 30
http://www.francisxavier.ac.in

Page 72

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- --------- ---------- --------- ---------- ---------- ---------7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
IMPLICIT CURSCORS
SQL> DECLARE
2 ena EMP.ENAME%TYPE;
3 esa EMP.SAL%TYPE;
4 BEGIN
5 SELECT ENAME,SAL INTO ENA,ESA FROM EMP
6 WHERE EMPNO = &EMPNO;
7 DBMS_OUTPUT.PUT_LINE('NAME :' || ENA);
8 DBMS_OUTPUT.PUT_LINE('SALARY :' || ESA);
9 EXCEPTION
10 WHEN NO_DATA_FOUND THEN
11 DBMS_OUTPUT.PUT_LINE('Employee no does not exits');
12 END;
13 /
Output:
Enter value for empno: 7844
old 6: WHERE EMPNO = &EMPNO;
new 6: WHERE EMPNO = 7844;
PL/SQL procedure successfully completed.
EXPLICIT CURSORS
SQL> DECLARE
2 ena EMP.ENAME%TYPE;
3 esa EMP.SAL%TYPE;
4 CURSOR c1 IS SELECT ename,sal FROM EMP;
5 BEGIN
http://www.francisxavier.ac.in

Page 73

6 OPEN c1;
7 FETCH c1 INTO ena,esa;
8 DBMS_OUTPUT.PUT_LINE(ena || ' salry is $ ' || esa);
9FETCH c1 INTO ena,esa;
10 DBMS_OUTPUT.PUT_LINE(ena || ' salry is $ ' || esa);
12 FETCH c1 INTO ena,esa;
13 DBMS_OUTPUT.PUT_LINE(ena || ' salry is $ ' || esa);
14 CLOSE c1;
15 END;
16 /

OUTPUT:
SMITH salry is $ 800
ALLEN salry is $ 1600
WARD salry is $ 1250

RESULT:
Thus, Procedures in Oracle Database using Procedural Language concepts were implemented
and executed successfully.

http://www.francisxavier.ac.in

Page 74

Ex. No 10

CREATION OF DATABASE TRIGGERS AND FUNCTIONS

AIM:
To create database triggers and functions.

DESCRIPTION:
TRIGGER
A trigger is a statement that is executed automatically by the system as a side effect of a
modification to the database. The parts of a trigger are,

Trigger statement: Specifies the DML statements and fires the trigger body. It also
specifies the table to which the trigger is associated.

Trigger body or trigger action: It is a PL/SQL block that is executed when the
triggering statement is used.

Trigger restriction: Restrictions on the trigger can be achieved

The different uses of triggers are as follows,

To generate data automatically

To enforce complex integrity constraints

To customize complex securing authorizations

To maintain the replicate table

To audit data modifications

TYPES OF TRIGGERS
The various types of triggers are as follows,

Before: It fires the trigger before executing the trigger statement.

After: It fires the trigger after executing the trigger statement.

For each row: It specifies that the trigger fires once per row.

For each statement: This is the default trigger that is invoked. It specifies that the trigger
fires once per statement.

VARIABLES USED IN TRIGGERS

:new

:old

http://www.francisxavier.ac.in

Page 75

These two variables retain the new and old values of the column updated in the database. The
values in these variables can be used in the database triggers for data manipulation.
SYNTAX
create or replace trigger trigger name [before/after] {DML statements}
on [table name] [for each row/statement]
begin
------------------------------------------------------------------------exception
end;
PROCEDURE
Step1:Creates a trigger for insertion of each row.
Step2:Declare a cursor which contains the roll number field
Step3:Before insertion check of the roll number already exists in the table
Step4:If it exists raise an application error and display roll no exists.
Step5:Else perform insertion
PROGRAM
SQL>create table poo(rno number(5),name varchar2(10));
Table created.
SQL>insert into poo values (01.kala);
1 row created.
SQL>select * from poo;
RNO

NAME

--------------------------------01

kala

02

priya

SQL>create or replace trigger pool before insert on poo for each row
2 declare
3 rno poo.rno%type
4 cursor c is select rno from poo;
http://www.francisxavier.ac.in

Page 76

5 begin
6 open c;
7 loop;
8 fetch c into rno;
9 if:new.rno=rno then
10 raise_application_error(-20005,rno already exist);
11 end if;
12 exit when c%NOTFOUND
13 end loop;
14 close c;
15 end;
16 /
Trigger created.
OUTPUT
SQL>insert into poo values(01,kala)
Insert into poo values (01,kala)
*
ERROR at line1:
ORA-20005:rno already exist
ORA-06512:SECONDCSEA.POOL,line 9
ORA-04088:error during execution at trigger SECONDCSEA.POOL

FUNCTIONS:
Functions are routines that accept parameters, perform an action such as a complex
calculation and return the result of that action as a value. The return value can either be a single
scalar value or a result set.

PROCEDURE
STEP 1: Start
STEP 2: Create the table with essential attributes.
STEP 3: Initialize the Function to carry out the searching procedure..
http://www.francisxavier.ac.in

Page 77

STEP 4: Frame the searching procedure for both positive and negative searching.
STEP 5: Execute the Function for both positive and negative result .
STEP 6: Stop
PROGRAM
SQL>create function fnfact(n number)
return number is
b number;
begin
b:=1;
for i in 1..n
loop
b:=b*i;
end loop;
return b;
end;
/
SQL>Declare
n number:=&n;
y number;
begin
y:=fnfact(n);
dbms_output.put_line(y);
end;
/
Function created.
INPUT
Enter value for n: 5
old 2: n number:=&n;
new 2: n number:=5;

http://www.francisxavier.ac.in

Page 78

OUTPUT
120
PL/SQL procedure successfully completed.
ALGORITHM
Step 1: Start the program
Step 2: Declare the variables f and i
Step 3: Initialize f to 1
Step 4: Start the for loop i in 1..a
Step 5: Compute f=f*i
Step 6: End the loop
Step 7: Return the factorial value
Step 8: Stop the program
PROGRAM
SQL> create or replace function fact(a number)return number as
2 i number;
3 f number;
4 begin
5 f:=1;
6 for i in 1..a
7 loop
8 f:=f*i;
9 end loop;
10 return f;
11 end fact;
12 /
Function created.
OUTPUT
SQL> set serveroutput on
SQL> begin
2 dbms_output.put_line('the factorial ='||fact(&a));

http://www.francisxavier.ac.in

Page 79

3 end;
4/
Enter value for a:4
old 2: dbms_output.put_line('the factorial ='||fact(&a));
new 2: dbms_output.put_line('the factorial ='||fact(4));
the factorial=24
PL/SQL procedure successfully completed.
ALGORITHM
Step 1: Start the program
Step 2: Declare the variables i and f
Step 3: Initialize the values for f and i as 1
Step 4: Start the while loop 1 <= a
Step 5: Compute f=f*i
Step 6: Compute i=i+1
Step 7: Exit the loop
Step 8: Return the factorial value
Step 9: Stop the program
PROGRAM
SQL> create or replace function fact(a number)return number as
2 i number;
3 f number;
4 begin
5 f:=1;
6 i:=1;
7 while(i<=a)
8 loop
9 f:=f*i;
10 i:=i+1;
11 end loop;
12 return f;
13 end fact;
http://www.francisxavier.ac.in

Page 80

14 /
Function created.
OUTPUT
SQL> set serveroutput on
SQL> begin
2 dbms_output.put_line('the factorial ='||fact(&a));
3 end;
4/
Enter value for a:5
old 2: dbms_output.put_line('the factorial ='||fact(&a));
new 2: dbms_output.put_line('the factorial ='||fact(5));
the factorial=120
PL/SQL procedure successfully completed.
PROGRAM
SQL> create table phonebook (phone_no number (6) primary key,username
varchar2(30),doorno varchar2(10),
street varchar2(30),place varchar2(30),pincode char(6));
Table created.
SQL> insert into phonebook values(20312,'vijay','120/5D','bharathi street','NGO
colony','629002');
1 row created.
SQL> insert into phonebook values(29467,'vasanth','39D4','RK bhavan','sarakkal vilai','629002');
1 row created.
SQL> select * from phonebook;
PHONE_NO USERNAME DOORNO STREET PLACE PINCODE
------------------------------- ------------- ---------------- -------------------20312 vijay 120/5D bharathi street NGO colony 629002
29467 vasanth 39D4 RK bhavan sarakkal vilai 629002
SQL> create or replace function findAddress(phone in number) return varchar2 as
address varchar2(100);
begin
http://www.francisxavier.ac.in

Page 81

select username||','||doorno ||','||street ||','||place||','||pincode into address from phonebook


where phone_no=phone;
return address;
exception
when no_data_found then return 'address not found';
end;
/
Function created.
SQL>declare
2 address varchar2(100);
3 begin
4 address:=findaddress(20312);
5 dbms_output.put_line(address);
6 end;
7/
OUTPUT 1
Vijay,120/5D,bharathi street,NGO colony,629002
PL/SQL procedure successfully completed.
SQL> declare
2 address varchar2(100);
3 begin
4 address:=findaddress(23556);
5 dbms_output.put_line(address);
6 end;
7/
OUTPUT2
Address not found
PL/SQL procedure successfully completed.
RESULT:
Thus the creation of database triggers and functions was implemented and
executed successfully.
http://www.francisxavier.ac.in

Page 82

Ex.No: 11

MINI PROJECTS (APPLICATION DEVELOPMENT USING ORACLE/


MYSQL)

DESIGN AND IMPLEMENTATION OF PAYROLL PROCESSING SYSTEM:


AIM:
To design the payroll processing system in visual basic using ORACLE as backend
DESCRIPTION:

PROCEDURE FOR CREATING TABLE:


1. Create table with following fields
NAME

NULL?

TYPE

---------------------------------------------EID

NUMBER(10)

ENAME

VARCHAR2(1 0)

DES

VARCHAR2(10)

BASICPAY

NUMBER(10)

HRA

NUMBER(10)

DA

NUMBER(10)

MA

NUMBER(10)

GROSSPAY

NUMBER(10)

DEDUCTION

NUMBER(10)

NETPAY

NUMBER(10)

2. Insert all possible values into the table.


3. Enter commit work command.

ALGORITHM FOR ADO CONNECTION:


After creating the table in ORACLE, go to start menu
1. Start --> Settings --> Control Panel --> Administrative tools --> Data
Sources(ODBC) --> User DSN --> Add --> Select ORACLE database driver -->
OK.

http://www.francisxavier.ac.in

Page 83

2. One new window will appear. In that window, type data source name as table
name created in ORACLE. Type user name as secondcsea.
ALGORITHM FOR ADODC IN VISUAL BASIC:
1. In visual basic create tables, command buttons and then text boxes.
2. In visual basic, go to start menu.
3. Projects --> Components --> Microsoft ADO Data Control 6.0 for OLEDB -->
OK.
4. Now ADODC Data Control available in tool box.
5. Drag and drop the ADODC Data Control in the form.
6. Right click in ADODC Data Control, then click ADODC properties.
7. One new window will appear.
8. Choose general tab, select ODBC Data Sources name as the table name created in
ORACLE
9. Choose authentication tab and select username password as secondcsea and
secondcsea
10. Choose record name-->select command type as adcmdTable.
11. Select table or store procedure name as table created in ORACLE.
12. Click Apply-->OK
13. Set properties of each text box.
14. Select the data source as ADODC1.
15. Select the Data field and set the required field name created in table

VB SCRIPT:
ADD:
Private Sub Add_Click()
Adodc1.Recordset.AddNew
Textl.SetFocus
End Sub
DELETE:
Private Sub Delete_Click()
If MsgBox ("DELETE IT?",vb OKCancel)= vbOK Then
http://www.francisxavier.ac.in

Page 84

Adodc1.Recordset.Delete
End If
MsgBox "ONE ROW DELETED"
Textl.Text - " "
Text2.Text - " "
Text3.Text - " "
Text4.Text - " "
Text5.Text - " "
Text6.Text - " "
Text7.Text - " "
Text8.Text - " "
Text9.Text - " "
Textl0.Text - " "
End Sub
SAVE:
Private Sub Save_Click()
If MsgBox ("SAVE IT?",vbOKCancel ) = vbOK Then
Adodc1.Recordset.Update
Else
Adodc1.Recordset.CancelUpdate
End If
End Sub
FIND:
Private Sub Find_Click()
Dim N as string
N = InputBox ("Enter the accno")
Adodc1.Recordset.Find "accno=" & N
If Adodcl.Recordset.BOF or Adodc1.Recordset.EOF Then
MsgBox "Record not found"
End If
End Sub
http://www.francisxavier.ac.in

Page 85

UPDATE:
Private Sub Update_Click()
Adodc1.Recordset.EditMode
Adodc1.Recordset.Update
End Sub
FIRST:
Private Sub First_Click()
Adodc1.Recordset.MoveFirst
End Sub
LAST:
Private Sub Last_Click()
Adodc1.Recordset.MoveLast
End Sub
NEXT:
Private Sub Next_Click()
Adodc1.Recordset.MoveNext
End Sub
PREVIOUS:
Private Sub Previous_Click()
Adodc1.Recordset.MovePrevious
End Sub
DEPOSIT:
Private Sub Deposit_Click0
Dim N1 as string
N = InputBox ("Enter the accno")
Adodcl.Recordset.Find "accno=" & N
Nl = InputBox ("Enter the amount")
Text4.Text= val (Text4.Text) + Nl
Adodc1.Recordset.Update
End Sub

http://www.francisxavier.ac.in

Page 86

WITHDRAW:
Private Sub Withdraw_Click()
Dim Nl as string
N = InputBox ("Enter the accno")
Adodcl.Recordset.Find "accno=" & N
Nl = InputBox ("Enter the amount")
Text4.Text= val (Text4.Text) - Nl
Adodc l.Recordset.Update
End Sub
EXIT:
Private Sub Add_Click()
Unload Me
End Sub
FUNCTION:
Function Calculate()
Text8.Text=val(Text4.Text) + val (Text5.Text) + val (Text6.Text) + val (Text7.Text)
Text9.Text=val(Text5.Text) + val (Text6.Text) + val (Text7.Text)
Text 10.Text=val(Text8.Text) + val (Text9.Text)
End Function
BASICPAY,HRA,DA,MA,GROSSPAY,DEDUCTION,NETPAY:
Private Sub Basicpay_Change()
Call Calculate
End Sub
Private Sub HRA_Change()
Call Calculate
End Sub
Private Sub DA_Change()
Call Calculate
End Sub
Private Sub MA_Change()
Call Calculate
http://www.francisxavier.ac.in

Page 87

End Sub
Private Sub Grosspay_Change()
Call Calculate
End Sub
Private Sub Deduction_Change()
Call Calculate
End Sub
Private Sub Netpay_Change()
Call Calculate
End Sub

http://www.francisxavier.ac.in

Page 88

OUTPUT:
STARTUP FORM

ADD FORM

http://www.francisxavier.ac.in

Page 89

SAVE FORM

RESULT:
Thus the payroll processing system was designed in Visual Basic using ORACLE as
backend and the output was verified.

http://www.francisxavier.ac.in

Page 90

DESIGN AND IMPLEMENTATION OF BANKING SYSTEM


AIM:
To design the banking system in visual basic using ORACLE as backend
DESCRIPTION:
PROCEDURE FOR CREATING TABLE:
1. Create table with following fields

NAME

NULL?

TYPE

---------------------------------------------ACCNO

NUMBER(10)

CUSTNAME

VARCHAR2(1 0)

CUSTCITY

VARCHAR2(10)

AMOUNT

NUMBER(10)

2.Insert all possible values into the table.


3.Enter commit work command.
ALGORITHM FOR ADO CONNECTION:
After creating the table in ORACLE, go to start menu
1.Start --> Settings --> Control Panel --> Administrative tools --> Data Sources(ODBC) --> User
DSN --> Add --> Select ORACLE database driver --> OK.
2 .One new window will appear. In that window, type data source name as table name created in
ORACLE. Type user name as secondcsea.
ALGORITHM FOR ADODC IN VISUAL BASIC:
1. In visual basic create tables, command buttons and then text boxes.
2. In visual basic, go to start menu.
3. Projects --> Components --> Microsoft ADO Data Control 6.0 for OLEDB -->
OK.
4. Now ADODC Data Control available in tool box.
5. Drag and drop the ADODC Data Control in the form.
6. Right click in ADODC Data Control, then click ADODC properties.
7. One new window will appear.

http://www.francisxavier.ac.in

Page 91

8. Choose general tab, select ODBC Data Sources name as the table name created in
ORACLE
9. Choose authentication tab and select username password as secondcsea and
secondcsea
10. Choose record name-->select command type as adcmdTable.
11. Select table or store procedure name as table created in ORACLE.
12. Click Apply-->OK
13. Set properties of each text box.
14. Select the data source as ADODC1.
15. Select the Data field and set the required field name created in table
VB SCRIPT:
FIRST:
Private Sub First_Click()
Adodc1.Recordset.MoveFirst
End Sub
LAST:
Private Sub Last_Click()
Adodc1.Recordset.Movelast
End Sub
NEXT:
Private Sub Next_Click()
Adodc1.Recordset.MoveNext
End Sub
PREVIOUS:
Private Sub Previous_Click()
Adodc1.Recordset.MovePrevious
End Sub
DEPOSIT:
Private Sub Deposit_Click()
Dim N1 as string
N = InputBox ("Enter the accno")
http://www.francisxavier.ac.in

Page 92

Adodc1.Recordset.Find "accno=" &


N1 = InputBox ("Enter the amount")
Text4.Text = val (Text4.Text) + N1
Adodc1.Recordset.Update
End Sub
WITHDRAW:
Private Sub Withdraw_Click()
Dim N1 as string
N = InputBox ("Enter the accno")
Adodcl.Recordset.Find "accno=" & N
N1 = InputBox ("Enter the amount")
Text4.Text: val (Text4.Text) - N1
Adodc1.Recordset.Update
End Sub
EXIT:
Private Sub Add_Click()
Unload Me
End Sub

http://www.francisxavier.ac.in

Page 93

OUTPUT:
START UP FORM

DEPOSIT FORM

http://www.francisxavier.ac.in

Page 94

SAVE FORM

RESULT:
Thus the banking system was designed in Visual Basic using ORACLE as backend.

http://www.francisxavier.ac.in

Page 95