DBMS Lab Manual New Format

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 106

FRANCIS XAVIER ENGINEERING COLLEGE, TIRUNELVELI

DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS

LABORATORY MANUAL

21CS4611 - DATABASE MANAGEMENT SYSTEMS LABORATORY

ACADEMIC YEAR : 2022 – 2023 / EVEN SEMESTER


CLASS/SEM : II YEAR, B.TECH CS & BS / IV SEM

1
PREFACE
Learning is a process that requires class instructions and practice labs. If we omit any of
the above then the learning process is clearly flawed. This manual is an attempt to standalone
the lab instructions through the development of lab curriculum that is based on the class
curriculum. This manual is intended to be used by lab instructors, course instructors and
students.
The intent of this curriculum is to define a clear lab structure that can be followed by
the lab instructor and the students. Perhaps one of the greatest problems faced by lab
instructors is that they are unable to keep the students occupied for the entire duration of the
lab due to which the learning process is greatly hampered.
The labs have been developed in such a way that there is synchronization between the
class and the lab. The manual has been divided into 15 labs having duration of 3 hours each.
Students of the course are expected to carefully read the concept map before coming to the lab.
Students come to the lab with a design/program that will be handed over to the lab instructor
for further grading. The code/design is based on previous learning and experiments. Each lab
has a detailed walk-through task which provides a problem statement and its programmable
solution to the students. The students can raise queries about the code provided and the lab
instructor will guide the students on how the solution has been designed.
Thereafter predefined practice questions have been presented such that each question
has a fix duration and grade. Students are graded upon their accomplishments in these
practice tasks. At the end of the lab, the lab instructor will assign an unseen task to the
students. This unseen task contains all the concepts taught in the lab. These unseen tasks have
a higher level of complexity and generally have a greater gain in terms of marks.
What sets these labs apart is the fact that a clear grading criterion has been defined for
each lab. Students are aware of the grading criteria and are expected to meet the requirements
for successful completion of each lab.

2
COLLEGE VISION AND MISSION

College Vision

Our Vision is "To create innovative and vibrant young leaders and entrepreneurs in
Engineering and Technology for building India as a super knowledge power and blossom into a
University of excellence recognized globally".

College Mission

To provide education in Engineering with excellence and ethics and to reach the unreached.

3
COLLEGE QUALITY POLICY

We aim at continuous pursuit for excellence through

 Quality education tapped from National and International Resources


 Modular approach to channelize knowledge and programmed evaluation
of knowledge accumulated.
 Continuous reviewal and renewal of quality systems leading to quality
output.
 Producing Engineers with strong ethical and moral background.

4
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
Computer Science and Business Systems (CSBS) is one of the popular courses among engineering
aspirants which mainly focuses on computation, analysis of algorithms, programming languages,
program design, software engineering, computer hardware, computer networks and problem-
solving skills. This course was established in the year 2021 in Francis Xavier Engineering College. To
address the growing need of Engineering talents with skills in digital technology, TCS, in partnership
with leading academicians across India, has designed a 4 years undergraduate programme on
Computer Science titled “Computer Science and Business Systems.

This curriculum aims to ensure that the students graduating from the program not only know the
core topics of Computer Science but also develop an equal appreciation of humanities, human
values, Financial Management, Services Science & Service Operational Management, Marketing
Research, and Marketing Management.

5
DEPARTMENT VISION AND MISSION

Department Vision

To become a center of excellence in Information Technology and to generate young


Engineers with enriched knowledge to serve industries with high values and social
responsibilities.

Department Mission

 To provide world class teaching learning environment and to offer computing

education programs.
 To inculcate varied skill sets that meets global industry standards and to practice

moral values.
 To enrich moral and ethical values to lead and serve the society.

6
DEPARTMENT QUALITY POLICY

We aim at continuous pursuit for excellence through

 Identify and prioritize Quality education in of Computer Science and Business systems

tapped from National and International Resources

 Promote Modular approach to channelize knowledge and sharing of best practices

relative to quality management in of Computer Science and Engineering.

 Provide a focal point for an extended IT quality network comprised of end users and

providers leading to quality output.

 To develop professional and ethical attitude, effective communication skills, moral

values and an ability to relate engineering issues to social welfare

7
PROGRAM EDUCATIONAL OBJECTIVES

S. PEOs Definition of
No PEOs
To apply problem solving skills in Computer science and
I PEO 1 Business Management by applying Engineering
fundamentals.
To improve communication skills, business management
skills, professional ethics, team work and to innovate
II PEO 2 technologies for the betterment of society.

To exhibit leadership qualities, interpersonal skills and


to progress through life-long learning.
III PEO 3
To develop professional and ethical attitude, effective
communication skills, moral values and an ability to
IV PEO 4 relate engineering issues to social welfare.

PROGRAM SPECIFIC OUTCOMES

S. No. Program Specific Outcomes

Enriched knowledge in Computer Science, Business Management and human


PSO1 ethics.

The students will have effective knowledge in software engineering


PSO2 principles and solving scientific and business problems.
The students will explore emerging technologies in Information and
Communication Technologies (ICT), Business Analytics and Machine
PSO3 Learning to innovate ideas and solutions to existing/novel Business
applications

8
PROGRAM OUTCOMES
S. No. Programme
Outcomes
Engineering knowledge: Apply the knowledge of mathematics, science,
PO1 engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
Problem analysis: Identify, formulate, review research literature, and
PO2 analyze complex engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering
sciences.
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
PO3 needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based
PO4 knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern tool usage: Create, select, and apply appropriate techniques,
PO5 resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
The engineer and society: Apply reasoning informed by the contextual
PO6 knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics
PO8 and responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a
PO9 member or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities
PO10 with the engineering community and with society at large, such as, being able
to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and
PO11 understanding of the engineering and management principles and apply these
to one’s own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and
PO12 ability to engage in independent and life-long learning in the broadest context
of technological change.

9
LBORATORY

INTRODUCTION

OBJECTIVE
A Database Management System (DBMS) is a software package with computer programs that
controls the creation, maintenance, and use of a database. It allows organizations to conveniently
develop databases for various applications. A database is an integrated collection of data records,
files, and other objects. A DBMS allows different user application programs to concurrently access
the same database. DBMSs may use a variety of database models, such as the relational model or
object model, to conveniently describe and support applications. It typically supports query
languages, which are in fact high-level programming languages, dedicated database languages that
considerably simplify writing database application programs. Database languages also simplify the
database organization as well as retrieving and presenting information from it. A DBMS provides
facilities for controlling data access, enforcing data integrity, managing concurrency control, and
recovering the database after failures and restoring it from backup files, as well as maintaining
database security.

SCOPE OF DBMS
DBMS may become a complex software system and its development typically requires thousands of
human years of development effort. Some general-purpose DBMSs such as Adabas, Oracle and DB2
have been used. General-purpose DBMSs aim to meet the needs of as many applications as possible,
which adds to the complexity. However, since their development cost can be spread over a large
number of users, they are often the most cost-effective approach. On the other hand, a general-
purpose DBMS may introduce unnecessary overhead. Therefore, many systems use a special-
purpose DBMS.

10
Do’s and Don’ts

Do’s
 Know the location of the fire extinguisher and the first aid box and how to use

them in case of emergency.

 Read and understand how to carry out an activity thoroughly before coming to the

laboratory.

 Report fires or accidents immediately.

 Report any broken plugs or exposed electrical wires immediately.

 Turn off the machine when it is not in use.

 Always maintain an extra copy of all your important data.

Dont’s
 Do not eat or drink in the laboratory.

 Avoid stepping on electrical wires or any other computer cables.

 Do not insert metal objects such as clips, pins and needles into the computer casings.

They may cause fire.

 Do not remove anything from the computer laboratory without permission.

 Do not touch, connect or disconnect any plug or cable without permission.

 Do not run inside the Lab.

 Do not personalize the computers, for example, installing screen savers,

changing the desktop back ground or changing the video and audio settings.

11
Safety Measures and Guidelines
 Take a note of all the exits in the room and also take note of the location of

the fire extinguishers in the room for the sake of fire safety.

 Try not to type continuously for extremely long periods.

 Look away from the screen once in a while to give your eyes a rest.

 Do not attempt to open any machines and do not touch the backs of machines when

they are switched on.

 Do not spill water or any other liquid on the machines in order to maintain electrical
safety.

 Do not personalize the computers , for example, installing screen savers,

changing the desktop back Ground or changing the video and audio settings.

 All connections and disconnections must be performed by the technical staff.

 Report fires or accidents immediately.

 Report any broken plugs or exposed electrical wires Immediately.

 Turn off the machine when it is not in use.

12
Instructions to Teachers
 Teacher should review the experiment’s instructions prior to class for proper
conduction of the experiments
 Teachers must instruct students in Internet Safety
 Teacher must remain in the lab at all times and is responsible for discipline.
 Teacher must report for any computer with missing or damaged hardware or peripherals
 Teachers are expected to closely monitor student activity by frequent screen checks.
 Teachers should report any non-functioning technology equipment to their
Department Head
 Teachers, should when using computer labs, turn off the digital projector, and return
the room key after doors have been locked. Doors to computer labs must be locked
when not in use.
 Everyone will adhere to federal copyright laws.

13
Instructions to Students
 Student should follow the Lab dress code whenever they avail the laboratory facilities
and make sure your ID cards are visible outside
 Whenever students enter into the lab, they should make the entry in the log register kept
for that purpose.
 Observation note books / record note books are only allowed inside the lab, other
belongings are not allowed.
 Maintain silence in the Lab.
 Only one user is allowed to work in one system at a time.
 If any problem occurs in the software or hardware it should be brought to the notice
of the staff in-charge, as well as entry should be made in the log register kept for that
purpose.
 The laboratory must be kept clean and neat.
 Arrange the chairs before leaving the lab.
 Shutdown the systems in a proper way before leaving the laboratory.

14
Lab Code of Conduct

 You must wear your ID and Lab Coat each time you enter a computer lab. If you do
not have your ID, or lab coat when entering the computer lab, you may be asked to
leave the computer lab.
 No drinking or eating is allowed in any computer lab. All open and unopened food,
and beverages are prohibited from entering the computer lab.
 You must be considerate of other users. Privacy and concentration are important in
computer labs. If you need to talk to somebody, please do so in a way that does not
disturb other users.
 Lab assistants are there to assist in using the technology so that you may complete
your work.
 The computer labs are an academic resource. As such, please respect the needs of
others by not monopolizing the computers for non-academic use.
 Lab staff is not responsible for any belongings left in the computer labs. Please make
sure you take your belongings with you when you leave.
 The computers in the labs have been set up in such a way as to be used by multiple
people having differing needs. Do not change or interfere with the configuration of
the computers.
 Software downloaded from the Internet is not to be installed on any lab computer for
any purpose.
 Documents should be saved to the D drive.
 Users are not allowed to print large quantities of flyers, banners or other distribution
materials. If print jobs of this nature are required, one copy may be printed in the
computer lab and copies will need to be processed through the alternative printing
facility.
 Attempting to damage or destroy information on the computers will not be tolerated.
 You are expected to leave your computer in the same condition as you found it. This
includes putting chairs back in place and logging out when you leave.
 You are responsible for reading and abiding by all signs posted in the computer labs.

15
Major Lab Equipment with Specifications

LAB EQUIPMENT FOR A BATCH OF 30 STUDENTS:


 Standalone desktops with Oracle
 Operating system: Windows

16
OBJECTIVES: Course Objectives and Course Outcomes

The student should be made to:

1. To explain basic database concepts, applications and types of data models


2. To demonstrate the use of constraints and relational algebra operations
3. To implement the basics of SQL and construct queries using SQL
4. To emphasize the correlation of SQL and programming languages
5. To facilitate students in Database design and development

OUTCOMES:

At the end of the course, the student should be able to

CO1 Apply the basic concepts of Database Systems and Applications


CO2 Understand and apply the relational model and relational algebra operations.
CO3 Construct queries using SQL in database creation, manipulation and interaction
CO4 Apply the programming aspects using SQL to create procedure and perform functions
CO5 Implement a project based on the Database concepts using SQL

17
Mapping Course Outcome with Program Outcome
Course

algorithms and recommendation systems

Work with big data tools and analysis


Build a predictive analytic solution
Understand knowledge discovery

Analyze data by using clustering,


association and classification
process and methodologies
Outcomes Program Outcomes

Learn and apply different mining

