SQL Transactions Explained

SQL Transactions 101 πŸ”
(BEGIN, COMMIT, ROLLBACK β€” The Ultimate Trio)

Imagine you’re transferring money between two accounts.
You want this to happen safely and completely β€” or not at all.

That’s exactly what SQL transactions help you do.

Here’s a simple example:

BEGIN TRANSACTION;

UPDATE accounts
SET balance = balance – 100
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 100
WHERE account_id = 2;

COMMIT;

βœ… BEGIN TRANSACTION β€” Starts the transaction.
β†’ From this point, all SQL changes are held temporarily.
β†’ Nothing is permanent until you say so.

βœ… COMMIT β€” Finalizes the transaction.
β†’ Makes all changes permanent.
β†’ The transfer is completed successfully.

❌ ROLLBACK β€” Undoes all changes.
β†’ If an error happens at any point, ROLLBACK returns the database to its original state.
β†’ No partial updates β€” so data stays consistent.

When to use them?
β†’ Financial transactions
β†’ Order placement & inventory updates
β†’ Multi-step data imports
β†’ Any process that must fully succeed or not happen at all

Pro tip: Always put related updates in the same transaction.
That way you avoid partial updates and data inconsistencies!

πŸ‘‰ Want to master SQL transactions?
Check these courses:
β†’ IBM Data Science: https://programmingvalley.com/course/ibm-data-science-free-course/
β†’ SQL for Data Science: https://programmingvalley.com/course/sql-for-data-science-free-course/

Amr Abdelkarem

Owner

No Comments

Leave a Comment