Nothing Special   »   [go: up one dir, main page]

Dbms Important Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

IMPORTANT QUESTIONS

2 MARKS
1. Define Physical Independence.
It refers to the ability to change the physical storage structures of a database without
affecting its conceptual schema or logical design.

2. Summarize various Data Model in DBMS.


Common data models include:
● Hierarchical Model
● Network Model
● Relational Model
● Object-oriented Model

3. Define Constraints
Constraints are rules enforced on data in a database to ensure its accuracy and integrity.
Examples include primary key, foreign key, and NOT NULL constraints.

4. Name few attribute types.


Common attribute types are:
● Integer
● Varchar
● Date
● Boolean

5. What are the pitfalls in relational database?


● Redundancy and inconsistency
● Difficulty in maintaining complex relationships
● Update anomalies (insert, delete, update anomalies)

6. Compare Non trivial and trivial functional Dependency.

● Trivial Functional Dependency: When a functional dependency X → Y holds, where


Y is a subset of X.
● Non-trivial Functional Dependency: When Y is not a subset of X, but X → Y holds.

7. List any 5 CODD Rules.


● Rule 1: Information Rule
● Rule 2: Guaranteed Access Rule
● Rule 3: Systematic Treatment of Null Values
● Rule 4: Dynamic Online Catalog Based on Relational Model
● Rule 5: Comprehensive Data Sub-language Rule

8. Explain Trigger.
A trigger is a procedural code in a DBMS that automatically executes in response to
certain events on a particular table or view, like INSERT, UPDATE, or DELETE.
9. Define Serializability.
It is the concept in transaction management that ensures that the concurrent execution
of transactions results in a system state that could be obtained if transactions were
executed serially.

10. What is Transaction State?


A transaction can be in one of these states:
● Active
● Partially Committed
● Failed
● Aborted
● Committed

11. Define DBMS.


A Database Management System (DBMS) is software that provides efficient, secure,
and convenient database management by enabling data storage, retrieval, and
manipulation.

12. Compare File System and Relational Database.

● File System: Data is stored in flat files.


● Relational Database: Data is stored in tables, and relationships are established
using keys.

13. List few design issues in ER Diagram.


● Entity vs Attribute
● Entity vs Relationship
● Representation of Relationships
● Proper cardinality

14. What is Mapping cardinality?


It refers to the number of entities in one entity set that can be associated with entities in
another entity set. Examples: One-to-one, One-to-many, Many-to-one, Many-to-many.

15. Define Functional Dependency.


A relationship between two attributes, typically between a primary key and a non-key
attribute, where one attribute uniquely determines another.

16. Compare the Primary Key and Foreign Key.


● Primary Key: Uniquely identifies records in a table.
● Foreign Key: Refers to the primary key in another table to establish a
relationship between the two.

17. How to declare variable in PL/SQL?


A variable is declared in PL/SQL as follows:
sql
DECLARE
variable_name datatype [:= value];

18. Define B-Tree.


A B-Tree is a self-balancing tree data structure that maintains sorted data and allows
searches, sequential access, insertions, and deletions in logarithmic time.

19. What is Transaction Management?


It refers to the process of managing multiple database operations to ensure ACID
properties (Atomicity, Consistency, Isolation, Durability) are upheld.

20. Explain Deadlock.


A deadlock occurs when two or more transactions are waiting for each other to release
locks on resources, creating a cycle of dependency that prevents the transactions from
proceeding.

16 MARKS

1. Explain in detail about Database System Architecture with neat diagram.


A Database stores a lot of critical information to access data quickly and securely. Hence it is
important to select the correct architecture for efficient data management. DBMS Architecture
helps users to get their requests done while connecting to the database. We choose database
architecture depending on several factors like the size of the database, number of users, and
relationships between the users. There are two types of database models that we generally use,
logical model and physical model. Several types of architecture are there in the database which
we will deal with in the next section.
Types of DBMS Architecture
There are several types of DBMS Architecture that we use according to the usage requirements.
Types of DBMS Architecture are discussed here.
● 1-Tier Architecture
● 2-Tier Architecture
● 3-Tier Architecture
The 3-level DBMS architecture provides logical and physical data independence. For more
insights, the GATE CS Self-Paced Course covers DBMS comprehensively
1-Tier Architecture
In 1-Tier Architecture the database is directly available to the user, the user can directly sit on
the DBMS and use it that is, the client, server, and Database are all present on the same
machine. For Example: to learn SQL we set up an SQL server and the database on the local
system. This enables us to directly interact with the relational database and execute operations.
The industry won’t use this architecture they logically go for 2-tier and 3-tier Architecture.

DBMS 1-Tier Architecture


Advantages of 1-Tier Architecture
Below mentioned are the advantages of 1-Tier Architecture.
● Simple Architecture: 1-Tier Architecture is the most simple architecture to set up, as
only a single machine is required to maintain it.
● Cost-Effective: No additional hardware is required for implementing 1-Tier
Architecture, which makes it cost-effective.
● Easy to Implement: 1-Tier Architecture can be easily deployed, and hence it is mostly
used in small projects.
2-Tier Architecture
The 2-tier architecture is similar to a basic client-server model . The application at the client
end directly communicates with the database on the server side. APIs like ODBC and JDBC
are used for this interaction. The server side is responsible for providing query processing and
transaction management functionalities. On the client side, the user interfaces and application
programs are run. The application on the client side establishes a connection with the server
side to communicate with the DBMS.
An advantage of this type is that maintenance and understanding are easier, and compatible
with existing systems. However, this model gives poor performance when there are a large
number of users.
DBMS 2-Tier Architecture
Advantages of 2-Tier Architecture
● Easy to Access: 2-Tier Architecture makes easy access to the database, which makes
fast retrieval.
● Scalable: We can scale the database easily, by adding clients or upgrading hardware.
● Low Cost: 2-Tier Architecture is cheaper than 3-Tier Architecture and Multi-Tier
Architecture .
● Easy Deployment: 2-Tier Architecture is easier to deploy than 3-Tier Architecture.
● Simple: 2-Tier Architecture is easily understandable as well as simple because of only
two components.
3-Tier Architecture
In 3-Tier Architecture , there is another layer between the client and the server. The client does
not directly communicate with the server. Instead, it interacts with an application server which
further communicates with the database system and then the query processing and transaction
management takes place. This intermediate layer acts as a medium for the exchange of partially
processed data between the server and the client. This type of architecture is used in the case
of large web applications.

DBMS 3-Tier Architecture


Advantages of 3-Tier Architecture
● Enhanced scalability: Scalability is enhanced due to the distributed deployment of
application servers. Now, individual connections need not be made between the client
and server.
● Data Integrity: 3-Tier Architecture maintains Data Integrity. Since there is a middle
layer between the client and the server, data corruption can be avoided/removed.
● Security: 3-Tier Architecture Improves Security. This type of model prevents direct
interaction of the client with the server thereby reducing access to unauthorized data.
Disadvantages of 3-Tier Architecture
● More Complex: 3-Tier Architecture is more complex in comparison to 2-Tier
Architecture. Communication Points are also doubled in 3-Tier Architecture.
● Difficult to Interact: It becomes difficult for this sort of interaction to take place due
to the presence of middle layers.

2. Discuss various DDL and DML commands with suitable example.


SQL Commands are like instructions to a table. It is used to interact with the database with
some operations. It is also used to perform specific tasks, functions, and queries of data. SQL
can perform various tasks like creating a table, adding data to tables, dropping the table,
modifying the table, set permission for users.
SQL Commands are mainly categorized into five categories:
1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language

DDL (Data Definition Language)


DDL or Data Definition Language actually consists of the SQL commands that can be used
to define the database schema. It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in the database.
DDL is a set of SQL commands used to create, modify, and delete database structures but not
data. These commands are normally not used by a general user, who should be accessing the
database via an application.
List of DDL Commands:
Here are all the main DDL (Data Definition Language) commands along with their syntax:

Command Description Syntax

CREATE TABLE table_name


CREATE Create database or its (column1 data_type, column2
objects (table, index, data_type, ...);
Command Description Syntax

function, views, store


procedure, and triggers)

Delete objects from the


DROP DROP TABLE table_name;
database

Alter the structure of the ALTER TABLE table_name ADD


ALTER
database COLUMN column_name data_type;

Remove all records from a


table, including all spaces
TRUNCATE TRUNCATE TABLE table_name;
allocated for the records
are removed

Add comments to the data COMMENT 'comment_text' ON


COMMENT
dictionary TABLE table_name;

Rename an object existing RENAME TABLE old_table_name


RENAME
in the database TO new_table_name;

DQL (Data Query Language)


DQL statements are used for performing queries on the data within schema objects. The
purpose of the DQL Command is to get some schema relation based on the query passed to
it. We can define DQL as follows it is a component of SQL statement that allows getting data
from the database and imposing order upon it. It includes the SELECT statement.
This command allows getting the data out of the database to perform operations with it. When
a SELECT is fired against a table or tables the result is compiled into a further temporary table,
which is displayed or perhaps received by the program i.e. a front-end.
DQL Command
There is only one DQL command in SQL i.e.
Command Description Syntax

It is used to retrieve data from SELECT column1, column2, ...FROM


SELECT
the database table_name WHERE condition;

