SQL
Transactions
Learn how databases use BEGIN, COMMIT, and ROLLBACK to keep your data safe, consistent, and reliable.
What Is a Transaction?
A transaction is a sequence of one or more SQL statements that are treated as a single, indivisible unit of work. Either every statement in the transaction succeeds, or none of them take effect.
Why Do We Need Transactions?
Imagine transferring money between two bank accounts. This requires two SQL statements: one to debit Account A, and one to credit Account B. What happens if the system crashes after the debit but before the credit?
The Three Key Commands
Transaction Lifecycle
The ACID Properties
Transactions guarantee four fundamental properties known by the acronym ACID. These ensure that your data remains correct even when things go wrong.
COMMIT vs ROLLBACK
| COMMIT | ROLLBACK | |
|---|---|---|
| Purpose | Save all changes permanently | Undo all changes |
| When to use | Everything succeeded | An error occurred |
| Effect on data | Changes become visible to others | Data reverts to pre-transaction state |
| Reversible? | No: committed data is final | The action is final; the transaction is aborted |
How to Write a Transaction
Example 1: Bank Transfer
Example 2: Handling Errors
Example 3: Multi-Table Insert
What Is Autocommit?
By default, most databases run in autocommit mode. This means every individual SQL statement is automatically wrapped in its own transaction and committed immediately.
Data Before and After
Implicit vs Explicit Transactions
| Implicit | Explicit | |
|---|---|---|
| Triggered by | Autocommit (default) | Writing BEGIN manually |
| Scope | Single statement | Multiple statements |
| Rollback possible? | No: committed instantly | Yes: until COMMIT |
| Use case | Simple reads, single inserts | Transfers, batch updates, multi-table writes |
Common Mistakes
Quick Reference Summary
| Command | What It Does | Analogy |
|---|---|---|
| BEGIN | Opens a new transaction | Opening a shopping cart |
| COMMIT | Saves all changes permanently | Clicking "Place Order" |
| ROLLBACK | Undoes all changes | Emptying the cart |
| ACID | Four guarantees of transactions | The receipt and warranty |
Question 1 of 5
What does the BEGIN command do in SQL?
Question 2 of 5
A bank transfer requires debiting one account and crediting another. If the system crashes after the debit but before the credit, what does ROLLBACK ensure?
Question 3 of 5
Which ACID property guarantees that committed data survives a power outage?
Question 4 of 5
In autocommit mode, what happens after each individual SQL statement executes?
Question 5 of 5
A developer writes the following SQL:
BEGIN;
INSERT INTO orders (customer_id, total) VALUES (7, 49.99);
UPDATE inventory SET stock = stock - 1 WHERE product_id = 55;
-- (no COMMIT or ROLLBACK written)
The developer then closes the database connection.
What most likely happens to the changes?