techniques
for large volumes of data.
Pa Engineering Knowledge: Apply
knowledge of mathematics, science, H H H H H
engineering fundamentals and an
engineering specialization
for building engineering models.
Pb Problem Analysis: Identify and solve
engineering problems reaching H
conclusions using mathematics and H H
engineering sciences.
Pc Design/Development of Solutions:
Design and develop solutions for H H H
engineering problems
that meet specified needs.
Pd Conduct Investigations of Complex
Problems: Conduct investigations of H H
complex problems including design of
experiments and
analysis to provide valid solutions.
Pe Modern Tool Usage: Create and apply
appropriate techniques, resources, and H H
modern engineering tools for H
executing engineering
activities.
Pf The Engineer and Society: Apply
reasoning of the societal, safety issues and
the consequent
responsibilities relevant to engineering
practice.
Pg Environment and Sustainability:
Understand the impact of engineering H H
solutions in the environment and exhibit
the knowledge for
sustainable development.
Ph Ethics: Apply ethical principles and
18
commit to professional ethics,
responsibilities and norms of
engineering practice.
Pi Individual and Team Work: Function
effectively as an individual, and as a
member or leader in diverse teams in
multi-disciplinary
settings.
Pj Communication: Communicate
effectively to the engineering community
and the outside world
and also to write effective reports.
Course

algorithms and recommendation systems

Work with big data tools and analysis


Build a predictive analytic solution
Understand knowledge discovery

Analyze data by using clustering,


association and classification
process and methodologies
Outcomes Program Outcomes

Learn and apply different mining

techniques
for large volumes of data.

Pk Project Management and Finance:


Understand engineering and management H
principles and apply them to handle
projects in
multi disciplinary environments.
Pl Life-Long Learning: Recognize the
need for life-long learning and apply in H H H
the context of
technological change.

19
LIST OF EXPERIMENTS

L T P
21CS4611 DATABASE MANAGEMENT SYSTEMS LABORATORY
0 0 4
Preamble
This lab enables efficient use of data to store and retrieve from the databases. By incorporating SQL,
practical experience is provided to students with real time examples. Provides knowledge to interface
Programming with databases to cater the needs of data driven businesses and application
development
Prerequisites for the course
 Data Structures
Objectives
6. To explain basic database concepts, applications and types of data models
7. To demonstrate the use of constraints and relational algebra operations
8. To implement the basics of SQL and construct queries using SQL
9. To emphasize the correlation of SQL and programming languages
10. To facilitate students in Database design and development

S.No List of Experiments

1 Student should decide on a case study and formulate the problem statement.

Conceptual Designing using ER Diagrams (Identifying entities, attributes, keys and


2 relationships between entities, cardinalities, generalization, specialization etc.) Note:
Student is required to submit a document by drawing ER Diagram
Converting ER Model to Relational Model (Represent entities and relationships in Tabular
3 form, represent attributes as columns, identifying keys) Note: Student is required to
submit a document showing the tables created from ER Model.
Creation of Tables using SQL- Overview of using SQL tool, Data types in SQL, Creating
4 Tables (along with Primary and Foreign keys), Altering Tables and
Dropping Tables, Constraints

5 Practicing DDL commands, Integrity constraints, DML commands

6 Practicing DCL, TCL commands, Views and operations on views

7 Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT, etc

8 Practicing Sub queries (Nested, Correlated) and Joins

Practice Queries using COUNT, SUM, AVG, MAX, MIN, GROUP BY, HAVING, VIEWS Creation
9
and Dropping.
Practicing on Triggers - creation of trigger, Insertion using trigger, Deletion using trigger,
10
Updating using trigger
Procedures- Creation of Stored Procedures, Execution of Procedure, and Modification of
11
Procedure.
20
12 Cursors- Declaring and Opening Cursor, Fetching the data, closing the cursor.

Total Periods :60


S. No List of Test Projects
1 College Admission Management System
2 Restaurant Management System
3 Movie booking Management System
4 Vehicle Parking Management System
5 Travel Planner Management System
6 Toll Booth Management System
7 Mini mart Management System
8 Hospital Data Management System
9 Bike/ Car rental Management System
10 Banking Management System
11 Library Management System
12 Product review Management System
13 Employee payslip Management System
14 School Management System
15 Online Shopping Management System

INDEX
21
List of Experiments Page No
S.No
1 Student should decide on a case study and formulate the 27
problem statement.

2 Conceptual Designing using ER Diagrams (Identifying 29


entities, attributes, keys and relationships between entities,
cardinalities, generalization, specialization etc.) Note:
Student is required to submit a document by drawing ER
Diagram
3 Converting ER Model to Relational Model (Represent 30
entities and relationships in Tabular form, represent
attributes as columns, identifying keys) Note: Student is
required to submit a document showing the tables created
from ER Model.
4 Creation of Tables using SQL- Overview of using SQL tool, 32
Data types in SQL, Creating Tables (along with Primary and
Foreign keys), Altering Tables and
Dropping Tables, Constraints
5 Practicing DDL commands, Integrity constraints, DML 33
commands
6 Practicing DCL, TCL commands, Views and operations on 35
views
7 Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS, 38
UNION, INTERSECT, etc
8 Practicing Sub queries (Nested, Correlated) and Joins 39

9 Practice Queries using COUNT, SUM, AVG, MAX, MIN, 40


GROUP BY, HAVING, VIEWS Creation and Dropping.
10 Practicing on Triggers - creation of trigger, Insertion using 42
trigger, Deletion using trigger, Updating using trigger
11 Practicing on Triggers - creation of trigger, Insertion using 44
trigger, Deletion using trigger, Updating using trigger
12 Cursors- Declaring and Opening Cursor, Fetching the data, 45
closing the cursor.

22
INDEX

S.No. List of Projects Related CO


Experiment
1. College Admission Management System Exp. 1,2,3,4 CO1- CO5

2. Restaurant Management System Exp. 5,6,7,8 CO1- CO5

3. Movie booking Management System Exp. 1 – 11 CO1- CO5

4. Vehicle Parking Management System Exp. 1,3,4,5,9 CO1- CO5

5. Travel Planner Management System Exp. 1 – 11 CO1- CO5

6. Toll Booth Management System Exp. 2,3,4,10 CO1- CO5

7. Mini mart Management System Exp. 1,2,3,7,8 CO1- CO5

8. Hospital Data Management System Exp. 3,5,6,7 CO1- CO5

9. Bike/ Car rental Management System Exp. 1 – 11 CO1- CO5

10. Banking Management System Exp. 1 – 11 CO1- CO5

11. Library Management System Exp. 1,2,3,10,11 CO1- CO5

12. Product review Management System Exp. 1,2,4,6 CO1- CO5

13. Stock management system Exp. 4,6,7,10 CO1- CO5

14. Payroll Management System Exp. 1 – 11 CO1- CO5

15. Exam Seating Arrangement System Exp. 1 – 11 CO1- CO5

23
YOU TUBE LINKS FOR THE LAB SESSION

Sl No. Session Topic Link Address


Student should decide on a case study and https://
1 Session 1 formulate the problem statement. www.youtube.com/
watch?v=Jg4TkMWAihE
Conceptual Designing using ER Diagrams
(Identifying entities, attributes, keys and https://
relationships between entities, cardinalities,
2 Session 2 generalization, specialization etc.) www.youtube.com/
Note: Student is required to submit a document watch?v=4UxB5MlhWvE
by drawing ER Diagram
Converting ER Model to Relational Model
(Represent entities and relationships in Tabular
form, Represent attributes as columns, https://
identifying keys)
3 Session 3 www.youtube.com/
Note: Student is required to submit a document
watch?v=Mj8uanC2Wn0
showing the database tables created from ER
Model.
Creation of Tables using SQL- Overview of
using SQL tool, Data types in SQL, Creating https://
4 Session 4 Tables (along with Primary and Foreign keys), www.youtube.com/
Altering Tables and Dropping Tables, shorts/fL6aSfL8TLw
Constraints
Practicing DDL commands, Integrity https://
Session 5 constraints, DML commands www.youtube.com/
5
watch?v=9kI0_F41i5Y
Practicing DCL, TCL commands, Views and https://
6 Session 6 operations on views www.youtube.com/
watch?v=VJgCjLuU4e8
Practicing Queries using ANY, ALL, IN, EXISTS, https://
7 Session 7 NOT EXISTS, UNION, INTERSECT, etc www.youtube.com/
watch?v=OJZrkoR7i88
8 Session 8 Practicing Sub queries (Nested, Correlated) and https://
24
Joins. www.youtube.com/
watch?v=TCd8QIS-2KI
Practice Queries using COUNT, SUM, AVG, MAX, https://
9 Session 9 MIN, GROUP BY, HAVING, VIEWS Creation and www.youtube.com/
Dropping. watch?v=EEy8kinU9yI
Practicing on Triggers - creation of trigger, https://
Session
10 Insertion using trigger, Deletion using trigger, www.youtube.com/
10
Updating using trigger watch?v=3OrEsC-QjUA
Procedures- Creation of Stored Procedures, https://
Session
11 Execution of Procedure, and Modification of www.youtube.com/
11
Procedure. watch?v=ILJgewz5Dxw
Cursors- Declaring Cursor, Opening Cursor,
Fetching the data, closing the cursor.

Project- Integrated implementation of the


database management system

25
EXPERIMENT 1: Student should decide on a case study and formulate the
problem statement

Case Study 1
Hospital Management System
Aim: XYZ hospital is a multi-specialty hospital that includes a number of departments,
rooms, doctors, nurses, compounders, and other staff working in the hospital. Patients
having different kinds of ailments come to the hospital and get checkup done from the
concerned doctors. If required they are admitted in the hospital and discharged after
treatment.
The aim of this case study is to design and develop a database for the hospital to
maintain the records of various departments, rooms, and doctors in the hospital. It also
maintains records of the regular patients, patients admitted in the hospital, the check-
up of patients done by the doctors, the patients that have been operated, and patients
discharged from the hospital.
Description: In hospital, there are many departments like Orthopedic, Pathology,
Emergency, Dental, Gynecology, Anesthetics, I.C.U., Blood Bank, Operation Theater,
Laboratory, M.R.I., Neurology, Cardiology, Cancer Department, Corpse, etc. There is an
OPD where patients come and get a card (that is, entry card of the patient) for check up
from the concerned doctor. After making entry in the card, they go to the concerned
doctor’s room and the doctor checks up their ailments. According to the ailments, the
doctor either prescribes medicine or admits the patient in the concerned department.
The patient may choose either private or general room according to his/her need. But
before getting admission in the hospital, the patient has to fulfill certain formalities of
the hospital like room charges, etc. After the treatment is completed, the doctor
discharges the patient. Before discharging from the hospital, the patient again has to
complete certain formalities of the hospital like balance charges, test charges, operation
charges (if any), blood charges, doctors’ charges, etc.
Next we talk about the doctors of the hospital. There are two types of the doctors in the
hospital, namely, regular doctors and call on doctors. Regular doctors are those doctors
who come to the hospital daily. Calls on doctors are those doctors who are called by the
hospital if the concerned doctor is not available.
Table Description:
Following are the tables along with constraints used in Hospital Management database.
1. DEPARTMENT: This table consists of details about the various departments in the
hospital. The information stored in this table includes department name, department
location, and facilities available in that department.
Constraint: Department name will be unique for each department.
2. ALL_DOCTORS: This table stores information about all the doctors working for the
hospital and the departments they are associated with. Each doctor is given an identity
number starting with DR or DC prefixes only.

