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

DBMS FINAL2

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)
13 views

DBMS FINAL2

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/ 6

(a) Difference between DBMS and RDBMS: (c) What is a relational algebra operation?

l algebra operation? What is (b) Distinguish strong entity set with weak entity
the purpose of the "SELECT" operation in set? Draw an ER diagram to illustrate Weak Entity
DBMS: Database Management System, stores data in relational algebra? What does the "PROJECT" Set.
a single file or a collection of files without enforcing operation do in relational algebra?
any relationships between them. Strong Entity Set Weak Entity Set
RDBMS: Relational Database Management System, Relational Algebra Operations: Relational algebra
stores data in tables with predefined relationships is a set of operations used to manipulate and query Can be uniquely Cannot be uniquely identified
(using keys and foreign keys). data in relational databases. These operations take one identified by its by its own attributes; relies on
or more relations (tables) as input and produce a new own primary key. a strong entity's key.
(b) Main Purpose of Using a Database Application: relation as the result.
To manage, store, retrieve, and manipulate data
efficiently and securely, supporting complex queries Purpose of the "SELECT" Operation: Exists
Relies on the existence of a
and ensuring data consistency. independently in
related strong entity.
Purpose: It selects only those rows that satisfy the the database.
(c) "PROJECT" Operation in Relational Algebra: given condition.Example: σ(age > 30)(Employee)
The "PROJECT" operation selects specific columns selects employees who are older than 30. Does not have a primary key;
(attributes) from a relation, removing duplicates and Has a primary key. uses a partial key and the
returning only the specified attributes. Purpose of the "PROJECT" Operation: strong entity's primary key.

Purpose: It reduces the number of columns in the


Independent of Dependent on a strong entity
result set, returning only the specified
(a) What are the different types of databases? other entities. for identification.
attributes.Example: π(Name, Age)(Employee) selects
Provide examples for each. only the Name and Age columns from the Employee
relation. Employee
Dependent (DependentName,
Relational Database (RDBMS): Stores data in tables (EmployeeID,
Relationship) for Employee.
with predefined relationships.Example: MySQL, (d) Explain the working of union, intersection, and Name, etc.).
PostgreSQL. except operations? Define Assertions? Discuss
triggers? Composite Key:
NoSQL Database: Non-relational, handles Primary Key:
Combination of the weak
unstructured or semi-structured data.Example: Union Operation (∪): If two relations have the same Unique to the
entity's partial key and the
MongoDB, Cassandra. entity.
schema, the union operation returns all unique rows strong entity's primary key.
from both relations.Example: Employee1 ∪
Hierarchical Database: Data stored in a tree-like
Employee2 returns all unique rows from both ER Diagram for Weak Entity Set
structure.Example: IBM IMS.
Employee1 and Employee2.
Object-Oriented Database (OODBMS): Stores data
Intersection Operation (∩): Only the common tuples
as objects.Example: db4o, ObjectDB.
between the two relations are included in the
Distributed Database: Data is distributed across result.Example:Employee1 ∩ Employee2 returns the
multiple locations.Example: Apache Cassandra, employees who appear in both Employee1 and
Google Spanner. Employee2.

