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

DBMS Mix Pyq Solutions

The document provides comprehensive notes for second-year engineering students at Mumbai University, focusing on Database Management Systems (DBMS). It includes solved past year questions, explanations of key concepts like data abstraction, types of users, and the role of a Database Administrator (DBA). Additionally, it covers various topics such as ER diagrams, relational schemas, and comparisons between file processing systems and DBMS.

Uploaded by

yofeg38927
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

DBMS Mix Pyq Solutions

The document provides comprehensive notes for second-year engineering students at Mumbai University, focusing on Database Management Systems (DBMS). It includes solved past year questions, explanations of key concepts like data abstraction, types of users, and the role of a Database Administrator (DBA). Additionally, it covers various topics such as ER diagrams, relational schemas, and comparisons between file processing systems and DBMS.

Uploaded by

yofeg38927
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

🎯 HERE YOU GET ALL BRANCHES (MUMBAI UNIVERSITY ) ENGINEERING NOTES 🎯

SECOND YEAR ENGINEERING NOTES (MU) 📚


😊 😊
JOIN TELEGRAM

🎗 🎗
👇👇👇👇👇👇👇👇👇👇👇👇
KEEP SHARE THIS LINKS

JOIN US TELEGRAM ALL LINKS FOR NOTES

⭐ 1.CLICK TO JOIN CHANNEL 👉


@engineeringnotes_mu

⭐ 2.CLICK TO JOIN GROUP 👉 @engineering_notes_mu

⭐ 3.CLICK TO JOIN 1ST YEAR NOTES BOT 👉@engineeringnotes_mubot

4.CLICK TO JOIN 2ND YEAR COMPUTER ENGINEERING NOTES BOT 👉 @computerengineeringmu_notes_bot

5.CLICK TO JOIN CODING CHANNEL 👉@codingnewbeginners

Join Telegram:- @engineeringnotes_mu


DATABASE MANAGEMENT SYSTEM
SOLVED PAST YEAR QUESTIONS
(N-22,M-23,N-23,M-24,N-24)
-BY AFFAN SHAIKH

Join Telegram:- @engineeringnotes_mu


MODULE-1

Solve The Following


Q.1: What is Data Abstraction & Data Independence ? (N-23,M-23)

Ans:

Data Abstraction:
The process of hiding irrelevant information at each level of a database is known as data
abstraction. Data abstraction in DBMS is very helpful in dealing with complex database
systems because it breaks the problem into sub-problems, making it easier to manage.

The database is divided into three levels of abstraction:

 Physical Level: Describes how a record is actually stored in the database.


 Logical Level: Describes the actual data stored in the database.
 View Level: Divides the data into multiple groups (views) as per the needs of the
application program.

Data Independence:
Data independence is an advantage of having levels of abstraction in a database management
system. It means that data at different levels are independent of each other. So, if we modify the
data at any level, the other levels will not be affected and will continue to work as expected.

Types of Data Independence:

 Physical Level Independence in DBMS: The physical level is separated from the
logical level.
 Logical Level Independence in DBMS: Changes at the logical level will not affect the
view level.

Feature Physical Data Independence Logical Data Independence


Ability to change the physical Ability to change the logical schema
Definition storage of data without affecting the without affecting the external schemas or
logical schema. application programs.
Level of Deals with the internal/physical Deals with the logical level and how data
Abstraction level. is structured.
Changes Changes like indexing, file Changes like adding/removing attributes,
Allowed organization, compression methods. tables, or relationships.
Should not affect the logical structure Should not affect how end users interact
Impact
or user views. with the database.

Join Telegram:- @engineeringnotes_mu


Q.2: Explain Type Of Users in DBMS ? (N-22,M-23)

Ans:

Database Users
Database users based on their interaction with a database system.

1. Naive Users
• Characteristics: Unsophisticated users who don’t interact directly with the database but rely
on predefined application programs.
• Examples: A bank teller using a transfer program, or a person accessing their account balance
on a website.
• User Interface: Typically a forms interface, where users input data into fields or read pre-
generated reports.

2. Application Programmers
• Characteristics: Computer professionals who write application programs to interact with the
database. They develop tools and user interfaces for others to use.
• Tools: They use Rapid Application Development (RAD) tools, fourth-generation languages, or
other specialized tools that integrate data manipulation language (DML) with programming
features.
• Examples: Developing software applications like inventory management systems.

3. Sophisticated Users
• Characteristics: Users who don’t write programs but interact with the database through query
languages (e.g., SQL). They typically include data analysts and researchers who need to analyze
and explore data.
• Tools: They use Online Analytical Processing (OLAP) tools to view and manipulate data
summaries, and data mining tools to uncover patterns.
• Examples: An analyst querying a database to explore sales trends by region, product, or other
criteria.

4. Specialized Users
• Characteristics: These users write specialized applications that don’t fit into traditional data-
processing tasks.
• Examples: Applications in fields like computer-aided design (CAD), knowledge bases, expert
systems, and systems for complex data types (e.g., graphics, audio).

Q.3: Discuss 3-Layer Schema Architecture With Diagram? Also Explain What is Data
Independence & Explain It Types ? Overall DBMS Architecture? (M-23,N-23,M-24,N-24)

Ans:

Join Telegram:- @engineeringnotes_mu


� Top Level: External Schema (View Level)

 Represents how different users view the data.


 Each user (e.g., Student, Faculty, Dean) sees a different “external schema” or
customized view of the database.
 This level hides the complexity of the database from the user and restricts access to
only the data relevant to that user.
 This is also called the View Level.

� Middle Level: Conceptual Schema (Logical Level)

 This level describes what data is stored in the database and the relationships among the
data.
 It represents the entire structure of the database for a community of users.
 It is independent of how data is stored (physical level) and how it is viewed (external
level).
 Called the Logical Level.

� Bottom Level: Physical Schema (Internal Level)

 Describes how the data is actually stored on storage devices like disks.
 It includes data structures, indexing, and file organization.
 Called the Internal or Physical Level.

� Database (Disk)

 The actual storage medium where data resides.


 This is where the physical schema operates directly.

Q.4: Role Of DBA ? (M-24)

Join Telegram:- @engineeringnotes_mu


Ans:

The Database Administrator (DBA) plays a crucial role in managing and maintaining a
database system. The responsibilities outlined for a DBA ensure that the system runs smoothly,
data remains secure, and users can efficiently access and modify the database. Here’s a
breakdown of the key functions of a DBA:

1. Schema Definition

• The DBA is responsible for creating the original database schema using Data Definition
Language (DDL).
• The schema defines the structure of the database, including tables, relationships, and
constraints.

2. Storage Structure and Access Method Definition

• The DBA defines how the data is stored and how it can be accessed efficiently.
• This includes deciding on storage formats, indexing methods, and optimizing access paths.

3. Schema and Physical Organization Modification

• As organizational needs evolve, the DBA updates the schema and physical storage structures.
• Tasks include adding new tables, modifying indexes, or restructuring storage for better
performance and scalability.

4. Granting Authorization for Data Access

• The DBA regulates user access to ensure data security.


• They grant specific permissions to users, ensuring access is limited based on roles.
• Authorization details are stored and checked whenever access is attempted.

Q.5: Compare File Processing System with Database management System?(M-24,N-24)

Ans:

Database Management System


Feature File Processing System (FPS)
(DBMS)
Data High – Same data may be stored in Low – Data is centralized and shared
Redundancy multiple files. across applications.
Data Low – Redundancy leads to High – Changes made once reflect across
Consistency inconsistency. the system.
Difficult – Data is isolated in Easy – Centralized access and sharing
Data Sharing
separate files. through queries.
Strong – Access controls and
Data Security Poor – Limited security features.
authorization mechanisms are built-in.

Join Telegram:- @engineeringnotes_mu


Database Management System
Feature File Processing System (FPS)
(DBMS)
Hard to enforce – Requires manual Enforced through constraints, rules, and
Data Integrity
checks. relationships.
Data No – Any change in data format Yes – Logical and physical data
Independence requires program changes. independence are supported.
Lower initial cost but higher long- Higher initial cost but more efficient and
Cost
term maintenance cost. scalable.

