0% found this document useful (0 votes)
4 views

dbms lab

The document is a lab manual for the Database Management Systems Laboratory at the Institute of Aeronautical Engineering, detailing course information, student and faculty responsibilities, lab policies, and grading criteria. It outlines various lab experiments focusing on SQL, PL/SQL, and database management practices, aiming to equip students with practical skills in managing and manipulating data. Additionally, it provides instructions for lab report preparation and emphasizes the importance of accurate data recording and communication of results.

Uploaded by

saipranya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

dbms lab

The document is a lab manual for the Database Management Systems Laboratory at the Institute of Aeronautical Engineering, detailing course information, student and faculty responsibilities, lab policies, and grading criteria. It outlines various lab experiments focusing on SQL, PL/SQL, and database management practices, aiming to equip students with practical skills in managing and manipulating data. Additionally, it provides instructions for lab report preparation and emphasizes the importance of accurate data recording and communication of results.

Uploaded by

saipranya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

INSTITUTE OF AERONAUTICAL ENGINEERING

(Autonomous)
Dundigal, Hyderabad - 500 043

Lab Manual:

DATABASE MANAGEMENT SYSTEMS LABORATORY(AITC07)

Prepared by

Y MANOHAR REDDY(IARE10857)

Department of Computer Science and Engineering(CS)


Institute of Aeronautical Engineering
MARCH 30, 2022
Contents
Course Information
1. Introduction ................i
1.1 Student Responsibilities ................ii
1.2 Laboratory Teaching Assistant Responsibilities ................iii
1.3 Faculty Coordinator Responsibilities ................iv
1.4 Lab Policy and Grading ................v
1.5 Course Goals and Objectives ................vi
1.6 Use of Laboratory Instruments ................vii
1.7 Instrument Protection Rules ................viii
2. Data Recording and Reports ................ix
2.1 The Laboratory Notebook ................x
2.2 TheLabReport ................xi

2.3 Order of Lab Report Components ................xii

Lab 1 - Creation of Tables 10

Lab 2 - Queries Using DDL and DML 16

Lab3- Queries using Aggregate Functions 24

Lab4- Programs n PL/SQL 29

Lab5- Procedures and Functions 33

Lab 6 -Triggers 37

Lab 7 - Procedures 42

Lab 8- Cursors 44

Lab 9- Case Study-1 46

Lab 10- Case Study-2 48

Lab 11 - Case Study-3 50

Lab 12 - Case Study-4 52

Page 2
Course Information

1 Introduction

The requirement of modern days is to have an automated system that manages, modifies and updates
data accurately. This is achieved by a DBMS in robust, correct and non-redundant way. DBMS lab
aims at practicing and achieving this aim by using various software’s such as SQL, ORACLE, and MS
– Access etc. It provides practice on built-in SQL functions using languages like DDL, DCL, DML
and TCL to create and manage database systems. This is essential for mobile and web application
development for business, scientific and engineering applications.

1.1 Student Responsibilities

The student is expected to be prepared for each lab.Lab preparation includes reading the labexperi-
ment and related textbook material. If you have questions or problems with the preparation, contact
your Laboratory Teaching faculty, but in a timely manner. Do not wait until an hour or two befor
the lab and then expect the lab faculty to be immediately available.

Active participation by each student in lab activities is expected. The student is expected to askthe
laboratory faculty any questions they may have.

A large portion of the student’s grade is determined in the comprehensive final exam, resulting in a
requirement of understanding the concepts and procedure of each lab experiment for the successful-
completion of the lab class. The student should remain alert and use common sense while performing
a lab experiment. They are also responsible for keeping a professional and accurate record of the
labexperiments in the lab manual wherever tables are provided. Students should report any errors in
the lab manual to the teaching assistant.

1.2 Laboratory Faculty Responsibilities

TThe laboratory faculty shall be completely familiar with each lab prior to class. The laboratory
faculty shall provide the students with a syllabus and safety review during the first class. The syllabus
shall include the laboratory faculty office hours, telephone number, and the name of the faculty coor-
dinator. The laboratory faculty is responsible for ensuring that all the necessary equipment and/or
preparations for the lab are available and in working condition. Lab experiments should be checked
in advance to make sure everything is in working order. The laboratory faculty should fully answer
any questions posed by the students and supervise the students performing the lab experiments. The
laboratory faculty is expected to grade the lab notebooks and reports in a fair and timely manner.
The reports should be returned to the students in the next lab period following submission. The
laboratory faculty should report any errors in the lab manual to the faculty coordinator.

1.3 Faculty Co-ordinator Responsibilities

The faculty coordinator should ensure that the laboratory is properly equipped, i.e., that the teaching
assistants receive any equipment necessary to perform the experiments. The coordinator is responsible
for supervising the teaching assistants and resolving any questions or problems that are identified by
the teaching assistants or the students. The coordinator may supervise the format of the final exam for
the lab. They are also responsible for making any necessary corrections to this manual and ensuring
that it is continually updated and available.

Page 3
1.4 Lab Policy and Grading

The student should understand the following policy:

Attendance

Attendance is mandatory and any absence must be for a valid excuse and must be documented.If the
instructor is more than 15 minutes late, students may consider lab for the day cancelled.

Lab Records

The student must:


1. Perform the Pre Lab assignment before the beginning of each lab,
2. Keep all work in preparation of and obtained during lab; and
3. Prepare a lab report on experiments selected by the laboratory faculty.

Grading Policy

The final grade of this course is determined using the criterion detailed in the syllabus.

Instructions to Students

• Before entering the lab the student should carry the following things (MANDATORY)
o Identity card issued by the college.
o Work Sheets
• Student must sign in and sign out in the register provided when attending the lab session without
fail.
• Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed to
attend the lab.
• Students need to maintain 100% attendance in lab if not a strict action will be taken.
• All students must follow a Dress Code while in the laboratory
• Foods, drinks are NOT allowed.
• All bags must be left at the indicated place.
• Refer to the lab staff if you need any help in using the lab.
• Respect the laboratory and its other users.
• Workspace must be kept clean and tidy after experiment is completed.
• Read the Manual carefully before coming to the laboratory and be sure about what you are sup-
posed to do.
• Do the experiments as per the instructions given in the manual.
• Copy all the programs to observation which are taught in class before attending the lab session.
• Students are not supposed to use floppy disks, pen drives without permission of lab- incharge.
• Lab records need to be submitted on or before the date of submission.
• Computer labs are established with sophisticated and high end branded systems, which should be
utilized properly.
• Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab ses-
sions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe
punishment.
• Students must take the permission of the faculty in case of any urgency to go out; if anybody found
loitering outside the lab / class without permission during working hours will be treated seriously and
punished appropriately.
• Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly.

Page 4
1.5 Course Goals and Objectives

Goal:

The goal of the laboratory course is to present an introduction to database management systems, with
an emphasis on how to organize, maintain and retrieve - efficiently, and effectively - information from
a DBMS.

Objectives:

Students will try to learn:

• The SQL commands for data definition, manipulation, control and perform transactions in database
systems.

• The procedural language for implementation of functions, procedures, cursors and triggers using
PL/SQL programs.

• The logical design of a real time database system with the help of Entity Relationship diagrams.

2 Data Recording and Reports

2.1 The Laboratory Note book

Students must write their experimental outputs in the provided tables in this laboratory manual and
reproduce them in the lab reports. Reports are integral to recording the methodology and results
of an experiment. In engineering practice, the laboratory notebook serves as an invaluable reference
to the technique used in the lab and is essential when trying to duplicate a result or write a report.
Therefore, it is important to learn to keep accurate data. Make plots of data and sketches when these
are appropriate in the recording and analysis of observations. Note that the data collected will be an
accurate and permanent record of the data obtained during the experiment and the analysis of the
results. You will need this record when you are ready to prepare a lab report.

2.2 The Lab Report

