DBMS Lab Manual New Format
DBMS Lab Manual New Format
DBMS Lab Manual New Format
LABORATORY MANUAL
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
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
Department Mission
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
Identify and prioritize Quality education in of Computer Science and Business systems
Provide a focal point for an extended IT quality network comprised of end users and
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.
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
Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
Dont’s
Do not eat or drink in the laboratory.
Do not insert metal objects such as clips, pins and needles into the computer casings.
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.
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
Do not spill water or any other liquid on the machines in order to maintain electrical
safety.
changing the desktop back Ground or changing the video and audio settings.
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
16
OBJECTIVES: Course Objectives and Course Outcomes
OUTCOMES:
17
Mapping Course Outcome with Program Outcome
Course
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
techniques
for large volumes of data.
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
1 Student should decide on a case study and formulate the problem statement.
7 Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT, etc
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.
INDEX
21
List of Experiments Page No
S.No
1 Student should decide on a case study and formulate the 27
problem statement.
22
INDEX
23
YOU TUBE LINKS FOR THE LAB SESSION
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
RESULT
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.
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:
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.
Example:
An employee reports to another Employee.
30
Now, let us move into the Cardinality.
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:
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.
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
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
In general conversion of E-R diagram into a relational model involves the following:
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.
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.
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.
RESULT
37
Thus, the Conversion of ER Model to Relational Model was executed successfully
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.
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.
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
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.
rows of data.
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
1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)
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.
(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));
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.
(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
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
47
defined as a Primary Key in the table which it is referring. One or more columns can
be defined as Foreign key.
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".
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
product(product_id),
product_name char(20),
supplier_name char(20),
48
unit_price number(10)
);
( order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
product(product_id)
);
( id number(5),
dept char(10),
49
age number(2),
salary number(10),
location char(10)
);
name char(20),
dept char(10),
age number(2),
salary number(10),
);
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
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
Check Constraint at table level:
CREATE TABLE employee
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'))
);
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;
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:
Syntax:
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:
Syntax:
ROLLBACK;
Example:
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?
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
You want to give a prize to all the Speakers and Authors at the annual conference.
Hence, how will you prepare the prize list?
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?
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?
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?
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 −
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 −
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.
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
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
Query
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
Query
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
Query
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
Query
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
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.
Count()
Sum()
Avg()
Min()
Max()
COUNT() Function
Syntax:
COUNT(*)
or
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.
The below-given command will display those product ids where the unit price is greater
than 4.
Let's look at how we can use GROUP BY and HAVING functions with the COUNT
function.
The SQL command given below will list the number of customers in each city.
71
This will produce the following results:
SUM() Function
Syntax:
SUM()
or
Example:
The following SQL statement finds the sum of the "unit price" fields in the "products"
table:
72
Let’s look at how we can use GROUP BY and HAVING functions with the SUM function.
The SQL command below will list the number of customers in each city, having a sum of
points greater than 3000.
AVG() Function
Syntax:
AVG()
or
73
AVG( [ALL|DISTINCT] expression )
Example:
MIN() Function
The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL
values.
Syntax:
MIN()
or
Example:
The above code will give us the minimum quantity in stock in the products table.
74
MAX() Function
The MAX() aggregate function returns the highest value (maximum) in a set of non-
NULL values.
Syntax:
AVG()
or
Example:
The code depicted below will give us the maximum quantity in stock in the products
table.
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.
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.
There are three types or classes of triggers in SQL Server, DML, DDL, and Logon triggers:
This article will focus on the most common of the three types of triggers: 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}
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.
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).
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.
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.
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:
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.
79
And the Employee log table should look like this:
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.
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.
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.
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.
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.
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.
84
INSERT INTO HREmployees(EmployeeID, FirstName, LastName, isActive)
VALUES (111, 'John', 'King', 1)
, (112, 'Sam', 'Smith', 1);
GO
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.
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
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.
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.
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 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.
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
Use the system stored procedure sp_rename to rename an existing stored procedure.
The following renames uspGetEmployeeList to uspGetEmployees.
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.
The following example handles the error in the uspEmpUpdate 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.
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 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.
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.
Use the system stored procedure sp_rename to rename an existing stored procedure.
The following renames uspGetEmployeeList to uspGetEmployees.
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.
The following example handles the error in the uspEmpUpdate stored procedure.
RESULT
97
EXPERIMENT 12: Cursors- Declaring and Opening Cursor, Fetching the
data, closing the cursor.
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.
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.
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.
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.
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.
10
6