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

dbms lec

notes

Uploaded by

siyadogra98
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

dbms lec

notes

Uploaded by

siyadogra98
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

DATABASE MANAGEMENT SYSTEMS (CST-011)

Dr. Ahmad Jamal


Associate Professor
Computer Science & Engineering

Unit – 4

Transaction processing
Course Outcomes
Course Description Mapping with Program
Outcomes Outcomes and Program
Specific Outcomes

CO1 PO[1,2,3,4,6,12]
Understand the data abstraction, data independence, various database models,
integrity constraints, and data operations.

CO2 PO[1,2,3,4,5,6,7,12]
Use SQL and relational algebra to create and manage databases, incorporating
advanced features like nested sub queries, views, and triggers.

CO3 Apply functional dependencies and normalization techniques to design efficient PO[1,2,4,6,12]
and consistent databases.

CO4 Demonstrate an understanding of transaction atomicity, consistency, isolation, PO[1,2,3,4,5,6,7,12]


and durability (ACID) properties using real-life examples.

CO5 Understand and apply storage structures, indexing, query processing, and PO[1,2,3,4,5,6,9,11,12]
advanced database concepts
Assessment and Evaluation Plan

Assessment Tools Evaluation


 Google form Internal examination= 50
 Assignments External examination=100
 Sessional
 Tutorial sheets
Transaction Processing
Transaction Processing is the method by
which databases handle multiple, sometimes
complex, operations reliably to ensure data
integrity. It involves managing sequences of
actions on a database (transactions) that
change the data state, adhering to strict rules
to ensure accuracy, consistency, and durability
even in the case of failures.
Prepared by : Dr. Ahmad Jamal
Transaction Concepts
Transaction Concepts are fundamental principles in database management,
ensuring that data remains consistent, accurate, and reliable even in the face of
concurrent access, errors, or system failures. A transaction is a logical unit of
work comprising one or more database operations (such as INSERT, UPDATE,
DELETE, etc.), which must all succeed together for the transaction to be
considered complete.

Here is the list of core transaction concepts:



Transaction

ACID Properties

Commit

Rollback

Save Points

Concurrency in Transactions

Two-Phase Commit (2PC) Prepared by : Dr. Ahmad Jamal
Transaction
A transaction is a logical unit of work composed of multiple database
operations (e.g., inserts, updates, deletes). Transactions allow users to group
these operations so they all succeed together or fail together, ensuring data
consistency.

Example:
Consider an online shopping system where a transaction includes two
operations:

Deducting money from the buyer’s account.

Adding money to the seller’s account.
Both operations must either complete fully or not
at all. If the buyer’s account is debited but the
seller’s account is not credited (or vice versa), it
would lead to data inconsistency. By treating
these two actions as a transaction, we ensure
that either both happen or neither does.

Prepared by : Dr. Ahmad Jamal


ACID
The ACID properties are a set of principles that ensure reliable processing of database
transactions. They are critical for maintaining the integrity of a database, particularly when
multiple transactions occur simultaneously or in the event of a system crash.

The four ACID properties are:


Atomicity

Consistency

Isolation

Durability

Prepared by : Dr. Ahmad Jamal


Atomicity
Atomicity in the context of database transactions refers to the principle that a
transaction must be treated as a single, indivisible unit of work. This means that
either all operations within the transaction are completed successfully, or none of
them are. Atomicity ensures that the database is left in a consistent state,
regardless of whether the transaction is fully successful or fails at any point.

Key Characteristics of Atomicity:



All-or-Nothing: If any operation within the transaction fails, the entire transaction is
rolled back, meaning none of the operations will be applied to the database.

Rollback Mechanism: If a transaction encounters an error or an issue, the
database system will revert any changes made by the transaction up to that point,
undoing all operations, as though the transaction never occurred.

Prepared by : Dr. Ahmad Jamal


Example of Atomicity
Let’s say we have a banking system where you want to transfer 1200 INR from
Account A to Account B.