Reports are the primary means of communicating your experience and conclusions to other profes-
sionals. In this course you will use the lab report to inform your laboratory faculty about what you
did and what youhave learned from the experience.Engineering results are meaningless unless they can
be communicated to others. You will be directed by your laboratory facultyto prepare a lab report on
a few selected lab experiments during the semester.Your assignment might be different from your lab
partner’s assignment.
Your laboratory report should be clear and concise.The lab report shall be typed on a word proces-
sor.As a guide,use the format on the next page.Use tables,diagrams, sketches, as necessaryto show
what you did, what was observed, and what conclusions you can draw from this. Even thoughyou will
work with one or more lab partners, your report will be the result of your individual effort in order to
provide you with practice in technical communication.

Formatting and Style

• The lab report shall be typed in a word processor.

Page 5
• All page margins must be 1.25 inches. All content (including text, figures, tables, etc.) must fit
within the margins.

• Body text should be double-spaced.

• Basic text should be in 12-point size in a commonly used text font.

• Set your main text justified (with even left/right margins).

• The first line of each paragraph should have a left indent.

• All the tables should have titles and should be numbered. Tables should be labeled numerically as
Table 1, Table 2, etc. Table captions appear above the table. The column headings should be labeled
with the units specified.

• Use MS-Word equation (under Insert Equation menu), MathType, or a similar tool to type formulas.

• If you need to copy a schematic or figure from the lab manual to your report, use Copy and Paste
function or take a screenshot by using Snipping Tool in MS-Windows.

• Do not place screenshots of your lab notebook in the report! Diagrams, tables, calculations, etc.
must be generated using the existing tools in the word processor.

2.3 Order of Lab Report Components

Coverpage

Cover page must include lab nameand number,your name,yourlab partner’s name,and the date the
lab was performed.

Objective

Clearly state the experiment objective in your own words.

Software Needed

Indicate which software was used in performing the experiment.

For Each Part of the Lab

• Write the lab’s part number and title in bold font. Firstly, describe the problem that you studied
in this part, give an introduction of the theory, and explain why you did this experiment.Do not lift
the text from the lab manual; use your ownwords.

•Secondly,describe the experimental setup and procedures.Do not follow the lab manual in listing out
individual pieces of equipment and assembly instructions.That is not relevant information in a lab
report! Your description should take the form of a narrative, and include information notpresent in
the manual,such as descriptions of what happened during intermediate steps of the experiment.

•Thirdly,explain your findings. This is the most important part of your report,because here,you show
that you understand the experiment beyond the simple level of completing it. Explain(compare ex-
pected results with those obtained). Analyse (analyze experimental error). Interpret(explain your

Page 6
results in terms of theoretical issues and relate to your experimental objectives).All the results should
be presented even if there is any inconsistency with the theory. It should be possible to understand
what is going onby just reading through the text paragraphs, without looking at the figures.

•Finally, provide a summary of what was learned from this part of the laboratory experiment.If the
results seem unexpected or unreliable,discuss them and give possible explanations.

Conclusion

The conclusion section should provide a take-home message summing up what has been learned from
the experiment:

• Briefly restate the purpose of the experiment (the question it was seeking to answer)

• Identify the main findings (answer to the research question)

• Note the main limitations that are relevant to the interpretation of the results

• Summarize what the experiment has contributed to your understanding of the problem.

Probing Further Experiments

Questions pertaining to this lab must be answered at the end of laboratory report.

Page 7
Lab-Orientation
Introduction

The students should become familiar with the oracle software in the lab, the course requirements, and
the teaching instructor. Students should also make sure that they have all of the co-requisites and
pre-requisites for the course at this time.

Objective

To familiarize the students with the introduction of oracle database management system and instal-
lation of oracle database management system software.

Software Needed

Oracle 10g Express Edition.

Oracle Database

Oracle database (Oracle DB) is a relational database management system (RDBMS) from the Oracle
Corporation. Originally developed in 1977 by Lawrence Ellison and other developers, Oracle DB is
one of the most trusted and widely-used relational database engines.

The system is built around a relational database framework in which data objects may be directly
accessed by users (or an application front end) through structured query language (SQL). Oracle is a
fully scalable relational database architecture and is often used by global enterprises, which manage
and process data across wide and local area networks. The Oracle database has its own network
component to allow communications across networks.

Oracle Database (known as Oracle RDBMS) is a Database Management System produced and mar-
keted by Oracle Corporation.The Most Fundamental and common usage of Oracle Database is to store
a Pre-Defined type of Data. It supports the Structured Query language (SQL) to Manage and Manip-
ulate the Data that it has. It is one of the most Reliable and highly used Relational Database Engines.

There are many versions of Oracle Database like Oracle Database 10g, Oracle Database 11g, Oracle
Database 12c, Oracle Database 19c, etc. from which Oracle 19c is the Latest Version. In this article,
we will learn how to Install version 11g on Windows.

Steps to install Oracle Database:

Step 1: Go to oracle.com and Click on Options Menu.

Step 2: Click the Download Button and Scroll Down to Database Section.

Step 3: Click Database 11g Enterprise/Standard Editions, after which you’ll find different versions of
Oracle for different OS. Download the Files according to your OS.

Step 4: After Clicking the Download Button, the page will be directed to Login Screen where you’ll
need to Sign In in Oracle Account. If you don’t have one, then you must Sign Up, because without
that you won’t be able to download the Files.

Step 5: Repeat the same steps for both the Files and Download them.

Page 8
Extraction of Downloaded Files:

Step 1: Extract both the files with the use of WinRAR or any other extraction tool of your choice in
the same directory.

Step 2: Go to Folder database -> Stage -> Components Copy all the content of this Folder

Step 3: Go to Main Database -> Stage Paste the copied content in Components Folder

Installation of Oracle Database:

Step 1: Go to Main Database Folder where you’ll find Setup. Right click the setup.exe file and choose
Run as Administrator.

Step 2: Click Yes to continue. This will start Oracle Universal Installer.

Step 3: Select any of the three different Installation Options according to your needs.

• Option 1 – If you want to Install Oracle Server Software and want to Create Database also.
• Option 2 – If you want to Install Oracle Server only.
• Option 3 – If you want to Upgrade your Existing Database.

Step 4: Choose between Server Class and Desktop Class as per your requirement and click on Next.

Step 5: Configure the basic settings and create a Password for your database. Once the configuration
is done click on Next to continue.

Step 6: Oracle Universal Installer(OUI) will check for the Prerequisites such as Hardware compatibility.

Step 7: Click on Finish to start the Installation process. This installation might take some time
depending on your Hardware.

Step 8: Click OK to finish the installation.

Step 9: Copy the localhost link provided to open your Enterprise Manager.

Step 10: Click the Close Button and you are done with the Installation Process.
Go to Start Menu and
• Search Oracle Folder
• Click on Database Control – Oracle (Your Global Database Name)
• This will take you to the Login Screen of your Oracle Enterprise Manager.

Page 9
Lab-1 CREATION OF TABLES
Introduction

Structure Query Language (SQL) is a database query language used for storing and managing data
in Relational DBMS. In RDBMS the data is stored in the form of tables. The create table state-
ment is used to create a table for the database. This table can have n rows and m columns based
on the requirement. So, with the help of this query, we can store data in the form of rows and columns.

Objective

By the end of this lab, the student should learn how to create the tables, inserting values into the
tables and updating the tables.

PreLab:

Prior coming to the lab, students should have knowledge on DDL commands and DML commands.

Software Needed

Oracle 10g Express Edition

Background

SQL Commands

DDL: Data Definition Language (DDL) statements are used to define the database structure or schema.

DDL Commands: Create, Alter, Drop, Rename, Truncate CREATE - to create objects in the database.

ALTER - alters the structure of the database DROP - delete objects from the database.

TRUNCATE - remove all records from a table, including all spaces allocated for the records are re-
moved RENAME - rename an object.

DML: Data Manipulation Language (DML) statements are used for managing data within schema
objects and to manipulate data of a database objects.

DML Commands: Insert, Update, Delete, Select INSERT - insert data into a table

UPDATE - updates existing data within a table.

DELETE - deletes all records from a table, the space for the records remain.

SELECT - retrieve data from the a database.