26
Constraint: Identity number is unique for each doctor and the corresponding
department should exist in DEPARTMENT table.
3. DOC_REG: This table stores details of regular doctors working in the hospital. Doctors
are referred to by their doctor number. This table also stores personal details of doctors
like name, qualification, address, phone number, salary, date of joining, etc.
Constraint: Doctor’s number entered should contain DR only as a prefix and must exist
in ALL_DOCTORS table.
4. DOC_ON_CALL: This table stores details of doctors called by hospital when additional
doctors are required. Doctors are referred to by their doctor number. Other personal
details like name, qualification, fees per call, payment due, address, phone number, etc.,
are also stored.
Constraint: Doctor’s number entered should contain DC only as a prefix and must exist
in ALL_DOCTORS table.
5. PAT_ENTRY: The record in this table is created when any patient arrives in the
hospital for a check up. When patient arrives, a patient number is generated which acts
as a primary key. Other details like name, age, sex, address, city, phone number, entry
date, name of the doctor referred to, diagnosis, and department name are also stored.
After storing the necessary details patient is sent to the doctor for check up.
Constraint: Patient number should begin with prefix PT. Sex should be M or F only.
Doctor’s name and department referred must exist.
6. PAT_CHKUP: This table stores the details about the patients who get treatment from
the doctor referred to. Details like patient number from patient entry table, doctor
number, date of check up, diagnosis, and treatment are stored. One more field status is
used to indicate whether patient is admitted, referred for operation or is a regular
patient to the hospital. If patient is admitted, further details are stored in
PAT_ADMIT table. If patient is referred for operation, the further details are stored in
PAT_OPR table and if patient is a regular patient to the hospital, the further details are
stored in PAT_REG table.
Constraint: Patient number should exist in PAT_ENTRY table and it should be unique.
7. PAT_ADMIT: When patient is admitted, his/her related details are stored in this table.
Information stored includes patient number, advance payment, mode of payment, room
number, department, date of admission, initial condition, diagnosis, treatment, number
of the doctor under whom treatment is done, attendant name, etc.
Constraint: Patient number should exist in PAT_ENTRY table. Department, doctor
number, room number must be valid.
8. PAT_DIS: An entry is made in this table whenever a patient gets discharged from the
hospital. Each entry includes details like patient number, treatment given, treatment
advice, payment made, mode of payment, date of discharge, etc.
Constraint: Patient number should exist in PAT_ENTRY table.
9. PAT_REG: Details of regular patients are stored in this table. Information stored
includes date of visit, diagnosis, treatment, medicine recommended, status of treatment,
etc.
Constraint: Patient number should exist in patient entry table. There can be multiple
entries of one patient as patient might be visiting hospital repeatedly for check up and
there will be entry for patient’s each visit.
10. PAT_OPR: If patient is operated in the hospital, his/her details are stored in this
27
table. Information stored includes patient number, date of admission, date of operation,
number of the doctor who conducted the operation, number of the operation theater in
which operation was carried out, type of operation, patient’s condition before and after
operation, treatment advice, etc.
Constraint: Patient number should exist in PAT_ENTRY table. Department, doctor
number should exist or should be valid.
11. ROOM_DETAILS: It contains details of all rooms in the hospital. The details stored in
this table include room number, room type (general or private), status (whether
occupied or not), if occupied, then patient number, patient name, charges per day, etc.
Constraint: Room number should be unique. Room type can only be G or P and status
can only be Y or N
E‐R Diagram

Relational Database Schema for Case Study

The relational database schema for Hospital Management database is as follows:


1. DEPARTMENT (D_NAME, D_LOCATION, FACILITIES)
2. ALL_DOCTORS (DOC_NO, DEPARTMENT)
3. DOC_REG(DOC_NO, D_NAME, QUALIFICATION, SALARY, EN_TIME, EX_TIME,
ADDRESS, PH_NO, DOJ)
4. DOC_ON_CALL (DOC_NO, D_NAME, QUALIFICATION, FS_PR_CL, PYMT_DU, ADDRESS,
PH_NO)
5. PAT_ENTRY (PAT_NO, PAT_NAME, CHKUP_DT, PT_AGE, SEX, RFRG_CSTNT,
DIAGNOSIS, RFD, ADDRESS, CITY, PH_NO, DEPARTMENT)
6. PAT_CHKUP (PAT_NO, DOC_NO, DIAGNOSIS, STATUS, TREATMENT)
7. PAT_ADMIT (PAT_NO, ADV_PYMT, MODE_PYMT, ROOM_NO, DEPTNAME, ADMTD_ON,
COND_ON, INVSTGTN_DN, TRMT_SDT, ATTDNT_NM)
8. PAT_DIS (PAT_NO, TR_ADVS, TR_GVN, MEDICINES, PYMT_GV, DIS_ON)
9. PAT_REG (PAT_NO, DATE_VIS, CONDITION, TREATMENT, MEDICINES, DOC_NO,
28
PAYMT)
10. PAT_OPR (PAT_NO, DATE_OPR, IN_COND, AFOP_COND, TY_OPERATION,
MEDICINES, DOC_NO, OPTH_NO, OTHER_SUG)
11. ROOM_DETAILS (ROOM_NO, TYPE, STATUS, RM_DL_CRG, OTHER_CRG)

RESULT

Thus, the case study was found and formulated successfully

EXPERIMENT 2: Conceptual Designing using ER Diagrams (Identifying


entities, attributes, keys and relationships between entities, cardinalities,
generalization, specialization etc.) Note: Student is required to submit a document by
drawing ER Diagram

What is an ER Diagram?
In the real world, you are often required to show the tables and their relationships,
suppose you are a part of database team in your company and you are required to
present the database design to business users.

The business users are non-technical and it’s difficult for them to read a verbose design
document. What can you do? You need to use an Entity Relation (ER), Model.

The ER Diagram helps us to represent tables and their relationships in a pictorial


format which would be easier to understand and more convincing to the clients and
your
colleagues.

A sample ER Diagram representing the Employee entity along with its attributes is
presented below:

Before drawing the ER diagram, we need to understand what relationships are and how
are they represented.
29
Relationship

Relationships are the association of one entity with another entity. Each relationship
has a name

Example:

A Computer is allocated to an Employee.

There can be more than one relationship between entities, e.g. an Employee works in a
Department while the head of the department (also an employee) manages a
Department.

A relationship can also exist between instances of the same entity,

Example:
An employee reports to another Employee.

30
Now, let us move into the Cardinality.

The cardinality of an ER Diagram

The cardinality of relationship is the number of instances in one entity which is


associated with the number of instances in another.

The relationship between Employee and Computer, it helps us answer questions like
how many computers can be allocated to an employee, can computers be shared
between employees, can employees exist without being allocated a computer etc.

Example:

If 0 or 1 computer can be allocated to 0 or 1 employee then the cardinality of the


relationship between these two entities will be 1:1.

The cardinality of relationships is of three types: 1:1, 1:N and M:N.

Now, let us learn the CrowFoot notations.

The Crowfoot notations


Crowfoot notation is one of the ways to represent the cardinality of the relationship in
an ER Model. The notation comprises of four symbols and one of them need to be used
for each entity in a relationship.

Let us say the relationship between employee and computer is such that a computer
must be allocated to one and only one employee but an employee can be allocated zero
or any number of computers. Such a relationship is represented by the diagram below.

31
Foreign keys need to be created in tables in order to establish the relationship between
entities.

The table in which foreign key will be created depends upon the cardinality of the
relationship. Let us now discuss types of cardinalities and how it impacts foreign key
creation.

Now let’s dive straight in all these different types of relationships.

 1:1 relationship

1:1 relationship represents the association between the single occurrence of one entity
and a single occurrence of the second entity. For e.g. consider a company where each
employee can be allocated a maximum of 1 computer and computers are not shared
between employees.

32
The Allot_Dt attribute is not a property of employee or computer. It belongs to
the relationship and is hence represented differently in the ER Model.

We can see that the employee table has two additional attributes:

 CompId
 Allot_Dt

CompId is a foreign key to establish the link between these two tables. Allot_Dt which is
the attribute of the relationship is always stored in the table that has the foreign key.

Alternatively, we could also have added Id and Allot_Dt attributes in computer table to
establish the link.

 1:N relationship

1 : N relationship represents the association between the single occurrence of one entity
and multiple occurrences of the second entity.

Example:

Consider a company where each employee can be allocated to many computers but still,
computers cannot be shared between employees.

In 1:N relationships, the foreign key and relationship attributes are always added to the
many (N) side of the relationship. Hence these attributes are added to the Computer
table. The reverse solution will not work.

In a many to one relationship, the primary key of one entity acts as a foreign key on the
side where many relationships are defined

 M : N relationship

M:N relationship represents an association between multiple occurrences of both


entities. For e.g. consider a company where each employee can be allocated to many
computers and computers can be shared between employees.

33
Weekday / Weekend BatchesSee Batch Details

In M:N relationships, the relationship is represented by a completely new table that has
a composite primary key. Such a structure requires two foreign keys on the new table
linking to the primary keys of each of the parent tables. The attribute of the relationship
resides on this new table.

A many to many relationships between two entities usually results in three tables.

34
RESULT

Thus, the conceptual designing using ER Diagrams were executed successfully.

EXPERIMENT 3: Converting ER Model to Relational Model


Conversion of an E-R diagram into a relational model is required because E-R diagrams
represent the conceptual level of the database design while the relational model
represents the logical level. The relational models can be easily implemented using
RDBMS like Oracle, MySQL, etc.

In general conversion of E-R diagram into a relational model involves the following:

1. Mapping of an entity set into relation (tables) of the database.


2. The attributes of a table include the attributes of an entity
3. The key attribute of an entity becomes the primary key of the relation
For example,

Consider the following E-R diagram in the figure below. The E-R diagram consists
of Employee as an entity set and EmpNo, EmpName, and Salary as its attributes. Here we
map entity set into a relation Employee and attributes of an entity set will become the
attributes inside the table. The key attribute will become the primary key of the table.

Conversion of a simple E-R diagram into a Table


The conversion of an E-R diagram into the relational model also depends on the type of
components used in the E-R diagram. The following section describes the different cases
of the E-R diagram and their conversion into their corresponding tables.

Entity set with a composite attribute


35
While converting an E-R diagram consisting of a composite attribute we do not include
the composite attribute in the relational model. The compositions of the composite
attribute will become the attributes in the relational model. For example in the figure
given below, Salary is the composite attribute, and Basic, DA, and HRA are its
compositions.

Conversion of an E-R diagram containing composite attribute


Entity set with multivalued attributes

If an entity contains a multivalued attribute, we split the attributes into two relations in
the relational model. One with key attribute and all simple attributes and other with key
attribute and all multivalued attributes. For example, in the figure given
below, PhoneNo is the multivalued attribute.

E-R diagram containing


multivalued attribute
If we include the PhoneNo in the table with all other attributes, then for a single-valued
tuple we may have multiple entries as shown in the table below

Duplicate values with multivalued attribute


36
However, to avoid duplicate values in the table, we split the attributes into two different
relations as shown in the figure below

Con
version of multivalued attributes into relation
Translation of a relationship into a relation

Likewise, we map the entity set into the relation in a relational model, we can also map
a relationship set into a relation. The attribute of such a relation includes key attributes
of the participating relations. The attributes are will become a foreign key.

For example, in the figure given below, there are two entity
sets Employee and Department. These entity sets are participating in a
relationship works in. The relationship set is converted into relation with attributes
EmpNo from Employee relation, D_id from Department relation and Since, the attribute
of the relationship set itself.

Translation of a relationship into a relation

RESULT

37
Thus, the Conversion of ER Model to Relational Model was executed successfully

EXPERIMENT 4: Creation of Tables using SQL- Overview of using SQL tool,


Data types in SQL, Creating Tables (along with Primary and Foreign keys), Altering
Tables and Dropping Tables, Constraints

Title: Implementation of DDL commands of SQL with suitable examples


 Create table
 Alter table
 Drop Table

Objective:
To understand the different issues involved in the design and
implementation of a database system
To understand and use data definition language to write query for a
database
Theory:
Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle
Report Writer, Oracle Graphics etc.

 SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. These
are
 Interactive SQL: Interactive SQL is designed for
create, access and manipulate data structures like
tables and indexes.
 PL/SQL: PL/SQL can be used to developed
programs for different applications.

 Oracle Forms: This tool allows you to create a data entry screen
along with the suitable menu objects. Thus it is the oracle forms
tool that handles data gathering and data validation in a
commercial application.

 Report Writer: Report writer allows programmers to prepare


innovative reports using data from the oracle structures like
tables, views etc. It is the report writer tool that handles the
38
reporting section of commercial application.

 Oracle Graphics: Some of the data can be better represented in


the form of pictures. The oracle graphics tool allows
programmers to prepare graphs using data from oracle structures
like tables, views etc.

SQL (Structured Query Language):


Structured Query Language is a database computer
language designed for managing data in relational database
management systems (RDBMS), and originally based upon
Relational Algebra. Its scope includes data query and update,
schema creation and modification, and data access control.
SQL was one of the first languages for Edgar F. Codd's
relational model and became the most widely used language for
relational databases.
 IBM developed SQL in mid of 1970’s.
 Oracle incorporated in the year 1979.
 SQL used by IBM/DB2 and DS Database Systems.
 SQL adopted as standard language for RDBS by ASNI in 1989.