Steps of the Transaction:


1)Deduct 1200 INR from Account A.
2)Add 1200 INR to Account B.

If the system crashes after deducting from Account A but before adding to Account
B, the database should roll back all the changes, meaning:

Account A’s balance should not reflect the 1200 INR deduction.

Account B’s balance should not reflect the 1200 INR addition.

This ensures that the transaction is atomic, and the database will not be left in an
inconsistent state where only part of the transaction is completed. Instead, the
transaction will be either fully applied (if both steps succeed) or fully reverted (if any
part fails). Prepared by : Dr. Ahmad Jamal
Consistency
Consistency in the context of database transactions refers to the property that a
transaction must take the database from one valid state to another, maintaining
all predefined rules, constraints, and relationships defined in the database
schema.

Key Characteristics of Consistency:


1)Database Rules: Every transaction must adhere to the integrity constraints of
the database, such as primary keys, foreign keys, unique constraints, etc.
2)Preservation of Business Logic: The database must remain in a valid state after
each transaction. If a transaction violates any rules or causes an inconsistency,
it will be rolled back.
3)Data Integrity: It ensures that only valid data is written to the database, and the
system's data will always remain in a logically correct state after the
transaction.
Prepared by : Dr. Ahmad Jamal
Example of Consistency
Let’s say we are working with a bank system where a
transaction involves transferring 1500 INR from Account A to
Account B. The following conditions must be true for the
database to remain consistent:

The balance of Account A should never be negative.

The balance of Account B should reflect the correct
amount.

If any integrity constraint is violated (such as insufficient
funds in Account A), the database must prevent the
transaction from happening and return to the previous
consistent state. Prepared by : Dr. Ahmad Jamal
Isolation
Isolation in the context of database transactions refers to the property that ensures
transactions are executed independently of each other, even if they are executed
concurrently. The goal is to ensure that the operations of one transaction do not
interfere with the operations of other concurrent transactions, thereby preventing
unwanted side effects such as dirty reads, non-repeatable reads, and phantom
reads.

Key Characteristics of Isolation:



Transaction Independence: Each transaction must execute as if it were the only
transaction running in the system, even if there are other transactions being
processed at the same time.

Concurrency Control: The database system uses mechanisms like locks,
timestamp ordering, or optimistic concurrency control to manage the interaction
between concurrent transactions.

Prepared by : Dr. Ahmad Jamal


Transaction Isolation Levels
To implement isolation, databases use different isolation levels, each offering a
different trade-off between performance and data consistency.

The four primary isolation levels are defined by the SQL standard:

1: Read Uncommitted: A transaction can read data that has been modified by
another transaction but not yet committed.

Problem: This allows dirty reads, where a transaction can read data that might later
be rolled back, leading to inconsistent results.

Example: Transaction 1 updates a record, but Transaction 2 reads that record


before Transaction 1 commits. If Transaction 1 rolls back, Transaction 2 will have
read invalid data.

Prepared by : Dr. Ahmad Jamal


Transaction Isolation Levels
2: Read Committed: A transaction can only read data that has been committed by other
transactions.

Problem: This prevents dirty reads, but non-repeatable reads can still occur. This means a value
read by a transaction may change if the transaction re-reads the same data, as other
transactions may have modified it in the meantime.

Example: Transaction 1 reads a balance, but before it commits, Transaction 2 updates the
balance. When Transaction 1 reads the balance again, it sees a different value.

3: Repeatable Read: A transaction can read the same data multiple times and will always see
the same value, even if other transactions modify that data.

Problem: This prevents non-repeatable reads but still allows phantom reads. A phantom read
occurs when a transaction reads a set of rows that satisfy a certain condition, but another
transaction inserts or deletes rows that would affect that set of rows.

Example: Transaction 1 reads all records for customers in a certain city, but Transaction 2
inserts a new customer. When Transaction 1 queries again, it seesPrepared by : result
a different Dr. Ahmad
dueJamal
to the
Transaction Isolation Levels