DML (Data Manipulation Language)


The SQL commands that deal with the manipulation of data present in the database belong to
DML or Data Manipulation Language and this includes most of the SQL statements.
It is the component of the SQL statement that controls access to data and to the database.
Basically, DCL statements are grouped with DML statements.
List of DML commands
Here are all the main DML (Data Manipulation Language) commands along with their syntax:

Command Description Syntax

Insert data into a INSERT INTO table_name (column1, column2, ...)


INSERT
table VALUES (value1, value2, ...);

Update existing UPDATE table_name SET column1 = value1,


UPDATE
data within a table column2 = value2 WHERE condition;

Delete records from


DELETE DELETE FROM table_name WHERE condition;
a database table

Table control
LOCK LOCK TABLE table_name IN lock_mode;
concurrency

Call a PL/SQL or
CALL CALL procedure_name(arguments);
JAVA subprogram

EXPLAIN Describe the access EXPLAIN PLAN FOR SELECT * FROM


PLAN path to data table_name;

DCL (Data Control Language)


DCL includes commands such as GRANT and REVOKE which mainly deal with the rights,
permissions, and other controls of the database system.
List of DCL commands:
Two important DCL commands and their syntax are:

Command Description Syntax

Assigns new privileges to a


GRANT privilege_type
user account, allowing
[(column_list)] ON [object_type]
GRANT access to specific database
object_name TO user [WITH
objects, actions, or
GRANT OPTION];
functions.

Removes previously
REVOKE [GRANT OPTION FOR]
granted privileges from a
privilege_type [(column_list)] ON
REVOKE user account, taking away
[object_type] object_name FROM
their access to certain
user [CASCADE];
database objects or actions.

TCL (Transaction Control Language)


Transactions group a set of tasks into a single execution unit. Each transaction begins with a
specific task and ends when all the tasks in the group are successfully completed. If any of the
tasks fail, the transaction fails.
Therefore, a transaction has only two results: success or failure. You can explore more about
transactions here.
List of TCL Commands
Some TCL commands and their syntax are:

Command Description Syntax

BEGIN BEGIN TRANSACTION


Starts a new transaction
TRANSACTION [transaction_name];

Saves all changes made


COMMIT COMMIT;
during the transaction

Undoes all changes made


ROLLBACK ROLLBACK;
during the transaction
Command Description Syntax

Creates a savepoint within the


SAVEPOINT SAVEPOINT savepoint_name;
current transaction

3. Illustrate ER Model with neat diagram and explain.


● ER diagrams represent the E-R model in a database, making them easy to convert into
relations (tables).
● ER diagrams provide the purpose of real-world modeling of objects which makes them
intently useful.
● ER diagrams require no technical knowledge and no hardware support.
● These diagrams are very easy to understand and easy to create even for a naive user.
● It gives a standard solution for visualizing the data logically.
A solid grasp of the ER Model is crucial for excelling in exams like GATE, where database
management is a key topic. Symbols Used in ER Model
ER Model is used to model the logical view of the system from a data perspective which
consists of these symbols:
● Rectangles: Rectangles represent Entities in the ER Model.
● Ellipses: Ellipses represent Attributes in the ER Model.
● Diamond: Diamonds represent Relationships among Entities.
● Lines: Lines represent attributes to entities and entity sets with other relationship types.
● Double Ellipse: Double Ellipses represent Multi-Valued Attributes.
● Double Rectangle: Double Rectangle represents a Weak Entity.
Components of the ER Diagram
This model is based on three basic concepts:
● Entities
● Attributes
● Relationship
ENTITY
A real-world thing either living or non-living that is easily recognizable and nonrecognizable.
It is anything in the enterprise that is to be represented in our database. It may be a physical
thing or simply a fact about the enterprise or an event that happens in the real world.
An entity can be place, person, object, event or a concept, which stores data in the database.
The characteristics of entities are must have an attribute, and a unique key. Every entity is
made up of some ‘attributes’ which represent that entity.
Examples of entities:
● Person: Employee, Student, Patient
● Place: Store, Building
● Object: Machine, product, and Car
● Event: Sale, Registration, Renewal
● Concept: Account, Course
Notation of an Entity
Entity set
Student
An entity set is a group of similar kind of entities. It may contain entities with attribute
sharing similar values. Entities are represented by their properties, which also called
attributes. All attributes have their separate values. For example, a student entity may have a
name, age, class, as attributes.

Example of Entities:
A university may have some departments. All these departments employ various lecturers
and offer several programs.

Relationship
Relationship is nothing but an association among two or more entities. E.g., Tom works in
the Chemistry department.

Entities take part in relationships. We can often identify relationships with verbs or verb
phrases.
Weak Entities
A weak entity is a type of entity which doesn’t have its key attribute. It can be identified
uniquely by considering the primary key of another entity. For that, weak entity sets need to
have participation.

In above ER Diagram examples, “Trans No” is a discriminator within a group of transactions


in an ATM.
Attributes
It is a single-valued property of either an entity-type or a relationship-type.
For example, a lecture might have attributes: time, date, duration, place, etc.
An attribute in ER Diagram examples, is represented by an Ellipse
Cardinality
Defines the numerical attributes of the relationship between two entities or entity sets.
Different types of cardinal relationships are:
● One-to-One Relationships
● One-to-Many Relationships
● May to One Relationships
● Many-to-Many Relationships
1.One-to-one:
One entity from entity set X can be associated with at most one entity of entity set Y and vice
versa.
Example: One student can register for numerous courses. However, all those courses have a
single line back to that one student.

2.One-to-many:
One entity from entity set X can be associated with multiple entities of entity set Y, but an
entity from entity set Y can be associated with at least one entity.
For example, one class is consisting of multiple students.

3. Many to One
More than one entity from entity set X can be associated with at most one entity of entity set
Y. However, an entity from entity set Y may or may not be associated with more than one
entity from entity set X.
For example, many students belong to the same class.
4. Many to Many:
One entity from X can be associated with more than one entity from Y and vice versa.
For example, Students as a group are associated with multiple faculty members, and faculty
members can be associated with multiple students.

Example For ER-Diagram

4. Explain in detail about set operations.


A set operation is one that combines the results of multiple query blocks into one. For example,
we could combine the result of two separate SELECT statements. The results are displayed in
a single result set as though we’d run a single query.
These Set Theory operations are the standard mathematical operations on set. These operations
are Binary operations that are, operated on 2 relations unlike PROJECT, SELECT and
RENAME operations. These operations are used to merge 2 sets in various ways.
The set operation is mainly categorized into the following:
1. Union operation
2. Intersection operation
3. Set difference or Minus operation
Before we apply one of the 3 set operations on relations, the two relations on which we are
performing the operations must have same type of tuples. This is also known as be Union
compatibility (or Type compatibility).
Type compatibility: Two relations A(P1, P2, …, Pn) and B(Q1, Q2, …, Qn) are said to be
Type compatible (or Union compatible) if both the relation have the same degree ‘k’ and
domain(Pi) = domain(Qi) for 1<= i <= k.
1. UNION Operation: Notation:
A∪S
where, A and S are the relations, symbol ‘∪’ is used to denote the Union operator. The result
of Union operation, which is denoted by A ∪ S, is a relation that basically includes all the tuples
that are present in A or in S, or in both, eliminating the duplicate tuples.
Important points on UNION Operation:
1. The UNION operation is commutative, that is :
A∪B=B∪A
2. The UNION is associative, that means it is applicable to any number of relation.
A∪(B∪C)=(A∪B)∪C
3. In SQL, the operation UNION is as same as UNION operation here.
4. Moreover, In SQL there is multiset operation UNION ALL.
2. INTERSECTION Operation:
Notations:
A∩S
where, A and S are the relations,
symbol ‘∩’ is used to denote the Intersection operator.
The result of Intersection operation, which is denoted by A ∩ S, is a relation that basically
includes all the tuples that are present in both A an S.
Important points on INTERSECTION Operation:
1. The INTERSECTION operation is commutative, that is :
A∩B=B∩A
2. The INTERSECTION is associative, that means it is applicable to any number of relation.
A∩(B∩C)=(A∩B)∩C
3. INTERSECTION can be formed using UNION and MINUS as follows:
A ∩ B = ((A ∪ B) - (A - B)) - (B - A)
4. In SQL, the operation INTERSECT is as same as INTERSECTION operation here.
5. Moreover, In SQL there is multiset operation INTERSECT ALL.
3. MINUS (or SET DIFFERENCE) Operation:
Notations:
A-S
where, A and S are the relations,
symbol ‘ – ’ is used to denote the Minus operator.
The result of Intersection operation, which is denoted by A – S, is a relation that basically
includes all the tuples that are present in A but not in S.
Important points on MINUS (or SET DIFFERENCE) Operation:
1. The SET DIFFERENCE operation is not commutative, that means :
A - B != B - A
2. In SQL, the operation EXCEPT is as same as MINUS operation here.
3. Moreover, In SQL there is multiset operation EXCEPT ALL.
Example: Consider a relation Student(FIRST, LAST) and Faculty(FIRSTN, LASTN) given
below :

First Last

Aisha Arora

Bikash Dutta

Makku Singh
First Last

Raju Chopra

FirstN LastN

