sql / beginner
Snippet
Ensuring Data Integrity with SQL Transactions
A transaction bundles multiple database modifications into a single unit of work. Using COMMIT saves all operations permanently, ensuring data stays consistent across multiple steps.
snippet.sql
sql
1
2
3
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;COMMIT;
Breakdown
1
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
Deducts 100 units from the balance of account 1 as the first step of the transfer.
2
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
Adds 100 units to the balance of account 2 as the second step of the transfer.
3
COMMIT;
Finalizes the transaction, permanently saving both updates to the database.