Join Telegram:- @engineeringnotes_mu


MODULE-2
Q.1: Draw EE-R For Hospital Management System ? (N-22,M-24,N-24)

Ans: Note: Separate Entities & Attributes Just Like Other Diagram

OR

Entities and Their Attributes

1. Patient
Patient(P_ID, P_name, Age, Mob)
o Primary Key: P_ID
2. Doctor
Doctor(D_ID, D_name, Dept, Qualification)
o Primary Key: D_ID
3. Nurse
Nurse(N_ID, N_name)
o Primary Key: N_ID
4. Bills
Bills(B_ID, Transaction_ID, Receipt, P_ID)
o Primary Key: B_ID
o Foreign Key: P_ID → Patient(P_ID)
5. Rooms
Rooms(R_ID, Availability)
o Primary Key: R_ID

Relationships

Join Telegram:- @engineeringnotes_mu


6. Consults (M:N)
Consults(P_ID, D_ID)
o Primary Key: (P_ID, D_ID)
o Foreign Keys:
P_ID → Patient(P_ID)
D_ID → Doctor(D_ID)
7. Assists (M:N)
Assists(D_ID, N_ID)
o Primary Key: (D_ID, N_ID)
o Foreign Keys:
D_ID → Doctor(D_ID)
N_ID → Nurse(N_ID)
8. Pays (1:N from Patient to Bills)
(Handled via foreign key in Bills table as above)
9. Maintains (N:M)
Maintains(N_ID, R_ID)
o Primary Key: (N_ID, R_ID)
o Foreign Keys:
N_ID → Nurse(N_ID)
R_ID → Rooms(R_ID)

Room Type (Generalization / Specialization)

10. Room_Types
Room_Types(R_ID, Type)

 Primary Key: R_ID


 Foreign Key: R_ID → Rooms(R_ID)
 Type values: 'B-class', 'C-class', 'Deluxe' (can be stored using ENUM or lookup table)

Q.2: Convert Following E-R into Relational Schema? (M-23)

Ans:

Join Telegram:- @engineeringnotes_mu


Here is the entity-relationship structure with attributes and relationships:

Entities and Attributes:

1. Account
o Attributes: A_no (Primary Key), Balance
o Relationship: Linked to Account_branch
2. Account_branch
o Attributes: B_city, Assets
o Relationship: Has Accounts and Loans
3. Customer
o Attributes: C_no (Primary Key), C_name, C_city
o Relationships: Depositor and Borrower
4. Loan
o Attributes: L_no (Primary Key), Amt
o Relationship: Linked to Loan_branch

Relationships (with Keys):

1. Depositor
o Links Customer(C_no) with Account(A_no)
o Relation: Depositor(C_no, A_no) – Composite Primary Key (C_no, A_no)
2. Borrower
o Links Customer(C_no) with Loan(L_no)
o Relation: Borrower(C_no, L_no) – Composite Primary Key (C_no, L_no)
3. Account
o Account (A_no, Balance, B_city) – B_city is a foreign key referencing
Account_branch(B_city)
4. Loan
o Loan (L_no, Amt, B_city) – B_city is a foreign key referencing
Loan_branch(B_city)
5. Branch (or Account_branch and Loan_branch treated together)
o Branch (B_city, Assets)

Q.3: Construct an ER diagram and convert it into a relational model for a company which
has several employees working on different types of Projects. Several employees are
working for one department, every department has a manager. Several employees are
supervised by one employee. Employees have zero or more dependents? (M-23)

Ans:

Join Telegram:- @engineeringnotes_mu


Relational Schema:

1. Company
Company(CID PRIMARY KEY, CName)
2. Department
Department(Dept_ID PRIMARY KEY, Dept_Name, CID FOREIGN KEY REFERENCES
Company(CID), Manager_EID FOREIGN KEY REFERENCES Employee(EID))
3. Employee
Employee(EID PRIMARY KEY, EName, Dept_ID FOREIGN KEY REFERENCES
Department(Dept_ID), Supervisor_EID FOREIGN KEY REFERENCES
Employee(EID))
4. Project
Project(PID PRIMARY KEY, PName)
5. Dependent
Dependent(EID FOREIGN KEY REFERENCES Employee(EID), D_Name, D_Relation,
PRIMARY KEY (EID, D_Name))
6. Works_On (M:N relationship between Employee and Project)
Works_On(EID FOREIGN KEY REFERENCES Employee(EID), PID FOREIGN KEY
REFERENCES Project(PID), PRIMARY KEY (EID, PID))

Q.4: Explain Types Of Attributes? (M-23,N-23)

Ans:

An attribute is a single-valued property of either an entity type or a relationship type. In ER


diagrams, attributes are represented using ellipses.

Types of Attributes:

Join Telegram:- @engineeringnotes_mu


1. Simple Attribute:

These are attributes that cannot be divided further.


Also called atomic attributes.
Example: Mobile number, Roll number, PRN number.

2. Composite Attribute:

These attributes can be divided into smaller subparts.


Useful for representing hierarchical data.
Example: A student's name can be divided into first name, middle name, and last name.
Another example is Address, which can include street, city, state, and country.

3. Derived Attribute:

These attributes are not stored in the physical database.


Their values are derived from other stored attributes.
Example: Age can be derived from Date of Birth (DOB).
In ER diagrams, derived attributes are shown as dashed ovals.

4. Multivalued Attribute:

These can have more than one value for a single entity.
Represented by double ovals in ER diagrams.
Example: A student can have multiple phone numbers or email addresses.

Q.5: Describe Strong & Weak Entity With Example? (D-23)

Ans:

Strong Entity

Join Telegram:- @engineeringnotes_mu


 A strong entity set is an entity that contains sufficient attributes to uniquely identify all
its entities.
 Simply, a strong entity is nothing but an entity set having a primary key attribute. The
primary key of the strong entity is represented by underlining it.
 The strong entity is represented by a single rectangle in an ER diagram.

Example:
Consider a Student entity with attributes Student_ID, Name, and DOB.
Here, Student_ID is the primary key and can uniquely identify each student, making it a strong
entity.

Weak Entity

 A weak entity is an entity set that does not have sufficient attributes for the unique
identification of its records.
 Simply, a weak entity is nothing but an entity set that does not have a primary key
attribute.
 It contains a partial key, which helps in identifying a group of entities from the entity
set.
 The partial key is represented by underlining with a dashed line.
 A double rectangle is used for representing a weak entity set.

Example:
Consider an Order Item entity in an order management system. The entity Order Item might
not have its own unique identifier but is identified in combination with the Order_ID and
Item_Number, forming the partial key.
Here, the Order Item would be a weak entity, and its partial key (Item_Number) would be
underlined with a dashed line.

Q.6: Draw an E-R For Library Management System & Covert into Relational Schema? (D-
23)

Ans:

Join Telegram:- @engineeringnotes_mu


Entities and Attributes:

 Staff(Staff_ID, Name, F_name, M_name, L_name)


 Readers(Reader_ID, Name, Class_no, Phone_no)
 Books(ISBN, Title, Author, SR_no, Publisher, Price, Category)
 Publisher(Pub_ID, Name, Address)
 Authentication_System(Username, Password)

Relationships:

 Login(Staff_ID, Username)
 Maintain(Staff_ID, Reader_ID)
 Keeps_Track(Staff_ID, Book_ID)
 Issue(Reader_ID, ISBN, Issue_date)
 Return(Reader_ID, ISBN, Return_date, Fine)
 Reserve(Reader_ID, ISBN, Reserve_date)
 Published_By(ISBN, Pub_ID)

Q.7: Define With Example Different Types Of Entities in E-R Diagram? (M-24,N-24)

Ans:

Entity

1. An entity is a thing, object, or person in the real world that is distinguishable from other
objects based on the values of the attributes it possesses.
2. An entity is represented by a rectangle in an Entity-Relationship (ER) diagram.

Types of Entities:

 Tangible Entities – Entities that physically exist in the real world.


o Examples: Car, pen, bank locker.

Join Telegram:- @engineeringnotes_mu


 Intangible Entities – Entities that exist logically and cannot be physically touched.
o Examples: Bank account, loan.