Raj Kumar

Honey Chand

Makku Singh

Karan Rao

1. Student UNION Faculty :


Student ∪ Faculty

First Last

Aisha Arora

Bikash Dutta

Makku Singh

Raju Chopra

Raj Kumar

Honey Chand

Karan Rao
2. Student INTERSECTION Faculty :
Student ∩ Faculty

First Last

Makku Singh

3. Student MINUS Faculty :


Student - Faculty

First Last

Aisha Arora

Bikash Dutta

Raju Chopra

5. Describe various Integrity constraints.


Integrity constraints are the set of predefined rules that are used to maintain the quality of
information. Integrity constraints ensure that the data insertion, data updating, data deleting
and other processes have to be performed in such a way that the data integrity is not affected.
They act as guidelines ensuring that data in the database remain accurate and consistent. So,
integrity constraints are used to protect databases. The various types of integrity constraints are
Types of Integrity Constraints:
● Domain Constraints
● Not-Null Constraints
● Entity integrity Constraints
● Key Constraints
● Primary Key Constrains
● Referential integrity constraints
Domain Constraints
These are defined as the definition of valid set of values for an attribute. The data type of
domain include string, char, time, integer, date, currency etc. The value of the attribute must
be available in comparable domains.
Example:

Student_Id Name Semester Age

21CSE100 Ramesh 5th 20

21CSE101 Kamlesh 5th 21

21CSE102 Aakash 5th 22

21CSE103 Mukesh 5th 20

Not-Null Constraints
It specifies that within a tuple, attributes overs which not-null constraint is specified must not
contain any null value.
Example:
Let, the not-null constraint be specified on the “Semester” attribute in the relation/table given
below, then the data entry of 4th tuple will violate this integrity constraint, because the
“Semester” attribute in this tuple contains null value. To make this database instance a legal
instance, its entry must not be allowed by database management system.

Student_id Name Semester Age

21CSE100 Ramesh 5th 20

21CSE101 Kamlesh 5th 21

21CSE102 Akash 5th 22

21CSE103 Mukesh 20

Entity Integrity Constraints


Entity integrity constraints state that primary key can never contain null value because primary
key is used to determine individual rows in a relation uniquely, if primary key contains null
value then we cannot identify those rows. A table can contain null value in it except primary
key field.
Example:
It is not allowed because it is containing primary key as NULL value.

Student_id Name Semester Age

21CSE101 Ramesh 5th 20

21CSE102 Kamlesh 5th 21

21CSE103 Aakash 5th 22

Mukesh 5th 20

Key Constraints
Keys are the entity set that are used to identify an entity within its entity set uniquely. An entity
set can contain multiple keys, bit out of them one key will be primary key. A primary key is
always unique, it does not contain any null value in table.
Example:
Student_id Name Semester Age

21CSE101 Ramesh 5th 20

21CSE102 Kamlesh 5th 21

21CSE103 Aakash 5th 22

21CSE102 Mukesh 5th 20

It is now acceptable because all rows must be unique.


Primary Key Constraints
It states that the primary key attributes are required to be unique and not null. That is, primary
key attributes of a relation must not have null values and primary key attributes of two tuples
must never be same. This constraint is specified on database schema to the primary key
attributes to ensure that no two tuples are same.
Example
Here, in the below example the Student_id is the primary key attribute. The data entry of 4th
tuple violates the primary key constraint that is specifies on the database schema and therefore
this instance of database is not a legal instance.

Student_id Name Semester Age

21CSE101 Ramesh 5th 20

21CSE102 Kamlesh 5th 21

21CSE103 Akash 5th 22

21CSE103 Mukesh 5th 20

Referential integrity constraints


It can be specified between two tables. In case of referential integrity constraints, if a Foreign
key in Table 1 refers to Primary key of Table 2 then every value of the Foreign key in Table 1
must be null or available in Table 2.
Example:
Here, in below example Block_No 22 entry is not allowed because it is not present in 2nd table.

Student_id Name Semester Block_No

22CSE101 Ramesh 5th 20

21CSE105 Kamlesh 6th 21

22CSE102 Aakash 5th 20

23CSE106 Mukesh 2nd 22

Block_No Block Location

20 Chandigarh

21 Punjab

25 Delhi

6. Articulate the join functions with student academic and personal databases.
Join functions in relational databases are used to retrieve data from two or more related tables
based on a common field between them. When dealing with student information systems, it is
common to have separate databases for academic and personal information of students.
These databases can be linked using a primary key and foreign key relationship, typically
based on a unique identifier such as student_id.
In this section, we will explore various join functions (INNER JOIN, LEFT JOIN, RIGHT
JOIN, FULL OUTER JOIN, and CROSS JOIN) by applying them to a Student Personal
Database and a Student Academic Database. These functions help in fetching combined
records that provide comprehensive information about students, such as their academic
performance along with their personal details.
1. INNER JOIN
The INNER JOIN retrieves only those records where there is a match between the two tables.
In the case of student databases, this means that only students who have records in both the
personal and academic tables will be included in the result set.
Example Scenario:
We have two tables:
● student_personal: Contains personal information such as student_id, name, email, and
phone_number.
● student_academic: Contains academic information such as student_id, course_name,
grade, and semester.
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
INNER JOIN student_academic sa ON sp.student_id = sa.student_id;
Explanation:
● In this query, we are joining the student_personal (aliased as sp) and student_academic
(aliased as sa) tables based on the student_id field.
● The result will include only those students who have both personal and academic
records, ensuring that there are matches in both tables.
● For example, if a student exists in the personal database but doesn’t have any academic
record, that student will not appear in the result.
Sample Output:
student_id name email course_name grade semester

101 Alice Smith alice@gmail.com Math A 1

102 Bob Johnson bob@gmail.com Science B 2

103 Carol White carolw@gmail.com Literature A 3

2. LEFT JOIN (LEFT OUTER JOIN)


The LEFT JOIN retrieves all records from the left table (student personal), along with the
matching records from the right table (student academic). If there is no match, NULL values
are returned for columns from the right table.
Example Scenario:
Retrieve all students from the personal database, even if they do not have academic records.
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
LEFT JOIN student_academic sa ON sp.student_id = sa.student_id;
Explanation:
● In this query, all students from the student_personal table are included in the result,
even if they do not have corresponding academic records in the student_academic table.
● If a student is missing academic information, the fields from student_academic
(course_name, grade, semester) will be NULL.
Sample Output:
student_id name email course_name grade semester

101 Alice Smith alice@gmail.com Math A 1

102 Bob Johnson bob@gmail.com Science B 2

103 Carol White carolw@gmail.com Literature A 3

104 David Brown davidb@gmail.com NULL NULL NULL


● As seen in the output, David Brown (student_id 104) does not have any academic
record, but he is still included in the result because of the LEFT JOIN.

3. RIGHT JOIN (RIGHT OUTER JOIN)


The RIGHT JOIN retrieves all records from the right table (student academic) and the
matching records from the left table (student personal). If there is no match, NULL values are
returned for columns from the left table.
Example Scenario:
Retrieve all students from the academic database, even if they do not have personal records.
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
RIGHT JOIN student_academic sa ON sp.student_id = sa.student_id;
Explanation:
● This query returns all records from the student_academic table. If a student doesn’t
have personal details in the student_personal table, those fields (name, email) will be
NULL.
Sample Output:
student_id name email course_name grade semester

101 Alice Smith alice@gmail.com Math A 1

102 Bob Johnson bob@gmail.com Science B 2

103 Carol White carolw@gmail.com Literature A 3

105 NULL NULL Physics B 2


● Student with student_id 105 doesn’t have personal information in the student_personal
table, so the personal columns are filled with NULL.

4. FULL OUTER JOIN


The FULL OUTER JOIN retrieves all records when there is a match in either the left or right
table. If there is no match, NULL values are returned for non-matching columns from the
respective table.
Example Scenario:
Retrieve all students from both personal and academic databases, including those who may not
have records in one of the tables.
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
FULL OUTER JOIN student_academic sa ON sp.student_id = sa.student_id;
Explanation:
● This query combines the results of both LEFT JOIN and RIGHT JOIN, ensuring that
all students are included, even if they have incomplete information in either table.
Sample Output:
student_id name email course_name grade semester

101 Alice Smith alice@gmail.com Math A 1

102 Bob Johnson bob@gmail.com Science B 2

103 Carol White carolw@gmail.com Literature A 3


student_id name email course_name grade semester

104 David Brown davidb@gmail.com NULL NULL NULL

105 NULL NULL Physics B 2

5. CROSS JOIN
The CROSS JOIN returns the Cartesian product of two tables, which means every row from
the first table is paired with every row from the second table.
Example Scenario:
Retrieve a combination of every student from the personal database with every academic record
(not commonly used, but useful in specific cases like creating testing datasets).
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
CROSS JOIN student_academic sa;
Explanation:
● This query will return every possible combination of student personal details and
academic details, regardless of whether they are related or not.
Sample Output:
student_id name email course_name grade semester

101 Alice Smith alice@gmail.com Math A 1

101 Alice Smith alice@gmail.com Science B 2

102 Bob Johnson bob@gmail.com Math A 1

102 Bob Johnson bob@gmail.com Science B 2