Cloud Database: Hosted on cloud platforms for Except Operation (−): It subtracts the tuples of the
scalability.Example: Amazon RDS, Google Firestore. second relation from the first
relation.Example:Employee1 − Employee2 returns
(a) Describe Second Normal Form (2NF).
(b) What is the Hierarchical model? What are its employees in Employee1 but not in Employee2.
advantages and disadvantages? The Second Normal Form (2NF) is a step in database
Assertions: Assertions are conditions or constraints
normalization designed to eliminate partial
Hierarchical Model: The hierarchical model that the database must always satisfy. They are used to
dependencies. A relation (table) is said to be in 2NF if
organizes data in a tree-like structure where each ensure that the data in the database adheres to certain
it satisfies the following conditions:
record has a single parent and potentially many rules.
children. This model is best suited for representing 1. It is in First Normal Form (1NF):The
one-to-many relationships, where each parent can Triggers: A trigger is a database object that
table must have atomic (indivisible)
have multiple children, but each child can have only automatically executes or fires when certain events
values.There must be no repeating
one parent.Example: A company hierarchy (CEO → occur on a table or view. These events can include
groups or arrays.
Managers → Employees). INSERT, UPDATE, or DELETE operations.
2. PL/SQL Trigger: Automatically
Advantages 1.Clear relationships between parent and (a) Discuss the importance of entity integrity and executes actions in response to events
referential integrity constraints? What is the usage (INSERT, UPDATE, DELETE) on a
child data ensure data consistency.
of 'GROUP BY' and 'HAVING' clauses in SQL? table, helping enforce rules or automate
2.Searching for data is efficient when accessing child
records directly. Disadvantages: 1. Data can only be processes.
Entity Integrity :1. Guarantees that each record is 3. Redo: Re-applies committed transactions
added or modified in predefined locations, limiting uniquely identifiable. 2.Prevents ambiguity when after a crash.Undo: Reverses
flexibility. 2.The model is not suited for many-to- referencing a record.3.Ensures the uniqueness of data, uncommitted transactions to maintain
many relationships, which require complex design. allowing efficient indexing and querying. consistency.
3.Redundant data storage may occur due to the parent- 4. Commit in Transaction Processing:
child relationship. 4.Hierarchical Referential Integrity: 1.Maintains the consistency Makes all changes permanent and visible
databases can be challenging to scale as the number of the database by preventing invalid to other transactions.
of relationships grows. references.2.Ensures that related data across tables
remains valid and intact.3.Prevents orphaned records
(a) Purpose of a PL/SQL Trigger:A PL/SQL trigger
(b) What is the difference between vertical and and ensures that foreign key values either correspond is used to automatically execute a specified action in
horizontal decomposition? to existing primary key values or are NULL. response to certain events (such as INSERT,
UPDATE, or DELETE) on a table or view. It helps
Vertical Decomposition: Splits a table into smaller GROUP BY and HAVING Clauses in SQL enforce business rules, data integrity, or automate
tables with fewer columns. processes like logging changes.
Horizontal Decomposition: Splits a table into GROUP BY:It helps to perform operations on
smaller tables with fewer rows. subsets of data, such as calculating the total sales per
employee or the average salary per (b) Purpose of Redo and Undo Operations in
(a) How does decomposition help in department.Example:SELECT Department, Recovery:Redo: Ensures that all committed
normalization? COUNT(EmployeeID) FROM Employees GROUP transactions are re-applied during recovery after a
Decomposition helps in breaking down a relation into BY Department; system crash.
smaller relations to eliminate redundancy and
HAVING:It is used after GROUP BY to filter groups Undo: Reverses changes made by uncommitted
dependency issues, ensuring data consistency.
based on aggregate functions, similar to how transactions during recovery to ensure the database
(c) Explain the concept of a functional dependency. WHERE filters rows.Example: SELECT remains consistent.
A functional dependency exists when one attribute Department, COUNT(EmployeeID) FROM
uniquely determines another. For example, in A→BA, Employees GROUP BY Department HAVING
attribute AA uniquely determines BB. COUNT(EmployeeID) > 5;
(c) Commit in Transaction Processing: (a) Build and explain the three-level architecture of Different Types of Relations in the ER Model
DBMS.
A commit is a transaction operation that makes all One-to-One (1:1) Relationship: In a one-to-one
changes permanent in the database. Once committed, relationship, one entity in the first set is related to
the changes are visible to other transactions and exactly one entity in the second set, and vice
cannot be undone. versa.Example: A Person entity might have a one-to-
one relationship with a Passport entity, where each
(c) Explain the fundamental operations in person has exactly one passport.
relational algebra with examples? With a suitable
example, explain Intersection, Join, Division, and One-to-Many (1:N) Relationship: In a one-to-many
Assignment operations in relational algebra. relationship, one entity in the first set can be related
to multiple entities in the second set, but each entity
Fundamental Operations in Relational Algebra in the second set is related to only one entity in the
first set.Example: A Department entity can have
Select (σ):Selects rows that satisfy a given predicate many Employees, but each Employee belongs to only
(condition). EX: (Age > 30) (Employee) one Department.