Procedure

Step 1: Go to run sql command line

Step 2: Connect to the database using username and password

Page 10
Step 3: Create table and update the table by using DDL and DML commands

Program:

1) Create a table called Employee with the following structure.

name type
Empno Number
Empname Varchar2(10)
Job Varchar2(10)
Mgr Number
Sal Number

a. Add a column commission with domain to the Employee table.


b. Insert any five records into the table.
c. Update the column details of job.
d. Rename the column of Employ table using alter command.
e. Delete the employee whose Empno is 105.

Solution
SQL> create table employee(empno number,ename varchar2(10),job varchar2(10),mgr number,sal
number);

Table created.
SQL> desc employee;
Name Null? Type
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER

a. Add a column commission with domain to the Employee table.

SQL> alter table employee add(commission number); Table altered.

SQL> desc employee;

Name Null? Type

EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
COMMISSION NUMBER

b. Insert any five records into the table.

SQL> insert into employee values(&empno,’&ename’,’&job’,&mgr,&sal,’&commission’);


Enter value for empno: 101
Enter value for ename: abhi Enter value for job: manager
Enter value for mgr: 1234 Enter value for sal: 10000 Enter value for commission: 70

Page 11
old 1: insert into employee values(&empno,’&ename’,’&job’,&mgr,&sal,’&commission’)
new 1: insert into employee values(101,’abhi’,’manager’,1234,10000,’70’)
1 row created.

SQL> /
Enter value for empno: 102 Enter value for ename: rohith Enter value for job: analyst
Enter value for mgr: 2345 Enter value for sal: 9000
Enter value for commission: 65
old 1: insert into employee values(&empno,’&ename’,’&job’,&mgr,&sal,’&commission’)
new 1: insert into employee values(102,’rohith’,’analyst’,2345,9000,’65’)
1 row created.

c. Update the column details of job

SQL> update employee set job=’trainee’ where empno=103; 1 row updated.


SQL> select * from employee;

EMPNO ENAME JOB MGR SAL COMMISSION

101 abhi manager 1234 10000 70


102 rohith analyst 2345 9000 65
103 david trainee 3456 9000 65
104 rahul Clerk 4567 7000 55
105 pramod salesman 5678 5000 50

d. Rename the column of Employ table using alter command.

SQL> alter table employee rename column mgr to manager_no;

Table altered.

SQL> desc employee;

Name Null? Type


EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MANAGER_NO NUMBER
SAL NUMBER
COMMISSION NUMBER

2) Create department table with the following structure.

Name Type
Deptno Number
Deptname Varchar2(10)
location Varchar2(10)

a. Add column designation to the department table.


b. Insert values into the table.
c. List the records of dept table grouped by deptno.
d. Update the record where deptno is 9.

Page 12
e. Delete any column data from the table.

SOLUTION:

SQL> create table department(deptno number,deptname varchar2(10),location varchar2(10));

Table created.

SQL> desc department;

DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)

a. Add column designation to the department table.

SQL> alter table department add(designation varchar2(10));

Table altered.

SQL> desc department;

DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)
DESIGNATION VARCHAR2(10)

b. Insert values into the table.

SQL> insert into department values(&deptno,’&deptname’,’&location’,&designation’);


Enter value for deptno: 9
Enter value for deptname: accounting Enter value for location: hyderabad Enter value for designation:
manager
old 1: insert into department values(&deptno,’&deptname’,’&location’,’&designation’)
new 1: insert into department values(9,’accounting’,’hyderabad’,’manager’)

1 row created.

SQL> /

Enter value for deptno: 10


Enter value for deptname: research Enter value for location: chennai Enter value for designation:
professor
old 1: insert into department values(&deptno,’&deptname’,’&location’,’&designation’)
new 1: insert into department values(10,’research’,’chennai’,’professor’)

1 row created.

c. List the records of dept table grouped by deptno.

SQL> select deptno,deptname from department group by deptno,deptname;

Page 13
DEPTNO DEPTNAME

9 accounting
12 operations
10 research
11 sales

d. Update the record where deptno is 9.

SQL> update department set designation=’accountant’ where deptno=9;

2 rows updated.

e. Delete any column data from the table.

SQL> alter table department drop(designation);

Table altered.

Probing Further Experiments

1.Create a table called Customer table

Name Type
Cust name Varchar2(20)
Cust street Varchar2(20)
Cust city Varchar2(20)

a. Insert records into the table.


b. Add salary column to the table.
c. Alter the table column domain.
d. Drop salary column of the customer table.
e. Delete the rows of customer table whose cust_city is hyd.

2. Create a table called branch table.

Name Type
Branch name Varchar2(20)
Branch city Varchar2(20)
Asserts Number

a. Increase the size of data type for asserts to the branch.


b. Add and drop a column to the branch table.
c. Insert values to the table.
d. Update the branch name column
e. Delete any two columns from the table

Viva Questions

1) What is DBMS?

2) What is a database?

Page 14
3) What is a database system?

4) What are the advantages of DBMS?

5) What is a checkpoint in DBMS?

Page 15
Lab 2 - QUERIES USING DDL AND DML

Introduction

DDL is short name of Data Definition Language, which deals with database schemas and descriptions,
of how the data should reside in the database. And DML is short name of Data Manipulation Lan-
guage which deals with data manipulation and includes most common SQL statements such SELECT,
INSERT, UPDATE, DELETE, etc., and it is used to store, modify, retrieve, delete and update data
in a database.

Objective

By the end of this lab, the student should learn how to grant permissions, create the tables, inserting
values into the tables and updating the tables.

PreLab

• Prior coming to the lab, student should come have knowledge on DDL commands, DML commands
and TCL Commands.

Software Needed

Oracle 10g Express Edition.

Background

SQL Commands

DDL: Data Definition Language (DDL) statements are used to define the database structure or schema.

DDL Commands: Create, Alter, Drop, Rename, Truncate

CREATE - to create objects in the database


ALTER - alters the structure of the database DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are re-
moved RENAME - rename an object

DML: Data Manipulation Language (DML) statements are used for managing data within schema
objects and to manipulate data of a database objects.

DML Commands: Insert, Update, Delete, Select

INSERT - insert data into a table


UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
SELECT - retrieve data from the a database

Create table by using Constraints:

Constraints are two types:

1. Table Level Constraints.

Page 16
2. Column Level Constraints.

1. NOT NULL:

a) Not null constraint at column level.

Syntax:

<col><datatype>(size)not null

SQL > create table emp(e_id varchar(5) NOT NULL,e_name varchar(10), e_design varchar(10),dept
varchar(10),mgr varchar(10),salary number(10));

2. UNIQUE :

Unique constraint at column level. Syntax: <col><datatype>(size)unique

Ex:- SQL > create table depositor(customer_name varchar(10),acc_no number(15) UNIQUE, brach_name
varchar(10));

Unique constraint at table level:

Syntax:

Create table tablename(col=format,col=format,unique(<col1>,<col2>));

Ex:-

SQL > create table depositor1(customer_name varchar(10),acc_no number(15), brach_name var-


char(10),UNIQUE(acc_no));

3. PRIMARY KEY:

Primary key constraint at column level

Syntax:

<col><datatype>(size)primary key;

Ex:-

SQL> create table customer(customer_id number (5) PRIMARY KEY, customer_name varchar(10),cus-
tomer_street varchar(10),brach_name varchar(10));

Primary key constraint at table level.

Syntax:

Create table tablename(col=format,col=format primary key(col1>,<col2>);

Ex:-

Page 17
SQL > create table customer1(customer_id number (5),customer_name varchar(10),customer_street
varchar(10),brach_name varchar(10),PRIMARY KEY(customer_id));

4. CHECK:

Check constraint constraint at column level.

Syntax: <col><datatype>(size) check(<logical expression>)

Ex:-create table loan(loan_no varchar(10),customer_name varchar(10), balance number (10) CHECK(bal-


ance>1000));

Check constraint constraint at table level.

Syntax: check(<logical expression>)

Ex:- create table loan1(loan_no varchar(10),customer_name varchar(10), balance number (10), CHECK(bal-
ance>1000));

5. FOREIGN KEY:

Foreign key constraint at column level.

Syntax:

Column_name Datatype(size) REFERENCES parent_table_name (parent_column_name)


Ex:- CREATE TABLE books (book_id NUMBER(3), book_title VARCHAR2(30), book_price NUM-
BER(3), book_author_id NUMBER(3) REFERENCES author(author_id ) );

Foreign key constraint at table level

Syntax:

CONSTRAINT constraint_name FOREIGN KEY(child_table_column) REFERENCES Parent_ta-


ble_name(parent_table_column)

Ex:-CREATE TABLE books (book_id NUMBER(3) CONSTRAINT bok_bi_pk PRIMARY KEY,


book_title VARCHAR2(30), book_price NUMBER(3), book_author_id NUMBER(3),CONSTRAINT
bok_ai_fk FOREIGN KEY (book_author_id) REFERENCES author(author_id) );

Procedure

Step 1: Go to run sql command line


Step 2: Connect to the database using username and password
Step 3: Create table and update the table by using DDL and DML commands

1. a. Create a user and grant all permissions to the user.


b. Insert the any three records in the employee table and use rollback. Check the result.
c. Add primary key constraint and not null constraint to the employee table.
d. Insert null values to the employee table and verify the result.

Page 18
SOLUTION:

a) create a user and grant all permissions to the user.

CONNECT <USER-NAME>/<PASSWORD>@<DATABASE NAME>;

–Create user query

CREATE USER <USER NAME> IDENTIFIED BY <PASSWORD>;

–Provide roles

GRANT CONNECT,RESOURCE,DBA TO <USER NAME>;

–Assigning privileges

GRANT CREATE SESSION

GRANT ANY PRIVILEGE TO <USER NAME>; GRANT UNLIMITED TABLESPACE TO <USER


NAME>;

–Provide access to tables.

GRANT SELECT, UPDATE, INSERT, DELETE ON <TABLE NAME> TO <USER NAME>;

b) Insert the any three records in the employee table and use rollback. Check the result.

SQL> SELECT * FROM EMPLOYEE;

EMPNO ENAME JOB MANAGER_NO SAL COMMISSION

101 abhi manager 1234 1100 70


102 rohith analyst 2345 9000 65
103 david trainee 3456 9000 65
104 rahul clerk 4567 7000 55

SQL> insert into employee values(&empno,’&ename’,’&job’,&manager_no,&sal,&commission);

Enter value for empno: 105

Enter value for ename: aravind


Enter value for job: salesman
Enter value for manager_no: 5678
Enter value for sal: 5000
Enter value for commission: 50

old 1: insert into employee values(&empno,’&ename’,’&job’,&manager_no,&sal,&commission)

new 1: insert into employee values(105,’aravind’,’salesman’,5678,5000,50)

1 row created.

Page 19
SQL> rollback;

Rollback complete.

c) Add primary key constraint and not null constraint to the employee table.

SQL> alter table employee modify(empno number primary key, ename varchar2(10) not null);

Table altered.

SQL> desc employee;

Name Null? Type

EMPNO NOT NULL NUMBER


ENAME NOT NULL VARCHAR2(10)
JOB VARCHAR2(10)
MANAGER_NO NUMBER
SAL NUMBER
COMMISSION NUMBER

d) Insert null values to the employee table and verify the result.

SQL> desc employee;

Name Null? Type

EMPNO NOT NULL NUMBER


ENAME NOT NULL VARCHAR2(10)
JOB NOT NULL VARCHAR2(10)
MANAGER_NO NUMBER
SAL NOT NULL NUMBER
COMMISSION NUMBER

SQL> insert into employee values(&empno,’&ename’,’&job’,&manager_no,&sal,&commission);

Enter value for empno: 105


Enter value for ename: mohith
Enter value for job: salesman
Enter value for manager_no: 5678

Enter value for sal: null


Enter value for commission: 50

old 1: insert into employee values(&empno,’&ename’,’&job’,&manager_no,&sal,&commission)

new 1: insert into employee values(105,’mohith’,’salesman’,5678,null,50)

2. a. create a user and grant all permissions to the user.


b. Insert values in the department table and use commit.
c. Add constraints like unique and not null to the department table.
d. Insert repeated values and null values into the table.

Page 20
SOLUTION:

a) create a user and grant all permissions to the user.

CONNECT <USER-NAME>/<PASSWORD>@<DATABASE NAME>;

–Create user query

CREATE USER <USER NAME> IDENTIFIED BY <PASSWORD>;

–Provide roles

GRANT CONNECT,RESOURCE,DBA TO <USER NAME>;

–Assigning privileges

GRANT CREATE SESSION GRANT ANY PRIVILEGE TO <USER NAME>; GRANT UNLIM-
ITED TABLESPACE TO <USER NAME>;

–Provide access to tables.

GRANT SELECT, UPDATE, INSERT, DELETE ON <TABLE NAME> TO <USER NAME>;

b) Insert values in the department table and use commit.

SQL> insert into department values(&deptno,’&deptname’,’&location’); Enter value for deptno: 13

Enter value for deptname: sales


Enter value for location: delhi

old 1: insert into department values(&deptno,’&deptname’,’&location’)

new 1: insert into department values(13,’sales’,’delhi’)

1 row created.

SQL> commit;

Commit complete.

SQL> select * from department;

DEPTNO DEPTNAME LOCATION

9 accounting Hyderabad
10 research Chennai
11 sales Banglore
12 operations Mumbai
9 accounting Chennai
13 sales Delhi

Page 21
6 rows selected.

c) Add constraints like unique and not null to the department table.

SQL> alter table department modify(deptno number unique);

Table altered.

SQL> alter table department modify(location varchar2(10) not null);

Table altered.

SQL> DESC DEPARTMENT;

Name Null? Type

DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION NOT NULL VARCHAR2(10)

d) Insert repeated values and null values into the table.

SQL> insert into department values(&deptno,’&deptname’,’&location’);

Enter value for deptno: 10


Enter value for deptname: research
Enter value for location:hyd

old 1: insert into department values( &deptno,’&deptname’,’&location’)

new 1: insert into department values(10,’research’,”)

insert into department values(10,’research’,”)

SQL> insert into department values(&deptno,’&deptname’,’&location’); Enter value for deptno: 10

Enter value for deptname: research


Enter value for location: hyderabad

old 1: insert into department values(&deptno,’&deptname’,’&location’)

new 1: insert into department values(10,’research’,’hyderabad’)

Probing Further Experiments

1 a. create a user and grant all permissions to the user.


b. Insert values into the table and use commit.
c. Delete any three records in the department table and use rollback.
d. Add constraint primary key and foreign key to the table.

2 a. create a user and grant all permissions to the user.


b. Insert records in the sailor table and use commit.

Page 22
c. Add save point after insertion of records and verify save point.
d. Add constraints not null and primary key to the sailor table.

3 a. create a user and grant all permissions to the user.


b. Use revoke command to remove user permissions.
c. Change password of the user created.
d. Add constraint foreign key and not null.

4 a. create a user and grant all permissions to the user.


b. Update the table reserves and use savepoint and rollback.
c. Add constraint primary key, foreign key and not null to the reserves table
d. Delete constraint not null to the table column.

Viva Questions

1. When does checkpoint occur in DBMS?

2. What do you mean by transparent DBMS?

3. What are the unary operations in Relational Algebra?

4. What is RDBMS?

5. How many types of database languages are?

Page 23
Lab 3 – QUERIES USING AGGREGATE FUNCTIONS

Introduction

In database management an aggregate function is a function where the values of multiple rows are
grouped together as input on certain criteria to form a single value of more significant meaning. Var-
ious Aggregate Functions are there such as count, sum, avg, min, max.

Objectives

By the end of this lab, the student should learn how various aggregate functions works and advantages
of using aggregate functions.

Prelab

Prior coming to the lab, student should come have knowledge on Aggregate Functions and syntax of
Aggregate Functions.

