A database transaction is a logical unit of work that consists of one or more operations (such as insert, update, or delete) performed on a database. These operations are grouped together and treated as a single, indivisible unit.
A transaction ensures that all the operations within it are either completely executed or none of them are executed at all. This guarantees the consistency and integrity of the database, even in the event of errors, power failures, or system crashes.
Key Features of a Database Transaction
-
Atomicity:
- A transaction is “all or nothing.”
- Example: When transferring money between accounts, the transaction debits one account and credits another. If one operation fails, the entire transaction is rolled back.
-
Consistency:
- A transaction ensures that the database transitions from one valid state to another.
- Example: After a transaction, all integrity rules (such as no negative balances) are maintained.
-
Isolation:
- Multiple transactions occur independently and do not interfere with each other.
- Example: Two customers booking the same plane seat are handled sequentially, ensuring only one succeeds.
-
Durability:
- Once a transaction is successfully completed, its changes are permanently stored in the database, even in the event of a system failure.
- Example: After a successful order placement, the details remain stored even if the server crashes.
Example of a Database Transaction
Consider transferring $100 from Account A to Account B:
- Begin the transaction.
- Debit $100 from Account A.
- Credit $100 to Account B.
- Commit the transaction.
If any step fails (e.g., the credit operation), the database rolls back to its original state, ensuring no partial changes occur.