What is Transaction in DBMS: Definition and Examples
transaction in DBMS is a sequence of database operations performed as a single unit to ensure data integrity. It either completes fully or does not happen at all, following the ACID properties to keep data consistent.How It Works
Think of a transaction like a bank transfer. When you send money, the system must subtract from your account and add to the receiver's account. Both steps must happen together; if one fails, the whole transfer is canceled to avoid errors.
In DBMS, a transaction groups multiple operations so they act as one. If all operations succeed, the transaction commits and saves changes. If any operation fails, the transaction rolls back, undoing all changes to keep the database safe and consistent.
Example
This example shows a simple transaction in SQL that transfers money between two accounts. It ensures both debit and credit happen together.
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE account_id = 1; UPDATE accounts SET balance = balance + 100 WHERE account_id = 2; COMMIT;
When to Use
Use transactions whenever you need to perform multiple related database changes that must all succeed or fail together. This is common in banking, booking systems, or inventory management to avoid partial updates that cause errors.
For example, when booking a flight, a transaction ensures seat availability is updated and payment is processed together. If payment fails, the seat remains available.
Key Points
- A transaction is a single unit of work in a database.
- It follows ACID properties: Atomicity, Consistency, Isolation, Durability.
- Transactions prevent partial updates and keep data reliable.
- They are essential in systems where data accuracy is critical.