Join Telegram:- @engineeringnotes_mu


MODULE-3

Q.1: Explain Types Of Join With Suitable Examples ? (N-22,N-24)

Ans:

Types of Joins in SQL

 Natural Join
 Conditional Join
 EQUI Join
 Self Join
 Outer Joins:
o Left Outer Join (LOJ)
o Right Outer Join (ROJ)
o Full Outer Join

� Natural Join

Definition:
A Natural Join combines rows from two tables based on all columns having the same names and
values. It removes duplicate columns from the result.

Emp Table:

E_No E_name Address

1 Ram Delhi

2 Varun Chd

3 Ravi Chd

4 Amit Delhi

Dept Table:

Dep_No Name E_No

Join Telegram:- @engineeringnotes_mu


Dep_No Name E_No

D1 HR 1

D2 IT 2

D3 MRKT 2

Output:

E_No E_name Address Dep_No Name

1 Ram Delhi D1 HR

2 Varun Chd D2 IT

2 Varun Chd D3 MRKT

� EQUI Join

Definition:
An EQUI Join uses a condition based on the equality operator (=) to match rows from two tables.

Emp Table:

E_No E_name Address

1 Ram Delhi

2 Varun Chd

3 Ravi Chd

4 Amit Delhi

Dept Table:

Dep_No Location E_No

D1 Delhi 1

Join Telegram:- @engineeringnotes_mu


Dep_No Location E_No

D2 Pune 2

D3 Patna 2

Output (Where Emp.Address = Dept.Location):

E_No E_name Address Dep_No Location

1 Ram Delhi D1 Delhi

4 Amit Delhi D1 Delhi

� Self Join

Definition:
A Self Join is a join where a table is joined with itself to find relationships within the same table.

Study Table:

s_id c_id since

S1 C1 2016

S2 C1 2016

S3 C2 2017

S3 C3 2017

Output (Students enrolled in at least two courses):

s_id

Join Telegram:- @engineeringnotes_mu


s_id

S3

�� Left Outer Join (LOJ)

Definition:
A Left Outer Join returns all records from the left table and the matched records from the right
table. Unmatched right-side rows return NULLs.

Emp Table:

Emp_no E_name Dept_no

E1 Varun D1

E2 Amit D2

E3 Ravi D1

E4 Neha

Dept Table:

Dept_no D_name LOC

D1 HR Delhi

D2 IT Hyd

D3 Finance Pune

Output:

Emp_no E_name D_name LOC

E1 Varun HR Delhi

E2 Amit IT Hyd

Join Telegram:- @engineeringnotes_mu


Emp_no E_name D_name LOC

E3 Ravi HR Delhi

E4 Neha NULL NULL

➡� Right Outer Join (ROJ)

Definition:
A Right Outer Join returns all records from the right table and matched records from the left
table. Unmatched left-side rows return NULLs.

Emp Table:

Emp_no E_name Dept_no

E1 Varun D1

E2 Amit D2

E3 Ravi D1

Dept Table:

Dept_no D_name LOC

D1 HR Delhi

D2 IT Hyd

D3 Finance Pune

D4 Testing Noida

Output:

Emp_no E_name D_name LOC

E1 Varun HR Delhi

Join Telegram:- @engineeringnotes_mu


Emp_no E_name D_name LOC

E2 Amit IT Hyd

E3 Ravi HR Delhi

NULL NULL Finance Pune

NULL NULL Testing Noida

� Full Outer Join

Definition:
A Full Outer Join returns all rows when there is a match in either left or right table. Unmatched
rows will contain NULLs.

Output (LOJ ∪ ROJ):

Emp_no E_name D_name LOC

E1 Varun HR Delhi

E2 Amit IT Hyd

E3 Ravi Finance Pune

NULL NULL Testing Noida

E4 Neha NULL NULL

Q.2: Explain Relational Algebra Operators With Example? (N-22,M-23,N-23,M-24,N-24)

Ans:

Definition:

Relational Algebra is a formal query language used to retrieve data from relational databases. It
uses a set of operations (operators) to manipulate relations (tables).

Key Points:

Join Telegram:- @engineeringnotes_mu


 It is one of two formal languages in the Relational Model (the other is Relational
Calculus).
 Operates on relations (tables).

Types of Operators in Relational Algebra

1. Basic / Fundamental Operations:

Operation Symbol Description Example

σ_age>30(Employee) → Selects employees


Select σ Filters rows based on a condition
older than 30

π_name, salary(Employee) → Shows only


Project π Selects specific columns (attributes)
name and salary columns

Combines tuples from two relations


Union ∪ A∪B
(no duplicates)

Set Returns tuples in one relation but


− A−B
Difference not in another

Cartesian Combines each row of one relation


× A×B
Product with each row of another

ρ(Emp)(Employee) → Renames Employee to


Rename ρ Renames the relation or attributes
Emp

2. Derived Operations:

Operation Symbol Description Example

Combines relations based on common


Natural Join ⨝ Employee ⨝ Department
attributes

Join ⟕, ⟖,
Left, Right, Full Outer Joins A ⟕ B (Left join)
Variants ⟗

Intersection ∩ Returns tuples common to both relations A ∩ B

Division ÷ Used when querying for "all" A ÷ B → Tuples in A related to all

Join Telegram:- @engineeringnotes_mu


Operation Symbol Description Example

relationships tuples in B

Sure! Let's go through examples of Relational Algebra operations using tables to make the
concepts clear. We'll use two sample relations:

Relation: Employee

EmpID Name DeptID Age

1 Alice 10 28

2 Bob 20 35

3 Carol 10 40

4 Dave 30 22

Relation: Department

DeptID DeptName

10 HR

20 IT

30 Marketing

� 1. Select (σ)

Operation:

Select employees older than 30


σ Age > 30 (Employee)

Result:

EmpID Name DeptID Age

Join Telegram:- @engineeringnotes_mu


EmpID Name DeptID Age

2 Bob 20 35

3 Carol 10 40

� 2. Project (π)

Operation:

Get only names and ages of employees


π Name, Age (Employee)

Result:

Name Age

Alice 28

Bob 35

Carol 40

Dave 22

� 3. Union (∪)

Operation:

Assume two relations A and B:


A:

EmpID Name

1 Alice

2 Bob

B:

Join Telegram:- @engineeringnotes_mu


EmpID Name

2 Bob

3 Carol

A∪B

Result:

EmpID Name

1 Alice

2 Bob

3 Carol

� 4. Set Difference (−)

Operation:

A−B

Result:

EmpID Name

1 Alice

� 5. Cartesian Product (×)

Operation:

Employee × Department

(Only showing 2 rows for brevity)

EmpID Name DeptID_E Age DeptID_D DeptName

Join Telegram:- @engineeringnotes_mu


EmpID Name DeptID_E Age DeptID_D DeptName

1 Alice 10 28 10 HR

1 Alice 10 28 20 IT

Note: This multiplies every row of Employee with every row of Department.

� 6. Rename (ρ)

Operation:

ρ EmpInfo (Employee)
This renames the "Employee" table to "EmpInfo"

EmpID Name DeptID Age

1 Alice 10 28

... ... ... ...

� 7. Natural Join (⨝)

Operation:

Employee ⨝ Department (joins on DeptID)

EmpID Name DeptID Age DeptName

1 Alice 10 28 HR

2 Bob 20 35 IT

3 Carol 10 40 HR

4 Dave 30 22 Marketing

Join Telegram:- @engineeringnotes_mu


� 8. Intersection (∩)

Operation:

Common rows between two relations.

A∩B

EmpID Name

2 Bob

� 9. Division (÷)

Used in queries like: “Find employees who work in all departments.”

Suppose:

WorksIn:

EmpID DeptID

1 10

1 20

1 30

2 10

2 30

Departments:

DeptID

10

20

30

Join Telegram:- @engineeringnotes_mu


WorksIn ÷ Departments
→ Only EmpID 1 works in all departments.

Result:

EmpID

Q.3: Write Short Note On Conversion Of Specialization to relational Schema with example
? (M-23,N-23)

Ans:

Specialization is a process in ER modeling where an entity is divided into sub-entities