Software Needed

Oracle 10g Express Edition

Background

An SQL aggregate function calculates on a set of values and returns a single value. For example, the
average function ( AVG) takes a list of values and returns the average.

Because an aggregate function operates on a set of values, it is often used with the GROUP BY clause
of the SELECT statement. The GROUP BY clause divides the result set into groups of values and
the aggregate function returns a single value for each group.

The following are the commonly used SQL aggregate functions:

• AVG() – returns the average of a set.


• COUNT() – returns the number of items in a set.
• MAX() – returns the maximum value in a set.
• MIN() – returns the minimum value in a set
• SUM() – returns the sum of all or distinct values in a set

Procedure

Step 1: Go to run sql command line


Step 2: Connect to the database using username and password
Step 3: Create table and update the table by using DDL and DML commands

(i) Create Employee table containing all Records.

SQL> create table emp(eid number,ename varchar2(10),age number,salary number);

Table created.

Page 24
SQL> desc emp;

Name Null? Type

EID NUMBER

ENAME VARCHAR2(10)

AGE NUMBER

SALARY NUMBER

(ii) Count number of employee names from employee table.

SQL> select count(ename) from emp; COUNT(ENAME)

(iii) Find the Maximum age from employee table.

SQL> select max(age) from emp; MAX(AGE)

44

(iv) Find the Minimum age from employee table.

SQL> select min(age) from emp; MIN(AGE)

22

(v) Display the Sum of age employee table.

SQL> select sum(age) from emp; SUM(AGE)

220

(vi) Display the Average of age from Employee table.

SQL> select avg(age) from emp; AVG(AGE)

31.4285714

(vii) Create a View for age in employee table.

SQL> create or replace view A as select age from emp where age<30;

View created.

(viii) Display views

SQL> select * from A;

Page 25
AGE

22
29
27
29

(ix) Find grouped salaries of employees.(group by clause)

SQL> select salary from emp group by salary;

SALARY

9000
10000
8000
6000
7000

(x).Find salaries of employee in Ascending Order.(order by clause)

SQL> select ename,salary from emp order by salary;

ENAME SALARY

rohan 6000
Alex 7000
shane 8000
abhi 8000
tiger 8000
Anu 9000
scott 10000

7 rows selected.

(xi) Find salaries of employee in Descending Order.

SQL> select ename,salary from emp order by salary desc;

ENAME SALARY

scott 10000
anu 9000
shane 8000
Abhi 8000
Tiger 8000
Alex 7000
Rohan 6000

7 rows selected.

(xii) Having Clause.

Page 26
SQL> select ename,salary from emp where age<29 group by ename,salary having salary<10000;

ENAME SALARY

alex 7000

anu 9000

Probing Further Experiments

1:
a) By using the group by clause, display the enames who belongs to deptno 10 along with average
salary.
b) Display lowest paid employee details under each department.
c) Display number of employees working in each department and their department number.
d) Using built in functions, display number of employees working in each department and their de-
partment name from dept table. Insert deptname to dept table and insert deptname for each row, do
the required thing specified above.
e) List all employees which start with either B or C.
f) Display only these ename of employees where the maximum salary is greater than or equal to 5000.

2:
a) Calculate the average salary for each different job.
b) Show the average salary of each job excluding manager.
c) Show the average salary for all departments employing more than three people.
d) Display employees who earn more than the lowest salary in department 30
e) Show that value returned by sign (n) function.
f) How many days between day of birth to current date.

3:
a) Show that two substring as single string.
b) List all employee names, salary and 15c) Display lowest paid emp details under each manager
d) Display the average monthly salary bill for each deptno.
e) Show the average salary for all departments employing more than two people.
f) By using the group by clause, display the eid who belongs to deptno 05 along with average salary.

4:
a) Count the number of employees in department 20
b) Find the minimum salary earned by clerk.
c) Find minimum, maximum, average salary of all employees.
d) List the minimum and maximum salaries for each job type
e) List the employee names in descending order.
f) List the employee id, names in ascending order by empid.

5:
a) Find the sids ,names of sailors who have reserved all boats called “INTERLAKE
b) Find the age of youngest sailor who is eligible to vote for each rating level with at least two such
sailors.
c) Find the sname , bid and reservation date for each reservation.
d) Find the ages of sailors whose name begin and end with B and has at least 3 characters.
e) List in alphabetic order all sailors who have reserved red boat.

Page 27
f) Find the age of youngest sailor for each rating level.

Viva Questions

1. What do you understand by Data Model?

2. Define a Relation Schema and a Relation.

3. What is a degree of Relation?

4. What is the Relationship?

5. What are the disadvantages of file processing systems?

Page 28
LAB 4-PROGRAMS ON PL/SQL

Introduction

PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL. PL/SQL is one
of three key programming languages embedded in the Oracle Database, along with SQL itself and Java.

Objective
By the end of this lab, the student should learn how to write programs by using PL/SQL.

Prelab

Prior coming to the lab, student should have a basic understanding of SQL Commands.

Software Needed

Oracle 10g Express Edition

Background

SQL Commands

DDL: Data Definition Language (DDL) statements are used to define the database structure or schema.

DDL Commands: Create, Alter, Drop, Rename, Truncate

CREATE - to create objects in the database


ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are re-
moved
RENAME - rename an object

DML: Data Manipulation Language (DML) statements are used for managing data within schema
objects and to manipulate data of a database objects.

DML Commands: Insert, Update, Delete, Select

INSERT - insert data into a table


UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
SELECT - retrieve data from the a database

Procedure

Step 1: Go to run sql command line


Step 2: Connect to the database using username and password
Step 3: Write a pl/sql program.
Step 4: Execute

Page 29
1 a) Write a PL/SQL block to find the maximum number from given three numbers.

declare
a number; b number; c number;
begin
a:=&a;
b:=&b;
c:=&c;
if (a>b and a>c) then
dbms_output.put_line(’a is maximum ’ || a); elsif (b>a and b>c) then
dbms_output.put_line(’b is maximum ’ || b);
else
end if;
end;
/
dbms_output

1b) write a PL/SQL program for swapping 2 numbers.

declare
a number(3); b number(3);
begin
a:=&a;
b:=&b;
dbms_output.put_line(Before swapping a= ||a|| and b= ||b);
a:=a+b;
b:=a-b;
a:=a-b;
dbms_output.put_line(After swapping a= ||a|| and b= ||b);
end;
/

2 a) Write a PL/SQL program to find the total and average of 4 subjects and display
the grade

declare
java number(10); dbms number(10); co number(10); mfcs number(10); total number(10); avgs num-
ber(10); per number(10);
begin
dbms_output.put_line(’ENTER THE MARKS’);
java:=&java; dbms:=&dbms; co:=&co; mfcs:=&mfcsl;
total:=(java+dbms+co+mfcs); per:=(total/600)*100;
if java<40 or dbms<40 or co<40 or mfcs<40 then dbms_output.put_line(’FAIL’);
if per>75 then dbms_output.put_line(’GRADE A’);
elsif per>65 and per<75 then dbms_output.put_line(’GRADE B’);
elsif per>55 and per<65 then dbms_output.put_line(’GRADE C’);
else
dbms_output.put_line(’INVALID INPUT’);
end if;
dbms_output.put_line(’PERCENTAGE IS ’||per);
end;
/

Page 30
2 b) Write a program to accept a number and find the sum of the digits

declare
n number(5):=&n; s number:=0;
r number(2):=0;
begin
while n !=0 loop r:=mod(n,10); s:=s+r; n:=trunc(n/10);
end loop;
dbms_output.put_line(’sum of digits of given number is ’||s);
end;
/

3 a) PL/SQL Program to accept a number from user and print number in reverse order.

declare
num1 number(5); num2 number(5); rev number(5); begin num1:=&num1; rev:=0;
while num1>0 loop
num2:=num1 mod 10; rev:=num2+(rev*10); num1:=floor(num1/10);
end loop;
dbms_output.put_line(’Reverse number is: ’||rev);
end;
/

