Introduction

A transaction is a sequence of operations performed on a database as a single logical unit of work. The effects of all the statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database). A database transaction must be atomic, consistent, isolated and durable.

Important Points

  • A transaction is a program unit whose execution may or may not change the contents of a database.
  • The transaction is executed as a single unit.
  • If database operations do not update the database but only retrieve data, this type of transaction is called a read-only transaction.
  • A successful transaction can change the database from one consistent state to another consistent state.
  • A transactions must be atomic, consistent, isolated and durable (ACID).

ACID Properties

A database is a shared resource accessed. It is used by many users and processes concurrently. For example, the banking system, railway, and air reservations systems, stock market monitoring, supermarket inventory, and checkouts, etc. For maintaining the integrity of data, DBMS system must ensure ACID properties i.e.

  • Atomicity: A transaction is a single unit of operation. You either execute it entirely or do not execute it at all. There cannot be partial execution.
  • Consistency: Once the transaction is executed, database should move from one consistent state to another.
  • Isolation: In a database system where more than one transaction are being executed simultaneously and in parallel. Property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.
  • Durability: · Database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.

Example

Let’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from A’s account to B’s account. This transaction involves several low-level tasks.

/* Operation in A's Account */
Open_Account(A)
Old_Balance = A.balance
New_Balance = Old_Balance - 500
A.balance = New_Balance
Close_Account(A)

/* Operation in B's Account */
Open_Account(B)
Old_Balance = B.balance
New_Balance = Old_Balance + 500
B.balance = New_Balance
Close_Account(B)

All types of database access operation which are held between the beginning and end transaction statements are considered as a single logical transaction. During the transaction the database is inconsistent. Only once the database is committed the state is changed from one consistent state to another.

Reference

Understanding Transactions in SQL Server