7. Explain in detail about various Normalization Form in DBMS


Normalization is a process used to minimize data redundancy and dependency by
organizing fields and tables in a relational database.

i) 1NF (First Normal Form)


A table is in 1NF if:
All columns contain atomic (indivisible) values.
Each record is unique.
Example: If a table has repeated or multi-valued attributes (e.g., multiple phone numbers
stored in one column), it must be divided so that each column contains only one value per
record.

ii) 2NF (Second Normal Form)


A table is in 2NF if:

It is in 1NF.
All non-key attributes are fully functionally dependent on the entire primary key. In other
words, no partial dependencies are allowed (i.e., attributes should depend on the entire
primary key, not a part of it).
Example: For a composite key, each non-key attribute must depend on the entire key, not just
part of it.

iii) 3NF (Third Normal Form)


A table is in 3NF if:

It is in 2NF.
All attributes are functionally dependent only on the primary key. There should be no
transitive dependencies (i.e., non-key attributes should not depend on other non-key
attributes).
Example: If in a table, City depends on ZIP Code, which in turn depends on Address, the
transitive dependency must be eliminated by creating separate tables for ZIP codes and cities.

iv) BCNF (Boyce-Codd Normal Form) & 4NF (Fourth Normal Form)
BCNF: A table is in BCNF if:
It is in 3NF.
Every determinant is a superkey. This means that for every functional dependency A -> B, A
must be a candidate key.
Example: Consider a table where a non-candidate key determines part of the primary key.
This table needs to be decomposed to achieve BCNF.

4NF: A table is in 4NF if:


It is in BCNF.
There are no multi-valued dependencies.

8. What do you understand by PL/SQL cursors? and Explain its various types.
In PL/SQL (Procedural Language for SQL), a cursor is a pointer or a handle to a context area,
which is a memory region where Oracle executes SQL statements. When you execute an SQL query,
Oracle needs to process and store the result set in a context area. Cursors allow you to fetch rows
from this result set one at a time, which is especially useful when working with queries that return
multiple rows.

There are two main types of cursors in PL/SQL:


1. Implicit Cursors
2. Explicit Cursors
1. Implicit Cursors
PL/SQL automatically creates an implicit cursor for SQL statements like INSERT, UPDATE,
DELETE, and SELECT INTO. These are single-row queries where the result set is expected
to return just one row. The implicit cursor is automatically managed by Oracle, and the
programmer doesn’t need to declare it or explicitly fetch the results.
Characteristics of Implicit Cursors:
● Automatically created by PL/SQL.
● Used when a SQL statement returns exactly one row.
● Simplifies coding since no declaration or fetching is required.
● Automatically closed after the execution of the SQL statement.
Example:
sql
Copy code
BEGIN
UPDATE employees
SET salary = salary * 1.1
WHERE employee_id = 100;

IF SQL%ROWCOUNT = 1 THEN
DBMS_OUTPUT.PUT_LINE('1 row updated successfully.');
END IF;
END;
In this example:
● An implicit cursor is created and executed for the UPDATE statement.
● SQL%ROWCOUNT is an implicit cursor attribute that returns the number of rows
affected by the SQL operation.
Common Implicit Cursor Attributes:
● SQL%FOUND: Returns TRUE if one or more rows are affected by the SQL statement.
● SQL%NOTFOUND: Returns TRUE if no rows are affected.
● SQL%ROWCOUNT: Returns the number of rows affected by the SQL statement.

2. Explicit Cursors
Explicit cursors are created and managed by the programmer when a query returns more than
one row. In these cases, you need to define a cursor, open it, fetch the rows into variables, and
finally close it. Explicit cursors provide greater control over the result set, allowing the
programmer to process each row one at a time.
Steps in Using Explicit Cursors:
1. Declare the cursor: Define the SQL query that will be associated with the cursor.
2. Open the cursor: Execute the query and allocate memory for the result set.
3. Fetch data: Retrieve rows from the cursor into PL/SQL variables one row at a time.
4. Close the cursor: Release the memory associated with the cursor.
Example:
sql
Copy code
DECLARE
CURSOR employee_cursor IS
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = 10;

v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN employee_cursor;

LOOP
FETCH employee_cursor INTO v_employee_id, v_first_name, v_last_name;
EXIT WHEN employee_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee_id || ', Name: ' || v_first_name || ' ' ||


v_last_name);
END LOOP;
CLOSE employee_cursor;
END;
In this example:
● A cursor named employee_cursor is declared for the SQL query.
● The cursor is opened, and each row is fetched into variables v_employee_id,
v_first_name, and v_last_name.
● The loop processes each row until there are no more rows
(employee_cursor%NOTFOUND).
● The cursor is then closed to free the memory.
Common Explicit Cursor Attributes:
● cursor_name%FOUND: Returns TRUE if a row was successfully fetched.
● cursor_name%NOTFOUND: Returns TRUE if no more rows are available.
● cursor_name%ROWCOUNT: Returns the number of rows fetched so far.

Types of Explicit Cursors:


1. Simple Explicit Cursor
o The basic cursor that selects a fixed set of records from the database.
o Example is shown above.
2. Parameterized Cursor
o A cursor that accepts parameters, allowing the query to be more dynamic and
flexible.
Example:
sql
DECLARE
CURSOR param_cursor (dept_id IN employees.department_id%TYPE) IS
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = dept_id;

v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN param_cursor(10); -- Passing department_id = 10 to the cursor.
LOOP
FETCH param_cursor INTO v_employee_id, v_first_name, v_last_name;
EXIT WHEN param_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee_id || ', Name: ' || v_first_name || ' ' ||
v_last_name);
END LOOP;

CLOSE param_cursor;
END;
o Here, the cursor param_cursor accepts a department ID as a parameter and
retrieves employee information based on that.
3. Ref Cursor (Cursor Variables)
o A REF CURSOR (cursor variable) allows for more flexibility since it can point
to different result sets at runtime.
o Unlike regular explicit cursors, a REF CURSOR is not tied to a particular query.
It can be passed as a parameter between procedures and can dynamically
associate itself with different queries during execution.
Example:
sql
DECLARE
TYPE ref_cursor_type IS REF CURSOR;
emp_cursor ref_cursor_type;
v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN emp_cursor FOR
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = 20;
LOOP
FETCH emp_cursor INTO v_employee_id, v_first_name, v_last_name;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee_id || ', Name: ' || v_first_name || ' ' ||
v_last_name);
END LOOP;
CLOSE emp_cursor;
END;

Advantages of Cursors:
1. Row-by-Row Processing: Cursors allow you to fetch and process rows one by one,
which is useful for handling large datasets where batch processing is required.
2. Control over Execution: Explicit cursors give more control over how and when data
is retrieved, enabling more complex and flexible operations.
3. Dynamic Query Handling: With REF CURSOR, you can handle different queries
dynamically, making it useful in scenarios where the SQL statement might change
during execution.
Disadvantages of Cursors:
1. Performance Overhead: Cursors can slow down performance, especially when used
in loops for large datasets, as row-by-row processing is typically slower than bulk
operations.
2. Memory Usage: Cursors allocate memory for the result set, which might lead to higher
memory usage, especially if not managed properly (e.g., failing to close cursors).
3. Complexity: The use of cursors can add complexity to PL/SQL code, making it harder
to debug and maintain.

9. Explain in detail about ACID properties.


Atomicity ensures that a transaction is treated as a single "atomic" unit, meaning that either
all the operations within the transaction are completed successfully, or none of them are. There is
no in-between state.

● If a transaction succeeds, all changes made during the transaction are saved to the
database.
● If a transaction fails at any point, all changes made are rolled back, and the database is
left as it was before the transaction began.
In simpler terms, atomicity guarantees that a transaction is "all or nothing." It ensures complete
execution or total rollback, protecting the database from partial updates.
Example:
Imagine a banking transaction where money is being transferred from Account A to Account
B. The transaction consists of two steps:
1. Deducting the amount from Account A.
2. Adding the same amount to Account B.
If the system fails after the deduction from Account A but before the addition to Account B,
without atomicity, the money would be deducted from Account A, and Account B would not
receive the amount, leading to an inconsistent state.
However, because of atomicity, if such a failure occurs, the system rolls back the deduction
from Account A, ensuring that no partial transaction takes place.
Implementation in DBMS:
● DBMS systems use a transaction log to record changes. If a failure occurs, the DBMS
uses the log to rollback incomplete transactions and restore the database to a consistent
state.
● Commit and Rollback operations are used to enforce atomicity. A transaction is
committed if it successfully completes, and it is rolled back if it encounters an error.