3b) Write a PL / SQL program to check whether the given number is prime or not.

declare
num number; i number:=1; c number:=0;
begin
num:=&num; for i in 1..num loop
if((mod(num,i))=0) then
c:=c+1;
end if;
end loop;
if(c>2) then
dbms_output.put_line(num||’ not a prime’);
else
dbms_output.put_line(num||’ is prime’);
end if;
end;
/

4 a) Write a PL/SQL program to find the factorial of a given number.

declare
i number(4):=1;
n number(4):=&n; f number(4):=1;
begin
for i in 1..n loop
f:=f*i;
end loop;
Dbms_output.put_line(’the factorial of ’||n||’ is:’||f);

Page 31
end;
/

4 b) calculate the area of a circle for a value of radius varying from 3 to 7. Store the
radius and the corresponding values of calculated area in table areas. Consisting of two
columns radius and area

Declare
pi constant number(4,2) := 3.14; radius number(5);
area number(14,2);
Begin radius := 3;
While radius <=7 Loop
area := pi* power(radius,2);
Insert into areas values (radius, area);
radius:= radius+1;
end loop;
end;
/

5a) Write a PL/SQL program to accept a string and remove the vowels from the string.
(When ‘hello’ passed to the program it should display ‘Hll’ removing e and o from the
world Hello).

set serveroutput on
set verify off
accept vstring prompt ”Please enter your string: ”;
declare
vnewstring varchar2(100);
begin
vnewstring := regexp_replace(’&vstring’, ’[aeiouAEIOU]’,”);
dbms_output.put_line(’The new string is: ’ || vnewstring);
end;
/

Probing Further Experiments

1. Write a PL/SQL program to accept a number and a divisor. Make sure the divisor is less than or
equal to 10. Else display an error message. Otherwise Display the remainder

VIiva Questions

1. What is data abstraction in DBMS?

2. What are the three levels of data abstraction?

3. What is DDL (Data Definition Language)?

4. What is DML (Data Manipulation Language)?

5. Explain the functionality of DML Compiler.

Page 32
Lab 5 - PROCEDURES AND FUNCTIONS

Introduction

A procudure is a named PL/SQL block which performs one or more specific task. This is similar to
a procedure in other programming languages. A procedure has a header and a body.The header con-
sists of the name of the procedure and the parameters or variables passed to the procedure. The body
consists or declaration section, execution section and exception section similar to a general PL/SQL
Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

A function is a named PL/SQL Block which is similar to a procedure. The major difference between
a procedure and a function is, a function must always return a value, but a procedure may or may
not return a value.

Objective
By the end of this lab, the student should learn how to write and execute Procedures and Functions
related programs by using PL/SQL .

PreLab
Prior coming to the lab, student should have strong knowledge on procedures and function concepts.

Software Needed

Oracle 10g Express Edition

Background

Students should have knowledge on procedures and functions concepts and syntax’s for creating pro-
cedure and function.
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows –

Where,
• procedure-name specifies the name of the procedure.
• [OR REPLACE] option allows the modification of an existing procedure.
• The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to return
a value outside of the procedure.
• procedure-body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone procedure.

Page 33
{Syntax to create a function:}

CREATE [OR REPLACE] FUNCTION function_name


RETURN return_datatype
{IS | AS}
BEGIN
program code
EXCEPTION
exception_section;
END function_name;

Procedure

Step 1: Go to run sql command line


Step 2: Connect to the database using username and password
Step 3: Write a pl/sql procedure/function program.
Step 4: Execute the procedure/function.

1) calculate the net salary and year salary if da is 30% of basic, hra is 10% of basic and
pf is 7% if basic salary is less than 8000, pf is 10% if basic sal between 8000 to 160000.

declare
ename varchar2(15); basic number;
da number; hra number; pf number;
netsalary number; yearsalary number;
begin
ename:=’&ename’; basic:=&basic; da:=basic * (30/100); hra:=basic * (10/100);
if (basic < 8000) then
pf:=basic * (8/100);
elsif (basic >= 8000 and basic <= 16000) then
pf:=basic * (10/100);
end if;
netsalary:=basic + da + hra - pf; yearsalary := netsalary*12;
dbms_output.put_line(’Employee name : ’ || ename);
dbms_output.put_line(’Providend Fund : ’ || pf); dbms_output.put_line(’Net salary : ’ || netsalary);
dbms_output.put_line(’Year salary : ’|| yearsalary); end;
/

2) Create a function to find the factorial of a given number and hence find NCR.

SQL> create or replace function fact(n number) return number is a number:=n; f number:=1; i num-
ber;
begin
for i in 1..n loop f:=f*a; a:=a-1;
end loop;
return f;
end;
/

SQL> create or replace function ncr(n number ,r number)


return number

Page 34
is
n1 number:=fact(n);
r1 number:=fact(r);
nr1 number:=fact(n-r);
result number;
begin result:=(n1)/(r1*nr1);
return result;
end;
/

3) Print Fibonacci series using local functions.

sql>create or replace function fib (n positive) return integer is begin if (n = 1) or (n = 2) then –


terminating condition return 1;
else
return fib(n - 1) + fib(n - 2); – recursive call end if;
end fib;
/

– Test Fibonacci Series:


SQL>SELECT fib(1), fib(2), fib(3), fib(4), fib(5) FROM dual;

4) write a pl/sql function accept date of birth as ”dd-mm-yyyy” and sum all digits till
you get single digit number to show as he lucky number.

SQL> set serverout on SQL>


declare
l_input varchar2(20) := ’31/01/1978’;
l_output int;
begin loop
dbms_output.put_line(’ ’);
dbms_output.put_line(’l_input=’||l_input); l_output := 0;
for i in 1 .. length(l_input) loop
if substr(l_input,i,1) between ’0’ and ’9’ then
l_output := l_output + to_number(substr(l_input,i,1));
end if;
end loop; dbms_output.put_line(’l_output=’||l_output);
exit
when l_output < 10;
l_input := to_char(l_output);
end loop;
dbms_output.put_line(’ ’);
dbms_output.put_line(’Lucky=’||l_output);
end;
/
l_input=31/01/1978 l_output=30
l_input=30 l_output=3
Lucky=3

PL/SQL procedure successfully completed.

Page 35
Probing Further Experiments

1.Write the PL/SQL programs to create the procedure to find sum of N natural number.

2.Write the PL/SQL programs to create the procedure to find Fibonacci series.

3.Write the PL/SQL programs to create the procedure to check the given number is perfect or not.

Viva Questions

1. What is Relational Algebra?

2. What is Relational Calculus?

3. What do you understand by query optimization?

4. What do you mean by durability in DBMS?

5. What is normalization?

Page 36
Lab-6 - TRIGGERS

Introduction

A trigger is a set of SQL statements that reside in system memory with unique names. It is a special-
ized category of stored procedure that is called automatically when a database server event occurs.
Each trigger is always associated with a table.

A trigger is called a special procedure because it cannot be called directly like a stored procedure.
The key distinction between the trigger and procedure is that a trigger is called automatically when
a data modification event occurs against a table. A stored procedure, on the other hand, must be
invoked directly.

Objective

By the end of this lab, the student should learn how to create triggers and when to use triggers.

Prelab

Prior coming to the lab, student should have a basic understanding of DML, TCL languages and
triggers.

Software Needed

Oracle 10g Express Edition

Background

Students should know about triggers and syntax to create trigger.

Syntax:

1. CREATE TRIGGER schema.trigger_name


2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}

Procedure

Step 1: Go to run sql command line


Step 2: Connect to the database using username and password
Step 3: Create a trigger.
Step 4: Execute the trigger.

1. Create a row level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger
will display the salary difference between the old values and new values:

CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT OR


UPDATE ON customers FOR EACH ROW

Page 37
WHEN (NEW.ID > 0) DECLARE
sal_diff number; BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line(’Old salary: ’ || :OLD.salary);
dbms_output.put_line(’New salary: ’ || :NEW.salary); dbms_output.put_line(’Salary difference: ’
|| sal_diff);
END;
/

