Transactions & Data Integrity (ACID)
Group multiple SQL writes into an all-or-nothing unit using BEGIN TRANSACTION, COMMIT, and ROLLBACK.
What you'll learn
- Wrap multi-step writes in BEGIN TRANSACTION ... COMMIT
- Undo partial changes safely with ROLLBACK if an error occurs
- Understand Atomicity in ACID databases
Imagine transferring 50 points from one account to another: two UPDATE statements must both succeed or both fail. Wrapping them in a transaction guarantees Atomicity (all-or-nothing).
BEGIN TRANSACTION;
UPDATE wallets SET points = points - 50 WHERE id = 1;
UPDATE wallets SET points = points + 50 WHERE id = 2;
COMMIT;
If anything fails before COMMIT, running ROLLBACK cleanly restores the database to its exact state before BEGIN TRANSACTION.
Fill-in-the-Blank Exercise
Commit or Rollback a Transaction
Save a transaction with COMMIT, or undo it with ROLLBACK.
BEGIN TRANSACTION;
UPDATE wallets SET points = points + 10 WHERE id = 1;
; -- save changes (or to undo)Try It Yourself
Notice how the ROLLBACK below undoes the accidental UPDATE, keeping Maya’s points safely at 100:
Click Run SQL to execute this query against a live in-browser SQLite database.
Check Your Understanding
1. What does ROLLBACK do inside an open SQL transaction?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.