(subclasses) based on some distinguishing characteristics.

 The superclass has general attributes.


 The subclasses inherit these attributes and may also have specific attributes.

� Converting Specialization to Relational Schema

When converting specialization into a relational schema, there are three main approaches,
depending on design requirements:

1. Option 1: One Table for Superclass and Each Subclass

 Create a table for the superclass.


 Create separate tables for each subclass.
 Subclass tables have a foreign key referencing the superclass.

� Example:

ER Diagram:

 Superclass: Person(EmpID, Name, Age)


 Subclasses:
o Student(Branch)
o Teacher(Salary)

Relational Schema:
Person(EmpID, Name, Age)
Student(EmpID, Branch) -- FK EmpID → Person
Teacher(EmpID, Salary) -- FK EmpID → Person

Join Telegram:- @engineeringnotes_mu


2. Option 2: One Table for Each Subclass (with all attributes)

 Do not create a table for the superclass.


 Create separate subclass tables that include inherited and specific attributes.

Relational Schema:
Student(EmpID, Name, Age, Branch)
Teacher(EmpID, Name, Age, Salary)

Note: Redundant data may exist across subclass tables.

3. Option 3: Single Table for All Entities

 Combine the superclass and subclasses into one table.


 Use nulls for irrelevant fields.

Relational Schema:
Person(EmpID, Name, Age, Branch, Salary)

 If a person is a student, Salary will be NULL.


 If a person is a teacher, Branch will be NULL.

Join Telegram:- @engineeringnotes_mu


MODULE-4
Q.1: Write SQL expressions for the following queries: (N-22)

Consider Employee relation (Emp_no, Emp_name, Emp_add, Ph_no, Email_id, Salary)

i) List the employee whose employee number is 100.

ii) List the Employee whose salary is between 50 K to 1 Lac.

iii) List the Employees whose name starts with ‘Ami’.

iv) Find 2nd highest salary of Employees.

v) Create two views on employee table.

Ans:

Consider the relation:


Employee(Emp_no, Emp_name, Emp_add, Ph_no, Email_id, Salary)

i) List the employee whose employee number is 100.


SELECT * FROM Employee
WHERE Emp_no = 100;

ii) List the employees whose salary is between 50 K to 1 Lac.


SELECT * FROM Employee
WHERE Salary BETWEEN 50000 AND 100000;

iii) List the employees whose name starts with ‘Ami’.


SELECT * FROM Employee
WHERE Emp_name LIKE 'Ami%';

iv) Find the 2nd highest salary of employees.


SELECT MAX(Salary) AS Second_Highest_Salary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);

Join Telegram:- @engineeringnotes_mu


v) Create two views on the employee table.

1. View for employee names and their salaries:


CREATE VIEW Emp_Salary_View AS
SELECT Emp_name, Salary
FROM Employee;

2. View for employee contact information:


CREATE VIEW Emp_Contact_View AS
SELECT Emp_name, Ph_no, Email_id
FROM Employee;

Q.2: What is Trigger ? Explain With Syntax & Example ? (N-22,M-23,N-23,M-24)

Ans:

A trigger is a special type of stored procedure that automatically executes or fires when a
specified event (such as INSERT, DELETE, or UPDATE) occurs in the database server.

Triggers are associated with a table and are used to maintain the integrity of the data, enforce
business rules, and perform automatic actions in response to data modifications.

Triggers are activated in response to:

 DML Statements: INSERT, UPDATE, DELETE


 DDL Statements: CREATE, ALTER, DROP
 Database Operations: LOGON, LOGOFF, STARTUP, SHUTDOWN

� Syntax of Trigger:
CREATE TRIGGER [trigger_name]
[BEFORE | AFTER]
[INSERT | UPDATE | DELETE]
ON [table_name]
FOR EACH ROW
BEGIN
[trigger_body]
END;

� Explanation of Syntax:

1. CREATE TRIGGER [trigger_name]: Defines a new trigger.


2. BEFORE | AFTER: Specifies when the trigger should execute — before or after the event.
3. INSERT | UPDATE | DELETE: The event that activates the trigger.

Join Telegram:- @engineeringnotes_mu


4. ON [table_name]: Specifies the table to which the trigger is linked.
5. FOR EACH ROW: The trigger will fire for each row affected.
6. [trigger_body]: The SQL statements to be executed when the trigger fires.

� Example of Trigger:

Scenario:

You want to insert total and average marks automatically into a StudentMarks table when a
new record is inserted.

Create Table:
CREATE TABLE StudentMarks (
RollNo INT,
Name VARCHAR(50),
Subject1 INT,
Subject2 INT,
Subject3 INT,
Total INT,
Average FLOAT
);

Create Trigger:
CREATE TRIGGER CalculateTotalAverage
BEFORE INSERT ON StudentMarks
FOR EACH ROW
BEGIN
SET NEW.Total = NEW.Subject1 + NEW.Subject2 + NEW.Subject3;
SET NEW.Average = NEW.Total / 3;
END;

Q.3: Explain All Types Of Integrity Constraints With Examples ? (M-23,M-24,D-24)

Ans:

Integrity Constraints

 Integrity constraints are a set of rules. It is used to maintain the quality of information.
 Integrity constraints ensure that the data insertion, updating, and other processes have to
be performed in such a way that data integrity is not affected.
 Thus, integrity constraint is used to guard against accidental damage to the database.

Types of Integrity Constraint

Join Telegram:- @engineeringnotes_mu


Integrity Constraint
├── Domain Constraint
├── Entity Integrity Constraint
├── Referential Integrity Constraint
└── Key Constraint & Check Constraint

1. Domain constraints

 Domain constraints can be defined as the definition of a valid set of values for an
attribute.
 The data type of domain includes string, character, integer, time, date, currency, etc. The
value of the attribute must be available in the corresponding domain.

Example:

ID NAME SEMESTER AGE


1000 Tom 1st 17
1001 Johnson 2nd 24
1002 Leonardo 5th 21
1003 Kate 3rd A X
1004 Morgan 8th 22

Kate-Not allowed. Because AGE is an integer attribute

2. Entity integrity constraints

 The entity integrity constraint states that primary key value can't be null.
 This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
 A table can contain a null value other than the primary key field.

Example:

EMP_ID EMP_NAME SALARY


123 Jack 30000
142 Harry 50000
John 20000 X
164 Jackson 20000

John-Not allowed as primary key can't contain a NULL value

Join Telegram:- @engineeringnotes_mu


3. Referential Integrity Constraints

 A Referential Integrity Constraint ensures a valid relationship between two tables in a


database.
 It is used when one table (called the Child table) has a foreign key that refers to the
primary key of another table (called the Master table).
 The purpose is to maintain consistency between records in both tables.

� Rules of Referential Integrity:

1. Insert Constraint:
o You cannot insert a value in the foreign key column of the child table if that
value doesn't exist as a primary key in the master table.
o This ensures that all references are valid.
2. Delete Constraint:
o You cannot delete a row in the master table if that value is being used in the
child table.
o This prevents deleting a record that is still being referenced.

� Example from the Image:

Table 1: Child Table

(D_No is a Foreign Key)

EMP_NAME NAME AGE D_No

1 Jack 20 11

2 Harry 24 12

3 John 27 15 ❌

4 Devil 30 13

Table 2: Master Table

(D_No is a Primary Key)

Join Telegram:- @engineeringnotes_mu


D_No D_Location

11 Mumbai

12 Delhi

13 Noida

� What’s wrong?

 D_No = 15 in Table 1 is not present in Table 2.


 Since 15 is not defined in the master table as a valid D_No, it violates the referential
integrity constraint.
 Therefore, inserting or keeping this value in the child table is not allowed.

4. Key constraints

 Keys are the entity set that is used to identify an entity within its entity set uniquely.
 An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.

Example:

ID NAME SEMESTER AGE


1000 Tom 1st 17
1001 Johnson 2nd 24
1002 Leonardo 5th 21
1003 Kate 3rd 19
1002 Morgan 8th 22 X

Morgan-Not allowed. Because all row must be unique

5. Check Constraint:

 Ensures that the value in a column meets a specific condition or condition set by the user.
 It can be used to validate input based on a condition.
 Example: CHECK (age >= 18)