Project (π): Selects specific columns from a table, Many-to-One (N:1) Relationship: A many-to-one
removing duplicates. EX: π (Name, Age) (Employee) relationship is the inverse of a one-to-many
Explanation of the Three-Level Architecture relationship. Multiple entities in the first set can relate
Union (∪): Combines the results of two relations and to one entity in the second set.Example: Many
returns the distinct rows present in either or both External Level:User/Applications: Each user or Employees can belong to one Department, but each
relations. EX: Employee ∪ Manager application may interact with the database through Employee belongs to exactly one Department.
their own customized view. For example, a finance
Difference (−): Returns the rows that are in the first department may need access to financial data, while Many-to-Many (M:N) Relationship: In a many-to-
relation but not in the second relation. EX: Employee the HR department may need employee many relationship, multiple entities in the first set can
− Manager records.Views: These are logical representations of be related to multiple entities in the second set, and
data that users can access without knowing the actual vice versa.Example: A Student can enroll in multiple
Cartesian Product (×): Returns all possible data storage mechanisms. Each view presents only Courses, and each Course can have multiple Students.
combinations of rows from two relations.Employee × relevant information to the user.
Department (c) Describe all the relational algebra operations.
Conceptual Level:Unified Schema: This level
Rename (ρ): Renames the attributes of a relation. defines the logical structure of the entire database. It Selection (σ): The Selection operation is used to
ρ(EmployeeNew) (Employee) presents data in terms of entities, attributes, and filter rows from a relation based on a given condition
relationships without concerning itself with how the (predicate). It selects a subset of rows that satisfy the
Detailed Operations data is physically stored.Data Integrity: This level condition.Syntax: σ(condition)(Relation)
ensures that the logical relationships and constraints
Intersection (∩): Returns rows that are common to (like primary and foreign keys) are enforced. Example: σ(Age > 30)(Employee)
both relations. It is the equivalent of a set intersection
in set theory.Example Employee ∩ Manager Internal Level:Storage and Performance: The Projection (π): The Projection operation is used to
internal level deals with the physical storage of the retrieve specific columns (attributes) from a relation.
Join (⨝): Combines rows from two relations based data, like how records are stored in files and indexed It eliminates duplicate rows and returns a new
on a common attribute (key).Example Student for efficient retrieval.Efficiency: It defines how data relation with only the selected attributes.Syntax:
(StudentID, Name, CourseID) is stored in the database (e.g., using indexing, data π(attribute1, attribute2, ...)(Relation)Example:
partitioning) and optimized for speed and resource π(Name, Salary)(Employee)
Course (CourseID, CourseName)
utilization.
Union (∪): The Union operation combines two
Division (÷): Used when we want to find all entities relations with the same schema and returns a relation
(b) Describe different types of keys and different
in one relation that are related to all entities in containing all the distinct tuples from both
types of relations in the ER model.
another relation.Example Student_Course ÷ Course relations.Syntax: Relation1 ∪ Relation2Example:
Primary Key: A primary key is a set of attributes Employees_A ∪ Employees_B
Assignment (←): The assignment operation is used
that uniquely identifies each entity in a set. It ensures
to assign the result of a relational algebra operation to Difference (−): The Difference operation returns the
that no two entities in the entity set can have the same
a temporary variable for further processing. values for these attributes.Example: In an Employee tuples that are present in the first relation but not in
entity, the EmpID could be a primary key since it the second relation. Both relations must have the
Temp ← π (Name, Age) (Employee) same schema.Syntax: Relation1 −
uniquely identifies each employee.
Relation2Example: Employees_A − Employees_B
(c) What are set operations in SQL? Explain with
Candidate Key: A candidate key is any set of
examples. Cartesian Product (×): The Cartesian Product
attributes that can uniquely identify an entity. There
can be more than one candidate key in an entity, but operation combines each tuple of the first relation
Set operations in SQL are used to combine the results
one is chosen as the primary key.Example: For an with each tuple of the second relation, resulting in all
of two or more queries. These operations treat the
Employee entity, both EmpID and Email could be possible combinations.Syntax: Relation1 ×
results of queries as sets and apply mathematical set Relation2Example: Employee × Department
candidate keys, as both can uniquely identify an
operations like union, intersection, and difference to
employee.
them. The participating queries must have the same Rename (ρ): The Rename operation is used to
number of columns with compatible data types. Foreign Key: A foreign key is an attribute (or set of rename the attributes of a relation or the relation
attributes) in one entity that refers to the primary key itself. It allows us to create a new name for the
UNION Combines the results of two queries and of another entity. It is used to establish and enforce a relation or its attributes for clarity.Syntax:
removes duplicate rows.Syntax:SELECT column1, link between the data in two entities.Example: In a ρ(newRelationName, Relation)Example: ρ(Worker,
column2 FROM table1 UNION SELECT column1, Works_on relationship between Employee and Employee)
column2 FROM table2; Project, the EmpID in the Works_on entity could be a
foreign key referring to the EmpID in the Employee Intersection (∩): The Intersection operation returns
UNION ALL Combines the results of two queries but the common tuples present in both relations. Both
entity.
does not remove duplicates. Syntax:SELECT relations must have the same schema.Syntax:
column1, column2 FROM table1 UNION ALL Composite Key: A composite key is a primary key Relation1 ∩ Relation2Example: Employees_A ∩
SELECT column1, column2 FROM table2; that consists of more than one attribute to uniquely Employees_B
identify an entity.Example: In the Enrollment
INTERSECT Returns only the rows that are Join (⨝): The Join operation combines two relations
relationship between Student and Course, the
common to the results of both queries. based on a related attribute, usually a foreign key in
combination of StudentID and CourseID might form
Syntax:SELECT column1, column2 FROM table1 one relation and a primary key in another. There are
a composite key.
INTERSECT SELECT column1, column2 FROM different types of joins, such as inner join, outer join,
table2; Super Key: A super key is any set of attributes that etc.Syntax: Relation1 ⨝ Relation2Example:
can uniquely identify an entity, but it may contain Employee ⨝ Department
EXCEPT (or MINUS)
unnecessary attributes. All primary keys are super
Returns the rows from the first query that are not Division (÷): The Division operation is used when
keys, but not all super keys are primary
present in the second query. Syntax:SELECT we want to find tuples in one relation that are
keys.Example: If the EmpID is a primary key, then
column1, column2 FROM table1 EXCEPT associated with all tuples in another relation. It is
{EmpID, Name} is also a super key, though it is not
SELECT column1, column2 FROM table2; often used for queries that involve "all" relationships.
minimal.
(d) Explain the INSERT INTO command with (b) What is the use of GROUP BY and HAVING
examples. clauses in SQL?
(b) What is DDL, and what are its main INSERT INTO Command in SQL
commands? 1. GROUP BY Clause The GROUP BY clause
The INSERT INTO command in SQL is used to add groups rows with the same values in specified
DDL (Data Definition Language) is a subset of SQL new rows of data into a table. This command allows columns. It is commonly used with aggregate
(Structured Query Language) used to define and inserting data into all columns or specific columns of functions (e.g., SUM(), COUNT(), AVG(), MIN(),
manage the structure of database objects such as a table. MAX()) to perform operations on each group.
tables, schemas, indexes, and constraints. It deals with
the schema and structure of a database rather than the To Insert Data into All Columns: Syntax:SELECTcolumn1,aggregate_function(colum
data itself. n2)FROM table_name GROUP BY column1;
INSERT INTO table_name VALUES (value1, value2,
Main DDL Commands ..., valueN); Example:

CREATE:Used to create new database objects like 1. Insert Data into All ColumnsCREATE TABLE Product Region Sales_Amount
tables, views, indexes, or students (student_id INT PRIMARY
schemas.Example:CREATE TABLE students KEY,student_name VARCHAR(50),age INT); A East 100
(student_id INT PRIMARY KEY, student_name
VARCHAR(50), age INT); To insert a row of data into all columns: B West 200

ALTER:Used to modify the structure of an existing INSERT INTO students VALUES (1, 'Alice', 20); A East 150
database object.Examples:
Result: B West 100

Add a new column: ALTER TABLE students ADD


email VARCHAR(100); student_id student_name age Query:

Modify a column: ALTER TABLE students 1 Alice 20 SELECT Product, SUM(Sales_Amount) AS


MODIFY age INT NOT NULL; Total_Sales FROM Sales GROUP BY Product;

Drop a column: ALTER TABLE students DROP Result:


COLUMN email; To Insert Data into Specific Columns:
Product Total_Sales
DROP:Used to delete database objects permanently. INSERT INTO table_name (column1, column2, ...,
columnN) VALUES (value1, value2, ..., valueN); A 250
Example:DROP TABLE students; EXAMPLE
B 300
TRUNCATE:Used to remove all rows from a table INSERT INTO students (student_id, student_name)
while keeping its structure VALUES (2, 'Bob'); 2. HAVING Clause
intact.Example:TRUNCATE TABLE students;
Result: 1.The HAVING clause is used to filter groups after
RENAME:Used to rename database the GROUP BY operation has been performed.
objects.Example:RENAME TABLE students TO student_id student_name age
learners; 2.Unlike the WHERE clause, which filters rows
1 Alice 20 before grouping, HAVING filters aggregated data.
(a) Explain different types of anomalies in
designing a database. 2 Bob NULL Syntax:SELECT column1, aggregate_function
(column2)FROM table_name GROUP BY column1
1. Insertion Anomaly 3. Insert Multiple Rows HAVING aggregate_function(column2) condition;

An insertion anomaly occurs when adding new data to INSERT INTO students (student_id, student_name, Example:
the database is either difficult or results in redundancy age) VALUES(3, 'Charlie', 22), (4, 'Diana', 21);
due to the design of the schema. Product Region Sales_Amount
Result:
Example A East 100
student_id student_name age
B West 200
Student_ID Student_Name Course_ID Course_Name
1 Alice 20
A East 150
1 Alice 101 Math 2 Bob NULL
B West 100
2 Bob 102 Science 3 Charlie 22
Query:
2. Update Anomaly 4 Diana 21
SELECT Product, SUM(Sales_Amount) AS
An update anomaly occurs when modifying existing 4. Insert Data from Another Table Total_Sales FROM Sales GROUP BY Product
data requires multiple updates, leading to potential HAVING SUM(Sales_Amount) > 200;
inconsistencies if all related fields are not updated. INSERT INTO new_students (student_id,
student_name) SELECT student_id, student_name Result:
Example: FROM students WHERE age > 20;
Product Total_Sales
Student_ID Student_Name Course_ID Course_Name