2. Consistency
Consistency ensures that a transaction brings the database from one valid state to another valid
state, maintaining all predefined rules, integrity constraints, and database invariants.
In other words, after the transaction is executed, the database should not violate any integrity
constraints (such as unique keys, foreign keys, data types, etc.) defined on the schema. The
database remains in a valid state before and after the transaction, even if the transaction alters
the data.
Example:
Consider a scenario where a bank has a rule that the balance of any account cannot go below
zero. If a transaction attempts to deduct more money than the account holds, the system should
reject the transaction to maintain consistency. Thus, a transaction should only be allowed if it
keeps the database in a consistent state according to all rules and constraints.
Implementation in DBMS:
● DBMS enforces consistency by applying integrity constraints. Any operation that
violates these constraints is aborted and rolled back.
● Constraints like primary keys, foreign keys, and check constraints are used to ensure
the consistency of the database throughout the transaction.
3. Isolation
Isolation ensures that the execution of multiple transactions occurs in isolation from one
another. Even if multiple transactions are executed concurrently, they should not interfere with
each other. Each transaction must be isolated from others, meaning that the result of each
transaction should be the same as if it were executed alone, without any other transactions
running simultaneously.
This property is critical for maintaining concurrency control in multi-user environments,
where several users or applications might access the database at the same time.
Example:
Consider two transactions happening at the same time:
● Transaction 1: Withdraws money from an account.
● Transaction 2: Checks the balance of the same account.
Without isolation, Transaction 2 might read the balance after the withdrawal but before the
transaction is committed, leading to inaccurate data. However, with isolation, Transaction 2
either sees the balance before Transaction 1 or after Transaction 1, but not during it.
Isolation Levels in DBMS:
DBMS systems implement different isolation levels to balance concurrency and performance:
● Read Uncommitted: A transaction may read data that is not yet committed by other
transactions (can lead to dirty reads).
● Read Committed: A transaction can only read data that has been committed (prevents
dirty reads, but other phenomena like non-repeatable reads may occur).
● Repeatable Read: A transaction can read the same data multiple times without seeing
any changes from other transactions (prevents non-repeatable reads).
● Serializable: The strictest level of isolation where transactions are executed
sequentially to ensure complete isolation.

4. Durability
Durability ensures that once a transaction has been committed, its changes are permanent.
Even in the event of a system crash or power failure, the changes made by the transaction are
saved and cannot be undone. This property guarantees that committed data will be available in
the database even after unexpected events.
Example:
Imagine a scenario where a transaction updates a customer’s information in the database. Once
the transaction commits, this updated information must be stored permanently, even if the
system crashes immediately afterward.
Implementation in DBMS:
● Write-ahead logging (WAL) is a mechanism used to ensure durability. Before making
any changes to the actual database, the DBMS writes the transaction details to a log
file. Once the log is written, the changes are made to the database.
● In case of a crash, the DBMS uses the log to restore the committed transactions,
ensuring that no committed data is lost.

Importance of ACID Properties


● Data Integrity: ACID properties ensure that the data remains accurate and reliable
despite errors, crashes, or other issues.
● Concurrency Control: Isolation helps manage multiple concurrent users effectively,
ensuring transactions do not interfere with each other.
● System Stability: Atomicity and durability guarantee the stability of the database, as
incomplete transactions are rolled back, and committed ones persist even in the event
of system failures.
● Consistency Maintenance: The consistency property ensures that all database rules
and constraints are enforced, preventing any form of corruption or invalid data entry.

Real-world Example of ACID Properties in Action


Consider a ticket booking system:
● Atomicity: When booking a ticket, both seat reservation and payment are part of a
transaction. If the payment is successful but the seat cannot be reserved (due to another
customer reserving it at the same time), the entire transaction is rolled back, and no
ticket is booked.
● Consistency: The system ensures that the number of available seats never exceeds the
maximum number of seats for an event.
● Isolation: Multiple customers booking tickets simultaneously will not see each other's
partial transactions. One customer’s seat reservation does not affect another’s in real-
time.
● Durability: Once the ticket is booked and payment is confirmed, the booking
information is permanently stored, ensuring that the ticket will remain valid even if the
system crashes.

10. Develop an application for employee pay role process.


A payroll system is essential for businesses to calculate employee salaries, manage taxes,
bonuses, and deductions, and ensure accurate payments. In this detailed guide, we will develop a
simple employee payroll system with the following features:
● Employee management (adding, updating, deleting employee records)
● Payroll generation
● Handling allowances, deductions, bonuses
● Tax calculation
● Generating payslips for employees
1. System Requirements and Overview
The application will consist of a database to store employee details, salary components, tax
rules, and other related information. The system should support:
● CRUD operations (Create, Read, Update, Delete) for employee records
● Automated payroll calculation
● Handling bonuses, deductions, and taxes
● Storing payroll history
● Generating and displaying payslips for employees
2. Database Design
The core of any payroll system is its database. Here, we will outline the key tables needed to
store data for our payroll system.
Database Tables:
● Employee Table: Contains employee details such as ID, name, department,
designation, basic salary, etc.
● Salary Table: Stores salary components like basic pay, allowances, deductions,
bonuses, and taxes.
● Payroll Table: Stores the monthly payroll details for each employee.
● Tax Table: Contains information on tax slabs and rules.
Employee Table Structure:
Column Data Type Description

emp_id INT (Primary Key) Unique ID for each employee

emp_name VARCHAR(100) Employee's name

emp_designation VARCHAR(50) Job title or designation

emp_department VARCHAR(50) Department where the employee works

emp_basic DECIMAL(10, 2) Basic salary of the employee

emp_bonus DECIMAL(10, 2) Bonus amount


Column Data Type Description

emp_deduction DECIMAL(10, 2) Deduction amount

emp_tax_rate DECIMAL(5, 2) Tax rate applicable to the employee

emp_net_salary DECIMAL(10, 2) Calculated net salary


Payroll Table Structure:
Column Data Type Description

payroll_id INT (Primary Key) Unique ID for each payroll record

emp_id INT (Foreign Key) Employee ID (linked to Employee Table)

payroll_month VARCHAR(10) Month for which the payroll is generated

basic_salary DECIMAL(10, 2) Basic salary for the month

allowances DECIMAL(10, 2) Allowances like HRA, Travel, etc.

deductions DECIMAL(10, 2) Total deductions like provident fund, tax, etc.

net_salary DECIMAL(10, 2) Net salary to be paid after taxes and deductions


3. Payroll Calculation Logic
Payroll Calculation Formula:
The net salary for an employee is calculated based on the following formula:
java
Net Salary = Basic Salary + Allowances + Bonus - Deductions - Taxes
● Basic Salary: The base salary of the employee.
● Allowances: Additional monetary benefits, like House Rent Allowance (HRA), Travel
Allowance, etc.
● Bonus: Extra payment based on employee performance or other factors.
● Deductions: Amount deducted for Provident Fund (PF), tax, or any other reasons.
● Taxes: Calculated based on the applicable tax slab.
Steps in Payroll Calculation:
1. Fetch the employee’s details such as basic salary, allowances, deductions, and tax rate.
2. Calculate the tax based on the basic salary using tax slabs.
3. Compute the gross salary by adding the allowances and bonuses to the basic salary.
4. Apply the deductions and tax to calculate the net salary.
5. Store the calculated payroll in the Payroll Table and generate the payslip.
4. Sample PL/SQL Code for Payroll Generation
Below is a sample implementation in PL/SQL for generating employee payroll:
sql
CREATE OR REPLACE PROCEDURE generate_payroll (p_emp_id INT, p_month
VARCHAR) IS
v_basic_salary DECIMAL(10, 2);
v_allowances DECIMAL(10, 2);
v_bonus DECIMAL(10, 2);
v_deductions DECIMAL(10, 2);
v_tax DECIMAL(10, 2);
v_net_salary DECIMAL(10, 2);
v_tax_rate DECIMAL(5, 2);
v_emp_name VARCHAR(100);
BEGIN
-- Fetch employee details
SELECT emp_basic, emp_bonus, emp_deduction, emp_tax_rate, emp_name
INTO v_basic_salary, v_bonus, v_deductions, v_tax_rate, v_emp_name
FROM Employee
WHERE emp_id = p_emp_id;

-- Calculate tax based on basic salary


v_tax := (v_basic_salary * v_tax_rate) / 100;

-- Calculate total allowances (this can be more complex based on allowance structure)
v_allowances := 0.20 * v_basic_salary; -- Example: Allowance is 20% of basic salary

-- Calculate net salary


v_net_salary := v_basic_salary + v_allowances + v_bonus - v_deductions - v_tax;

-- Insert payroll record for the month


INSERT INTO Payroll (payroll_id, emp_id, payroll_month, basic_salary, allowances,
deductions, net_salary)
VALUES (payroll_seq.NEXTVAL, p_emp_id, p_month, v_basic_salary, v_allowances,
v_deductions, v_net_salary);

-- Display payroll details


DBMS_OUTPUT.PUT_LINE('Payroll generated for ' || v_emp_name || ' for month ' ||
p_month);
DBMS_OUTPUT.PUT_LINE('Net Salary: ' || v_net_salary);

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ID not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred during payroll generation.');
END;
5. Generating Employee Payslip
A simple payslip can be generated by fetching the payroll details from the database. Here's a
basic SQL query to display the payslip for an employee:
sql
Copy code
SELECT e.emp_name, p.payroll_month, p.basic_salary, p.allowances, p.deductions,
p.net_salary
FROM Employee e
JOIN Payroll p ON e.emp_id = p.emp_id
WHERE e.emp_id = 101 AND p.payroll_month = 'September';
Output Example (payslip):
yaml
Employee Name: John Doe
Payroll Month: September
Basic Salary: 50,000
Allowances: 10,000
Deductions: 8,000
Net Salary: 52,000
6. User Interface for Payroll System
In a full-fledged system, a graphical user interface (GUI) can be built using any web framework
like Java (JSP/Servlets), Python (Django/Flask), or PHP. The interface will allow users to:
● Add new employees
● Update salary details
● Generate payroll
● View and print payslips
7. Advanced Features to Include
● Taxation Rules: Different employees may have different tax slabs or deductions, so
it’s essential to implement a tax table with variable rates based on income levels.
● Leave Management: Deduct salary for unpaid leaves.
● Bonus Calculation: Vary the bonus based on employee performance or company
policies.
● Reports: Monthly or yearly payroll reports for management, tax compliance, or
auditing purposes.