Join Telegram:- @engineeringnotes_mu


Q.4: Write SQL queries for the given database (M-23)
Book(book_id, title, author, cost)
Store(store_no, city, state, inventory_val)
Stock(store_no, book_id, quantity)

Ans:

i) Modify the cost of DBMS books by 10%.

UPDATE Book
SET cost = cost * 1.10
WHERE title LIKE '%DBMS%';

ii) Find the total number of books in Mumbai stores.

SELECT SUM(quantity) AS Total_Books


FROM Stock
WHERE store_no IN (
SELECT store_no
FROM Store
WHERE city = 'Mumbai'
);

iii) Find title of all books whose title contains the word ‘System’.

SELECT title
FROM Book
WHERE title LIKE '%System%';

iv) Find title of the most expensive book.

SELECT title
FROM Book
WHERE cost = (SELECT MAX(cost) FROM Book);

v) Add a new record in Book (Assume values as per requirement).

INSERT INTO Book (book_id, title, author, cost)


VALUES (101, 'Introduction to AI', 'John Smith', 750);

Join Telegram:- @engineeringnotes_mu


Q.5: List & Briefly Explain SQL Aggregate Function With Examples ? (N-23,M-24,N-24)

Ans:

Aggregate Functions in SQL

SQL aggregation function is used to perform calculations on multiple rows of a single column
of a table. It returns a single value.
It is also used to summarize the data.

Various Aggregate Functions:

1. COUNT()
2. SUM()
3. AVG()
4. MIN()
5. MAX()

COUNT FUNCTION

 COUNT function is used to count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
 COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and NULL.

Syntax:

COUNT(*)
or
COUNT([ALL|DISTINCT] expression)

Example: COUNT()

SELECT COUNT(*)
FROM PRODUCT_MAST;

Output:
10

Example: COUNT with WHERE

SELECT COUNT(*)

Join Telegram:- @engineeringnotes_mu


FROM PRODUCT_MAST
WHERE RATE >= 20;

Output:
7

SUM Function

 SUM function is used to calculate the sum of all selected columns. It works on numeric
fields only.

Syntax:

SUM()
or
SUM([ALL|DISTINCT] expression)

Example: SUM()

SELECT SUM(COST)
FROM PRODUCT_MAST;

Output:
670

Example: SUM() with WHERE

SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY > 3;

Output:
320

AVG Function

 The AVG function is used to calculate the average value of the numeric type.
 AVG function returns the average of all non-null values.
 The SQL DISTINCT keyword is used in conjunction with the SELECT statement to
eliminate all the duplicate records and fetch only unique records.

Join Telegram:- @engineeringnotes_mu


Syntax:

AVG()
or
AVG([ALL|DISTINCT] expression)

Example:

SELECT AVG(COST)
FROM PRODUCT_MAST;

Output:
67.00

MAX Function

 MAX function is used to find the maximum value of a certain column.


 This function determines the largest value of all selected values of a column.

Syntax:

MAX()
or
MAX([ALL|DISTINCT] expression)

Example:

SELECT MAX(RATE)
FROM PRODUCT_MAST;

Output:
30

MIN Function

 MIN function is used to find the minimum value of a certain column.


 This function determines the smallest value of all selected values of a column.

Syntax:

MIN()
or
MIN([ALL|DISTINCT] expression)

Join Telegram:- @engineeringnotes_mu


Example: MIN()
SELECT MIN(RATE)
FROM PRODUCT_MAST;

Output:
10

Q.6: Write SQL commands for the following: (N-23,M-24)

 Employee(empname, street, city, date_of_joining)


 Works(empname, company_name, salary)
 Company(company_name, city)
 Manages (empname,manager_name)

1. Modify the database so that ‘John’ now lives in ‘Mumbai’.


2. Find all employees who joined in the month of October.
3. Give all employees of ‘ABC Corporation’ a 10% raise.
4. Find all employees who earn more than the average salary of all employees of their
company.
5. List names of companies starting with the letter “A”.
6. Find all employees in the database who live in the same cities as the companies for
which they work.
7. Find all employees who earn more than the average salary of all employees of their
compan

Ans:

Tables:

 Employee(empname, street, city, date_of_joining)


 Works(empname, company_name, salary)
 Company(company_name, city)

1. Modify the database so that ‘John’ now lives in ‘Mumbai’:

UPDATE Employee
SET city = 'Mumbai'
WHERE empname = 'John';

Join Telegram:- @engineeringnotes_mu


2. Find all employees who joined in the month of October:

SELECT empname
FROM Employee
WHERE MONTH(date_of_joining) = 10;

(If using Oracle, use: EXTRACT(MONTH FROM date_of_joining) = 10 )

3. Give all employees of ‘ABC Corporation’ a 10% raise:

UPDATE Works
SET salary = salary * 1.10
WHERE company_name = 'ABC Corporation';

4. Find all employees who earn more than the average salary of all employees of their
company:

SELECT W1.empname, W1.company_name, W1.salary


FROM Works W1
JOIN (
SELECT company_name, AVG(salary) AS avg_salary
FROM Works
GROUP BY company_name
) W2 ON W1.company_name = W2.company_name
WHERE W1.salary > W2.avg_salary;

5. List names of companies starting with letter “A”:

SELECT company_name
FROM Company
WHERE company_name LIKE 'A%';

6. Find all employees in the database who live in the same cities as the companies
for which they work:
SELECT E.empname
FROM Employee E
JOIN Works W ON E.empname = W.empname
JOIN Company C ON W.company_name = C.company_name
WHERE E.city = C.city;

7. Find all employees who earn more than the average salary of all employees of
their company:

Join Telegram:- @engineeringnotes_mu


SELECT W1.empname, W1.company_name, W1.salary
FROM Works W1
JOIN (
SELECT company_name, AVG(salary) AS avg_salary
FROM Works
GROUP BY company_name
) W2 ON W1.company_name = W2.company_name
WHERE W1.salary > W2.avg_salary;

Q.7: Solve Queries (N-24)

employee (eno, ename, bdate, title, salary, dno)

project (pno, pname, budget, dno)

department (dno, dname, mgreno)

works (eno, pno, resp, hours)

1. Find the project number and name for projects with a budget greater than 100,000.
2. Find the employees (name only) in department 'D1' ordered by descending salary.
3. Find all works records where hours worked is less than 10 and the responsibility is
'Manager'.
4. Find the name of employees that are ending with the letter ‘s’.
5. Find the total number of employees.
6. Write the query to increase the salary of the employees by 10%.
7. Find the employee with the maximum salary.

Ans:

1. Find the project number and name for projects with a budget greater than 100,000:

SELECT pno, pname


FROM project
WHERE budget > 100000;

2. Find the employees (name only) in department 'D1' ordered by descending salary:

SELECT ename
FROM employee
WHERE dno = 'D1'
ORDER BY salary DESC;

3. Find all works records where hours worked is less than 10 and the responsibility is
'Manager':

Join Telegram:- @engineeringnotes_mu


SELECT *
FROM works
WHERE hours < 10 AND resp = 'Manager';

4. Find name of employees that are ending with letter ‘s’:

SELECT ename
FROM employee
WHERE ename LIKE '%s';

5. Find total number of employees:

SELECT COUNT(*) AS total_employees


FROM employee;

6. Write the query to increase salary of the employees by 10%:

UPDATE employee
SET salary = salary * 1.10;

7. Find employee with maximum salary:

SELECT *
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee);

Join Telegram:- @engineeringnotes_mu


MODULE-5
Q.1: What is Normalization ? Explain 1NF,2NF,3NF,BCNF,4NF With Example ? (N-22,N-
23,M-24,N-24)

Ans:

What is Normalization?

Normalization is the process of organizing data in a database to eliminate redundancy (duplicate


data) and ensure data dependencies make sense (logical structure). It involves breaking down
large, complex tables into simpler ones and defining relationships between them to improve data
integrity and efficiency.

1. First Normal Form (1NF)

 Rule: Each column must contain atomic (indivisible) values, and each record must be
unique.
 Goal: Remove repeating groups or arrays.