1 Alice 101 Math B 300

2 Bob 101 Math

3. Deletion Anomaly

A deletion anomaly occurs when deleting data


inadvertently removes other valuable information.

Example:

Student_ Student_Na Course_I Course_Na


ID me D me

1 Alice 101 Math


(c) What is the difference between 3NF and (b) Explain all the five aggregate functions with an (c)Relationalschema:•student(student_id,student_
BCNF? example. name)student(student\_id, student\_name)

Difference Between 3NF and BCNF Aggregate functions perform a calculation on a set of •registered(student_id,course_id)registered(stude
values and return a single value. They are typically nt\_id, course\_id)
Third Normal Form (3NF)
Boyce-Codd Normal used with the GROUP BY clause to aggregate data
Form (BCNF) based on one or more columns. Write an SQL query to list the student ID and
name of each student along with the total number
A table is in 3NF if: A table is in BCNF if: EXAMPLE Consider a table Sale_list of courses that the student is registered for.
Students who are not registered for any course
- It is in 2NF. - It is in 3NF. Product Sales_Amount must also be listed, with the number of registered
courses shown as 0.
- No non-prime attribute - For every functional A 100
depends transitively on the dependency X → Y, X SQL Query:SELECT s.student_id, s.student_name,
primary key. must be a superkey. B 200 COALESCE(COUNT(r.course_id),0)AS
total_courses FROM student s LEFT JOIN registered
Eliminates overlapping A 150 r ON s.student_id = r.student_id GROUP BY
Eliminates transitive candidate keys or s.student_id, s.student_name;
dependencies. violations of functional A 50
dependencies. EXPLANATION :

Allows non-prime attributes to


Does not allow any LEFT JOIN: Ensures all students are included.
depend on candidate keys, as 1. COUNT() The COUNT() function returns the
dependency violation of
long as they don’t create number of rows in a specified column or table that COUNT(): Counts the courses per student.
superkey requirements.
transitive dependencies.
meet a certain condition.
COALESCE(): Converts NULL to 0 for students
Deals with functional Deals with all functional Query:SELECT COUNT(*) AS Total_Sales FROM with no courses.
dependencies involving non- dependencies, including Sales;
prime attributes. prime attributes. GROUP BY: Groups by student to calculate the
Total_Sales course count.
Required when a table has
Sufficient for most practical
overlapping candidate Result Example:
database designs. 4
keys.

2. SUM() The SUM() function calculates the total student_id student_name total_courses
Easier to achieve More complex
sum of a numeric column.
4. Long Answer Questions 1 John Doe 3
Query: SELECT SUM(Sales_Amount) AS
Total_Sales FROM Sales;
(a) Given R(A,B,C,D,E,F,G,H,I,J)R(A, B, C, D, E, 2 Jane Smith 0
F, G, H, I, J)(FD):{AB→C, A→DE,
B→F,F→GH,D→IJ}Determine the key for RR. Total_Sales
3 Alice Brown 2
Decompose RR into 2NF and 3NF
500
MODULE-3
The candidate key for the relation
R(A,B,C,D,E,F,G,H,I,J)R(A, B, C, D, E, F, G, H, I, J), 3. AVG() The AVG() function calculates the average 2. Answer any TWO
given the functional dependencies, is ABAB. This is of a numeric column.
because the closure of ABAB includes all attributes in (a) Explain serializability in the context of
the relation, making it a candidate key. Query: SELECT AVG(Sales_Amount) AS database transactions. How does the concept of
Average_Sales FROM Sales; serializability guarantee the correctness of
Decomposition into 2NF To decompose RR into concurrent transactions?
2NF, we remove partial dependencies, which occur Average_Sales
when non-prime attributes depend on only a part of Serializability in Database Transactions ensures that
the candidate key. 125 concurrent transactions produce the same results as if
they were executed one after the other in some serial
1. R1(A,D,E)R1(A, D, E), with the functional order, maintaining the database’s consistency.
4. MIN() The MIN() function returns the smallest
dependency A→DE
(minimum) value in a specified column.
Types of Serializability: Conflict Serializability: A
2. R2(B,F)R2(B, F), with the functional dependency schedule is conflict serializable if its transactions can
Query: SELECT MIN(Sales_Amount) AS
B→F . be reordered to form a serial schedule by swapping
Min_Sales FROM Sales;
non-conflicting operations.View Serializability: A
3. R3(F,G,H)R3(F, G, H), with the functional schedule is view serializable if its transactions
dependency F→GH. Result:
produce the same result as a serial execution, even if
Min_Sales
operations aren't conflict-free.
4. R4(D,I,J)R4(D, I, J), with the functional
dependency D→IJ Guaranteeing Correctness:Consistency: Ensures
50
the database remains in a consistent state, just like
5. R5(A,B,C)R5(A, B, C), with the functional serial execution.No Anomalies: Prevents issues like
dependency AB→C 5. MAX() The MAX() function returns the largest
dirty reads and lost updates.Isolation: Transactions
(maximum) value in a specified column.
appear as if executed in isolation.Conflict-Free:
Decomposition into 3NF To decompose into 3NF, we
Ensures no conflicting operations on the same data
ensure that there are no transitive dependencies. After Query:SELECT MAX(Sales_Amount) AS
items.
removing transitive dependencies, the relations are Max_Sales FROM Sales;
further decomposed into: (b) What is transaction scheduling in the context of
Max_Sales concurrency control?
R1(A,D,E)R1(A, D, E), with A→DE
200 Transaction scheduling in the context of concurrency
R2(B,F)R2(B, F), with B→F control is the process of arranging the execution order
of multiple transactions in a database system to
R5(A,B,C)R5(A, B, C), with AB→C maintain data consistency and integrity while
allowing concurrent access. It ensures that
R6(F,G)R6(F, G), with F→G transactions are executed in a manner equivalent to a
serial execution to avoid conflicts such as dirty reads,
R7(F,H)R7(F, H), with F→H lost updates, and other anomalies. Effective
scheduling balances the need for concurrency and
R8(D,I)R8(D, I), with D→I performance with the requirement to uphold database
correctness, using techniques like locking protocols,
R9(D,J)R9(D, J), with D→J timestamp ordering, or multiversion concurrency
control (MVCC).
(c) What is the difference between the COMMIT (a) Differentiate between conflict serializability (c) Draw the Transaction State Transition Diagram
and ROLLBACK operations? Write an SQL code and view serializability. and explain all the transaction steps.
that demonstrates the use of both in handling a
transaction involving multiple DML operations. Conflict Serializability View Serializability