DATA TYPES:

1. CHAR (Size): This data type is used to store character strings values of
fixed length. The size in brackets determines the number of characters the
cell can hold. The maximum number of character is 255 characters.

2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store


variable length alphanumeric data. The maximum character can hold is
2000 character.

3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or
floating point). Number of virtually any magnitude may be stored up to 38

39
digits of precision. Number as large as 9.99 * 10 124. The precision (p)
determines the number of places to the right of the decimal. If scale is
omitted then the default is zero. If precision is omitted, values are stored
with their original precision up to the maximum of 38 digits.

4. DATE: This data type is used to represent date and time. The standard
format is DD- MM-YY as in 17-SEP-2009. To enter dates other than the
standard format, use the appropriate functions. Date time stores date in
the 24-Hours format. By default the time

in a date field is 12:00:00 am, if no time portion is specified.


The default date for a date field is the first day the current
month.

5. LONG: This data type is used to store variable length character strings
containing up to 2GB. Long data can be used to store arrays of binary data
in ASCII format. LONG values cannot be indexed, and the normal
character functions such as SUBSTR cannot be applied.

6. RAW: The RAW data type is used to store binary data, such as digitized
picture or image. Data loaded into columns of these data types are stored
without any further conversion. RAW data type can have a maximum
length of 255 bytes. LONG RAW data type can contain up to 2GB.

SQL language is sub-divided into several language


elements, including:
 Clauses, which are in some cases optional, constituent components

of statements and queries.

 Expressions, which can produce either scalar values or tables consisting of


columns and

rows of data.

 Predicates which specify conditions that can be evaluated to SQL three-


valued logic
40
(3VL) Boolean truth values and which are used to limit the effects
of statements and

queries, or to change program flow.

 Queries which retrieve data based on specific criteria.

 Statements which may have a persistent effect on schemas and

data, or which may control transactions, program flow,

connections, sessions, or diagnostics.

 SQL statements also include the semicolon (";") statement terminator.


Though not

ALTER TABLE
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE lets you add columns to a table in a database.

AND
SELECT column_name(s)
FROM table_name
WHERE column_1 = value_1
AND column_2 = value_2;
AND is an operator that combines two conditions. Both conditions must be true for the row to
be included in the result set.

AS
SELECT column_name AS 'Alias'
FROM table_name;
AS is a keyword in SQL that allows you to rename a column or table using an alias.

AVG()
SELECT AVG(column_name)
FROM table_name;
AVG() is an aggregate function that returns the average value for a numeric column.

BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value_1 AND value_2;
The BETWEEN operator is used to filter the result set within a certain range. The values can be
numbers, text or dates.

CASE
SELECT column_name,
CASE
WHEN condition THEN 'Result_1'
41
WHEN condition THEN 'Result_2'
ELSE 'Result_3'
END
FROM table_name;
CASE statements are used to create different outputs (usually in the SELECT statement). It is
SQL’s way of handling if-then logic.

COUNT()
SELECT COUNT(column_name)
FROM table_name;
COUNT() is a function that takes the name of a column as an argument and counts the number
of rows where the column is not NULL.

CREATE TABLE
CREATE TABLE table_name (
column_1 datatype,
column_2 datatype,
column_3 datatype
);
CREATE TABLE creates a new table in the database. It allows you to specify the name of the
table and the name of each column in the table.

DELETE
DELETE FROM table_name
WHERE some_column = some_value;
DELETE statements are used to remove rows from a table.

GROUP BY
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name;
GROUP BY is a clause in SQL that is only used with aggregate functions. It is used in
collaboration with the SELECT statement to arrange identical data into groups.

HAVING
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > value;
HAVING was added to SQL because the WHERE keyword could not be used with aggregate
functions.

INNER JOIN
SELECT column_name(s)
FROM table_1
JOIN table_2
ON table_1.column_name = table_2.column_name;
An inner join will combine rows from different tables if the join condition is true.

INSERT
INSERT INTO table_name (column_1, column_2, column_3)
VALUES (value_1, 'value_2', value_3);
42
INSERT statements are used to add a new row to a table.
IS NULL / IS NOT NULL
SELECT column_name(s)
FROM table_name
WHERE column_name IS NULL;
IS NULL and IS NOT NULL are operators used with the WHERE clause to test for empty
values.

LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
LIKE is a special operator used with the WHERE clause to search for a specific pattern in a
column.
LIMIT
SELECT column_name(s)
FROM table_name
LIMIT number;
LIMIT is a clause that lets you specify the maximum number of rows the result set will have.

MAX()
SELECT MAX(column_name)
FROM table_name;
MAX() is a function that takes the name of a column as an argument and returns the largest
value in that column.

MIN()
SELECT MIN(column_name)
FROM table_name;
MIN() is a function that takes the name of a column as an argument and returns the smallest
value in that column.

OR
SELECT column_name
FROM table_name
WHERE column_name = value_1
OR column_name = value_2;
OR is an operator that filters the result set to only include rows where either condition is true.
ORDER BY
SELECT column_name
FROM table_name
ORDER BY column_name ASC | DESC;
ORDER BY is a clause that indicates you want to sort the result set by a particular column
either alphabetically or numerically.

OUTER JOIN
SELECT column_name(s)
FROM table_1
LEFT JOIN table_2
ON table_1.column_name = table_2.column_name;
An outer join will combine rows from different tables even if the join condition is not met. Every
row in the left table is returned in the result set, and if the join condition is not met,
43
then NULL values are used to fill in the columns from the right table.

ROUND()
SELECT ROUND(column_name, integer)
FROM table_name;
ROUND() is a function that takes a column name and an integer as arguments. It rounds the
values in the column to the number of decimal places specified by the integer.
SELECT
SELECT column_name
FROM table_name;
SELECT statements are used to fetch data from a database. Every query will begin
with SELECT.
SELECT DISTINCT
SELECT DISTINCT column_name
FROM table_name;
SELECT DISTINCT specifies that the statement is going to be a query that returns unique
values in the specified column(s).
SUM
SELECT SUM(column_name)
FROM table_name;
SUM() is a function that takes the name of a column as an argument and returns the sum of all
the values in that column.

UPDATE
UPDATE table_name
SET some_column = some_value
WHERE some_column = some_value;
UPDATE statements allow you to edit rows in a table.

WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value;
WHERE is a clause that indicates you want to filter the result set to include only rows where
the following condition is true.

WITH
WITH temporary_name AS (
SELECT *
FROM table_name)
SELECT *
FROM temporary_name
WHERE column_name operator value;
WITH clause lets you store the result of a query in a temporary table using an alias. You can
also define multiple temporary tables using a comma and with one instance of
the WITH keyword.
The WITH clause is also known as common table expression (CTE) and subquery factoring.

44
RESULT

Thus, the Creation of Tables using SQL was implemented successfully.

EXPERIMENT 5: Practicing DDL commands, Integrity constraints, DML


commands

1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is


used to create and destroy databases and database objects. These commands
will primarily be used by database administrators during the setup and
removal phases of a database project. Let's take a look at the structure and
usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. RENAME

1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)

Syntax: CREATE TABLE


<relation_name/table_name > (field_1
data_type(size),field_2 data_type(size), .. . );

Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR
(5));

2. ALTER:
(a) ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.

Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new


field_2 data_type(size),..);
Example: SQL>ALTER TABLE std ADD (Address CHAR(10));

(b) ALTER TABLE...MODIFY...: This is used to change the width as well as data
type of fields of existing relations.
45
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size),
field_2 newdata_type(Size),... field_newdata_type(Size));

Example:SQL>ALTER TABLE student MODIFY(sname


VARCHAR(10),class VARCHAR(5));

c) ALTER TABLE..DROP.....................................This is used to remove any field of


existing relations.

Syntax: ALTER TABLE relation_name DROP COLUMN (field_name);

Example:SQL>ALTER TABLE student DROP column (sname);

d) ALTER TABLE..RENAME...: This is used to change the name of


fields in existing relations.

Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD


field_name) to (NEW field_name);

Example: SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;

3. DROP TABLE: This is used to delete the structure of a relation. It


permanently deletes the records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;

4. RENAME: It is used to modify the name of the existing


database object. Syntax: RENAME TABLE old_relation_name
TO new_relation_name; Example: SQL>RENAME TABLE std
TO std1;

SQL Integrity Constraints


Integrity Constraints are used to apply business rules for the database tables.
The constraints available in SQL are Foreign Key, Not Null, Unique, Check.
Constraints can be defined in two ways

46
1) The constraints can be specified immediately after the column definition. This is
called column-level definition.
2) The constraints can be specified after all the columns are defined. This is called
table-level definition.

1) SQL Primary key:


This constraint defines a column or combination of columns which uniquely
identifies each row in the table.
Syntax to define a Primary key at column level:
column name datatype [CONSTRAINT constraint_name] PRIMARY KEY
Syntax to define a Primary key at table level:
[CONSTRAINT constraint_name] PRIMARY KEY

(column_name1,column_name2,..)
column_name1, column_name2 are the names of the columns which
define the primary Key.
 The syntax within the bracket i.e. [CONSTRAINT constraint_name] is
optional.
For Example: To create an employee table with Primary Key constraint, the query
would be like.
Primary Key at column level:
CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

salary number(10),

location char(10)

);

2) SQL Foreign key or Referential Integrity :


This constraint identifies any column referencing the PRIMARY KEY in another
table. It establishes a relationship between two columns in the same table or
between different tables. For a column to be defined as a Foreign Key, it should be a

47
defined as a Primary Key in the table which it is referring. One or more columns can
be defined as Foreign key.

Syntax to define a Foreign key at column level:


[CONSTRAINT constraint_name] REFERENCES

Referenced_Table_name(column_name)
Syntax to define a Foreign key at table level:
[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES

referenced_table_name(column_name);
For Example:
1) Lets use the "product" table and "order_items".

Foreign Key at column level:


CREATE TABLE product

( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY,

product_name char(20),

supplier_name char(20),

unit_price number(10)

);

CREATE TABLE order_items

( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY,

product_id number(5) CONSTRAINT pd_id_fk REFERENCES,

product(product_id),

product_name char(20),

supplier_name char(20),

48
unit_price number(10)

);

Foreign Key at table level:


CREATE TABLE order_items

( order_id number(5) ,

product_id number(5),

product_name char(20),

supplier_name char(20),

unit_price number(10)

CONSTRAINT od_id_pk PRIMARY KEY(order_id),

CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES

product(product_id)

);

3) SQL Not Null Constraint :


This constraint ensures all rows in the table contain a definite value for the column
which is specified as not null. Which means a null value is not allowed.
Syntax to define a Not Null constraint:
[CONSTRAINT constraint name] NOT NULL
For Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee

( id number(5),

name char(20) CONSTRAINT nm_nn NOT NULL,

dept char(10),
49
age number(2),

salary number(10),

location char(10)

);

4) SQL Unique Key:


This constraint ensures that a column or a group of columns in each row have a
distinct value. A column(s) can have a null value but the values cannot be
duplicated.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE
Syntax to define a Unique key at table level:
[CONSTRAINT constraint_name] UNIQUE(column_name)
For Example: To create an employee table with Unique key, the query would be
like,
Unique Key at column level:
CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

salary number(10),

location char(10) UNIQUE

);

5) SQL Check Constraint :


This constraint defines a business rule on a column. All the rows must satisfy this
rule. The constraint can be applied for a single column or a group of columns.
Syntax to define a Check constraint:

50
[CONSTRAINT constraint_name] CHECK (condition)

For Example: In the employee table to select the gender of a person, the query
would be like
Check Constraint at column level:
CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

gender char(1) CHECK (gender in ('M','F')),

salary number(10),

location char(10)

);
Check Constraint at table level:
CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

gender char(1),

salary number(10),

location char(10),

51
CONSTRAINT gender_ck CHECK (gender in ('M','F'))

);

Data Manipulation Language (DML) commands in SQL deals with manipulation of


data records stored within the database tables. It does not deal with changes to
database objects and its structure. The commonly known DML commands are INSERT,
UPDATE and DELETE. Liberally speaking, we can consider even SELECT statement as a
part of DML commands. Albeit, it strictly forms part of the Data Query Language (DQL)
command.
we will be learning about all the above mentioned DML commands in great detail in the
subsequent sections. But let us first have a look at this summary table for a brief
overview on each of them.
Command Description

SELECT Used to query or fetch selected fields or columns from


a database table

INSERT Used to insert new data records or rows in the