11. Explain in detail about view of data.


In a Database Management System (DBMS), the view of data refers to how data is
represented, structured, and managed at different levels of abstraction. This concept is essential in
understanding how data is accessed, stored, and manipulated by users, developers, and database
administrators. The three main levels in the view of data are physical, logical, and external views.
Each level offers a different perspective on the data stored in a database, which allows efficient
management of large datasets while maintaining security and consistency.

1. Physical View (Storage Level)


The physical view of data is the lowest level of abstraction in a DBMS and deals with the actual
storage of data on the hardware (such as hard drives, SSDs, or in the cloud). This level defines
how the data is physically organized and stored in blocks, files, or records. It also includes the
methods used for data retrieval and placement within the storage media.
Key Features:
● Physical independence: Users and developers do not need to know how data is stored
physically. Changes in storage mechanisms (e.g., switching from one storage medium
to another) do not affect how data is accessed.
● Efficient storage management: This layer optimizes the storage of data by organizing
it in a way that minimizes space usage and retrieval time.
Example:
In India, where e-commerce companies like Flipkart and Amazon India manage massive
amounts of data, the physical view would include how product details, customer orders, and
payment information are stored across distributed servers. Despite changes in storage
technology, users continue to interact with the website seamlessly without any knowledge of
how or where the data is physically stored.
2. Logical View (Conceptual Level)
The logical view, also called the conceptual view, is the middle level of abstraction that
focuses on the structure of the entire database. It defines what data is stored, the relationships
between different data elements, and how they are logically organized in the form of schemas.
This is the level at which most database management occurs and where database administrators
and developers work to design efficient systems.
Key Features:
● Data independence: Changes made at the physical level (e.g., indexing, compression)
do not affect the logical view of the data.
● Entity-relationship models: This level typically uses an entity-relationship (ER)
model to represent data in tables, columns, and rows, where data entities and
relationships are mapped out clearly.
● Database design: This is the level where developers define relationships, constraints,
and data types.
Example:
Consider a banking application like SBI’s YONO app. The logical view would include entities
such as Customers, Accounts, Transactions, and their relationships. For instance, one
customer can have multiple accounts, and each account is associated with multiple transactions.
This abstraction allows the bank to manage its database efficiently while keeping customer
information secure and accessible.
3. External View (User Level)
The external view, also known as the view level, is the highest level of abstraction and focuses
on how end-users interact with the data. This level provides a tailored view of the database to
specific users or user groups. Different users may have different views depending on their roles
and permissions. For example, a marketing team might need access to customer data for
analytics, while the HR department only sees employee-related data.
Key Features:
● Custom views: Multiple users can have different external views of the same database.
For example, one user might see a summary of orders, while another sees detailed
customer information.
● Security and privacy: The external view helps to enforce access control by showing
users only the data they are permitted to see, enhancing data security.
● Simplicity for users: End-users are presented with an interface that hides the
complexity of the underlying database structure.

12. Construct employee table with empno,name,salary and apply various


manipulation operations..
create an employee table named Employee with three columns: empno (Employee Number),
name (Employee Name), and salary (Employee Salary). After constructing the table, we'll perform
various SQL manipulation operations such as insertion, update, deletion, and retrieval.

Step 1: Constructing the Employee Table


The following SQL command creates the Employee table with the required columns:
sql
CREATE TABLE Employee (
empno INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);
● empno: This column stores the unique employee number. It is defined as the Primary
Key to ensure uniqueness.
● name: This column stores the name of the employee with a maximum length of 50
characters.
● salary: This column stores the salary of the employee, defined as a decimal value with
two decimal points.
Step 2: Inserting Data into the Employee Table
We can now insert data into the Employee table using the INSERT INTO SQL command.
Here’s how you insert three employee records:
sql
INSERT INTO Employee (empno, name, salary)
VALUES (101, 'John Doe', 50000.00),
(102, 'Jane Smith', 60000.00),
(103, 'Raj Kumar', 55000.00);
● Employee 101: John Doe, with a salary of 50,000.
● Employee 102: Jane Smith, with a salary of 60,000.
● Employee 103: Raj Kumar, with a salary of 55,000.
Step 3: Retrieving Data from the Employee Table
To view the data in the Employee table, we use the SELECT statement:
sql
SELECT * FROM Employee;
Result:
empno name salary

101 John Doe 50000.00

102 Jane Smith 60000.00

103 Raj Kumar 55000.00


Step 4: Updating Data in the Employee Table
sql
UPDATE Employee
SET salary = 55000.00
WHERE empno = 101;
After this update, John Doe’s salary will be reflected as 55,000 in the database. To verify this
change, we can use a SELECT statement again:
sql
SELECT * FROM Employee WHERE empno = 101;
Result:
empno name salary

101 John Doe 55000.00


Step 5: Deleting Data from the Employee Table
Suppose Raj Kumar leaves the company, and his record needs to be removed from the table.
We use the DELETE command to remove his record:
sql
DELETE FROM Employee
WHERE empno = 103;
To confirm that the record has been deleted, we can check the table again:
Sql
SELECT * FROM Employee;
Result:
empno name salary

101 John Doe 55000.00

102 Jane Smith 60000.00


Raj Kumar's record has been successfully deleted.
Step 6: Modifying the Structure of the Table (ALTER)
If we want to add a new column to the Employee table (for example, a column to store
employee department), we can use the ALTER TABLE command:
sql
ALTER TABLE Employee
ADD department VARCHAR(50);
After running this query, the Employee table will have a new column named department. You
can insert department values for existing employees like this:
sql
UPDATE Employee
SET department = 'Finance'
WHERE empno = 102;

UPDATE Employee
SET department = 'HR'
WHERE empno = 101;
Step 7: Displaying Data after Alteration
After adding the department and updating values, you can retrieve the data using the following
query:
sql
SELECT * FROM Employee;
Result:
empno name salary department

101 John Doe 55000.00 HR

102 Jane Smith 60000.00 Finance

13. Develop a ER Diagram for Banking System and Explain.


ER diagram is known as Entity-Relationship diagram. It is used to analyze to structure of the
Database. It shows relationships between entities and their attributes. An ER model provides a means
of communication.

ER diagram of Bank has the following description :

● Bank have Customer.


● Banks are identified by a name, code, address of main office.
● Banks have branches.
● Branches are identified by a branch_no., branch_name, address.
● Customers are identified by name, cust-id, phone number, address.
● Customer can have one or more accounts.
● Accounts are identified by account_no., acc_type, balance.
● Customer can avail loans.
● Loans are identified by loan_id, loan_type and amount.
● Account and loans are related to bank’s branch.
ER Diagram of Bank Management System :
This bank ER diagram illustrates key information about bank, including entities such as
branches, customers, accounts, and loans. It allows us to understand the relationships between
entities. Entities and their Attributes are :

● Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address.
Code is Primary Key for Bank Entity.
● Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone
Number and Address.
Customer_id is Primary Key for Customer Entity.
● Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address.
Branch_id is Primary Key for Branch Entity.
● Account Entity : Attributes of Account Entity are Account_number, Account_Type
and Balance.
Account_number is Primary Key for Account Entity.
● Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount.
Loan_id is Primary Key for Loan Entity.
Relationships are :

Bank has Branches => 1 : N


One Bank can have many Branches but one Branch can not belong to many Banks, so the
relationship between Bank and Branch is one to many relationship.

Branch maintain Accounts => 1 : N


One Branch can have many Accounts but one Account can not belong to many Branches, so the
relationship between Branch and Account is one to many relationship.

Branch offer Loans => 1 : N


One Branch can have many Loans but one Loan can not belong to many Branches, so the
relationship between Branch and Loan is one to many relationship.

Account held by Customers => M : N


One Customer can have more than one Accounts and also One Account can be held by one or more
Customers, so the relationship between Account and Customers is many to many relationship.

Loan availed by Customer => M : N


(Assume loan can be jointly held by many Customers).
One Customer can have more than one Loans and also One Loan can be availed by one or more
Customers, so the relationship between Loan and Customers is many to many relationship.

14. Explain in detail about Aggregation Functions.


SQL Aggregate functions are functions where the values of multiple rows are grouped as
input on certain criteria to form a single value result of more significant meaning.

It is used to summarize data, by combining multiple values to form a single result.


