sql / beginner
Snippet
Bundling Related Operations in Database Transactions
Transactions group multiple SQL operations into an all-or-nothing unit of work. COMMIT saves all changes permanently, preserving data consistency across multi-step updates.
snippet.sql
sql
1
2
3
4
BEGIN TRANSACTION;UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;COMMIT;
Breakdown
1
BEGIN TRANSACTION;
Marks the start of a logical transaction block.
2
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
Deducts 100 units from account 1 as the first step.
3
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
Adds 100 units to account 2 as the second step.
4
COMMIT;
Finalizes and permanently saves all changes made within the transaction.