database table

UPDATE Used to set the value of a field or column for a


particular record to a new value

DELETE Used to remove one or more rows from the database


table

Commands of DML
Now let us try to understand each of the above mentioned DML commands in detail one
by one.
1. SELECT
SELECT command or statement in SQL is used to fetch data records from the database
table and present it in the form of a result set. It is usually considered as a DQL
command but it can also be considered as DML.
The basic syntax for writing a SELECT query in SQL is as follows :
SELECT column_name1, column_name2, …
FROM table_name
WHERE condition_ expression;
The parameters used in the above syntax are as follows :
column_name1, column_name2, … : Specify the column_names which have to be
fetched or selected for the final result set.
table_name: Specify the name of the database table from which these results have to be
fetched.
condition_expression: Specify the condition expression for filtering records for the
final result set.
Here are a few examples to illustrate the use of SELECT command.
52
SELECT customer_id,
sale_date,
order_id,
store_state
FROM customers;

The query returns the following output.

In this example, we have fetched fields such as customer_id, sale_date, order_id and
store_state from customers table. Next, suppose if we want to fetch all the records from
the customers table. This can be achieved by a simple query as shown below.
SELECT * FROM customers;
The query returns the following output.

2. INSERT
INSERT commands in SQL are used to insert data records or rows in a database table. In
an INSERT statement, we specify both the column_names for which the entry has to be
made along with the data value that has to be inserted.
The basic syntax for writing INSERT statements in SQL is as follows :
INSERT INTO table_name (column_name_1, column_name_2, column_name_3, ...)
VALUES (value1, value2, value3, ...)
53
By VALUES, we mean the value of the corresponding columns.
Here are a few examples to further illustrate the INSERT statement.
INSERT INTO public.customers(
customer_id, sale_date, sale_amount, salesperson, store_state, order_id)
VALUES (1005,'2019-12-12',4200,'R K Rakesh','MH','1007');

Here we have tried to insert a new row in the Customers table using the INSERT
command. The query accepts two sets of arguments, namely field names or column
names and their corresponding values.
Suppose if we have to insert values into all the fields of the database table, then we need
not specify the column names, unlike the previous query. Follow the following query for
further illustration.
INSERT INTO customers
VALUES ('1006','2020-03-04',3200,'DL', '1008');

In this example, we have successfully inserted all the values without having to specify
the fieldnames.

3. UPDATE
UPDATE command or statement is used to modify the value of an existing column in a
database table.
The syntax for writing an UPDATE statement is as follows :
UPDATE table_name
SET column_name_1 = value1, column_name_2 = value2, ...
WHERE condition;
Having learnt the syntax, let us now try an example based on the UPDATE statement in
SQL.
54
UPDATE customers
SET store_state = 'DL'
WHERE store_state = 'NY';

In this example, we have modified the value of store_state for a record where store_state
was ‘NY’ and set it to a new value ‘DL’.

4. DELETE
DELETE statement in SQL is used to remove one or more rows from the database table.
It does not delete the data records permanently. We can always perform a rollback
operation to undo a DELETE command. With DELETE statements we can use the
WHERE clause for filtering specific rows.
The syntax for writing an DELETE statement is as follows :
DELETE FROM table_name WHERE condition;
Having learnt the syntax, we are all set to try an example based on the DELETE
command in SQL.
DELETE FROM customers
WHERE store_state = 'MH'
AND customer_id = '1001';

In this example, we have removed a row from the customer’s table where store_state
was ‘MH’ and customer_id was ‘1001’.

RESULT
55
Thus, the DDL commands, Integrity constraints, DML commands were executed
successfully
EXPERIMENT 6: Practicing DCL, TCL commands, Views and operations on
views.

DCL (Data Control Language) includes commands like GRANT and REVOKE, which are
useful to give “rights & permissions.” Other permission controls parameters of the
database system.
Examples of DCL commands:
Commands that come under DCL:

 Grant
 Revoke

Grant:
This command is use to give user access privileges to a database.

Syntax:

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;


For example:

GRANT SELECT ON Users TO'Tom'@'localhost;


Revoke:
It is useful to back permissions from the user.

Syntax:

REVOKE privilege_nameON object_nameFROM {user_name |PUBLIC |role_name}


For example:

REVOKE SELECT, UPDATE ON student FROM BCA, MCA;

Transaction control language or TCL commands deal with the transaction within the
database.
Commit
This command is used to save all the transactions to the database.

Syntax:

Commit;
For example:

DELETE FROM Students


56
WHERE RollNo =25;
COMMIT;
Rollback
Rollback command allows you to undo transactions that have not already been saved to
the database.

Syntax:

ROLLBACK;
Example:

DELETE FROM Students


WHERE RollNo =25;
SAVEPOINT
This command helps you to sets a savepoint within a transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;
Example:

SAVEPOINT RollNo;

RESULT

Thus, the DCL, TCL commands, Views and operations on views were executed
successfully
57
EXPERIMENT 7: Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS,
UNION, INTERSECT, etc

UNION

Union is used to combine the results of two queries into a single result set of all
matching rows. Both the queries must result in the same number of columns and
compatible data types in order to unite. All duplicate records are removed automatically
unless UNION ALL is used.

Generally, it can be useful in applications where tables aren't perfectly normalized, for
example, a data warehouse application.

Syntax
{ <query_specification> | ( <query_expression> ) }
{ UNION | UNION ALL}
{ <query_specification> | ( <query_expression> ) }

Example 1.

You want to invite all the Speakers and Authors to the annual conference. Hence, how
will you prepare the invitation list?

select name from Speakers


union
select name from Authors
order by name
SQL
Copy

Output

As you can see here, the default order is ascending order and you have to use the last
query instead of both queries.

UNION ALL

It will not remove duplicate records. It can be faster than UNION.


58
Example 2.

You want to give a prize to all the Speakers and Authors at the annual conference.
Hence, how will you prepare the prize list?

select name, 'Speaker' as 'Role' from Speakers


union all
select name, 'Author' as 'Role' from Authors
order by name
SQL
Copy
Output

INTERSECT

It is used to take the result of two queries and returns only those rows which are
common in both result sets. It removes duplicate records from the final result set.

Syntax
{ <query_specification> | ( <query_expression> ) }
{ EXCEPT | INTERSECT }
{ <query_specification> | ( <query_expression> ) }
Example 3.

You want the list of people who are Speakers and they are also Authors. Hence, how will
you prepare such a list?

select name from Speakers


intersect
select name from Authors
order by name
SQL
Copy
Output

59
EXCEPT

It is used to take the distinct records of two one query and returns only those rows
which do not appear in the second result set.

Syntax
{ <query_specification> | ( <query_expression> ) }
{ EXCEPT | INTERSECT }
{ <query_specification> | ( <query_expression> ) }
Example 4.

You want the list of people who are only Speakers and they are not Authors. Hence, how
will you prepare such a list?

select name from Speakers


except
select name from Authors
order by name
SQL
Copy
Output

Example 5.

You want the list of people who are only Authors and they are not Speakers. Hence, how
will you prepare such a list?

select name from Authors


except
select name from Speakers
order by name
SQL
Copy
Output

60
RESULT

Thus, the Queries using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT were
executed successfully
EXPERIMENT 8: Practicing Sub queries (Nested, Correlated) and
Joins

A nested query is a query that has another query embedded within it. The embedded
query is called a subquery.
A subquery typically appears within the WHERE clause of a query. It can sometimes
appear in the FROM clause or HAVING clause.
Example
Let’s learn about nested queries with the help of an example.
Find the names of employee who have regno=103
The query is as follows −
select E.ename from employee E where E.eid IN (select S.eid from salary S where
S.regno=103);
Student table
The student table is created as follows −

create table student(id number(10), name varchar2(20),classID number(10), marks


varchar2(20));
Insert into student values(1,'pinky',3,2.4);
Insert into student values(2,'bob',3,1.44);
Insert into student values(3,'Jam',1,3.24);
Insert into student values(4,'lucky',2,2.67);
Insert into student values(5,'ram',2,4.56);
select * from student;
Output
You will get the following output −

Id Name classID Marks

1 Pinky 3 2.4

2 Bob 3 1.44

3 Jam 1 3.24

4 Lucky 2 2.67

5 Ram 2 4.56
61
Teacher table
The teacher table is created as follows −
Example
Create table teacher(id number(10), name varchar(20), subject varchar2(10), classID
number(10), salary number(30));
Insert into teacher values(1,’bhanu’,’computer’,3,5000);
Insert into teacher values(2,'rekha','science',1,5000);
Insert into teacher values(3,'siri','social',NULL,4500);
Insert into teacher values(4,'kittu','mathsr',2,5500);
select * from teacher;
Output
You will get the following output −

Id Name Subject classID Salary

1 Bhanu Computer 3 5000

2 Rekha Science 1 5000

3 Siri Social NULL 4500

4 Kittu Maths 2 5500


Class table
The class table is created as follows −
Example
Create table class(id number(10), grade number(10), teacherID number(10),
noofstudents number(10));
insert into class values(1,8,2,20);
insert into class values(2,9,3,40);
insert into class values(3,10,1,38);
select * from class;
Output
You will get the following output −

Id Grade teacherID No.ofstudents

1 8 2 20

2 9 3 40