SQL Aggregate functions are mostly used with the GROUP BY clause of the SELECT
statement.
Various Aggregate Functions
1. Count()
2. Sum()
3. Avg()
4. Min()
5. Max()
Aggregate Functions in SQL
Below is the list of SQL aggregate functions, with examples
Count():
● Count(*): Returns the total number of records .i.e 6.
● Count(salary): Return the number of Non-Null values over the column salary. i.e 5.
● Count(Distinct Salary): Return the number of distinct Non-Null values over the
column salary .i.e 5.
Sum():
● sum(salary): Sum all Non-Null values of Column salary i.e., 3120.
● sum(Distinct salary): Sum of all distinct Non-Null values i.e., 3120..
Avg():
● Avg(salary) = Sum(salary) / count(salary) = 3120 / 5 = 624
● Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 3120 / 5 = 624
Min():
● Min(salary): Minimum value in the salary column except NULL i.e., 403.
Max():
● Max(salary): Maximum value in the salary i.e., 802.
Demo SQL Database
In this tutorial on aggregate functions, we will use the following table for examples:
Id Name Salary

1 A 802

2 B 403

3 C 604

4 D 705

5 E 606

6 F NULL

15. Describe various Join operations with suitable example.

16. Explain various Armstrong’s axioms/properties of functional dependencies with


suitable example.
In relational databases, joins are used to combine rows from two or more tables based on a
related column between them. Joins help retrieve meaningful data across multiple tables that are
connected by primary keys and foreign keys. There are several types of join operations, and each one
serves a different purpose depending on how the data needs to be retrieved.

The main types of joins in SQL are:


1. Inner Join
2. Left (Outer) Join
3. Right (Outer) Join
4. Full (Outer) Join
5. Cross Join
6. Self Join

1. Inner Join
An Inner Join returns only the rows that have matching values in both tables. If there is no
match, the rows are not included in the result.
Syntax:
sql
SELECT column_names
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example:
Consider two tables, Students and Courses.
Students Table:

student_id name

101 John

102 Jane

103 Alice

Courses Table:

course_id student_id course_name

201 101 Math

202 102 Physics

203 104 Chemistry

sql
SELECT Students.name, Courses.course_name
FROM Students
INNER JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name

John Math

Jane Physics
2. Left (Outer) Join
A Left Join returns all the rows from the left table and the matching rows from the right table.
If no match is found, NULL values are returned for columns from the right table.
Syntax:
sql
SELECT column_names
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Example:
Using the same Students and Courses tables, let's perform a Left Join to get all students and
their enrolled courses (including students who are not enrolled in any courses):
sql
SELECT Students.name, Courses.course_name
FROM Students
LEFT JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name

John Math

Jane Physics

Alice NULL

3. Right (Outer) Join


A Right Join is the opposite of a Left Join. It returns all rows from the right table and the
matching rows from the left table. If no match is found, NULL values are returned for columns
from the left table.
Syntax:
sql
SELECT column_names
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
Example:
To list all courses and the students enrolled in them (including courses with no students), we
use the Right Join:
sql
SELECT Students.name, Courses.course_name
FROM Students
RIGHT JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name

John Math

Jane Physics

NULL Chemistry
4. Full (Outer) Join
A Full Outer Join returns all the rows when there is a match in either the left or right table. If
there is no match, NULL values are returned for the missing side.
Syntax:
sql
SELECT column_names
FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;
Example:
Let’s retrieve all students and all courses, including students without courses and courses
without students:
sql
SELECT Students.name, Courses.course_name
FROM Students
FULL OUTER JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name

John Math

Jane Physics

Alice NULL

NULL Chemistry

5. Cross Join
A Cross Join returns the Cartesian product of two tables, meaning every row from the first
table is combined with every row from the second table.
Syntax:
sql
SELECT column_names
FROM table1
CROSS JOIN table2;
Example:
Let’s perform a Cross Join between the Students and Courses tables:
sql
SELECT Students.name, Courses.course_name
FROM Students
CROSS JOIN Courses;
Result:
name course_name

John Math

John Physics

John Chemistry

Jane Math

Jane Physics

Jane Chemistry
name course_name

Alice Math

Alice Physics

Alice Chemistry

6. Self Join
A Self Join is a join where a table is joined with itself. This is often useful for comparing rows
within the same table.
Syntax:
sql
SELECT A.column_name, B.column_name
FROM table_name A, table_name B
WHERE condition;
Example:
Suppose we have an Employees table with a hierarchical structure (e.g., a manager supervises
other employees). We want to list all employees and their managers.
Employees Table:
emp_id name manager_id

1 John NULL

2 Jane 1

3 Alice 1

4 Bob 2
We can use a Self Join to retrieve the employee names along with their respective manager
names:
sql
SELECT A.name AS Employee, B.name AS Manager
FROM Employees A
LEFT JOIN Employees B
ON A.manager_id = B.emp_id;
Result:
Employee Manager

John NULL

Jane John

Alice John

Bob Jane

17. What do you understand by PL/SQL Trigger? and Explain with suitable example.
A PL/SQL Trigger is a named block of PL/SQL code that automatically executes (or "fires") in
response to certain events on a particular table or view. Triggers are used to enforce business rules,
maintain data integrity, and automate certain tasks within the database. They are invoked
automatically by the database, ensuring that actions are taken consistently whenever data
modifications occur.

Types of Triggers
There are primarily two types of triggers in PL/SQL:
1. Row-Level Triggers: These triggers fire for each row affected by a triggering event.
For example, if an INSERT operation affects five rows, the row-level trigger executes
five times.
2. Statement-Level Triggers: These triggers fire once for each triggering event,
regardless of how many rows are affected. For instance, if an INSERT operation affects
five rows, the statement-level trigger executes only once.
Triggers can also be classified based on the timing of their execution:
● BEFORE Trigger: Executes before the triggering event (e.g., before an INSERT,
UPDATE, or DELETE operation).
● AFTER Trigger: Executes after the triggering event.
Syntax of PL/SQL Trigger
The basic syntax of creating a trigger is as follows:
sql
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH ROW]
BEGIN
-- PL/SQL code to execute
END;
Example of a PL/SQL Trigger
Let’s consider a scenario where we have an Employees table. We want to create a trigger that
automatically updates a last_updated timestamp column whenever an employee's salary is
updated.
Step 1: Create the Employees Table
First, we’ll create the Employees table with the necessary columns:
sql
CREATE TABLE Employees (
emp_id NUMBER PRIMARY KEY,
name VARCHAR2(100),
salary NUMBER(10, 2),
last_updated TIMESTAMP
);
Step 2: Create the Trigger
Next, we’ll create a trigger that updates the last_updated column whenever an employee’s
salary is modified.
sql
CREATE OR REPLACE TRIGGER trg_salary_update
BEFORE UPDATE OF salary
ON Employees
FOR EACH ROW
BEGIN
:NEW.last_updated := SYSTIMESTAMP; -- Set the last_updated to the current timestamp
END;
Explanation:
● Trigger Name: trg_salary_update.
● Timing: BEFORE UPDATE OF salary means this trigger will fire before an update
operation specifically on the salary column.
● Target Table: The trigger is defined on the Employees table.
● FOR EACH ROW: This clause indicates that the trigger will execute once for each
row affected by the update operation.
● : A PL/SQL context variable that holds the new value of the row being modified. In this
case, we assign the current timestamp (SYSTIMESTAMP) to the last_updated column.
Step 3: Testing the Trigger
Now, let’s insert some initial data into the Employees table and test the trigger.
sql
INSERT INTO Employees (emp_id, name, salary, last_updated)
VALUES (1, 'John Doe', 50000, SYSTIMESTAMP);

INSERT INTO Employees (emp_id, name, salary, last_updated)


VALUES (2, 'Jane Smith', 60000, SYSTIMESTAMP);
Now, we can update an employee's salary to see if the trigger works as expected.
sql
UPDATE Employees
SET salary = 55000
WHERE emp_id = 1;
Step 4: Checking the Results
After executing the update, let’s check the Employees table to see if the last_updated column
has been correctly modified.
sql
SELECT emp_id, name, salary, last_updated
FROM Employees;
Expected Result:

emp_id name salary last_updated

1 John Doe 55000 2024-10-13 10:15:30.123

2 Jane Smith 60000 2024-10-13 10:10:00.456

In this example, the last_updated column for John Doe should reflect the current timestamp
when his salary was updated.
Advantages of Using Triggers
1. Automatic Actions: Triggers allow automatic execution of code in response to specific
changes in the database.
2. Data Integrity: Triggers can help enforce data integrity rules that cannot be enforced
by constraints alone.
3. Audit Trails: Triggers can maintain an audit trail of changes to data for compliance or
monitoring purposes.
4. Business Logic Enforcement: They can be used to enforce complex business logic
within the database.
Disadvantages of Using Triggers
1. Complexity: Overusing triggers can lead to complex interdependencies that are hard to
maintain and troubleshoot.
2. Performance Impact: Triggers can affect performance, especially if they contain
complex logic or if they are fired frequently.
3. Hidden Logic: Triggers operate in the background, which can make the logic less
transparent to developers and database administrators.

18. Explain in detail about Transaction Management.


Transaction Management is a critical component of database systems that ensures the
integrity and consistency of data in a database. A transaction is defined as a sequence of one or more
operations that are treated as a single unit of work. Each transaction must follow the principles of the
ACID properties—Atomicity, Consistency, Isolation, and Durability—to ensure reliable processing of
database operations.

Key Concepts in Transaction Management