Example (Not in 1NF):

StudentID Name Subjects


101 Alice Math, Science, History

Problem: The Subjects column contains multiple values, which is not atomic.

Converted to 1NF:

StudentID Name Subject


101 Alice Math
101 Alice Science
101 Alice History

Now, each cell contains atomic values and there are no repeating groups.

2. Second Normal Form (2NF)

 Rule: Be in 1NF and remove partial dependency (non-key columns must depend on the
whole primary key).

Join Telegram:- @engineeringnotes_mu


 Goal: Eliminate dependencies on part of a composite primary key.

Example (Not in 2NF):

StudentID CourseID CourseName InstructorName


1 C101 Physics Dr. Smith
1 C102 Chemistry Dr. Johnson
2 C101 Physics Dr. Smith

Problem: CourseName depends only on CourseID, not on the full key (StudentID, CourseID).
This is a partial dependency.

Convert to 2NF:

Enrollment Table:

StudentID CourseID
1 C101
1 C102
2 C101

Course Table:

CourseID CourseName InstructorName


C101 Physics Dr. Smith
C102 Chemistry Dr. Johnson

Now, non-key attributes depend only on the whole primary key.

3. Third Normal Form (3NF)

 Rule: Be in 2NF and remove transitive dependency (non-key attributes must not depend
on other non-key attributes).
 Goal: Non-key fields should depend only on the primary key.

Example (Not in 3NF):

StudentID Department DeptHead


1 Science Dr. Smith
2 Math Dr. Johnson

Join Telegram:- @engineeringnotes_mu


Problem: DeptHead depends on Department, not on StudentID. This is a transitive dependency.

Convert to 3NF:

Student Table:

StudentID Department
1 Science
2 Math

Department Table:

Department DeptHead
Science Dr. Smith
Math Dr. Johnson

Now, non-key attributes (DeptHead) only depend on the primary key (Department).

4. Boyce-Codd Normal Form (BCNF)

 Rule: A stricter version of 3NF where every determinant is a candidate key.


 Goal: Handle certain anomalies not addressed by 3NF.

Example (Not in BCNF):

Course Instructor Room


DBMS John 101
DBMS Mike 102

Problem: Course → Instructor, but Course is not a candidate key. This violates BCNF.

Fix (BCNF):

Course-Instructor Table:

Course Instructor
DBMS John
DBMS Mike

Course-Room Table:

Join Telegram:- @engineeringnotes_mu


Course Room
DBMS 101
DBMS 102

Now, every determinant (Course) is a candidate key.

5. Fourth Normal Form (4NF)

 Rule: Be in BCNF and no multi-valued dependencies.


 Goal: Eliminate independent multi-valued facts.

Example (Not in 4NF):

Student Course Hobby


Alice Math Reading
Alice Science Painting
Bob Math Swimming
Bob English Singing

Problem: The Student table has two independent multi-valued attributes (Course and Hobby),
which should be separated.

Convert to 4NF:

Student-Course Table:

Student Course
Alice Math
Alice Science
Bob Math
Bob English

Student-Hobby Table:

Student Hobby
Alice Reading
Alice Painting
Bob Swimming
Bob Singing

Join Telegram:- @engineeringnotes_mu


Now, there are no multi-valued dependencies.

Q.2: List All Functional Dependencies Of Relation ? (M-23)

Ans:

Step-by-step analysis:

1. Determine if X → Y

 X1 maps to both Y1 and Y2 → violates functional dependency.


 X2 maps to only Y2 → OK.
❌ So, X → Y is not valid.

2. Determine if X → Z

 X1 maps to Z1
 X2 maps to Z1
→ Both consistently map to Z1.
❌ X → Z is valid.

3. Determine if Y → Z

 Y1 → Z1
 Y2 → Z1
→ All Y values map to Z1.
❌ Y → Z is valid.

4. Determine if Z → Y or Z → X

Join Telegram:- @engineeringnotes_mu


 Z1 maps to multiple Y and X values → Not unique.
❌ Z → X or Z → Y are not valid.

5. Determine if (X,Y) → Z

 Each unique (X,Y) pair maps to Z1.


❌ (X,Y) → Z is valid.

6. Determine if (X,Y) → X or Y

 Trivially valid because X and Y are part of the key.


❌ (X,Y) → X (trivial)
❌ (X,Y) → Y (trivial)

� Final List of Functional Dependencies:

 X→Z
 Y→Z
 (X,Y) → Z
 (X,Y) → X (trivial)
 (X,Y) → Y (trivial)

Q.3: Need Of Normalization ? (M-23,N-23,M-24)

Ans:

� Need for Normalization in DBMS

Normalization is essential in database design to ensure data integrity, reduce redundancy, and
improve efficiency. Here's why normalization is needed:

1. Eliminate Data Redundancy

 Without normalization: Same data is stored in multiple places.


 Problem: Increases storage usage and chances of inconsistency.
 With normalization: Data is stored only once and linked through keys.

Join Telegram:- @engineeringnotes_mu


2. Avoid Update Anomalies

 Example: Changing a customer’s phone number in one place but forgetting to update it
elsewhere.
 Normalization ensures a single source of truth, avoiding inconsistent updates.

3. Avoid Insertion Anomalies

 Without normalization: You may not be able to insert data unless other data is also
available.
 With normalization: Related data is split into logical tables, allowing independent
insertion.

4. Avoid Deletion Anomalies

 Example: Deleting a student record also deletes the last record of a course.
 Normalization helps preserve essential information by separating related data.

Q.4: Draw Precedence Graph Of Schedule ? (M-24)

Ans:

Join Telegram:- @engineeringnotes_mu


Q.5: Explain Types Of Functional Dependency ? (N-24)

Ans:

� Types of Functional Dependency in DBMS

Functional dependency describes the relationship between attributes in a relation. If attribute B is


functionally dependent on A (written as A → B), then A uniquely determines B.

1. Partial Dependency

Definition: An attribute is partially dependent if it is dependent on part of a composite primary


key.

Example:
In R(StudentID, CourseID, StudentName),
StudentName depends only on StudentID → Partial Dependency.

2. Transitive Dependency

Definition: A transitive dependency occurs when A → B and B → C, then A → C (indirect


dependency).

Example:
If StudentID → DeptName and DeptName → HOD,
Then StudentID → HOD (transitive).

3. Multivalued Dependency (MVD)

Join Telegram:- @engineeringnotes_mu


Definition: Attribute A has a multivalued dependency on B if, for each value of B, there is a set
of values of A independent of other attributes.

Notation: B ↠ A

Example:
If a student can have multiple phone numbers and multiple hobbies,
StudentID ↠ PhoneNumber and StudentID ↠ Hobby

4. Join Dependency

Definition: A join dependency occurs when a relation R can be reconstructed by joining multiple
smaller relations without data loss.

Example:
Used in 5NF, where the relation is decomposed into 3 or more tables and then joined back
without loss.

Join Telegram:- @engineeringnotes_mu


MODULE-6
Q.1: Define Deadlock & Explain Deadlock Handling? (N-22,M-23,N-23,M-24,N-24)

Ans:

Deadlock in DBMS

A deadlock is a condition where two or more transactions are waiting indefinitely for one
another to release locks. As a result, no transaction can proceed.

Example:

 Transaction T1 locks rows in the Student table and wants to access Grade.
 Transaction T2 locks rows in the Grade table and wants to access Student.

This leads to:

 T1 waiting for T2
 T2 waiting for T1

This forms a cycle — a deadlock.

Deadlock Handling in DBMS

There are three main strategies to handle deadlocks: Deadlock handling in DBMS refers to the
methods used to prevent, avoid, or resolve deadlocks.

Join Telegram:- @engineeringnotes_mu


1. Deadlock Detection and Recovery
o The system detects deadlocks after they occur.
o It recovers by aborting one or more transactions involved in the cycle.
2. Deadlock Avoidance
o The system analyzes each request to avoid circular wait.
o Uses techniques like Wait-for Graph to predict and avoid deadlocks.
3. Deadlock Prevention
o The system is designed to disallow at least one of the four necessary conditions
for deadlock (e.g., circular wait, hold and wait, etc.).
o Locks are granted in such a way that deadlocks never occur.