3 10 1 38
Now let’s work on nested queries
62
A correlated subquery is evaluated once for each row processed by the parent
statement. The parent statement can be a SELECT, UPDATE, or DELETE statement.
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);
A correlated subquery is one way of reading every row in a table and comparing
values in each row against related data. It is used whenever a subquery must return a
different result or set of results for each candidate row considered by the main query.
In other words, you can use a correlated subquery to answer a multipart question
whose answer depends on the value in each row processed by the parent statement.
Nested Subqueries Versus Correlated Subqueries :
With a normal nested subquery, the inner SELECT query runs first and executes once,
returning values to be used by the main query. A correlated subquery, however,
executes once for each candidate row considered by the outer query. In other words,
the inner query is driven by the outer query.
NOTE: You can also use the ANY and ALL operator in a correlated subquery. EXAMPLE
of Correlated Subqueries : Find all the employees who earn more than the average
salary in their department.
SELECT last_name, salary, department_id
FROM employees outer
WHERE salary >
(SELECT AVG(salary)
FROM employees
WHERE department_id =
outer.department_id group by department_id);
Other use of correlation is in UPDATE and DELETE
CORRELATED UPDATE :
UPDATE table1 alias1
SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column =
alias2.column);
Use a correlated subquery to update rows in one table based on rows from another
table.
CORRELATED DELETE :
63
DELETE FROM table1 alias1
WHERE column1 operator
(SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows from another
table.
Using the EXISTS Operator :
The EXISTS operator tests for existence of rows in the results set of the subquery. If a
subquery row value is found the condition is flagged TRUE and the search does not
continue in the inner query, and if it is not found then the condition is
flagged FALSE and the search continues in the inner query.
EXAMPLE of using EXIST operator :
Find employees who have at least one person reporting to them.

SELECT employee_id, last_name, job_id, department_id


FROM employees outer
WHERE EXISTS ( SELECT ’X’
FROM employees
WHERE manager_id =
outer.employee_id);
OUTPUT :

EXAMPLE of using NOT EXIST operator :


Find all departments that do not have any employees.

SELECT department_id, department_name


FROM departments d
WHERE NOT EXISTS (SELECT ’X’
64
FROM employees
WHERE department_id
= d.department_id);
OUTPUT :

SQL Join statement is used to combine data or rows from two or more tables based on
a common field between them. Different types of Joins are as follows:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
Sample Table

EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT
65
Backward Skip 10sPlay VideoForward Skip 10s
PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as
the condition is satisfied. It returns the combination of all rows from both the tables
where the condition satisfies.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values from the
right table. If there is no matching join value, it will return NULL.
66
Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

3. RIGHT JOIN

In SQL, RIGHT JOIN returns all the values from the values from the rows of right table
and the matched values from the left table. If there is no matching in both tables, it will
return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


67
2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches not
found.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing
68
Kristen Development

Russell NULL

Marry NULL

RESULT

Thus, the Sub queries (Nested, Correlated) and Joins were executed successfully

EXPERIMENT 9: Practice Queries using COUNT, SUM, AVG, MAX, MIN,


GROUP BY, HAVING, VIEWS Creation and Dropping.

69
SQL Aggregate Functions: SUM(), COUNT(), AVG(), Functions
An aggregate function in SQL performs a calculation on multiple values and returns a
single value. SQL provides many aggregate functions that include avg, count, sum, min,
max, etc. An aggregate function ignores NULL values when it performs the calculation,
except for the count function.

Various types of SQL aggregate functions are:

 Count()

 Sum()

 Avg()

 Min()

 Max()

COUNT() Function

The COUNT() function returns the number of rows in a database table.

Syntax:

COUNT(*)

or

COUNT( [ALL|DISTINCT] expression )

Example:

We will use the ‘products’ table from the sample database for our demonstration.

70
The following SQL statement fetches the number of products in the table.

This will produce the following result.

The below-given command will display those product ids where the unit price is greater
than 4.

This will display the following result.

Let's look at how we can use GROUP BY and HAVING functions with the COUNT
function.

Consider the following dataset:

The SQL command given below will list the number of customers in each city.

71
This will produce the following results:

SUM() Function

The SUM() function returns the total sum of a numeric column.

Syntax:

SUM()

or

SUM( [ALL|DISTINCT] expression )

Example:

The following SQL statement finds the sum of the "unit price" fields in the "products"
table:

This will produce the following result.

72
Let’s look at how we can use GROUP BY and HAVING functions with the SUM function.

Consider the following dataset:

The SQL command below will list the number of customers in each city, having a sum of
points greater than 3000.

This will produce the following result:

AVG() Function

The AVG() function calculates the average of a set of values.

Syntax:

AVG()

or

73
AVG( [ALL|DISTINCT] expression )

Example:

The following SQL command calculates the average quantity in stock.

This will produce the following result.

MIN() Function

The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL
values.

Syntax:

MIN()

or

MIN( [ALL|DISTINCT] expression )

Example:

The above code will give us the minimum quantity in stock in the products table.

Also Read: How to Aggregate Data Using Group By in SQL?

74
MAX() Function

The MAX() aggregate function returns the highest value (maximum) in a set of non-
NULL values.

Syntax:

AVG()

or

AVG( [ALL|DISTINCT] expression )

Example:

The code depicted below will give us the maximum quantity in stock in the products
table.

This will produce the following result.

RESULT

Thus, the Queries using COUNT, SUM, AVG, MAX, MIN, GROUP BY, HAVING, VIEWS
Creation and Dropping was executed successfully.
EXPERIMENT 10: Practicing on Triggers - creation of trigger, Insertion
using trigger, Deletion using trigger, Updating using trigger .

A SQL Server Trigger is a block of procedural code executed when a specified event
occurs with which the trigger is associated.

The most common triggers are DML triggers that log events, such as when a user
INSERTS, UPDATES, or DELETES a row in a table which is issued in a SQL query or
stored procedure. SQL triggers can also be used to log (insert into a log table) when a
user connects to a database. SQL triggers can also record when a user or event modifies
a table and more.

75
Triggers can be nested—that is to say, you can create a trigger on Table A that updates
Table B, and Table B could have a trigger that updates Table C. The maximum number of
nested trigger executions is 32.

SQL Server Trigger Points of Interest:

 Triggers cannot be manually executed.


 Triggers cannot contain or receive parameters.
 You cannot use commit or rollback inside a trigger.
 The triggers schema must be the same as the schema of the table or view
associated with the trigger.

It is important to note that all triggers on a table will be deleted when the table itself is
deleted. If you are trying to delete and rebuild a table, you will also need to rebuild any
triggers on that table.

Classes of Triggers in SQL Server

There are three types or classes of triggers in SQL Server, DML, DDL, and Logon triggers:

 DML (Data Manipulation Language) Triggers – Fire when an INSERT, UPDATE, or


DELETE event occurs on a table, view, etc.
 DDL (Data Definition Language) Triggers – Fire when a CREATE, ALTER, or
DROP event occurs on a database object.
 Logon Triggers – Fire when a user logs into a database i.e. logon event.

This article will focus on the most common of the three types of triggers: DML triggers.

SQL Server supports three types of DML triggers:

 BEFORE Triggers – This type of trigger fires before the data has been committed
into the database.
 AFTER Triggers – This type of trigger fires after the event it is associated with
completes and can only be defined on permanent tables.
 INSTEAD OF Triggers – This type of trigger fires instead of the event it is
associated with and can be applied to tables or views.
INSERTED and DELETED Table Reference

DML triggers use two temporary tables created automatically by SQL Server named
"INSERTED" and "DELETED". It's a good idea NOT to use one of these names when
creating tables for your use. These tables contain the data (rows) that were affected by
the modification that caused the trigger to fire.

The temporary table INSERTED holds the new data of the affected rows when an
INSERT or UPDATE statement has been executed.

The temporary table DELETED holds the old data of the affected rows when an UPDATE
or DELETED statement has been executed. See the chart below for a visual comparison.

76
INSERTED Table DELETED Table
Holds the new values to be inserted Holds a copy of DELETED (old) data during
during INSERT or UPDATE event. a DELETE or UPDATE event.
No records from DELETE statements. No records from INSERT statements.
Basic Syntax for a DML Trigger
CREATE TRIGGER [schema_name.]trigger_name -- Create Trigger Statement
ON { table_name | view_name }
{ FOR | AFTER | INSTEAD OF } {[INSERT],[UPDATE],[DELETE]}
[NOT FOR REPLICATION]
AS
{sql_statements}

Here is a breakdown of the syntax in the code block above.

 CREATE TRIGGER – The SQL command to start creating a SQL Trigger.


 Schema_name – (Optional) Name of the SQL schema the trigger will be created
in. If left blank, SQL will, by default, assign it to the "dbo" schema.
 Trigger_name – The name we provide for the new trigger. Make this descriptive
of what the trigger does.
 ON table_name or view_name – Specifies which table or view the trigger will be
created.
 FOR AFTER or INSTEAD OF INSERT UPDATE or DELETE
o The AFTER and INSTEAD OF are optional, but the INSERT, UPDATE, or
DELETE are mandatory.
o The AFTER clause means that the trigger will only fire after the SQL query
that fires the trigger completes successfully.
o The INSTEAD OF skips the INSERT, UPDATE, or DELETE statements to a
table and executes other statements defined in the trigger. Note: The
INSTEAD OF clause cannot be used on DDL triggers, only DML triggers.
 NOT FOR REPLICATION –Instructs SQL Server not to run the trigger when a
replication agent modifies the table. However, the NOT FOR REPLICATION clause
is not needed on single standalone database servers or servers that are part of an
Availability Group.

Creating Your First Trigger

This article will cover a simple DML trigger in four steps. We will create two simple
tables followed by an INSERT trigger, an UPDATE trigger, and a DELETE trigger.
Afterward, we roll them all into one cohesive trigger.

Our first step is to build a sample "data" table to work with, along with a sample "log"
table. We will use those tables to create our triggers against and test them. Note: Try
this on your test environment, NOT your production environment in SQL Server
Management Studio.

Create the Employee Table


77
CREATE TABLE Employee
(
EmployeeID int NOT NULL,
FirstName nvarchar(50) NOT NULL,
LastName nvarchar(50) NOT NULL,
HireDate date,
);
Create the Log Table

The Log table should contain one or more columns from the primary table. In this case,
there is the Employee table and some additional columns. In our sample Log table, we
will also capture the current date and time (UpdatedOn column) along with the user
that made the changes to the Employee table (UpdatedBy column).

CREATE TABLE EmpLog (


logID INT IDENTITY(1,1) NOT NULL
, EmployeeID INT NOT NULL
, FirstName NVARCHAR(50) NOT NULL
, LastName NVARCHAR(50) NOT NULL
, HireDate date NOT NULL
, Operation NVARCHAR(50)
, UpdatedOn DATETIME
, UpdatedBy NVARCHAR(50)
);
GO
The INSERT Trigger

Now that we have our two sample tables to work with, let's create a simple INSERT
trigger to capture any INSERT actions that a user might apply to the Employee table.
Notice, in our "FROM" statement, we are getting the data for our EmpLog table from the
SQL Server temporary table "INSERTED," as we discussed earlier.

We are also adding a string value ‘INSERT' along with the current date and time via the
"GETDATE()" function and the current user with the "SUSER_NAME()" function in the
"SELECT" command.

CREATE TRIGGER trgEmployeeInsert


ON Employee
FOR INSERT
AS
INSERT INTO EmpLog(EmployeeID, FirstName, LastName, HireDate, Operation,
UpdatedOn, UpdatedBy)
SELECT EmployeeID, Firstname, LastName, HireDate, 'INSERT', GETDATE(),
SUSER_NAME()
FROM INSERTED;
GO

78
Now that we have our two tables and trigger created on our "Employee" table, let's
insert data into our "Employee" table and see the results when we query the "EmpLog"
table.

INSERT INTO Employee


VALUES(101, 'Neena','Kochhar','05-12-2018'),
(112, 'John','King','01-01-2015');
GO

A simple query on the "EmpLog" table will show who updated the "Employee" table,
what time they did so, and what action was taken.

SELECT *
FROM EmpLog
ORDER BY EmployeeID;
GO

Results:

The DELETE Trigger

Now that we understand how to create a basic INSERT trigger, let's apply the same logic
to create a DELETE trigger. The similarities of these two triggers are so close that it
allows us to simply copy/paste the INSERT trigger and give the delete trigger a
distinctive name. We will replace the instances of INSERT or INSERTED with DELETE
and DELETED, respectively. Those are the only changes that need to be applied.

Note: With the DELETE trigger, we will pull values from the SQL temporary table
"DELETED" instead of the SQL temporary table "INSERTED". You can reference "Table
1" to refresh your memory on what is stored in which SQL temporary table.

Before we create the DELETE trigger, let's populate our Employee table with a few more
entries.

INSERT INTO Employee


VALUES (203, 'Catherine','Abel','07-21-2010'),
(411, 'Sam','Abolrous','03-12-2016');
GO

The Employee table should look like this:

79
And the Employee log table should look like this:

As mentioned earlier, creating the DELETE trigger involves copying/pasting and


changing the values from insert to delete.

CREATE TRIGGER trgEmployeeDelete


ON Employee
FOR DELETE
AS
INSERT INTO EmpLog(EmployeeID, FirstName, LastName, HireDate, Operation,
UpdatedOn, UpdatedBy)
SELECT EmployeeID, Firstname, LastName, HireDate, 'DELETED', GETDATE(),
SUSER_NAME()
FROM DELETED;
GO

Now that we have created our INSERTED and DELETED triggers, let's test the delete
operation with this SQL query.

DELETE
FROM Employee
WHERE EmployeeID = 203;
GO

Let's run a query for the Employee table and the EmpLog table to see our results.

SELECT *
FROM Employee;
GO
SELECT *
FROM EmpLog;
GO
80
Results:

Notice that we are now missing Employee number 203 (Catherine Abel) from the
Employee table, and we have a new row marked as DELETED in the EmpLog table.

The UPDATE Trigger

This section will create an UPDATE trigger as we did with the INSERT and DELETE
triggers from above. Again, the only difference between the three triggers, besides the
trigger's name, is that we are replacing INSERT with UPDATE. Aside from those
changes, the triggers will be identical.

Remember: The updated values can be pulled from the INSERTED or DELETED
temporary tables created by SQL Server. You can call either one in the example below.

Still working with our current tables, let's do another copy/paste to create our update
trigger.

CREATE TRIGGER trgEmployeeUpdate


ON Employee
FOR UPDATE
AS
INSERT INTO EmpLog(EmployeeID, FirstName, LastName, HireDate, Operation,
UpdatedOn, UpdatedBy)
SELECT EmployeeID, Firstname, LastName, HireDate, 'UPDATE', GETDATE(),
SUSER_NAME()
FROM INSERTED;
GO

Next, we just need to call an update on our table to see the changes. Let's assume that
Neena Kochhar just got married and needs to change her last name to Adams.

UPDATE Employee
SET LastName = 'Adams'
WHERE EmployeeID = 101;
GO
81
Now, let's query both tables again to see the new results.

SELECT * FROM Employee;


GO
SELECT * FROM EmpLog;
GO

Results:

This time, the "Operation" column has UPDATE, and her new name appears in the
Employee table and the EmpLog table in the most recent entry. However, there was no
change to the first "INSERT" entry in the Emplog table, as seen on line 2 in the EmpLog
table. The UPDATE statement only changes items (values) in the Employee table, not the
log.

INSERT, UPDATE, DELETE Trigger

This section will put all three trigger options (INSERT, UPDATE, and DELETE) into one
trigger. Some may argue this is a good idea, while others contend it's not a good option.
I'll explain that in the following two paragraphs, and you can decide which option is best
for you.

Putting all three clauses (INSERT, UPDATE, and DELETE) into one trigger means fewer
triggers in your database.

Separating them into three different triggers means that if one fails, the other two
should complete successfully. With this, you still have some record of what action was
taken.

In the sample script below, we will combine all three triggers, INSERT, UPDATE, and
DELETE, into one. For this example, we will need to use the BEGIN and END statements
to create a break between one clause and the other. Notice that we are still getting data
from the INSERTED and DELETED temporary tables we discussed earlier.

Sample trigger to combine INSERT, UPDATE, and DELETE into one trigger.
82
CREATE TRIGGER trgEmployeeAudit ON dbo.Employee
FOR INSERT, UPDATE, DELETE
AS
IF EXISTS ( SELECT 0 FROM Deleted )
BEGIN
IF EXISTS ( SELECT 0 FROM Inserted )
BEGIN
INSERT INTO dbo.EmpLog
( EmployeeID,
FirstName,
LastName,
HireDate,
Operation,
UpdatedOn,
UpdatedBy
)
SELECT u.EmployeeID ,
u.FirstName,
u.LastName ,
u.HireDate ,
'Updated',
GETDATE() ,
SUSER_NAME()
FROM deleted as u
END
ELSE
BEGIN
INSERT INTO dbo.EmpLog
( EmployeeID ,
FirstName,
LastName,
HireDate,
Operation,
UpdatedOn,
UpdatedBy
)
SELECT d.EmployeeID ,
d.FirstName ,
d.LastName ,
d.HireDate ,
'Deleted',
GETDATE() ,
SUSER_NAME()
FROM deleted as d
END
END
ELSE
BEGIN
INSERT INTO dbo.EmpLog
( EmployeeID ,
83
FirstName,
LastName,
HireDate,
Operation,
UpdatedOn,
UpdatedBy
)
SELECT i.EmployeeID ,
i.FirstName ,
i.LastName ,
i.HireDate ,
'Inserted',
GETDATE() ,
SUSER_NAME()
FROM inserted as i
END
GO
The INSTEAD OF Clause

Okay, we have learned how to use the INSERT, DELETE, and UPDATE trigger functions,
but each required creating a separate table to hold the modified data. What if I don't
have or can't create a separate table?

The INSTEAD OF trigger allows us to modify the table in a way that appears to INSERT,
DELETE, or UPDATE values in a table when in fact, those actions are diverted, and
another action takes place instead.

In this section, we are going to do the following steps:

1. Create a new table, HREmployee. So we will have a clean slate to work with.
2. Populate the table with generic data.
3. Create an INSTEAD OF trigger on the table.
4. Create a view for users to access.
5. Attempt to delete one row.
6. Query the HREmployee table as an administrator.
7. Query the view as an end user.

Create a new table:

CREATE TABLE HREmployees(


EmployeeID INT
, FirstName VARCHAR(20)
, LastName VARCHAR(20)
, isActive BIT
);
GO

Add some data to the table.

84
INSERT INTO HREmployees(EmployeeID, FirstName, LastName, isActive)
VALUES (111, 'John', 'King', 1)
, (112, 'Sam', 'Smith', 1);
GO

Query the table to verify the entries.

SELECT *
FROM HREmployees;
GO

Results:

Now, let's create a view for the users to access instead of the table itself. In this view, we
will not allow them to see the "isActive" column and only allow them to see rows whose
"isActive" value is 1.

CREATE VIEW vHREmployees


AS
SELECT
EmployeeID
, FirstName
, LastName
FROM HREmployees
WHERE isActive = 1;
GO

When we run a query against the view, we get the following results:

Now, let's create the INSTEAD OF trigger on our HREmployees table. We do not allow a
user to delete any rows in this trigger. Instead, we will change the "isActive" value from
1 to 0 (zero). Remember, our view (what the user sees) does not have the "isActive"
column, and it will only return rows that have a 1 in the "isActive" column.

85
CREATE TRIGGER trgHREmployeeDoNotDelete
ON HREmployees
INSTEAD OF DELETE
AS
UPDATE HREmployees
SET isActive = 0
WHERE EmployeeID IN (SELECT EmployeeID FROM DELETED)
GO

As a user, we will try deleting from the table.

DELETE
FROM HREmployees
WHERE EmployeeID = 111;
GO

If we query the table as an administrator, we can see the new values of the "isActive"
column.

SELECT *
FROM HREmployees;
GO

Results:

As you can see, the DELETE statement did not delete any rows but simply changed the
"isActive" value from 1 to 0 (zero) as defined within our INSTEAD OF trigger.

Finally, let's query the view we created and see what is returned to the end user.

SELECT *
FROM vHREmployees;
GO

Results

86
The end user thinks the row has been deleted, but we know it has not. It's merely been
set to inactive, and the data remains in the table.

RESULT

Thus, the Triggers - creation of trigger, Insertion using trigger, Deletion using trigger,
Updating using trigger was executed successfully

87
EXPERIMENT 11: Procedures- Creation of Stored Procedures, Execution of
Procedure, and Modification of Procedure.

Create Stored Procedure

Use the CREATE statement to create a stored procedure.

Syntax:
CREATE [OR ALTER] {PROC | PROCEDURE} [schema_name.]
procedure_name([@parameter data_type [ OUT | OUTPUT | [READONLY]]
[ WITH <procedure_option> ]
[ FOR REPLICATION ]
AS
BEGIN
sql_statements
END

A stored procedure can contain one or more select, insert, update, or delete
statements. The following is an example of a simple stored procedure that returns the
records from the Employee table using the SELECT query.

Example: Simple Stored Procedure


Copy
CREATE PROCEDURE uspGetEmployeeList
AS
BEGIN
SELECT EmpID
,FirstName
,LastName
FROM dbo.Employee
END

Execute the above T-SQL script in the query editor to compile and create it in the
database, as shown below.

88
The above stored procedure can be executed using the EXEC keyword, as shown
below.

The following stored procedure inserts values in the Employee table.

Example: Stored Procedure for Insert Operation


Copy
CREATE PROCEDURE dbo.uspInsertEmployee
(
@FirstName nvarchar(50)
,@LastName nvarchar(50)
,@Email nvarchar(50)
,@PhoneNo nvarchar(20)
,@Salary money
)
89
AS
BEGIN
INSERT INTO dbo.Employee
(FirstName
,LastName
,Email
,PhoneNo
,Salary)
VALUES
(
@FirstName
,@LastName
,@Email
,@PhoneNo
,@Salary
)
END

The above stored procedure can be used to insert values to the Employee table
instead of the INSERT statement. Values are passed as parameters to the stored
procedure. The @ symbol is used as a prefix for parameter variables.

You can execute the uspInsertEmployee stored procedure using the EXEC keyword,
as shown below.

Example: Execute Stored Procedure


Copy
EXEC dbo.uspInsertEmployeeDetails
@FirstName ='Swati'
,@LastName = 'Karia'
,@Email = '[email protected]'
,@PhoneNo = '6657890980'
,@Salary = 300000

Specify each parameter separated by a command while executing a stored procedure.

90
View Stored procedure

Use sp_help or sp_helptext to see the text of an existing stored procedure, as shown
below.

91
All the stored procedures are listed under Programmability > Stored Procedures

folder under the database.

Modify Stored Procedure

Use the ALTER PROCEDURE statement to modify a stored procedure.

Example: Modify Stored Procedure


Copy
ALTER PROCEDURE dbo.uspGetEmployees
AS
BEGIN
SELECT EmpID
,FirstName
,LastName
,Salary
FROM dbo.Employee
END
92
Renaming Stored Procedure

Use the system stored procedure sp_rename to rename an existing stored procedure.
The following renames uspGetEmployeeList to uspGetEmployees.

Example: Rename Stored Procedure


Copy
sp_rename 'uspGetEmployeeList','uspGetEmployees'
Delete Stored Procedure

Use the DROP PROCEDURE statement to delete a stored procedure.

Example: Delete Stored Procedure


Copy
DROP PROCEDURE dbo.uspGetEmployees;
Handling Exceptions in Stored Procedures

In SQL Server, the TRY..CATCH block is used to handle exceptions gracefully. A group
of T-SQL statements can be enclosed in a TRY block. If an error is encountered in the
TRY block, the control is then passed to the CATCH block which will have another set
of SQL statements to handle the error.

In the CATCH block, system functions


like ERROR_NUMBER(), ERROR_STATE(), ERROR_SEVERITY() can be used to get
information about an error.

The following example handles the error in the uspEmpUpdate stored procedure.

Example: Exception Handling in Stored Procdure


Copy
CREATE PROCEDURE uspUpdateEmpSalary
(
@empId int
,@salary float
)
AS
BEGIN TRY
UPDATE dbo.Employee
SET Salary = @salary
WHERE EmployeeID = @empId
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
Create Stored Procedure

93
Use the CREATE statement to create a stored procedure.

Syntax:
CREATE [OR ALTER] {PROC | PROCEDURE} [schema_name.]
procedure_name([@parameter data_type [ OUT | OUTPUT | [READONLY]]
[ WITH <procedure_option> ]
[ FOR REPLICATION ]
AS
BEGIN
sql_statements
END

A stored procedure can contain one or more select, insert, update, or delete
statements. The following is an example of a simple stored procedure that returns the
records from the Employee table using the SELECT query.

Example: Simple Stored Procedure


Copy
CREATE PROCEDURE uspGetEmployeeList
AS
BEGIN
SELECT EmpID
,FirstName
,LastName
FROM dbo.Employee
END

Execute the above T-SQL script in the query editor to compile and create it in the
database, as shown below.

The above stored procedure can be executed using the EXEC keyword, as shown
below.

The following stored procedure inserts values in the Employee table.

Example: Stored Procedure for Insert Operation


Copy
CREATE PROCEDURE dbo.uspInsertEmployee
(
@FirstName nvarchar(50)
,@LastName nvarchar(50)
,@Email nvarchar(50)
,@PhoneNo nvarchar(20)
,@Salary money
)
AS
BEGIN
INSERT INTO dbo.Employee
(FirstName
,LastName
94
,Email
,PhoneNo
,Salary)
VALUES
(
@FirstName
,@LastName
,@Email
,@PhoneNo
,@Salary
)
END

The above stored procedure can be used to insert values to the Employee table
instead of the INSERT statement. Values are passed as parameters to the stored
procedure. The @ symbol is used as a prefix for parameter variables.

You can execute the uspInsertEmployee stored procedure using the EXEC keyword,
as shown below.

Example: Execute Stored Procedure


Copy
EXEC dbo.uspInsertEmployeeDetails
@FirstName ='Swati'
,@LastName = 'Karia'
,@Email = '[email protected]'
,@PhoneNo = '6657890980'
,@Salary = 300000

Specify each parameter separated by a command while executing a stored procedure.

View Stored Procedure

Use sp_help or sp_helptext to see the text of an existing stored procedure, as shown
below.

All the stored procedures are listed under Programmability > Stored Procedures
folder under the database.

Modify Stored Procedure

Use the ALTER PROCEDURE statement to modify a stored procedure.

Example: Modify Stored Procedure


Copy
95
ALTER PROCEDURE dbo.uspGetEmployees
AS
BEGIN
SELECT EmpID
,FirstName
,LastName
,Salary
FROM dbo.Employee
END
Renaming Stored Procedure

Use the system stored procedure sp_rename to rename an existing stored procedure.
The following renames uspGetEmployeeList to uspGetEmployees.

Example: Rename Stored Procedure


Copy
sp_rename 'uspGetEmployeeList','uspGetEmployees'
Delete Stored Procedure

Use the DROP PROCEDURE statement to delete a stored procedure.

Example: Delete Stored Procedure


Copy
DROP PROCEDURE dbo.uspGetEmployees;
Handling Exceptions in Stored Procedures

In SQL Server, the TRY..CATCH block is used to handle exceptions gracefully. A group
of T-SQL statements can be enclosed in a TRY block. If an error is encountered in the
TRY block, the control is then passed to the CATCH block which will have another set
of SQL statements to handle the error.

In the CATCH block, system functions


like ERROR_NUMBER(), ERROR_STATE(), ERROR_SEVERITY() can be used to get
information about an error.

The following example handles the error in the uspEmpUpdate stored procedure.

Example: Exception Handling in Stored Procdure


Copy
CREATE PROCEDURE uspUpdateEmpSalary
(
@empId int
,@salary float
)
AS
BEGIN TRY
UPDATE dbo.Employee
SET Salary = @salary
WHERE EmployeeID = @empId
END TRY
96
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

RESULT

Thus, the queries for Procedures- Creation of Stored Procedures, Execution of


Procedure, and Modification of Procedure was executed successfully.

97
EXPERIMENT 12: Cursors- Declaring and Opening Cursor, Fetching the
data, closing the cursor.

What is CURSOR in PL/SQL?


A Cursor is a pointer to this context area. Oracle creates context area for processing an
SQL statement which contains all information about the statement.

PL/SQL allows the programmer to control the context area through the cursor. A cursor
holds the rows returned by the SQL statement. The set of rows the cursor holds is
referred as active set. These cursors can also be named so that they can be referred
from another place of the code.

The cursor is of two types.

 Implicit Cursor
 Explicit Cursor

Implicit Cursor
Whenever any DML operations occur in the database, an implicit cursor is created that
holds the rows affected, in that particular operation. These cursors cannot be named
and, hence they cannot be controlled or referred from another place of the code. We can
refer only to the most recent cursor through the cursor attributes.

Explicit Cursor
Programmers are allowed to create named context area to execute their DML
operations to get more control over it. The explicit cursor should be defined in the
declaration section of the PL/SQL block, and it is created for the ‘SELECT’ statement that
needs to be used in the code.

Below are steps that involved in working with explicit cursors.

Declaring the cursor Declaring the cursor simply means to create one named context
area for the ‘SELECT’ statement that is defined in the declaration part. The name of this
context area is same as the cursor name.

 Opening CursorOpening the cursor will instruct the PL/SQL to allocate the
memory for this cursor. It will make the cursor ready to fetch the records.

 Fetching Data from the CursorIn this process, the ‘SELECT’ statement is
executed and the rows fetched is stored in the allocated memory. These are now
called as active sets. Fetching data from the cursor is a record-level activity that
means we can access the data in a record-by-record way. Each fetch statement
will fetch one active set and holds the information of that particular record. This
98
statement is same as ‘SELECT’ statement that fetches the record and assigns to
the variable in the ‘INTO’ clause, but it will not throw any exceptions.

 Closing the CursorOnce all the record is fetched now, we need to close the
cursor so that the memory allocated to this context area will be released.

Syntax:
DECLARE
CURSOR <cursor_name> IS <SELECT statement^>
<cursor_variable declaration>
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
.
.
CLOSE <cursor_name>;
END;

 In the above syntax, the declaration part contains the declaration of the cursor
and the cursor variable in which the fetched data will be assigned.
 The cursor is created for the ‘SELECT’ statement that is given in the cursor
declaration.
 In execution part, the declared cursor is opened, fetched and closed.

Cursor Attributes
Both Implicit cursor and the explicit cursor has certain attributes that can be accessed.
These attributes give more information about the cursor operations. Below are the
different cursor attributes and their usage.

Cursor
Description
Attribute
It returns the Boolean result ‘TRUE’ if the most recent fetch operation fetched a reco
%FOUND
it will return FALSE.
This works oppositely to %FOUND it will return ‘TRUE’ if the most recent fetch oper
%NOTFOUND
to fetch any record.
%ISOPEN It returns Boolean result ‘TRUE’ if the given cursor is already opened, else it returns ‘F
%ROWCOUNT It returns the numerical value. It gives the actual count of records that got affected by
Explicit Cursor Example:
In this example, we are going to see how to declare, open, fetch and close the explicit
cursor.

We will project all the employee’s name from emp table using a cursor. We will also use
cursor attribute to set the loop to fetch all the record from the cursor.

99
DECLARE
CURSOR guru99_det IS SELECT emp_name FROM emp;
lv_emp_name emp.emp_name%type;

BEGIN
OPEN guru99_det;

LOOP
FETCH guru99_det INTO lv_emp_name;
IF guru99_det%NOTFOUND
THEN
EXIT;
END IF;
Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name);
END LOOP;
Dbms_output.put_line(‘Total rows fetched is‘||guru99_det%R0WCOUNT);
CLOSE guru99_det;
END:
/
Output

Employee Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY
Total rows fetched is 3

10
0
Code Explanation:

 Code line 2: Declaring the cursor guru99_det for statement ‘SELECT emp_name
FROM emp’.
 Code line 3: Declaring variable lv_emp_name.

 Code line 5: Opening the cursor guru99_det.


 Code line 6: Setting the Basic loop statement to fetch all the records in the ’emp’
table.
 Code line 7: Fetches the guru99_det data and assign the value to lv_emp_name.
 Code line 9: Using the cursor attribute ‘%NOTFOUND’ to find whether all the
record in the cursor is fetched. If fetched then it will return ‘TRUE’ and control
will exit from the loop, else the control will keep on fetching the data from the
cursor and print the data.
 Code line 11: EXIT condition for the loop statement.
 Code line 12: Print the fetched employee name.
 Code line 14: Using the cursor attribute ‘%ROWCOUNT’ to find the total number
of records that got affected/fetched in the cursor.
 Code line 15: After exiting from the loop the cursor is closed and the memory
allocated is set free.

FOR Loop Cursor statement


“FOR LOOP” statement can be used for working with cursors. We can give the cursor
name instead of range limit in the FOR loop statement so that the loop will work from
the first record of the cursor to the last record of the cursor. The cursor variable,
opening of cursor, fetching and closing of the cursor will be done implicitly by the FOR
loop.

Syntax:
DECLARE
CURSOR <cursor_name> IS <SELECT statement>;
BEGIN
FOR I IN <cursor_name>
LOOP
.
.
END LOOP;
END;

 In the above syntax, the declaration part contains the declaration of the cursor.
 The cursor is created for the ‘SELECT’ statement that is given in the cursor
declaration.
 In execution part, the declared cursor is setup in the FOR loop and the loop
variable ‘I’ will behave as cursor variable in this case.

Oracle Cursor for Loop Example:


In this example, we will project all the employee name from emp table using a cursor-
FOR loop.
10
1
DECLARE
CURSOR guru99_det IS SELECT emp_name FROM emp;
BEGIN
FOR lv_emp_name IN guru99_det
LOOP
Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name.emp_name);
END LOOP;
END;
/
Output

Employee Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY

RESULT

Thus, the Cursors- Declaring and Opening Cursor, Fetching the data, closing the cursor
was executed successfully.

10
2
TEST PROJECT DESCRIPTION
S.No. List of Projects Project Description
1. College Admission The admission management system is a digital tool
Management System that helps educational institutions manage the student
enrollment process effortlessly. It lets admission teams
capture student inquiries, check their eligibility, follow-
up, collect documents, and complete the application
process digitally.
2. Restaurant Restaurant management refers to the process of
Management managing day-to-day operations within a restaurant or
System similar setting. It encompasses a broad range of tasks and
responsibilities, from overseeing company finances and
facilitating business growth to overseeing marketing,
managing the workforce, and delivering a great customer
experience.
3. Movie The project objective is to book cinema tickets in
booking online. The Ticket Reservation Systemis an Internet based
Management application that can be accessed throughout the Net and
System can be accessed by anyone who has a net connection. This
applicationwill reserve the tickets. This online ticket
reservation system provides a website for a cinema hall
where any user of internet can access it. User is required
to login to the system and needs a credit card for booking
the tickets. Tickets can be collected at the counter and
Watching movies with family and friendsin theatresis one
ofthe best medium of entertainment after having a hectic
schedule. But all this excitement vanishes after standing
in hours in long queues to get tickets booked. The website
provides complete information regarding currently
running movies on allthe screens with details
ofshowtimings, available seats
4. Vehicle A parking management system automates a car
Parking parking system. It optimizes parking space and make
Management processes efficient. It gives real-time car parking
System information such as vehicle & slot counts, available slots
display, reserved parking, pay-and-park options, easy
payments, reports, and a host of other features.
5. Travel Travel Management System (TMS) is an end to end
Planner complete software solution which helps the end-users or
Management travel agents to manage service providers, bookings,
System pricing, tracking, analyzing the inventory, etc.
This travel management solution may include all the
travel branches like Hotel, Car, Bus, Rail, Air, individual,
or group tourist package.
6. Toll Booth Toll Plaze Management system is designed to
Management automatically keep track of the vehicle’s movement,
System record the time and the details like Owner’s name, date of
registration, vehicle model etc. This system is very useful
10
3
for automatic vehicle tracking, time management and also
for automation of Toll gate. Online Toll Gate Management
systems have been of great assistance in lessening the
over congestion that has become a part of the
metropolitan cities these days. It is one of the
uncomplicated ways to manage the great run of traffic.
The travelers passing through this mode of transport,
carried by their transport that allows them to be aware of
the account of money that has been paid and the money
left in the tag. It relieves the traveler of the burden of
waiting in the queue to make the toll payment, which
decreases the fuel-consumption and also taking cash with
them can be avoided.

7. Mini mart With the development of science and technology


Management and popularity of computer, people have deeply realized
System computers bring convenience to our work and life.
Computer has entered the human society and is playing
an important role increasingly. Therefore, for a small
supermarket, also it is necessary to develop a system to
manage all kinds of data information in a supermarket.
This paper mainly discusses the design thought and
implementation method based on VFP small supermarket
management system. Aiming at breaking the closure and
limitation of small supermarket management system, this
system can not only deal with VFP data, but also can
import and export Excel, Word data and Web data,
improving the sharing of heterogeneous data, avoiding
the repetition input of the same data, to effectively
improve the efficiency of the supermarket.
8. Hospital Data Hospital Management System is a system enabling
Management hospitals to manage information and data related to all
System aspects of healthcare – processes, providers, patients, and
more, which in turn ensures that processes are completed
swiftly and effectively.
9. Bike/ Car The advancement in Information Technology and
rental internet penetration has greatly
Management enhanced various business processes and communication
System between companies services
provider and their customers of which bike rental
industry is not left out. This E-Bike
Rental system is developed to provide the following
services
•Enhance Business Processes To be able to use internet
technology to project the rental
company to the global world instead of limiting their
services to their local domain alone,
thus increase their return on investmen
This system is designed to help the customers to
take bikes or two-wheelers for rent. When we go on any
10
4
trip outside the town or country, we want to be free of
time so instead of going through metros and taxis, we
prefer to have our own vehicle for rent. Using this system
vehicle owners can register as sellers and customers who
want to take bikes on rent can register themselves as
renters and can take any bike on rent. Address of the both
are required as the customer can only take bike by going
to the address provided and the vehicle owners can know
the address that a customer is verified or not. The
customer also has to upload some proofs to take the bike
on rent.
10. Banking - Bank management system can be consider as a
Management most important thing in economic world.in the present
System scenario the banking sector is the common need in
everyday life.in day to day life we face the problems and
then we realize something is not done in this sector like
we want to change the location (branch) of our account
then we need to fill the application and then some day
waiting to complete bank process. In this process amount
of time is more as well as here occur manual work which
is increases man power. Also in current scenario aadhar
card linking is must with bank account and it is possible
through the ATM but if in urgent we want to link aadhar it
may be not possible there is no ATM are available in that
case we provide this facility through the our project i.e.
Bank management system.
11. Library A library management system is software that is
Management designed to manage all the functions of a library. It helps
System librarian to maintain the database of new books and the
books that are borrowed by members along with their
due dates. This system completely automates all your
library's activities.
12. Product Review management is the process of monitoring
review customer reviews posted about your brand on websites
Management and social media channels. Every small and large business
System should actively monitor, analyze, and respond to all
reviews, regardless of sentiment. An efficient customer
review management strategy can help you tackle negative
(and fake) reviews and promote positive ones to build a
positive brand image.
13. Employee a payroll management system is the process by
payslip which employers pay wages to their employees. It's also
Management how they demonstrate their commitment to their
System workers, fulfill their obligations to government agencies
and keep financial records in order.
14. School A school management system is a software
Management application that is designed to streamline various
System administrative tasks within a school. This system is
designed to automate a range of processes such as
student enrolment, course scheduling, fee management,
10
5
library management, attendance tracking, and more.
15. Online An online shopping system is a process in which
Shopping people (specifical customers) are being provided with the
Management option of purchasing goods and services directly from the
System seller, all in a real-time environment. Online shopping is
an application of the internet as electronic commerce.
From the business perspective, customers usually find the
products more attractive, on websites, as they get all the
details available there.

10
6

You might also like