Trigger created.

Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, ’Kriti’, 22, ’HP’,


7500.00 );

When a record is created in CUSTOMERS table, above create trigger display_salary_changes will
be fired and it will display the following result:

Old salary:
New salary: 7500 Salary difference:

2) Convert employee name into uppercase whenever an employee record is inserted or


updated. Trigger to fire before the insert or update.

SQL> create table Employee(


2 ID VARCHAR2(4 BYTE) NOT NULL,
3 First_Name VARCHAR2(10 BYTE),
4 Last_Name VARCHAR2(10 BYTE),
5 Start_Date DATE,
6 End_Date DATE,
7 Salary NUMBER(8,2),
8 City VARCHAR2(10 BYTE),
9 Description VARCHAR2(15 BYTE) 10 )
11 /

Table created.

SQL> CREATE OR REPLACE TRIGGER employee_insert_update


2 BEFORE INSERT OR UPDATE ON employee
3 FOR EACH ROW
4 DECLARE
5 dup_flag INTEGER;
6 BEGIN
7 –Force all employee names to uppercase.
8 :NEW.first_name := UPPER(:NEW.first_name);
9 END; 10 /

Trigger created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)

Page 38
2 values (’01’,’Jason’, ’Martin’, to_date(’19960725’,’YYYYMMDD’), to_date(’20060725’,’YYYYM-
MDD’), 1234.56, ’Toronto’, ’Programmer’)
3/

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’02’,’Alison’, ’Mathews’, to_date(’19760321’,’YYYYMMDD’), to_date(’19860221’,’YYYYM-
MDD’), 6661.78, ’Vancouver’,’Tester’)
3/

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’03’,’James’, ’Smith’, to_date(’19781212’,’YYYYMMDD’), to_date(’19900315’,’YYYYM-
MDD’), 6544.78, ’Vancouver’,’Tester’)
3/

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’04’,’Celia’, ’Rice’, to_date(’19821024’,’YYYYMMDD’), to_date(’19990421’,’YYYYMMDD’),
2344.78, ’Vancouver’,’Manager’)
3/

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’05’,’Robert’, ’Black’, to_date(’19840115’,’YYYYMMDD’), to_date(’19980808’,’YYYYM-
MDD’), 2334.78, ’Vancouver’,’Tester’)
3/

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’06’,’Linda’, ’Green’, to_date(’19870730’,’YYYYMMDD’), to_date(’19960104’,’YYYYMMDD’),
4322.78,’New York’, ’Tester’)
3/

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’07’,’David’, ’Larry’, to_date(’19901231’,’YYYYMMDD’), to_date(’19980212’,’YYYYMMDD’),
7897.78,’New York’, ’Manager’)
3/

Page 39
1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary, City, De-
scription)
2 values(’08’,’James’, ’Cat’, to_date(’19960917’,’YYYYMMDD’), to_date(’20020415’,’YYYYMMDD’),
1232.78,’Vancouver’, ’Tester’)
3/

1 row created.

SQL> select * from Employee


2/
ID FIRST_NAME ,LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION

01 JASON Martin 25-JUL-96 25-JUL-06 1234.56 Toronto Programmer


02 ALISON Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester
03 JAMES Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester
04 CELIA Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager
05 ROBERT Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester
06 LINDA Green 30-JUL-87 04-JAN-96 4322.78 New York Tester
07 DAVID Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager
08 JAMES Cat 17-SEP-96 15-APR-02 1232.78 Vancouver Tester

8 rows selected.

SQL> drop table Employee


2/

Table dropped.

3) Trigger before deleting a record from emp table. Trigger will insert the row to be
deleted into another table and also record the user who has deleted the record.

SQL> CREATE OR REPLACE TRIGGER employee_before_delete


2 BEFORE DELETE
3 ON employee
4 FOR EACH ROW
5 DECLARE
6 v_username varchar2(10);
7 BEGIN
8 – Find username of person performing the DELETE on the table
9 SELECT user INTO v_username
10 FROM dual;
11 – Insert record into audit table
12 INSERT INTO employee_audit (id, salary, delete_date,deleted_by )
13 VALUES (:old.id,:old.salary, sysdate, v_username );
14 END;
15 /

Trigger created.

SQL> delete from employee;

Page 40
8 rows deleted.

SQL> select * from employee_audit;

ID SALARY DELETE_DA DELETED_BY

01 1234.56 09-SEP-06 JAVA2S


02 6661.78 09-SEP-06 JAVA2S
03 6544.78 09-SEP-06 JAVA2S
04 2344.78 09-SEP-06 JAVA2S
05 2334.78 09-SEP-06 JAVA2S
06 4322.78 09-SEP-06 JAVA2S
07 7897.78 09-SEP-06 JAVA2S
08 1232.78 09-SEP-06 JAVA2S

8 rows selected.

SQL> drop table employee_audit;

Table dropped.

Probinh Further Experiments

1. Creation of insert trigger, delete trigger, update trigger practice triggers using the passenger
database. Passenger( Passport_ id INTEGER PRIMARY KEY, Name VARCHAR (50) Not NULL,
Age Integer Not NULL, Sex Char, Address VARCHAR (50) Not NULL); Write a Insert Trigger to
check the Passport_id is exactly six digits or not. Write a trigger on passenger to display messages „1
Record is inserted�, „1 record is deleted�, „1 record is updated� when insertion, deletion and updation
are done on passenger respectively.

2. Insert row in employee table using Triggers. Every trigger is created with name any trigger have
same name must be replaced by new name. These triggers can raised before insert, update or delete
rows on data base. The main difference between a trigger and a stored procedure is that the former
is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs.

3. Create a transparent audit system for a table CUST_MSTR. The system must keep track of the
records that are being deleted or updated.

Viva Questions:

1 What is Denormalization?

2 What is functional Dependency?

3 What is the E-R model?

4 What is an entity?

5 What is an Entity type?

Page 41
Lab 7 - PROCEDURES

Introduction
A procudure is a named PL/SQL block which performs one or more specific task. This is similar to
a procedure in other programming languages. A procedure has a header and a body The header con-
sists of the name of the procedure and the parameters or variables passed to the procedure. The body
consists or declaration section, execution section and exception section similar to a general PL/SQL
Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

Objective

By the end of this lab, the student should learn how to write and execute Procedures and Functions
related programs by using PL/SQL .

Prelab

Prior coming to the lab, student should have strong knowledge on procedures and function concepts.

Software Needed

Oracle 10g Express Edition

Background

Students should have knowledge on procedures and functions concepts and syntax’s for creating pro-
cedure and function. A procedure is created with the CREATE OR REPLACE PROCEDURE state-
ment. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows –

Where,
• procedure-name specifies the name of the procedure.
• [OR REPLACE] option allows the modification of an existing procedure.
• The optional parameter list contains name, mode and types of the parameters.
IN represents the value that will be passed from outside and OUT represents the parameter that will
be used to return a value outside of the procedure.
• procedure-body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone procedure.

Procedure

Step 1: Go to run sql command line

Page 42
Step 2: Connect to the database using username and password
Step 3: Write a pl/sql procedure/function program.
Step 4: Execute the procedure/function.

1. Create a procedure to reverse a string.

CREATE OR REPLACE PROCEDURE ReverseOf(input IN varchar2(50)) IS DECLARE reverse


varchar2(50);
BEGIN
FOR i in reverse 1..length(input) LOOP reverse := reverse||”||substr(input, i, 1);
END LOOP;
dbms_output.put_line(reverse);
END;
/

Probing Further Experiments

1. Create the procedure for palindrome of given number.

2. Create the procedure for GCD: Program should load two registers with two Numbers and then
apply the logic for GCD of two numbers. GCD of two numbers is performed by dividing the greater
number by the smaller number till the remainder is zero. If it is zero, the divisor is the GCD if not
the remainder and the divisors of the previous division are the new set of two numbers. The process
is repeated by dividing greater of the two numbers by the smaller number till the remainder is zero
and GCD is found.

3. Write the PL/SQL programs to create the procedure for factorial of given number.