Q.2: What is Two Phase Locking? Explain Its types? Concurrency Control Protocol ? (N-
22,M-23,N-23)

Ans:

Introduction:

Two-Phase Locking (2PL) synchronizes reads and writes by explicitly detecting and preventing
conflicts between concurrent operations.

 Before reading data item X → transaction must hold a read lock on X.


 Before writing data item X → transaction must hold a write lock on X.
 Locking rules:
1. Two transactions cannot hold conflicting locks (e.g., read vs. write) on the same
data.
2. Once a transaction releases a lock, it cannot acquire new locks.

Conflicting Locks:

 RW Synchronization:
Two locks conflict if:
o Both operate on the same data item.
o One is a read lock, the other is a write lock.
 WW Synchronization:
Two locks conflict if:
o Both operate on the same data item.
o Both are write locks.

Concurrency Control Protocol (2PL Rules):

Join Telegram:- @engineeringnotes_mu


Each transaction must follow two phases:

1. Growing Phase:
o Transaction can acquire new locks.
o Cannot release any lock.
2. Shrinking Phase:
o Transaction can release locks.
o Cannot acquire new locks.

 The lock point marks the transition from growing to shrinking phase.
 All locks are released automatically when the transaction terminates (commit/abort).

� Types of Two-Phase Locking (2PL) Protocols:

1. Basic Two-Phase Locking (2PL)

 Follows growing and shrinking phases.


 Ensures conflict-serializability.
 Does not prevent cascading rollbacks or deadlocks.

2. Strict Two-Phase Locking Protocol (Strict 2PL)

 Holds all exclusive locks until the transaction commits or aborts.


 Prevents cascading rollbacks.
 Ensures recoverability.
 Not deadlock-free.

3. Rigorous Two-Phase Locking Protocol (Rigorous 2PL)

 Holds both shared and exclusive locks until the transaction commits.
 Prevents cascading rollbacks.
 Transactions can be serialized in commit order.
 Common in database systems.

Q.3: Explain View & Conflict Serializability With Example ? (N-22,N-23,M-24)

Ans: Serializability is the concept in database systems that ensures the correctness of
transactions executed concurrently. It guarantees that the final outcome of executing multiple

Join Telegram:- @engineeringnotes_mu


transactions simultaneously is the same as if they were executed serially (one after the other)
without any overlapping.

In simpler terms, serializability ensures that even when transactions run concurrently, the result
will be consistent, and there will be no data anomalies like lost updates or inconsistent reads.

1. Conflict Serializability

 A schedule is conflict serializable if it can be transformed into a serial schedule (where


transactions execute one after another) by swapping non-conflicting operations.

Conflicting Operations:

Two operations conflict if:

 They belong to different transactions.


 They operate on the same data item.
 At least one is a write operation.

Conflict Pairs:

 R-W (Read-Write)
 W-R (Write-Read)
 W-W (Write-Write)

Example:

Schedule:
T1: R(A), W(A),R(B)
T2: R(A)

Here, W1(A) and R2(A) conflict.

 If this schedule creates a cycle in the precedence graph, it is not conflict serializable.
 If the precedence graph has no cycles, then the schedule is conflict serializable.

2. View Serializability

 A schedule is view serializable if it is view equivalent to a serial schedule.

Join Telegram:- @engineeringnotes_mu


 It is more flexible than conflict serializability.

View Equivalence Conditions:

1. Initial Reads Match: The first read of each data item must be from the same transaction
in both schedules.
2. Write-Read Correspondence: If a transaction reads a value written by another, this
must be preserved.
3. Final Writes Match: The final write on each data item must be by the same transaction
in both schedules.

Example:

Schedule S1:
T1: W(A)
T2: R(A)
T3: W(A)

Schedule S2 (Serial):
T1: W(A)
T2: R(A)
T3: W(A)

S1 is view serializable with S2 because:

 First read is from T1 in both.


 T2 reads from T1 in both.
 T3 does the final write in both.

Even if S1 is not conflict serializable, it is view serializable.

Q.4: Explain ACID Properties Of Transaction With Example ? (N-22,M-23,N-23,M-24)

Ans:

ACID properties of transaction:


The transaction has four properties. These are used to maintain consistency in a database before
and after the transaction.

1. The properties are called ACID properties.


2. ACID properties (Atomicity, Consistency, Isolation, and Durability) are crucial for
reliable database transactions, ensuring data integrity even during failures or concurrent
access.

Join Telegram:- @engineeringnotes_mu


1. Atomicity

1. Atomicity means that the entire transaction takes place at once or doesn't happen at all. A
transaction does not occur partially.
2. It involves two operations:
o Abort: Changes made to the database are not visible.
o Commit: Changes made are visible.

Example: Bank transfer


A bank transfer from Account A to Account B must either succeed entirely (debiting A and
crediting B) or fail entirely (no transaction). If any part fails, the entire transaction is rolled back
to maintain data integrity.

2. Consistency

This means that integrity constraints must be maintained so that the database is consistent before
and after the transaction. It refers to the correctness of a database.

Example: Bank transfer


Before and after the transfer, the total amount of money in the database must remain consistent.

3. Isolation

This property ensures that multiple transactions can occur concurrently without leading to the
inconsistency of the database state. Transactions occur independently without interference.

Example: Bank transfer


If multiple users attempt to transfer funds from the same account concurrently, the system must
ensure that each transaction is isolated from the other one. One user’s transaction should not
affect the other until it has completed and committed.

4. Durability

This property ensures that once the transaction has completed execution, the updates and
modifications to the database are stored and written to disk, and they persist even if a system
failure occurs. These updates now become permanent and are stored in non-volatile memory.
The effects of the transaction are never lost.

Join Telegram:- @engineeringnotes_mu


Example: After a user places an order online, the order and stock updates are stored in the database.
If a power failure occurs right after the transaction, the changes will still persist when the system
restarts, ensuring the transaction is not lost.

Q.5 : Explain Transaction State Diagram & TCL Commands? (N-22)

Ans:

Transaction states

A transaction in a database can be in one of the following states:

Active state
The active state is the first state of every transaction. In this state, the transaction is being
executed.
For example: Insertion or deletion or updating a record is done here. But all the records are still
not saved to the database.

Partially committed
In the partially committed state, a transaction executes its final operation, but the data is still not
saved to the database.
In the total mark calculation example, a final display of the total marks step is executed in this
state.

Committed
A transaction is said to be in a committed state if it executes all its operations successfully.
In this state, all the effects are now permanently saved on the database system.

Join Telegram:- @engineeringnotes_mu


Failed state
If any of the checks made by the database recovery system fails, then the transaction is said to be
in the failed state.
In the example of total mark calculation, if the database is not able to fire a query to fetch the
marks, then the transaction will fail to execute.

Aborted
If any of the checks fail and the transaction has reached a failed state, then the database recovery
system will make sure that the database is in its previous consistent state. If not, then it will abort
or roll back the transaction to bring the database into a consistent state.
If the transaction fails in the middle of the transaction, then before executing the transaction, all
the executed transactions are rolled back to their consistent state.
After aborting the transaction, the database recovery module will select one of the two
operations:

1. Re-start the transaction


2. Kill the transaction

TCL (Transaction Control Language) Commands (Short)

1. COMMIT:
o Purpose: Saves all changes made in the current transaction.
o Syntax: COMMIT;
2. ROLLBACK:
o Purpose: Undoes changes made in the current transaction.
o Syntax: ROLLBACK;
3. SAVEPOINT:
o Purpose: Sets a point to roll back to within a transaction.
o Syntax: SAVEPOINT savepoint_name;
4. SET TRANSACTION:
o Purpose: Configures transaction properties like isolation level.
o Syntax: SET TRANSACTION ISOLATION LEVEL level;

These commands help manage and control database transactions, ensuring ACID properties.

Q.6: Explain Log Based Recovery? (M-23,N-23,M-24,N-24)

Ans:

Log-Based Recovery

The log is a sequence of records. A log of each transaction is maintained in some stable storage
so that if any failure occurs, it can be recovered from there.

