SQL Transactions (BEGIN, COMMIT, ROLLBACK)

Article Summary

A transaction is a sequence of SQL operations treated as a single unit. Transactions ensure data integrity β€” either all operations succeed, or none do. πŸ”Ή Key Concepts πŸ”Ή Basic Commands πŸ”Ή Example If any step fails, use ROLLBACK; to undo changes and keep data consistent. πŸ”Ή Use Cases πŸ”Ή Important Notes 🧠 Quick Recap […]

A transaction is a sequence of SQL operations treated as a single unit. Transactions ensure data integrity β€” either all operations succeed, or none do.

πŸ”Ή Key Concepts

  • Transactions maintain ACID properties: Atomicity, Consistency, Isolation, Durability.
  • Use transactions to group related changes so your database stays consistent.

πŸ”Ή Basic Commands

BEGIN;             -- Start a transaction
-- Your SQL operations here
COMMIT;            -- Save all changes permanently
ROLLBACK;          -- Undo all changes since BEGIN

πŸ”Ή Example

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

If any step fails, use ROLLBACK; to undo changes and keep data consistent.

πŸ”Ή Use Cases

  • Transferring money between bank accounts
  • Batch inserts/updates that must succeed together
  • Complex business logic requiring multiple updates

πŸ”Ή Important Notes

  • If a transaction isn’t explicitly committed, it may auto-rollback depending on DBMS.
  • Long transactions can block resources β€” keep them short.
  • Use SAVEPOINT to create intermediate rollback points within a transaction (supported in many DBMS).

🧠 Quick Recap

PointExplanation
BEGINStarts a transaction
COMMITSaves changes permanently
ROLLBACKUndoes changes since BEGIN
PurposeEnsures data integrity & consistency
Best PracticeKeep transactions short

πŸ’‘ Transactions protect your data from partial updates and keep your database reliable.

Was this helpful?