Imagine you are transferring money between two bank accounts. Why is it important to use a transaction for this operation?
Think about what happens if only one part of the transfer happens and the other does not.
Transactions make sure that all steps in a process happen completely or not at all. This avoids problems like losing money if only one step succeeds.
Which problem is solved by using transactions in a multi-user database?
Think about what happens if a process stops halfway through.
Transactions prevent partial changes that could cause wrong or broken data when multiple users work at the same time.
Consider this SQL sequence:
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; ROLLBACK;
What is the balance change after this sequence?
ROLLBACK cancels all changes in the transaction.
ROLLBACK undoes all changes made in the transaction, so balances remain as before.
Two users update the same row at the same time without transactions:
User1: UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 10; User2: UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 10;
What problem can occur?
Think about what happens if both read the same initial quantity before updating.
Without transactions and proper locking, both users might read the same quantity and overwrite each other's update, causing lost updates.
Atomicity means a transaction is all-or-nothing. Why is this property crucial for database reliability?
Consider what happens if a system crashes during a multi-step update.
Atomicity ensures that either all steps succeed or none do, so data never ends up in a broken or partial state.