A database transaction is a group of database operations treated as one logical unit of work.
Transactions are essential when multiple operations must succeed together. Without them, an application can end up with incomplete or inconsistent data.
Let's understand this with a practical example.
A real-world example
Imagine transferring $100 from Account A to Account B.
Two operations are required:
Subtract $100 from Account A.
Add $100 to Account B.
What happens if the first operation succeeds but the second fails?
Money could disappear from the system.
A database transaction helps prevent this situation.
Example using SQL
BEGIN ;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1 ;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2 ;
COMMIT ;
Enter fullscreen mode
Exit fullscreen mode
If an operation fails, the application can roll back the transaction:
ROLLBACK ;
Enter fullscreen mode
Exit fullscreen mode
The exact transaction behavior depends on the…