Introduction
Transactions help keep data safe and correct when many people use a database at the same time. They make sure all parts of a task finish together or not at all.
Transactions help keep data safe and correct when many people use a database at the same time. They make sure all parts of a task finish together or not at all.
BEGIN TRANSACTION; -- SQL statements here COMMIT; -- or ROLLBACK;
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;
BEGIN TRANSACTION; INSERT INTO orders (id, product) VALUES (1, 'Book'); ROLLBACK;
This example transfers 50 units from account 1 to account 2 and then shows the updated balances.
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 50 WHERE id = 1; UPDATE accounts SET balance = balance + 50 WHERE id = 2; COMMIT; SELECT id, balance FROM accounts ORDER BY id;
Without transactions, partial updates can leave data wrong or incomplete.
Transactions help databases handle errors and multiple users safely.
Transactions group multiple steps into one safe action.
They ensure data stays correct even if something fails.
Use COMMIT to save changes or ROLLBACK to undo them.
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;START TRANSACTION; or BEGIN TRANSACTION;.BEGIN TRANSACTION; UPDATE inventory SET quantity = quantity - 5 WHERE product_id = 10; UPDATE sales SET total = total + 5 WHERE sale_id = 3; ROLLBACK;
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 50 WHERE id = 1; UPDATE accounts SET balance = balance + 50 WHERE id = 2; COMMIT
1. BEGIN TRANSACTION; 2. UPDATE accounts SET balance = balance - 200 WHERE id = A; 3. UPDATE accounts SET balance = balance + 200 WHERE id = B; 4. COMMIT;
Pass the test and this pattern moves unknown