4: Serializable: The highest isolation level. It ensures that transactions are executed in such a
way that the final outcome is equivalent to some serial execution of the transactions (i.e., one
transaction completes before another begins).

Problem: This level provides the highest level of isolation but also the lowest concurrency and
performance. It prevents dirty reads, non-repeatable reads, and phantom reads.

Example: Transaction 1 and Transaction 2 both try to read and modify the same data, but they
are executed one after the other, ensuring no conflicts or inconsistencies.

Prepared by : Dr. Ahmad Jamal


Durability
Durability is the final property in the ACID model of database transactions, ensuring that once a transaction is
committed, its effects are permanent in the database, even if the system crashes or fails immediately
afterward. This property is crucial in maintaining data integrity and reliability in databases, particularly in
systems where data loss can have serious consequences, such as in financial or medical records systems.

Key Points of Durability:



Permanent Commit: Once a transaction has been committed, all changes made by that transaction are
written to a non-volatile storage medium (e.g., disk), making them permanent.

Recovery Mechanisms: Durability is supported by recovery mechanisms like transaction logs, write-ahead
logging (WAL), and checkpoints, which allow the database to recover and reapply transactions in the event
of a crash.

Data Persistence: Even in the event of power failures, crashes, or other disruptions, the database ensures
that committed data will be restored and accessible upon restarting.

Prepared by : Dr. Ahmad Jamal


Example of Durability
Consider a banking application where Transaction 1 transfers 200 from Account A to Account B.

Initial State:
Account A has a balance of 1000 INR.
Account B has a balance of 500 INR.

Transaction Steps:
Step 1: Deduct 200 from Account A, updating its balance to 800.
Step 2: Add 200 to Account B, updating its balance to 700.
Step 3: Commit the transaction.

Commit and Crash:


Once Transaction 1 is committed, the database writes these updates to durable storage.
If there’s a sudden crash right after the transaction commits, the database can restart and still show Account A
with 800 and Account B with 700, preserving the changes made by the transaction.

Recovery Process:
After the system restarts, the database uses its transaction logs or checkpoint data to confirm the committed
transaction, reapplying any committed changes if needed, ensuring Account A and Account B reflect their
updated balances.

Prepared by : Dr. Ahmad Jamal


Commit
A commit is a database operation that makes the changes made by a transaction permanent. Once a
transaction is committed, its changes are saved in the database, ensuring they are durable and visible to other
users.

Key Features of Commit


Permanence: The changes made during the transaction are saved permanently in the database.
Durability (ACID): Once committed, changes are safe even in the event of a system crash.
Visibility: After a commit, other transactions and users can see the changes.
Irreversible: Committed changes cannot be undone, except by performing a new transaction.
Syntax:

COMMIT;

Prepared by : Dr. Ahmad Jamal


Commit Example
Use Case: Transferring money between two bank accounts
BEGIN TRANSACTION;

-- Deduct 100 from Account A


UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 'A';

-- Add 100 to Account B


UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 'B';

-- Commit the transaction


COMMIT;

Prepared by : Dr. Ahmad Jamal


Rollback
A rollback is a database operation that reverses all changes made by a transaction, returning the database to its
state before the transaction began. It is used when an error occurs or when a transaction cannot be completed
successfully, ensuring the consistency of the database.

Key Features of Rollback



Reverses Changes: Undoes all modifications made by the current transaction.

Maintains Consistency: Prevents incomplete or erroneous changes from being saved.

Transactional Control: Can be applied to a full transaction or to a specific point using savepoints.

Temporary Changes: Before a commit, all changes are temporary and can be rolled back.

Syntax:

ROLLBACK;

Prepared by : Dr. Ahmad Jamal


Rollback Example
Use Case: Reverting a failed transaction in a banking system
BEGIN TRANSACTION;

-- Deduct 500 from Account A