Join Telegram:- @engineeringnotes_mu


If any operation is performed on the database, then it will be recorded in the log.

But the process of storing the logs should be done before the actual transaction is applied in the
database.

Let’s assume there is a transaction to modify the City of a student. The following logs are
written for this transaction:

 When the transaction is initiated, then it writes a start log:


<Tn, Start>
 When the transaction modifies the City from 'Noida' to 'Bangalore', then another log is
written:
<Tn, City, 'Noida', 'Bangalore'>
 When the transaction is finished, it writes a commit log:
<Tn, Commit>

There are two approaches to modify the database:

1. Deferred database modification:

 In deferred modification, the transaction does not modify the database until it has
committed.
 All the logs are created and stored in stable storage, and only when the transaction
commits is the database updated.

2. Immediate database modification:

 In immediate modification, the database is modified while the transaction is still active.
 Here, the database is modified immediately after each operation.

Recovery using Log Records

 When the system crashes, it consults the log to find:


o which transactions need to be undone
o which need to be redone

1. If the log contains the records <Ti, Start> and <Ti, Commit> or <Ti, Abort>,
then Transaction Ti needs to be redone.

Join Telegram:- @engineeringnotes_mu


2. If the log contains the record <Ti, Start> but does not contain <Ti, Commit> or <Ti,
Abort>,
then Transaction Ti needs to be undone.

Note: It is quite time-consuming to redo all the transactions that are committed, so the concept of
checkpoint occurs.

Q.7: Explain Deadlock Prevention Methods ? (M-23,N-23,M-24,N-24)

Ans:

Deadlock Prevention

Deadlock prevention method is suitable for a large database. If the resources are allocated in
such a way that deadlock never occurs, then the deadlock can be prevented.

The Database Management System analyzes the operations of the transaction whether they can
create a deadlock situation or not. If they do, then the DBMS never allows that transaction to be
executed.

Wait-Die Scheme

In this scheme, if a transaction requests for a resource which is already held with a conflicting
lock by another transaction, then the DBMS simply checks the timestamp of both transactions. It
allows the older transaction to wait until the resource is available for execution.

Let’s assume there are two transactions Ti and Tj, and let TS(T) be the timestamp of any
transaction T.

 If TS(Ti) < TS(Tj)


→ Ti is older and requesting a resource held by Tj
→ Ti is allowed to wait
 If TS(Ti) > TS(Tj)
→ Ti is younger and requesting a resource held by Tj
→ Ti is killed and restarted later with the same timestamp

Wound-Wait Scheme

In this scheme, if the older transaction requests for a resource held by a younger transaction, then
the older transaction forces the younger one to abort and release the resource.

After a delay, the younger transaction is restarted with the same timestamp.

Join Telegram:- @engineeringnotes_mu


If the younger transaction requests for a resource held by the older one, then the younger
transaction is asked to wait.

Q.8: Give example of serial schedule and equivalent to serial schedule with respect to
conflict serializability. ? (M-23,N-24)

Ans:

Serial Schedule

A serial schedule is a type of schedule where transactions are executed one after another, without
any interleaving of operations from different transactions.

Example (Serial Schedule):


Let there be two transactions:

T1: Read(A), Write(A)


T2: Read(B), Write(B)

Schedule S1:
T1: Read(A) → Write(A)
T2: Read(B) → Write(B)

In this schedule, T1 completes all its operations before T2 starts. This is a serial schedule.

Equivalent Serial Schedule and Conflict Serializability

A schedule is conflict serializable if it can be transformed into a serial schedule by swapping


non-conflicting operations (i.e., operations that don't access the same data item or at least one of
them is a Read).

Example (Non-Serial but Conflict Serializable Schedule):

Schedule S2:
T1: Read(A)
T2: Read(B)
T1: Write(A)
T2: Write(B)

This is not a serial schedule, as operations from T1 and T2 are interleaved.


But no conflicting operations are reordered—T1 operates on A and T2 on B—so we can
transform it into a serial schedule like S1.

Therefore, S2 is conflict serializable and equivalent to serial schedule S1.

Join Telegram:- @engineeringnotes_mu


Q.9: Explain Lock Based Protocol Of 2PL Concurrency With Example? (N-23,N-24)

Ans:

Lock-Based Protocol (Concurrency Control)

A lock-based protocol is a method used in databases to manage concurrent access to data


items. It ensures that multiple transactions can safely access and modify shared data without
conflicts, maintaining data consistency and isolation.

Key Concepts

1. Lock: A mechanism to restrict access to a data item.


o Before a transaction can read or write a data item, it must acquire a lock on it.
o Locks are released after the transaction completes (or is rolled back).
2. Modes of Locking:
o Exclusive (X) Lock:
 Acquired using lock-X instruction.
 Allows both read and write access.
 No other transaction can hold any lock on that item simultaneously.
o Shared (S) Lock:
 Acquired using lock-S instruction.
 Allows only read access.
 Multiple transactions can hold shared locks at the same time.

Lock Compatibility Matrix

Requested \ Held Shared (S) Exclusive (X)

Shared (S) T (True) F (False)

Exclusive (X) F (False) F (False)

 T (True): Lock can be granted.


 F (False): Lock cannot be granted.
 This matrix ensures that:
o Multiple shared locks are allowed.
o No transaction can acquire a lock if another transaction holds an exclusive lock.

Join Telegram:- @engineeringnotes_mu


Working

1. A transaction requests a lock.


2. If compatible, the lock is granted.
3. If not, the transaction waits until the lock is available.
4. Once done, it releases the lock.

Example of Lock-Based Protocol:

Scenario:

 T1 wants to read A (shared lock) and write B (exclusive lock).


 T2 wants to write A (exclusive lock) and read B (shared lock).

Step-by-Step:

1. T1 locks A (shared) and B (exclusive).


2. T2 requests a write lock on A (but T1 has a shared lock on A, so T2 waits).
3. T2 also wants a read lock on B, but T1 holds an exclusive lock on B, so T2 waits.

Result:

 Deadlock occurs, as T1 and T2 are waiting for each other’s locks.

Solution:

 One transaction (e.g., T2) is rolled back to break the deadlock.

Q.10: Explain Concurrency Control & Explain Timestamp Based Protocol ? (M-24,N-24)

Ans:

Concurrency Control in DBMS

Concurrency control is a mechanism used in database systems to ensure that multiple


transactions can execute simultaneously without affecting the consistency and integrity of the
database. The primary goals of concurrency control are:

 Consistency: Ensure that the database remains in a valid state.


 Isolation: Ensure that the outcome of a transaction is not affected by other concurrently
executing transactions.
 Avoidance of issues like lost updates, temporary inconsistency, and uncommitted data.

Join Telegram:- @engineeringnotes_mu


Timestamp-Based Protocol (Explained from the Image)

In Timestamp-Based Concurrency Control, each transaction is assigned a unique timestamp


when it enters the system. This timestamp determines the order of execution.

Key Components:

 TS(Ti): Timestamp of transaction Ti.


 Read_TS(Q): Largest timestamp of any transaction that successfully read data item Q.
 Write_TS(Q): Largest timestamp of any transaction that successfully wrote data item Q.

Rules for Read(Q):

Suppose transaction Ti wants to read(Q):

1. If TS(Ti) < Write_TS(Q):


o Ti is too old; Q was updated by a newer transaction.
o Read is rejected, and Ti is rolled back.
2. If TS(Ti) ≥ Write_TS(Q):
o Read is allowed.
o Update Read_TS(Q) to max(Read_TS(Q), TS(Ti)).

Rules for Write(Q):

Suppose transaction Ti wants to write(Q):

1. If TS(Ti) < Read_TS(Q):


o The value Ti wants to write has already been read by a newer transaction.
o Write is rejected, and Ti is rolled back.
2. If TS(Ti) < Write_TS(Q):
o Ti is trying to write an obsolete value.
o Write is rejected, and Ti is rolled back.
3. If TS(Ti) ≥ Read_TS(Q) and TS(Ti) ≥ Write_TS(Q):
o Write is allowed.
o Update Write_TS(Q) = TS(Ti).

Join Telegram:- @engineeringnotes_mu

You might also like