Difference between COMMIT and ROLLBACK: Schedule can be transformed


Schedule is equivalent to a
into a serial schedule by
serial schedule in terms of
COMMIT: Finalizes the transaction and makes all swapping non-conflicting
final result.
changes permanent in the database. operations.

ROLLBACK: Reverts all changes made during the Based on conflicts (read-write, Based on the overall final
transaction, restoring the database to its state before write-read) between operations. result, not just conflicts.
the transaction started.
Less restrictive, allows Explanation of Transaction Steps
More restrictive, only allows
SQL Example Demonstrating COMMIT and non-conflicting swaps.
more flexibility in
ROLLBACK: operation order. Active State:1.Transaction is executing operations
(read, write, insert, update, delete).2.Remains active
BEGIN; Harder to check; checks until the final operation is completed.
Can be checked using a
read-from relationships
precedence graph.
INSERT INTO Employees (EmpID, Name, Position) and consistency. Partially Committed State:1.Transaction has
VALUES (101, 'John Doe', 'Manager'); finished all operations but not yet
Operations can be committed.2.Operations are logged, and it can be
Conflicting operations must
UPDATE Employees SET Position = 'Senior reordered, as long as the safely committed.
respect serial order.
Manager' WHERE EmpID = 101; final result is consistent.

Committed State:1.Transaction completes


COMMIT; Must match a serial schedule in Must match a serial successfully.2.Changes are permanently applied to
conflict order. schedule in final state.
the database and visible to other transactions.
BEGIN starts the transaction.
Failed State:1.Transaction encounters an error (e.g.,
COMMIT makes the changes permanent. deadlock, system failure).2.No changes are applied to
(b) Which of the following schedules are conflict the database, and recovery is attempted.
ROLLBACK would undo the changes if it were used serializable:
instead of COMMIT. Aborted State:1.Transaction is rolled back (due to
- r1(x);r3(x);w1(x);r2(x);w3(x)r_1(x); r_3(x); failure or explicit rollback).2.Changes are undone,
(d) Explain the concept of COMMIT, w_1(x);r_2(x);w_3(x)r1(x);r3(x);w3(x);w1(x);r2(x ensuring database consistency; transaction may need
ROLLBACK, and SAVEPOINT in transaction )r_1(x)r_3(x); w_3(x); w_1(x); r_2(x)- to be retried.
processing. Provide examples where each of these r3(x);r2(x);w3(x);r1(x);w1(x)r_3(x);
commands would be used. r_2(x);w_3(x); (a) Consider the following schema and draw the
r_1(x);w_1(x)r3(x);r2(x);r1(x);w3(x);w1(x)r_3(x); optimal Query Tree for its query:
COMMIT: The COMMIT command is used to make
r_2(x); r_1(x); w_3(x); w_1(x)
all changes made during a transaction permanent in •Employee (SSN, Name, Bdate, Address)Works_on
the database. Once a transaction is committed, the Schedule 1:r1(x); r3(x); w1(x); r2(x); w3(x) (ESSN, Pno)Project (Pnumber, Pname)Find the
changes are visible to other transactions and cannot names of employees born after 2000 and who work
be undone. Operations: on a project named "CSE_3rd_sem".
Example: BEGIN;INSERT INTO Employees r1(x) and r3(x) (both reads) → No conflict. SQL Query:
(EmpID, Name, Position) VALUES (101, 'John Doe', r1(x) and w1(x) → No conflict.
'Manager');UPDATE Employees SET Position = r1(x) and r2(x) → No conflict. SELECT E.Name FROM Employee E, Works_on W,
'Senior Manager' WHERE EmpID = 101;COMMIT; r3(x) and w1(x) → Conflict (write after read). Project P WHERE E.SSN = W.ESSN AND W.Pno =
w1(x) and w3(x) → Conflict (write on the same P.Pnumber AND E.Bdate > '2000-01-01' AND
ROLLBACK: The ROLLBACK command is used to item).This schedule is not conflict serializable P.Pname = 'CSE_3rd_sem';
undo all changes made by the current transaction,
reverting the database to the state before the Schedule 2:r1(x); r3(x); w3(x); w1(x); r2(x) Optimal Query Tree:
transaction started. This is useful when an error
occurs or when you want to discard the transaction. Operations:

Example BEGIN;INSERT INTO Employees r1(x) and r3(x) (both reads) → No conflict.
(EmpID, Name, Position) VALUES (102, 'Jane Doe', r1(x) and w3(x) → Conflict (write after read).
'Developer');UPDATE Employees SET Position = w3(x) and w1(x) → Conflict (write after write).
'Lead Developer' WHERE EmpID = w1(x) and r2(x) → No conflict (write before
102;ROLLBACK;
read).This schedule is conflict serializable.
SAVEPOINT: A SAVEPOINT creates a point within
Schedule 3:r3(x); r2(x); w3(x); r1(x); w1(x)
a transaction that allows you to roll back to that point,
instead of rolling back the entire transaction. It
Operations:
enables partial rollback within a larger transaction.
r3(x) and r2(x) (both reads) → No conflict.
Example: BEGIN;INSERT INTO Employees
r2(x) and w3(x) → Conflict (write after read).
(EmpID, Name, Position) VALUES (103, 'Alice w3(x) and r1(x) → Conflict (write after read).
Smith', 'Intern');SAVEPOINT savepoint1; -- Set a
r1(x) and w1(x) → No conflict.This schedule is
savepoint after the first operationUPDATE
conflict serializable.
Employees SET Position = 'Manager' WHERE
EmpID = 103;ROLLBACK TO savepoint1; -- Rolls Schedule 4:r3(x); r2(x); r1(x); w3(x); w1(x)
back to the state after the first operationCOMMIT;
Operations:

r3(x) and r2(x) (both reads) → No conflict.


r2(x) and r1(x) (both reads) → No conflict.
w3(x) and w1(x) → Conflict (write on the same
item).This schedule is conflict serializable.
(b) Draw the query processing diagram and (a) What is the role of indexes in query First Normal Form (1NF): A relation is in 1NF if all
explain its steps. optimization? What are joins in SQL, and how can attributes contain atomic (indivisible) values and each
the join affect the performance of a query? record has a unique identifier.

Role of Indexes Indexes improve query performance Second Normal Form (2NF): A relation is in 2NF if
by enabling the database to locate data faster without it is in 1NF and all non-key attributes are fully
scanning the entire table. dependent on the primary key.

Joins Joins combine rows from two or more tables Normalization vs Denormalization:
based on related columns.
Normalization reduces redundancy by organizing
Types: data into smaller, related tables.

INNER JOIN: Matches rows with common values in Denormalization involves combining tables to
both tables. reduce complexity and improve query performance.

LEFT JOIN: Includes all rows from the left table and Boyce-Codd Normal Form (BCNF): A relation is in
Steps in Query Processing: matched rows from the right. BCNF if it is in 3NF and every determinant is a
candidate key.
SQL Query Input: RIGHT JOIN: Includes all rows from the right table
and matched rows from the left. Entity-Relationship (ER) Model: An ER model is a
The process starts when a user submits an SQL query conceptual framework used to visually describe the
to the DBMS. FULL JOIN: Includes all rows from both tables, with data and relationships in a database.
NULLs for unmatched rows.
Query Parsing:1.The SQL query is parsed to check Hierarchical vs Network Data Model:
its syntax and structure.2.The DBMS builds a Parse Effect of Joins on Query Performance
Tree (or Abstract Syntax Tree) that represents the Hierarchical has a tree-like structure with a single
logical structure of the query. Simple Joins (e.g., small tables or indexed columns) parent for each child.
are efficient.
Query Optimization:1.The query optimizer analyzes Network allows multiple parent-child relationships,
different execution plans for the query.2.It selects the Complex Joins (e.g., large tables, unindexed forming a graph.
most efficient plan based on factors like data columns) can lead to slow performance due to
distribution, index availability, and resource extensive comparisons and table scans. DDL (Data Definition Language):
usage.3.This step improves performance by choosing DDL is used to define and manage database
the best approach for accessing the data (e.g., (b) What is the Two-Phase Locking (2PL) protocol structures, such as tables, schemas, views, and
choosing the right indexes, join strategies). in concurrency control? Explain how it helps in indexes. The primary role of DDL is to specify the
ensuring serializability in database transactions. structure and organization of the data in a database. It
Query Execution:1.The DBMS executes the allows database administrators and developers to
optimized query plan.2.The actual data retrieval and The Two-Phase Locking protocol is a concurrency
create, modify, and remove database objects. DDL
manipulation occur at this stage using operations such control mechanism used in databases to ensure
statements affect the database schema and do not
as scans, joins, sorting, and aggregation. serializability (a property where concurrent
modify the actual data.
transactions produce the same result as if they were
Results Output:1.After executing the query, the executed sequentially). 1.CREATE: Used to create new tables, views,
results are returned to the user or application.2.This
indexes, or databases. 2.ALTER: Modifies an existing
step might involve formatting the data for Ensuring Serializability:
database object, such as adding or deleting columns
presentation.
Conflict Avoidance: By controlling the order of lock from a table. 3.DROP: Deletes an existing database
(c) Differentiate between serial schedule and acquisition and release, 2PL prevents conflicting object, such as a table or view. 4.TRUNCATE:
parallel schedule. operations from occurring simultaneously. Removes all records from a table but retains the table
structure.
Serial Schedule Parallel Schedule Strict Order: Transactions lock resources in a way
DML (Data Manipulation Language):
that guarantees consistent ordering, which ensures
serializability. DML is used to manage and manipulate the data
One transaction runs Multiple transactions run within the tables of a database. Unlike DDL, which
after the other. concurrently. deals with the structure, DML operations work
No Interleaving: During execution, the lock
mechanism avoids non-serializable interleavings of directly on the data itself. DML allows users to query,
No concurrency Transactions execute in operations. insert, update, and delete records in the database.
between transactions. parallel.
Types of 2PL:Basic 2PL,Strict 2PL,Rigorous 2PL SELECT: Retrieves data from one or more tables
Requires careful based on specified criteria.
Easier to maintain Transaction Logs in DBMS Recovery: Transaction
management to avoid
consistency. logs record all changes made to the database, allowing INSERT: Adds new rows of data into a table.
conflicts.
the system to recover to a consistent state after a UPDATE: Modifies existing data within a table.
failure by replaying or rolling back transactions. DELETE: Removes data from a table based on
Low resource
Higher resource utilization. specified conditions.
utilization.
Undo Logging in Error Recovery: Undo logging MERGE: A combination of INSERT,
keeps a record of changes made during a transaction UPDATE, and DELETE, which is used to
More complex to manage
Simpler to implement. to revert or undo the modifications in case of errors or synchronize data between two tables.
and implement.
rollbacks.
DCL (Data Control Language):
Simplicity, no Better throughput and faster Basic Structure of a Trigger: A trigger consists of an DCL is used to control access to data in a database,
concurrency issues. execution. event (INSERT, UPDATE, DELETE), a condition defining user permissions and security levels. DCL
(optional), and an action (the operation to perform statements enable database administrators to grant or
Less efficient, slow Potential deadlocks and when the trigger is fired). revoke privileges to users and roles, ensuring that the
execution. inconsistencies. right individuals have the correct level of access to the
Decomposition in DBMS: Decomposition is the database and its data.
process of breaking down a relation into smaller,
simpler relations to eliminate redundancy and GRANT: Grants specific privileges to users or roles.
NATURAL JOIN vs Regular JOIN: A NATURAL improve data integrity. For example, it can provide permissions to perform
JOIN automatically joins tables based on columns operations such as SELECT, INSERT, or UPDATE on
with the same name, while a regular JOIN requires Vertical vs Horizontal Decomposition: certain tables.
explicit conditions.
Vertical Decomposition splits a relation into smaller REVOKE: Removes specific privileges that were
EQUIJOIN in Extended Relational Algebra: An relations by columns. granted to users or roles, restricting their access to
EQUIJOIN is a join where the joining condition certain database operations or objects.
Horizontal Decomposition divides a relation by rows
involves equality (i.e., attributes from both relations
(tuples).
are equal).

You might also like