UPDATE Accounts In this example, the
SET Balance = Balance - 500 deduction from Account A will
WHERE AccountID = 'A'; also be reverted because the
transaction is rolled back.
-- Simulate an error (e.g., Account B does not exist)
UPDATE Accounts
SET Balance = Balance + 500
WHERE AccountID = 'NonExistentAccount';

-- Revert changes due to the error


ROLLBACK;

Prepared by : Dr. Ahmad Jamal


Save Points
Savepoints are intermediate points within a transaction that allow you to partially roll back changes without
undoing the entire transaction. They provide finer control over transaction management by letting you define
specific points to which you can revert in case of errors.

Key Features of Savepoints



Partial Rollback: Enables rolling back to a specific point in a transaction.

Error Recovery: Useful for large or complex transactions where only certain parts might need to be reverted.

Flexible Transaction Management: Allows selective undoing of changes without affecting the entire
transaction.
Syntax:

Defining a Savepoint Rolling Back to a Savepoint

SAVEPOINT savepoint_name; ROLLBACK TO savepoint_name;

Prepared by : Dr. Ahmad Jamal


Save Points Example
Use Case: Savepoints in a Banking System
BEGIN TRANSACTION;

-- Step 1: Deduct 500 from Account A The transaction begins by


SAVEPOINT DeductAmount; deducting 500 from Account
UPDATE Accounts A after marking a savepoint
SET Balance = Balance - 500 (DeductAmount) and then
WHERE AccountID = 'A'; adds 500 to Account B after
another savepoint
-- Step 2: Add 500 to Account B (AddAmount). When an
SAVEPOINT AddAmount; error is encountered, a
UPDATE Accounts rollback to DeductAmount
SET Balance = Balance + 500 undoes the deduction from
WHERE AccountID = 'B'; Account A while leaving
earlier changes intact. The
-- Simulate an error in the process transaction is then
ROLLBACK TO DeductAmount; committed, finalizing only
the operations before
-- Only the deduction from Account A is reverted; other changes remain intact DeductAmount.
COMMIT;
Prepared by : Dr. Ahmad Jamal
Rollback vs Commit
Aspect Commit Rollback
Purpose Finalizes a transaction, making all Reverts a transaction, undoing all changes
changes permanent. made during it.

Effect Changes are saved to the database Discards all changes made since the
and visible to others. transaction began or since a savepoint.

Command COMMIT; ROLLBACK;


Visibility Changes become visible to other Changes remain invisible as they are undone.
transactions or users.

Use Case Used when a transaction completes Used when a transaction fails or an error
successfully. occurs.

Reversibility Irreversible; changes cannot be Fully reversible; undoes all uncommitted


undone after commit. changes.

Scope Applies to the entire transaction. Can apply to the entire transaction or a
savepoint.

Error Handling Does not handle errors; assumes the Used to recover from errors by restoring the
transaction is correct. database to a previous state.
Prepared by : Dr. Ahmad Jamal
Concurrency in Transactions
Concurrency in transactions refers to the simultaneous execution of multiple transactions in a database. It is
essential in multi-user environments to improve performance and ensure the efficient use of system
resources. However, it introduces challenges in maintaining data consistency, integrity, and isolation.

Advantages of Concurrency

Increased Throughput: Multiple transactions can be executed concurrently, maximizing resource utilization.

Reduced Waiting Time: Users do not need to wait for other transactions to complete, improving response
time.

Improved Scalability: Supports multiple users and operations effectively.
Challenges in Concurrency


Dirty Read: A transaction reads data that has been modified but not yet committed by another transaction.

Non-Repeatable Read: A transaction reads the same data multiple times but gets different results because
another transaction modified it in the meantime.

Phantom Read: A transaction reads a set of rows, but the result changes because another transaction
added or deleted rows.

Lost Update: Two transactions modify the same data simultaneously, and one of the updates is lost.
Prepared by : Dr. Ahmad Jamal
Challenges in Concurrency

Concurrency Description Example