1. Transaction Properties (ACID)
● Atomicity: This property ensures that a transaction is treated as an indivisible unit.
Either all operations within the transaction are executed, or none are. If any part of the
transaction fails, the entire transaction is rolled back to maintain the original state.
● Consistency: A transaction must bring the database from one valid state to another
valid state. It ensures that any transaction will only bring about changes that respect all
defined rules and constraints, maintaining the integrity of the database.
● Isolation: This property ensures that concurrent execution of transactions does not lead
to inconsistencies. Each transaction should operate independently, and intermediate
states of a transaction should not be visible to others until the transaction is committed.
● Durability: Once a transaction is committed, its effects are permanent and should
survive any subsequent system failures. The changes made by the transaction should
persist in the database, ensuring that the system can recover from crashes.
2. Types of Transactions
● Local Transactions: These transactions involve a single database and are managed by
a single database management system (DBMS).
● Distributed Transactions: These transactions span multiple databases or multiple
DBMSs. They are more complex and require a transaction manager to coordinate
actions across different systems.
3. Transaction States
A transaction can be in one of the following states:
● Active: The transaction is currently being executed.
● Partially Committed: The transaction has executed its final operation but has not yet
been committed.
● Failed: The transaction cannot proceed due to an error.
● Aborted: The transaction has been rolled back, and its effects have been undone.
● Committed: The transaction has successfully completed, and all changes are now
permanent in the database.
4. Transaction Control Statements
In SQL and PL/SQL, several statements are used to manage transactions:
● BEGIN: Starts a transaction.
● COMMIT: Saves all changes made during the transaction and makes them permanent.
● ROLLBACK: Undoes all changes made during the transaction if an error occurs.
● SAVEPOINT: Allows you to set a point within a transaction to which you can roll
back without affecting the entire transaction.
Example of Transaction Management
Let’s consider a banking system where a user wants to transfer money from Account A to
Account B. This operation involves two primary actions: debiting Account A and crediting
Account B. Both actions must be treated as a single transaction to ensure that the system
maintains data integrity.
Step 1: Begin the Transaction
sql
BEGIN;
Step 2: Debit from Account A
sql
UPDATE Accounts
SET balance = balance - 100
WHERE account_id = 'A';
Step 3: Credit to Account B
sql
UPDATE Accounts
SET balance = balance + 100
WHERE account_id = 'B';
Step 4: Commit the Transaction
sql
COMMIT;
Step 5: Rollback in Case of an Error
If, during the debit or credit operation, an error occurs (e.g., insufficient funds in Account A),
you would want to roll back the entire transaction to ensure that neither account reflects an
inconsistent state:
sql
ROLLBACK;
5. Concurrency Control
In a multi-user environment, concurrency control is essential to ensure that multiple
transactions can occur simultaneously without leading to inconsistencies. There are several
methods for concurrency control:
● Locking Protocols: These prevent other transactions from accessing data that is
currently being modified. Locks can be shared (read locks) or exclusive (write locks).
● Timestamp Ordering: Each transaction is given a unique timestamp. Transactions are
then executed based on their timestamps, ensuring consistency.
● Optimistic Concurrency Control: Transactions are allowed to proceed without
locking resources. Only when a transaction is ready to commit does it check for
conflicts with other transactions.
6. Challenges in Transaction Management
Transaction management is not without its challenges:
● Deadlocks: A situation where two or more transactions are waiting for each other to
release locks, causing all involved transactions to be stuck. Deadlock detection and
resolution mechanisms are necessary to handle such cases.
● Resource Contention: When multiple transactions compete for limited resources (e.g.,
CPU, memory), performance can degrade.
● Isolation Levels: Choosing the right isolation level (Read Uncommitted, Read
Committed, Repeatable Read, Serializable) is crucial. Higher isolation levels provide
greater consistency but may lead to reduced concurrency and performance.
19. Explain in detail about Concurrency Control.

Concurrency Control is a crucial aspect of database management systems (DBMS)


that ensures the correct execution of concurrent transactions without leading to data
inconsistencies. When multiple transactions are executed simultaneously in a multi-
user environment, it is essential to manage their interactions to maintain data integrity
and consistency. Concurrency control mechanisms help prevent issues such as lost
updates, temporary inconsistencies, and other anomalies that may arise from concurrent
operations.

Key Concepts in Concurrency Control


1. Concurrent Transactions
A transaction is a sequence of operations performed as a single logical unit of work.
Concurrent transactions are transactions that execute simultaneously, potentially
interacting with shared data. To ensure that these transactions do not interfere with each
other, concurrency control mechanisms must be implemented.
2. Problems Arising from Concurrency
When multiple transactions execute concurrently, several problems can arise,
including:
● Lost Update: Occurs when two transactions read the same data and update it, resulting
in one update being lost.
● Temporary Inconsistency: When one transaction reads data modified by another
transaction that has not yet committed, leading to incorrect results.
● Uncommitted Dependency (Dirty Read): A transaction reads data that has been
modified by another transaction that has not yet committed, resulting in inconsistencies.
● Inconsistent Analysis: When a transaction reads multiple data items, and those data
items are modified by other transactions in between the reads, leading to
inconsistencies.
3. Concurrency Control Techniques
Several techniques can be employed to achieve concurrency control in a DBMS:
a. Lock-Based Protocols
Lock-based protocols are the most widely used methods for managing concurrency.
They involve acquiring locks on data items to prevent conflicting operations.
● Shared Locks: Allow multiple transactions to read a data item simultaneously but
prevent any transaction from modifying it.
● Exclusive Locks: Allow a single transaction to modify a data item, preventing any
other transaction from accessing it (either for read or write).
● Two-Phase Locking (2PL): This protocol consists of two phases:
o Growing Phase: A transaction can acquire locks but cannot release any.
o Shrinking Phase: A transaction can release locks but cannot acquire any new
ones.
o Strict 2PL: All locks are held until the transaction is committed or aborted,
ensuring serializability.
Example:
sql
-- Transaction 1
LOCK TABLE accounts IN EXCLUSIVE MODE; -- locks the accounts table
UPDATE accounts SET balance = balance - 100 WHERE account_id = 'A';
-- Transaction 1 is committed or rolled back

-- Transaction 2
LOCK TABLE accounts IN SHARE MODE; -- waits for Transaction 1 to release the
lock
SELECT balance FROM accounts WHERE account_id = 'A';
b. Timestamp-Based Protocols
In timestamp-based protocols, each transaction is assigned a unique timestamp when it
starts. The timestamps determine the order of transaction execution and maintain
consistency.
● Basic Idea: Each operation is checked against the timestamps of other operations to
ensure serializability. If a transaction attempts to perform an operation that would
violate the timestamp order, it is rolled back.
● Read and Write Timestamps: Each data item maintains a read timestamp and a write
timestamp to track the last transaction that read or wrote to it.
Example:
1. Transaction T1 reads item A and is assigned a timestamp.
2. Transaction T2 tries to write to item A. If T2's timestamp is earlier than T1's read
timestamp, T2 is rolled back.
c. Optimistic Concurrency Control
Optimistic concurrency control allows transactions to execute without locking
resources, under the assumption that conflicts are rare. It consists of three phases:
1. Read Phase: The transaction reads data and performs its operations in a private
workspace.
2. Validation Phase: Before committing, the system checks for conflicts with other
transactions that might have modified the data during the transaction’s execution.
3. Write Phase: If validation is successful, changes are applied to the database; otherwise,
the transaction is rolled back.
Example:
sql
-- Transaction T1
READ A;
-- Modify A to A' in the private workspace

-- Transaction T2
READ A;
-- Modify A to A'' in the private workspace

-- Validation phase for T1


IF A's current value in DB matches the value read by T1 THEN
WRITE A' TO DB;
ELSE
ROLLBACK T1; -- Conflict detected, rollback
4. Isolation Levels
Isolation levels define the extent to which the operations in one transaction are isolated
from those in other concurrent transactions. SQL standard defines four isolation levels:
● Read Uncommitted: Allows dirty reads; transactions can see uncommitted changes
made by other transactions.
● Read Committed: Prevents dirty reads; a transaction can only see committed changes.
● Repeatable Read: Prevents non-repeatable reads; a transaction sees a consistent
snapshot of the data during its execution.
● Serializable: The highest isolation level, ensuring complete isolation from other
transactions, resulting in serial execution of transactions.
5. Deadlock Management
A deadlock occurs when two or more transactions are waiting for each other to release
locks, causing all of them to remain in a waiting state indefinitely. To manage
deadlocks, the following techniques can be used:
● Deadlock Detection: The system periodically checks for deadlocks and aborts one of
the transactions to break the deadlock.
● Deadlock Prevention: Design protocols that prevent deadlocks from occurring by
imposing restrictions on how locks are acquired.
● Wait-Die and Wound-Wait Schemes: These techniques prioritize transactions based
on their timestamps, allowing older transactions to proceed while younger transactions
may be aborted or delayed.
6. Challenges in Concurrency Control
● Performance: Concurrency control mechanisms can introduce overhead, potentially
degrading performance. Balancing between consistency and performance is critical.
● Complexity: Designing an effective concurrency control protocol that efficiently
handles all edge cases is complex and requires careful consideration.
● User Experience: Long wait times due to locks can lead to a poor user experience,
especially in applications requiring high responsiveness.

You might also like