DBMS Lab Manual
DBMS Lab Manual
Lab Manual
Third Year Semester-V
Subject: Database and Information System Lab
Odd Semester
1
Institutional Vision, Mission and Quality Policy
Our Vision
To foster and permeate higher and quality education with value added engineering, technology
programs, providing all facilities in terms of technology and platforms for all round development with
societal awareness and nurture the youth with international competencies and exemplary level of
employability even under highly competitive environment so that they are innovative adaptable and
capable of handling problems faced by our country and world at large.
RAIT’s firm belief in new form of engineering education that lays equal stress on academics and
leadership building extracurricular skills has been a major contribution to the success of RAIT as one
of the most reputed institution of higher learning. The challenges faced by our country and world in
the 21 Century needs a whole new range of thought and action leaders, which a conventional
educational system in engineering disciplines are ill equipped to produce. Our reputation in providing
good engineering education with additional life skills ensure that high grade and highly motivated
students join us. Our laboratories and practical sessions reflect the latest that is being followed in the
Industry. The project works and summer projects make our students adept at handling the real life
problems and be Industry ready. Our students are well placed in the Industry and their performance
makes reputed companies visit us with renewed demands and vigour.
Our Mission
The Institution is committed to mobilize the resources and equip itself with men and materials of
excellence thereby ensuring that the Institution becomes pivotal center of service to Industry,
academia, and society with the latest technology. RAIT engages different platforms such as
technology enhancing Student Technical Societies, Cultural platforms, Sports excellence centers,
Entrepreneurial Development Center and Societal Interaction Cell. To develop the college to become
an autonomous Institution & deemed university at the earliest with facilities for advanced research
and development programs on par with international standards. To invite international and reputed
national Institutions and Universities to collaborate with our institution on the issues of common
interest of teaching and learning sophistication.
RAIT’s Mission is to produce engineering and technology professionals who are innovative and
inspiring thought leaders, adept at solving problems faced by our nation and world by providing
quality education.
The Institute is working closely with all stake holders like industry, academia to foster knowledge
generation, acquisition, dissemination using best available resources to address the great challenges
being faced by our country and World. RAIT is fully dedicated to provide its students skills that make
them leaders and solution providers and are Industry ready when they graduate from the Institution.
2
We at RAIT assure our main stakeholders of students 100% quality for the programmes we deliver.
This quality assurance stems from the teaching and learning processes we have at work at our campus
and the teachers who are handpicked from reputed institutions IIT/NIT/MU, etc. and they inspire the
students to be innovative in thinking and practical in approach. We have installed internal procedures
to better skills set of instructors by sending them to training courses, workshops, seminars and
conferences. We have also a full fledged course curriculum and deliveries planned in advance for a
structured semester long programme. We have well developed feedback system employers, alumni,
students and parents from to fine tune Learning and Teaching processes. These tools help us to ensure
same quality of teaching independent of any individual instructor. Each classroom is equipped with
Internet and other digital learning resources.
The effective learning process in the campus comprises a clean and stimulating classroom
environment and availability of lecture notes and digital resources prepared by instructor from the
comfort of home. In addition student is provided with good number of assignments that would trigger
his thinking process. The testing process involves an objective test paper that would gauge the
understanding of concepts by the students. The quality assurance process also ensures that the
learning process is effective. The summer internships and project work based training ensure learning
process to include practical and industry relevant aspects. Various technical events, seminars and
conferences make the student learning complete.
It is our earnest endeavour to produce high quality engineering professionals who are
innovative and inspiring, thought and action leaders, competent to solve problems faced
by society, nation and world at large by striving towards very high standards in learning,
teaching and training methodology.
Dr. Vijay
D.PatilPresident,
RAES
3
Departmental Vision, Mission
Vision
To impart higher and quality education in computer science with value added engineering and
technology programs to prepare technically sound, ethically strong engineers with social awareness.
To extend the facilities, to meet the fast changing requirements and nurture the youths with
international competencies and exemplary level of employability and research under highly
competitive environments.
Mission
To mobilize the resources and equip the institution with men and materials of excellence to provide
knowledge and develop technologies in the thrust areas of computer science and Engineering. To
provide the diverse platforms of sports, technical, cocurricular and extracurricular activities for the
overall development of student with ethical attitude. To prepare the students to sustain the impact of
computer education for social needs encompassing industry, educational institutions and public
service. To collaborate with IITs, reputed universities and industries for the technical and overall
upliftment of students for continuing learning and entrepreneurship.
4
Departmental Program Outcomes (POs)
5
give and receive clear instructions.
PO11. Project management and finance: Demonstrate knowledge and 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.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
PSO1. To build competencies towards problem solving with an ability to understand, identify,
analyze and design the problem, implement and validate the solution including both hardware and
software.
PSO2. To build appreciation and knowledge acquiring of current computer techniques with an ability
to use skills and tools necessary for computing practice.
PSO3.To be able to match the industry requirements in the area of computer science and engineering.
To equip skills to adopt and imbibe new technologies.
6
Index
Sr. No. Contents Page No.
1. List of Experiments 8
7
List of Experiments
Sr. No. Experiments Name
8
Course Objective, Course Outcome&
Experiment Plan
Course Objective:
Course Outcomes:
CO1 Formulate problem Statement for real world example by using the fundamental
concept of database system.
CO2 Design with and draw ER and EER diagram for the real life problem.
CO3 Convert conceptual model into relational model with different DDL and DML
statements and Apply /Add integrity constraints and able to provide security to data.
CO4 Implement and execute Simple, Complex queries and join operations.
CO6 Understand the concept of concurrent transactions and able to access data through
front end (using JDBC/ODBC connectivity).
9
Experiment Plan
10
Co-Po Mapping for Practical
Subject Course Outcomes Contribution to Program outcomes
Weight
P P Pc P P P P P P P P P
O O O O O O O O O O O O
1 2 3 4 5 6 7 8 9 10 11 12
11
Mapping Course Outcomes (CO) –
Program Specific Outcomes (PSO)
CO2: Design with and draw ER and EER diagram for the 2 3 -
real life problem.
12
Study and Evaluation Scheme
Course
Course Name Teaching Scheme Credits Assigned
Code
Database & Theory Practical Tutorial Theory Practical Tutorial Total
CSL503 Info. System
Lab -
- 02 1 -- 01
Term Work
Practical and oral Exam should be conducted for the Lab, on Database Management System
subject for given list of experiments.
13
Database & Info. System Lab
Experiment No. : 1
14
Experiment No.1
1. Aim: Identify the case study and detail statement of problem.
2. Objectives:
Understand the Need and importance of Database Management
System in today’s world.
Problem Statement has to be written on any dbms case study. Problems statement
should consist of following points.
6. Conclusion: Formulate the problem statement for given case study and understand
the use and its applications in today’s world.
7. Viva Questions:
What is Need of DBMS?
Have you ever interacted with Database?
What is Meta-Data?
8. References:
15
1. G. K. Gupta :‖Database Management Systems‖, McGraw – Hill.
2. Korth, Slberchatz,Sudarshan, :‖Database System Concepts‖, 6th Edition, McGraw –
Hill
3. Elmasri and Navathe, ― Fundamentals of Database Systems‖, 5thEdition,
PEARSON
4. Peter Rob and Carlos Coronel, ― Database Systems Design, Implementation and
Management‖, Thomson Learning, 5th Edition.
16
Database & Info. System Lab
Experiment No.: 2
17
Experiment No.2
1. Aim: Design an Entity-Relationship (ER) / Extended Entity-Relationship (EER)
Model.
2. Objectives:
3. Outcomes:Design and draw ER and EER diagram for the real life problem.
ER- Diagram:
It is an Entity –Relationship diagram which is used to represent the relationship
between different entities. An entity is an object in the real world which is
distinguishable from other objects. The overall logical structure of a database can be
expressed graphically by an ER diagram, which is built up from following
components.
Mapping Cardinalities:
It expresses the number of entities to which another entity can be associated via
relationship set. For a binary relationship set R between entity sets A and B. The
Mapping Cardinalities must be one of the following.
• One to one
• One to many
• Many to one
• Many to many
18
4. Lines: link attribute to entity sets and entity sets to relationships.
5. Double eclipse represents multivalve attributes.
6. Double rectangle represents Weak entity sets.
7. Primary key attributes are underlined.
19
Example of Generalization and specialization.
Note: -Students has to draw ER diagram of their own case study by adding EER features.
Below is the example of ER diagram.
20
Example: Sample ER diagram for Company Management System
Note: Students has to draw the ER diagram for their case study topic.
9. Conclusion: Designed the ER and EER of the assigned case study topics and
understand the ER and EER Model in depth.
21
3. Elmasri and Navathe, ― Fundamentals of Database Systems‖, 5thEdition,
PEARSON
4. Peter Rob and Carlos Coronel, ― Database Systems Design, Implementation and
Management‖, Thomson Learning, 5th Edition.
22
Database & Info. System Lab
Experiment No.: 3
23
Experiment No.3
1. Aim:Perform experiment on mapping of ER/EER to Relational schema model
2. Objectives:
3. Outcomes:Design and draw ER and EER diagram for the real life problem.
5. Theory:
Rules to convert ER schema to relational schema.
For each weak entity type W in the ER schema with owner entity type E,
create a relation R & include all simple attributes (or simple components of
composite attributes) of W as attributes of R.
Also, include as foreign key attributes of R the primary key attribute(s) of the
relation(s) that correspond to the owner entity type(s).
The primary key of R is the combination of the primary key(s) of the owner(s)
and the partial key of the weak entity type W, if any.
For each binary 1:1 relationship type R in the ER schema, identify the
relations S and T that correspond to the entity types participating in R.
24
For each regular binary 1:N relationship type R, identify the relation S that
represent the participating entity type at the N-side of the relationship type.
Include as foreign key in S the primary key of the relation T that represents the
other entity type participating in R.
Include any simple attributes of the 1:N relation type as attributes of S.
For each regular binary M:N relationship type R, create a new relation S to
represent R.
Include as foreign key attributes in S the primary keys of the relations that
represent the participating entity types; their combination will form the
primary key of S.
Also include any simple attributes of the M:N relationship type (or
Simple components of composite attributes) as attributes of S.
For each n-ary relationship type R, where n>2, create a new relationship S to
represent R.
Include as foreign key attributes in S the primary keys of the relations that
represent the participating entity types.
Also include any simple attributes of the n-ary relationship type (or simple
components of composite attributes) as attributes of S.
Summary
25
n-ary relationship type Relationship relation and n foreign keys
Option 8A: Multiple relations—super class and subclasses, K for the relations
For any specialization (total or partial, disjoint or overlapping).
6. Conclusion :
After performing this experiment we are able to convert the Entity Relationship model
into relational model along with extended features of ER model.
26
7. Viva Questions:
8. References:
1. Elmasri and Navathe, ― Fundamentals of Database Systems‖, 5thEdition, PEARSON
2. Peter Rob and Carlos Coronel, ― Database Systems Design, Implementation and
Management‖, Thomson Learning, 5th Edition.
27
Database & Info. System Lab
Experiment No. : 4
28
Experiment No.4
1. Aim:Create and populate database using Data Definition Language (DDL) and DML
Commands for specified System.
3. Outcomes: Create and update database and tables with different DDL and DML
statements.
5. Theory:
Data types in SQL:-
Char (n)- A fixed length character length string with user specified length.
Number- Number is used to store numbers (fixed or floating point).
Int- an integer
Varchar (n)- A variable character length string with user specified maximum
length n.
Date- A calendar date containing a (four digit) year, month and day of the
month.
Time: The time of day, in hours, minutes and seconds Eg. Time ’09:30:00’.
SQL: It is structured query language, basically used to pass the query to retrieve
andmanipulate the information from database. Depending upon the nature of
query, SQL is divided into different components:
• DDL(Data Definition Language )
• DML(Data Manipulation Language )
• DCL(Data Control Language )
DDL: The Data Definition Language (DDL) is used to create the database (i.e.
tables, keys, relationships etc), maintain the structure of the database and
destroy databases and database objects.
Eg. Create, Drop, Alter, Describe, Truncate
29
CREATE TABLE table_name(columnName1 datatype(size), columnName2
datatype(size),………);
Syntax:
DESC table_name;
Syntax:
TRUNCATE TABLE table_name;
30
INSERT:
INSERT statement adds one or more records to any single table in a relational
database.
Syntax:
INSERT INTO tablename VALUES (expr1,expr2……..);
SELECT:
SELECT statement returns a result set of records from one or more tables.
The select statement has optional clauses:
Syntax:
SELECT<attribute list>
FROM<table list>
WHERE<condition>
Where
• Attribute list is a list of attribute name whose values to be retrieved by the query.
• Table list is a list of table name required to process query.
• Condition is a Boolean expression that identifies the tuples to be retrieved by query.
UPDATE:
UPDATE statement that changes the data of one or more records in a table.
Either all therows can be updated, or a subset may be chosen using a condition.
Syntax:
UPDATE table_name SET column_name = value [, column_name = value ...]
[WHERE
condition]
DELETE:
DELETE statement removes one or more records from a table. A subset may
be defined for deletion using a condition, otherwise all records are removed.
Syntax:
DELETE FROM tablename WHERE condition:
6. Conclusion:
For the given case study designed the databases schema and implemented queries
using DDL and DML commands.
7. Viva Questions:
How will you create the table?
What are DDL and DML commands?
What effect will cause by DROP table command?
31
9. References:
1. Elmasri and Navathe, ― Fundamentals of Database Systems‖, 5thEdition, PEARSON
2. Peter Rob and Carlos Coronel, ― Database Systems Design, Implementation and
Management‖, Thomson Learning, 5th Edition.
32
Database & Info. System Lab
Experiment No. : 5
33
Experiment No.5
1. Aim:Apply Integrity Constraints for the specified system.
2. Objectives:
Understand database Integrity Constraints.
To make the database schema more secure.
3. Outcomes: Apply /Add integrity constraints and able to provide security to data.
5. Theory:
Constraints are the Rules which are enforced on the data being stored in a table are
called Constraints.
-Table-level & Row-level constraints
-Types of constraints
1. NOT NULL
NOT NULL constraints are in-line constraints that indicate that a column can not
contain NULL values.
2. PRIMARY KEY
Primary key constraints define a column or series of columns that uniquely identify a
given row in a table. Defining a primary key on a table is optional and you can only
define a single primary key on a table. A primary key constraint can consist of one or
many columns (up to 32). Any column that is defined as a primary key column is
automatically set with a NOT NULL status.
34
Example:
CREATE TABLE SUPPLIER
( SUPPLIER_ID NUMERIC(10) NOT NULL,
SUPPLIER_NAME VARCHAR2(50) NOT NULL,
CONTACT_NAME VARCHAR2(50),
CONSTRAINT SUPPLIER_PK PRIMARY KEY (SUPPLIER_ID)
);
4. CHECK
Check constraints validate that values in a given column meet a specific criteria.
Example:
CREATE TABLE CUSTOMER
(SID NUMBER CHECK(SID>10),
LASTNAME VARCHAR(10),
FIRSTNAME VARCHAR(10|));
5. UNIQUE
Unique constraints are like alternative primary key constraints. A unique
constraint defines a column, or series of columns, that must be unique in
value.
6. Conclusion:For the case study topic created the schema according to entity and
referential integrity constraints.
7. Viva Questions:
What do you mean by constraints?
What are referential integrity constraints?
8. References:
35
Database & Info. System Lab Experiment
No. : 6
36
Experiment No. 6
1. Aim: Perform simple queries and string manipulation operations.
2. Find the names of all branches in the loan relations, and remove
duplicates
select distinct branch_name from loan
3. The keyword all specifies that duplicates not be removed.
select allbranch_namefrom loan
Where Clause:The where clause specifies conditions that the result must satisfy.
Example:To find all loan number for loans made at the Perryridge branch with
loan amounts greater than $1200.
37
The from Clause:The from clause lists the relations involved in the query
Example:Find the names of all customers whose street includes the substring “Main”.
select customer_namefrom customerwherecustomer_street like '% Main%'
LIKE is the ANSI/ISO standard operator for comparing a column value to another
column value, or to a quoted string. Returns either 1 (TRUE) or 0 (FALSE)
The SQL LIKE operator is only applied on a field of types CHAR or VARCHAR
to match a pattern.
To match a pattern from a word, special characters, and wildcards characters may
have used with LIKE operator.
WHERE CUSTOMERNAME LIKE 'A%' FINDS ANY VALUES THAT START WITH "A"
WHERE CUSTOMERNAME LIKE '% A' FINDS ANY VALUES THAT END WITH "A"
WHERE CUSTOMERNAME LIKE FINDS ANY VALUES THAT HAVE "R" IN THE
'_R%' SECOND POSITION
WHERE CUSTOMERNAME LIKE FINDS ANY VALUES THAT START WITH "A"
'A_%_%' AND ARE AT LEAST 3 CHARACTERS IN
LENGTH
38
WHERE CONTACT NAME LIKE 'A% O' FINDS ANY VALUES THAT START WITH "A"
AND ENDS WITH " O"
WHERE CUSTOMERNAME LIKE 'A%' FINDS ANY VALUES THAT START WITH "A"
The following SQL statement selects all customers with a CustomerName starting
with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending
with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have
"or" in any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have
"r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that starts
with "a" and are at least 3 characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a_%_%';
The following SQL statement selects all customers with a ContactName that starts
with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
39
The following SQL statement selects all customers with a CustomerName that does
NOT start with "a":
7. Viva Questions:
What is the use of where clause?
What are the two string operators mostly used in SQL?
8. References:
1. Elmasri and Navathe, ― Fundamentals of Database Systems‖, 5thEdition,
PEARSON
2. G. K. Gupta :‖Database Management Systems‖, McGraw – Hill.
3. Korth, Slberchatz,Sudarshan, :‖Database System Concepts‖, 6th Edition,
McGraw – Hill
40
Database & Info. System Lab
Experiment No. : 7
41
Experiment No. 7
1. Aim: Implement and execute Nested queries and Complex queries
5. Theory:
A Subquery or Inner query or Nested query is a query within another SQL query and
embedded within the WHERE clause.A subquery is used to return data that will be
used in the main query as a condition to further restrict the data to be retrieved.
SQL provides a mechanism for the nesting of subqueries.
A subquery is a select-from-where expression that is nested within another query.
A common use of subqueries is to perform tests for set membership, set
comparisons, and set cardinality.
2. Find all customers who have a loan at the bank but do not have an account at the bank.
42
3. Find all customers who have both an account and a loan at the Perryridge branch
select distinctcustomer_name
from borrower, loan
where borrower.loan_number = loan.loan_number and
branch_name = 'Perryridge' and
(branch_name, customer_name )in
(select branch_name, customer_name
from depositor, account
where depositor.account_number =
account.account_number )
Set Comparison
4. Find all branches that have greater assets than some branch located in Brooklyn.
6. Find the names of all branches that have greater assets than all branches located in
Brooklyn.
select branch_name
from branch
where assets >all
(select assets
from branch
where branch_city = 'Brooklyn')
43
7. Above query using >some clause
select branch_name
from branch
where assets >some
(select assets
from branch
where branch_city = 'Brooklyn')
8. Find the names of all branches that have greater assets than all branches located in
Brooklyn.
select branch_name
from branch
where assets >all
(select assets
from branch
where branch_city = 'Brooklyn')
The exists construct returns the value true if the argument subquery is nonempty.
exists r r Ø
not exists r r = Ø
Find all customers who have an account at all branches located in Brooklyn.
Derived Relations
Find the average account balance of those branches where the average account
balance is greater than $1200.
44
select branch_name, avg_balance
from (select branch_name, avg (balance)
from account
group by branch_name )
as branch_avg ( branch_name, avg_balance )
where avg_balance >1200
Note that we do not need to use the having clause, since we compute the temporary
(view) relation branch_avg in the from clause, and the attributes of branch_avg can be
used directly in the where clause.
With Clause
The with clause provides a way of defining a temporary view whose definition is
available only to the query in which the withclause occurs.
withmax_balance (value) as
selectmax (balance)
fromaccount
selectaccount_number
fromaccount, max_balance
whereaccount.balance = max_balance.value
7. Conclusion: We have studied the how sub-query expression can be used in from
clause to create temporary relation and as well as in where clause to perform tests for
set membership, set comparisons, and set cardinality.
8. Viva Questions:
45
Database & Info. System Lab
Experiment No. : 8
46
Experiment No. 8
1. Aim: Perform and Implement Join operations.
3. Outcomes: Implement and execute Simple, Complex queries and join operations.
5. Theory: SQL Join is used to fetch data from two or more tables, which is joined to
appear as single set of data. It is used for combining column from two or more tables
by using values common to both tables.
Types of JOIN
Following are the types of JOIN that we can use in SQL:
Inner Join
Outer Join
Left Join
Right Join
SELECT column-name-list
FROM
47
table-name1 CROSS JOIN table-name2;
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and
same datatype present in both the tables to be joined.
SELECT * FROM
OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide
further into,
The left outer join returns a resultset table with the matched data from the two tables
and then the remaining rows of the left table and null from the right table's columns.
48
table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
To specify a condition, we use the ON keyword with Outer Join.
The right outer join returns a resultset table with the matched data from the two tables
being joined, then the remaining rows of the right table and null for the remaining left
table's columns.
49
6. Conclusion: In this experiment we have studied and seen how the data stored across
multiple relation can be combined and retrieved as it were stored in single relation.
Also we have studied different form of joins and their usage and implementation as
well.
7. Viva Questions:
• What are the different types of SQL JOIN clauses, and how are they used?
• What is the difference between INNER JOIN and LEFT JOIN?
50
Database & Info. System Lab
Experiment No. : 9
51
Experiment No.9
1. Aim:Implement Views and Triggers.
2. Objectives:
Understand the customization of External schema using views.
Execution of procedures on event of modification to database.
A. Views
Views are virtual tables formed by a query. A view is a dictionary object that you can
use until you drop it. In Short, a view is a virtual table based on the result-set of an
SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
Syntax:
desc EMP_NO_DEPT_NO;
or
select * from EMP_NO_DEPT_NO;
The structure of view can also be updated with as structure of table is modified with
ALTER command, using following syntax:
52
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Now, to modifying the structure of view "EMP_NO_DEPT_NO" to add "SALARY"
column.
CREATE OR REPLACE VIEW EMP_NO_DEPT_NO AS SELECT EMPNO, DEPTNO, SAL FROM EMP;
Trigger:
Triggers; that is, procedures that are stored in the database and implicitly executed
("fired") when a table is modified. i.e define procedures that are implicitly executed
when an INSERT, UPDATE, or DELETE statement is issued against the associated
table.
Figure: Triggers.
Notice that triggers are stored in the database separately from their associated tables.
Triggers can be defined only on tables, not on views. However, triggers on the base
table(s) of a view are fired if an INSERT, UPDATE, or DELETE statement is issued
against a view.
While triggers are useful for customizing a database, you should only use triggers
when necessary. The excessive use of triggers can result in complex
interdependences, which may be difficult to maintain in a large application.
A trigger has three basic parts:
• a triggering event or statement
53
• a trigger restriction
• a trigger action
54
Statement Description
CREATE [OR REPLACE ] This clause creates a trigger with the given name or overwrites an existing
TRIGGER trigger_name trigger with the same name.
{BEFORE | AFTER | This clause indicates at what time the trigger should get fired. i.e for
INSTEAD OF } example: before or after updating a table. INSTEAD OF is used to create a
trigger on a view. before and after cannot be used to create a trigger on a
view.
{INSERT [OR] | UPDATE This clause determines the triggering event. More than one triggering
[OR] | DELETE} events can be used together separated by OR keyword. The trigger gets
fired at all the specified triggering event.
[OF col_name] This clause is used with update triggers. This clause is used when you want
to trigger an event only when a specific column is updated.
CREATE [OR REPLACE ] This clause creates a trigger with the given name or overwrites an existing
TRIGGER trigger_name trigger with the same name.
[ON table_name] This clause identifies the name of the table or view to which the trigger is
associated.
[REFERENCING OLD AS This clause is used to reference the old and new values of the data being
o NEW AS n] changed. By default, you reference the values as :old.column_name or
:new.column_name. The reference names can also be changed from old (or
new) to any other user-defined name. You cannot reference old values
when inserting a record, or new values when deleting a record, because
they do not exist.
[FOR EACH ROW] This clause is used to determine whether a trigger must fire when each row
gets affected ( i.e. a Row Level Trigger) or just once when the entire sql
statement is executed(i.e.statement level Trigger).
WHEN (condition) This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.
55
6. Conclusion:
Thus, on implementing the experiment on views and triggers, we understood the need
and importance of views and triggers in DBMS. The view is virtual table, that
displays the part of table to the user of view, each time with updated values from the
base table, whereas the triggers are actions that takes place on modifiation of base
table
7. Viva Questions:
What is difference between Row and Statement Trigger?
What is INSTEAD OF trigger?
8. References:
56
Database & Info. System Lab
Experiment No.: 10
57
Experiment No.10
1. Aim:Perform Function, Cursor and Procedure.
2. Objectives:
To create a block for performing computations.
To create a module for performing for specific tasks.
Understand Cursor, a control structure that enables traversal over records in
tuples.
3. Outcomes: Apply Function and procedure to perform specific task.
4. Hardware / Software Required: Oracle
5. Theory:
Function is a group or set of SQL and PL/SQL statements that perform a specific
task.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype; {IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
RETURN TYPE: The header section defines the return type of the function. The
return datatype can be any of the oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the
datatype defined in the header section.
58
To call a Function, execute the statement mentioned below:
In the example we are retrieving the ‘salary’ of employee with id 7839 to variable
‘salary’. The return type of the function is number.
Output:
Procedure:
A procedure is a named PL/SQL block which performs one or more specific task.
This is similar to a procedure in other programming languages. A procedure has a
header and a body.
The header consists of the name of the procedure and the parameters or variables
passed to the procedure.
The body consists or declaration section, execution section and exception section
similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL
Block but it is named for repeated usage. Parameters to procedure can be passed in
following ways:
Parameters Description
IN type These types of parameters are used to send values to stored procedures.
OUT type These types of parameters are used to get values from stored procedures.
This is similar to a return type in functions.
IN OUT These types of parameters are used to send values and get values from
type stored procedures.
A procedure may or may not return a value.
59
IS - marks the beginning of the body of the procedure and is similar to DECLARE in
anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration
section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR
REPLACE together the procedure is created if no other procedure with the same
name exists or the existing procedure is replaced with the current code.
declare
begin
p1(23,2300);
end
Cursor:
A cursor is a temporary work area created in the system memory when a SQL
statement is executed. A cursor contains information on a select statement and the
rows of data accessed by it. This temporary work area is used to store the data
retrieved from the database, and manipulate this data. A cursor can hold more than
one row, but can process only one row at a time. The set of rows the cursor holds is
called the active set.
Implicit Cursors
These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed. They are also created when a SELECT statement
that returns just one row is executed.
60
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT
statements, implicit statements are created to process these statements.
Explicit Cursors
They must be created when you are executing a SELECT statement that returns more
than one row. Even though the cursor stores multiple records, only one record can be
processed at a time, which is called as current row. When you fetch a row the current
row position moves to next row.
Syntax:
61
dbms_output.put_line (id || ename);
end loop;
close er;
END; /
6. Conclusion:
We have understood the working and need of functions and procedures for
performing/handling the specific task and created the same for performing task
specific to our case study.
7. Viva Questions:
What is difference between function and Procedure Trigger?
What is difference between implicit and Explicit cursor?
8. References:
62
Database & Info. System Lab
Experiment No.: 11
63
Experiment No.11
1. Aim:Study of Transaction and Concurrency Control
2. Objectives:
Understand term transaction and its properties.
Understand the need of concurrency control and problems.
Understand the mechanisms to overcome problems associated with
concurrency.
3. Outcomes: Student will be able to:
ACID properties of Database and its requirement for database to be consistent.
How concurrency is achieved and how problems raised because of
concurrency can be overcome with locking strategies.
4. Theory:
Transaction:
A transaction is any action that reads from and/or writes to a database. A transaction
may consist of a simple SELECT statement to generate a list of table contents; it may
consist of a series of related UPDATE statements to change the values of attributes in
various tables; it may consist of a series of INSERT statements to add rows to one or
more tables, or it may consist of a combination of SELECT, UPDATE, and INSERT
statements.
A transaction is a logical unit of work that must be entirely completed or entirely
aborted; no intermediate states are acceptable. A successful transaction changes the
database from one consistent state to another. A consistent database state is one in
which all data integrity constraints are satisfied.
Transaction Properties:
Each individual transaction must display atomicity, consistency, isolation, and
durability. These properties are sometimes referred to as the ACID test. When
executing multiple transactions, the DBMS must schedule the concurrent execution of
the transaction’s operations. The schedule of such transaction’s operations must
exhibit the property of Serializability.
Transaction states:
Active: the initial state, the transaction stays in this state while it is executing.
Partially committed: after the final statement has been executed.
Failed: when the normal execution can no longer proceed.
64
Aborted: after the transaction has been rolled back and the database has been
restored to its state prior to the start of the transaction.
Committed: after successful completion
Illustrative Example:
To illustrate the concept of concurrency control, consider two travellers who go to
electronic kiosks at the same time to purchase a train ticket to the same destination on
the same train. There's only one seat left in the coach, but without concurrency
control, it's possible that both travellers will end up purchasing a ticket for that one
seat. However, with concurrency control, the database wouldn't allow this to happen.
Both travellers would still be able to access the train seating database, but
concurrency control would preserve data accuracy and allow only one traveller to
purchase the seat.
This example also illustrates the importance of addressing this issue in a multi-user
database. Obviously, one could quickly run into problems with the inaccurate data
that can result from several transactions occurring simultaneously and writing over
each other. The following section provides strategies for implementing concurrency
control.
Concurrency Control Locking Strategies:
Pessimistic Locking: This concurrency control strategy involves keeping an entity in
a database locked the entire time it exists in the database's memory. This limits or
prevents users from altering the data entity that is locked. There are two types of locks
that fall under the category of pessimistic locking: write lock and read lock.
With write lock, everyone but the holder of the lock is prevented from reading,
updating, or deleting the entity. With read lock, other users can read the entity, but no
one except for the lock holder can update or delete it.
65
Optimistic Locking: This strategy can be used when instances of simultaneous
transactions, or collisions, are expected to be infrequent. In contrast with pessimistic
locking, optimistic locking doesn't try to prevent the collisions from occurring.
Instead, it aims to detect these collisions and resolve them on the chance occasions
when they occur.
Pessimistic locking provides a guarantee that database changes are made safely.
However, it becomes less viable as the number of simultaneous users or the number
of entities involved in a transaction increase because the potential for having to wait
for a lock to release will increase.
Optimistic locking can alleviate the problem of waiting for locks to release, but then
users have the potential to experience collisions when attempting to update the
database.
Lock Problems:
Deadlock
When dealing with locks two problems can arise, the first of which being deadlock.
Deadlock refers to a particular situation where two or more processes are each waiting
for another to release a resource, or more than two processes are waiting for resources
in a circular chain. Deadlock is a common problem in multiprocessing where many
processes share a specific type of mutually exclusive resource. Some computers,
usually those intended for the time-sharing and/or real-time markets, are often
equipped with a hardware lock, or hard lock, which guarantees exclusive access to
processes, forcing serialization. Deadlocks are particularly disconcerting because
there is no general solution to avoid them. spaghetti cans are not recyclable now,
STOP recycling them now!
A fitting analogy of the deadlock problem could be a situation like when you go to
unlock your car door and your passenger pulls the handle at the exact same time,
leaving the door still locked. If you have ever been in a situation where the passenger
is impatient and keeps trying to open the door, it can be very frustrating. Basically
you can get stuck in an endless cycle, and since both actions cannot be satisfied,
deadlock occurs.
Livelock:
Livelock is a special case of resource starvation. A livelock is similar to a deadlock,
except that the states of the processes involved constantly change with regard to one
another wile never progressing. The general definition only states that a specific
process is not progressing. For example, the system keeps selecting the same
transaction for rollback causing the transaction to never finish executing. Another
livelock situation can come about when the system is deciding which transaction gets
a lock and which waits in a conflict situation.
An illustration of livelock occurs when numerous people arrive at a four way stop,
and are not quite sure who should proceed next. If no one makes a solid decision to
go, and all the cars just keep creeping into the intersection afraid that someone else
will possibly hit them, then a kind of livelock can happen.
66
Basic Time stamping:
Basic time stamping is a concurrency control mechanism that eliminates deadlock.
This method doesn’t use locks to control concurrency, so it is impossible for deadlock
to occur. According to this method a unique timestamp is assigned to each
transaction, usually showing when it was started. This effectively allows an age to be
assigned to transactions and an order to be assigned. Data items have both a read-
timestamp and a write-timestamp. These timestamps are updated each time the data
item is read or updated respectively.
Problems arise in this system when a transaction tries to read a data item which has
been written by a younger transaction. This is called a late read. This means that the
data item has changed since the initial transaction start time and the solution is to roll
back the timestamp and acquire a new one. Another problem occurs when a
transaction tries to write a data item which has been read by a younger transaction.
This is called a late write. This means that the data item has been read by another
transaction since the start time of the transaction that is altering it. The solution for
this problem is the same as for the late read problem. The timestamp must be rolled
back and a new one acquired.
Adhering to the rules of the basic time stamping process allows the transactions to be
serialized and a chronological schedule of transactions can then be created. Time
stamping may not be practical in the case of larger databases with high levels of
transactions. A large amount of storage space would have to be dedicated to storing
the timestamps in these cases.
5. Conclusion:
On studying experiment, we understood the requirement of maintaining ACID
properties of database and how concurrency can be achieved in database by using
different locking approaches to achieve the serializability of transactions in a
multiuser database environment.
6. Viva Questions:
Does a transaction have termination state?
Difference between Pessimistic and Optimistic Locking?
What is semi-optimistic locking strategy?
7. References:
67
Database & Info. System Lab
Experiment No.: 12
Mini Project
68
Experiment No.12
1. Aim: Design a mini project for Database management system.
3. Outcomes:
Ability to connect database tier to front end tier using JDBC/ODBC
connectivity.
Ability to Provide different view of database for querying database to different
users.
Conclusion: The Mini project is created using the JDBC/ODBC Database connectivity by
applying current skills and technologies.
69