Issue
Dirty Read A transaction reads data modified by another transaction that T1 modifies a value in row 1.
hasn’t yet been committed. T2 reads the updated value in row 1 before T1
commits.
T1 aborts, making T2’s read data invalid.
Non-Repeatable A transaction re-reads data and finds it altered or deleted by T1 reads a record.
Read another transaction. T2 updates/deletes that record and commits.
T1 re-reads the record and finds a different value or
discovers that the record is gone.
Phantom Read A transaction re-executes a query and finds the set of rows T1 runs a query to count rows meeting a condition.
meeting the criteria has changed due to another committed T2 inserts/deletes rows affecting this condition and
transaction. commits.
T1 re-runs the query and gets a different count.
Lost Update Two transactions updating the same dataset, resulting in one T1 and T2 both read row 1.
update being lost as it is overwritten by the latter. In short, T1 modifies row1 and commits.
the last update wins. T2 updates row1, not knowing the changes made
by T1.
T2 commits, it will lead to overwriting T1’s
changes.
Two-Phase Commit (2PC)
The Two-Phase Commit Protocol (2PC) is a distributed algorithm used in database systems to ensure that a
transaction spanning multiple nodes or systems either commits fully or rolls back entirely. It ensures atomicity and
consistency in distributed systems by coordinating the commit process.

Phases of 2PC

1. Prepare Phase (Voting Phase)


The coordinator (a central entity managing the transaction) ensures all participants (nodes involved in the transaction)
are ready to commit.
Steps:

Coordinator sends a PREPARE request to all participants.

Participants check their local transaction status:
If ready to commit, they reply with YES.
If an issue is detected, they reply with NO.

2. Commit Phase (Decision Phase)


Based on the responses from all participants, the coordinator decides whether to commit or roll back the transaction.
Steps:

If all participants replied YES, the coordinator sends a COMMIT request, and all nodes commit the changes.

If any participant replied NO, the coordinator sends a ROLLBACK request, and all nodes undo the changes.
Prepared by : Dr. Ahmad Jamal
Flow of 2PC
1 - Begin Transaction: The transaction starts across multiple systems.

2 - Prepare Phase:
Coordinator sends PREPARE to all participants.
Participants vote: YES (ready) or NO (not ready).
3 - Decision Phase:
If all vote YES: Coordinator sends COMMIT.
If any vote NO: Coordinator sends ROLLBACK.

Advantages of 2PC

Atomicity Across Nodes: Ensures that all systems commit or rollback as a single unit.

Consistency: Prevents partial commits, maintaining data integrity.

Disadvantages of 2PC

Blocking Protocol: Participants remain locked until the coordinator decides, reducing concurrency.

Single Point of Failure: If the coordinator crashes, the system can be left in an uncertain state.

Overhead: Increased communication and logging requirements. Prepared by : Dr. Ahmad Jamal
Two-Phase Commit (2PC) : Example
Money Transfer
A transaction involves transferring 500 from a bank account managed by System A to
another account in System B:

Coordinator sends PREPARE to System A and System B.

Both systems reply YES (ready to commit).

Coordinator sends COMMIT to both systems.

If System B had replied NO, the coordinator would send ROLLBACK to both systems,
reverting all changes.

To address 2PC’s blocking issue, the Three-Phase Commit Protocol introduces a third phase, adding a
timeout mechanism and reducing uncertainty in case of coordinator failure.

Prepared by : Dr. Ahmad Jamal


Concurrency Control techniques
Concurrency control techniques are used in databases to ensure that multiple transactions can execute
concurrently without leading to inconsistencies, anomalies, or conflicts. These techniques ensure that the
database remains in a consistent state, even in multi-user environments. Some common concurrency control
techniques are:

1. Locking Mechanisms
2. Timestamp Ordering
3. Optimistic Concurrency Control
4. Multiversion Concurrency Control (MVCC)
5. Serializability
6. Two-Phase Locking (2PL)
7. Query Serialization

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal


Heading

Prepared by : Dr. Ahmad Jamal

You might also like