Viva Questions

1. What is an Entity set?

2. What is an Extension of entity type?

3. What is Weak Entity set?

4. What is an attribute?

5. What are the integrity rules in DBMS?

Page 43
Lab 8-CURSORS

Introduction

The ‘Cursor’ is the PL/SQL construct that allows the user to name the work area and access the stored
information in it. Cursors are used when the user needs to update records in a singleton fashion or in
a row by row manner, in a database table.
The Data that is stored in the Cursor is called the Active Data Set. Oracle DBMS has another pre-
defined area in the main memory Set, within which the cursors are opened.

Objective
By the end of this lab, the student should learn how to write and execute programs by using Cursors.

Prelab

Prior coming to the lab, student should have a basic understanding of DML, TCL languages and
triggers.

Software Needed

Oracle 10g Express Edition

Background

Students should know about triggers and syntax to create trigger.

Syntax:

DECLARE cursor_name CURSOR


FOR select_statement;
OPEN cursor_name;
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursor_name;
END;
CLOSE cursor_name;
DEALLOCATE cursor_name;

Procedure

Step 1: Go to run sql command line


Step 2: Connect to the database using username and password
Step 3: Create a cursor
Step 4: Execute the cursor.

1.
declare
cursor xx is select empno,ename,sal from emp26; a_empno emp26.empno%type;
a_ename emp26.ename%type; a_sal emp26.sal%type;
begin open xx;
loop
fetch xx into a_empno,a_ename,a_sal;

Page 44
exit when xx% not found;
dbms_output.put_line(a_empno||’ ’||a_ename||’ ’||a_sal);
end loop;
close xx;
end;

SQL> /

Probing Further Experiments

1. Write a PL/SQL block that will display the name, dept no, salary of fist highest paid employees.

2. Update the balance stock in the item master table each time a transaction takes place in the item
transaction table. The change in item master table depends on the item id is already present in the
item master then update operation is performed to decrease the balance stock by the quantity specified
in the item transaction in case the item id is not present in the item master table then the record is
inserted in the item master table.

3. Write a PL/SQL block that will display the employee details along with salary using cursors.

4. To write a Cursor to display the list of employees who are working as a Managers or Analyst.

5. To write a Cursor to find employee with given job and deptno.

6. Write a PL/SQL block using implicit cursor that will display message, the salaries of all the em-
ployees in the „employee� table are updated. If none of the employee�s salary are updated we get a
message ’None of the salaries were updated’. Else we get a message like for example, ’Salaries for 1000
employees are updated’ if there are 1000 rows in „employee� table.

Viva Questions

1. What do you mean by extension and intension?

2. What is Data Independence?

3. What are the three levels of data abstraction?

4. What is Join?

5. What is 1NF?

Page 45
Lab 9 - CASE STUDY: BOOK PUBLISHING COMPANY

Introduction

ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.

Objective

By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.

Background

1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.

Procedure

A publishing company produces scientific books on various subjects. The books are written by authors
who specialize in one particular subject. The company employs editors who, not necessarily being
specialists in a particular area, each take sole responsibility for editing one or more publications.A
publication covers essentially one of the specialist subjects and is normally written by a single author.
When writing a particular book, each author works with on editor, but may submit another work for
publication to be supervised by other editors. To improve their competitiveness, the company tries to
employ a variety of authors, more than one author being a specialist in a particular subject.

Probing Further Questions

1. Analyze the data required.

2. Normalize the attributes.

3. Create the logical data model using E-R diagram

Page 46
Viva Questions

1. What is 2NF?

2. What is 3NF?

3. What is BCNF?

4. Explain ACID properties

5. What is stored procedure?

Page 47
Lab 10 -CASE STUDY: GENERAL HOSPITAL

Introduction

ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.

Objective

By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.

Background

1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.

Procedure

A General Hospital consists of a number of specialized wards (such as Maternity, Paediatry, Oncology,
etc). Each ward hosts a number of patients, who were admitted on the recommendation of their own
GP and confirmed by a consultant employed by the Hospital. On admission, the personal details of
every patient are recorded. A separate register is to be held to store the information of the tests
undertaken and the results of a prescribed treatment. A number of tests may be conducted for each
patient. Each patient is assigned to one leading consultant but may be examined by another doctor,
if required. Doctors are specialists in some branch of medicine and may be leading consultants for a
number of patients, not necessarily from the same ward.

Probing Further Experiments

1. Analyze the data required.

2. Normalize the attributes.

Page 48
3. Create the logical data model using E-R diagram

Viva Questions

1. What is the difference between a DELETE command and TRUNCATE command?

2. What is 2-Tier architecture?

3. What is the 3-Tier architecture?

4. What is the difference between a shared lock and exclusive lock?

5. Describe the types of keys?

Page 49
Lab 11 - CASE STUDY: CAR RENTAL COMPANY

Introduction

ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.

Objective

By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.

Background

1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.

Procedure

A database is to be designed for a Car Rental Co. (CRC). The information required includes a descrip-
tion of cars, subcontractors (i.e. garages), company expenditures, company revenues and customers.
Cars are to be described by such data as: make, model, year of production, engine size, and fuel type,
number of passengers, registration number, purchase price, purchase date, rent price and insurance
details. It is the company policy not to keep any car for a period exceeding one year. All major repairs
and maintenance are done by subcontractors (i.e. franchised garages), with whom CRC has long-term
agreements. Therefore the data about garages to be kept in the database includes garage names,
addresses, range of services and the like. Some garages require payments immediately after a repair
has been made; with others CRC has made arrangements for credit facilities. Company expenditures
are to be registered for all outgoings connected with purchases, repairs, maintenance, insurance etc.
Similarly the cash inflow coming from all sources - car hire, car sales, insurance claims - must be
kept of file. CRC maintains a reasonably stable client base. For this privileged category of customers
special credit card facilities are provided. These customers may also book in advance a particular car.
These reservations can be made for any period of time up to one month. Casual customers must pay a
deposit for an estimated time of rental, unless they wish to pay by credit card. All major credit cards
are accepted. Personal details (such as name, address, telephone number, driving license, number)
about each customer are kept in the database.

Page 50
Probing Further Experiments

1. Analyze the data required.

2. Normalize the attributes.

3. Create the logical data model using E-R diagram

Viva Questions

1. What is SQL?

2. What are the usages of SQL?

3. What are the subsets of SQL?

4. What is the purpose of DDL Language?

5. What is the purpose of DML Language?

Page 51
Lab 12 -CASE STUDY: STUDENT PROGRESS MONITORING SYSTEM

Introduction

ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER
model helps to systematically analyze data requirements to produce a well-designed database. The
ER Model represents real-world entities and the relationships between them
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database.

Objective

By the end of this lab, the student should learn how to draw E-R Diagram for the given case study.

Background

1. Determine the Entities in Your ERD. Start by identifying the “what”s in your system or architec-
ture.
2. Add Attributes to Each Entity.
3. Define the Relationships Between Entities.
4. Add Cardinality to Every Relationship.
5. Finish and Save Your ERD.

Procedure

A database is to be designed for a college to monitor students’ progress throughout their course of
study. The students are reading for a degree (such as BA, BA(Hons) MSc, etc) within the framework
of the modular system. The college provides a number of module, each being characterised by its code,
title, credit value, module leader, teaching staff and the department they come from. A module is co-
ordinated by a module leader who shares teaching duties with one or more lecturers. A lecturer may
teach (and be a module leader for) more than one module. Students are free to choose any module
they wish but the following rules must be observed: some modules require pre-requisites modules and
some degree programmes have compulsory modules. The database is also to contain some informa-
tion about students including their numbers, names, addresses, degrees they read for, and their past
performance (i.e. modules taken and examination results).

Page 52
Probing Further Experiments

1. Analyze the data required.

2. Normalize the attributes.

3. Create the logical data model using E-R diagram

Viva Questions

1. What is ER Diagram?

2. What is ER Model?

3. What is Entity?

4. What is relationship?

5. What is weak entity?

Page 53

You might also like