01 / 21

SQL
Transactions

Learn how databases use BEGIN, COMMIT, and ROLLBACK to keep your data safe, consistent, and reliable.

Computer Science

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?

✕ Without Transactions
Money disappears from Account A but never arrives in Account B. Data is now inconsistent.
✓ With Transactions
Both operations succeed together, or the database rolls everything back. No money is lost.

The Three Key Commands

BEGIN
Starts a new transaction. All following SQL statements are grouped together until a COMMIT or ROLLBACK.
COMMIT
Saves all changes made during the transaction permanently to the database.
ROLLBACK
Undoes all changes made during the transaction, restoring the database to its state before BEGIN.

Transaction Lifecycle

BEGIN Active SQL statements execute here COMMIT Changes saved ROLLBACK Changes undone

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.

Atomicity
All or nothing: every statement succeeds, or none take effect.
Consistency
The database moves from one valid state to another. Rules are never violated.
Isolation
Concurrent transactions do not interfere with each other.
Durability
Once committed, changes survive power outages, crashes, and errors.

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

1
Start with BEGIN. This signals the database that a transaction is starting.
2
Write your SQL statements. INSERT, UPDATE, DELETE: any changes you need.
3
Check for errors. Did everything run correctly? Were constraints satisfied?
4
COMMIT if successful. Lock in the changes permanently.
5
ROLLBACK if something failed. Undo everything and try again or handle the error.

Example 1: Bank Transfer

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

Example 2: Handling Errors

BEGIN; INSERT INTO orders (customer_id, total) VALUES (42, 199.99); UPDATE inventory SET stock = stock - 1 WHERE product_id = 101; -- At this point, application code would check if the update -- caused stock to become negative. If so, it issues a ROLLBACK. -- For this example, we assume an error was found: ROLLBACK;

Example 3: Multi-Table Insert

BEGIN; INSERT INTO students (name, email) VALUES ('Alice', 'alice@school.edu'); SET @new_id = LAST_INSERT_ID(); INSERT INTO enrollments (student_id, course_id) VALUES (@new_id, 301); INSERT INTO grades (student_id, course_id, grade) VALUES (@new_id, 301, NULL); COMMIT;

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.

Autocommit ON
Each statement is its own transaction. No explicit BEGIN or COMMIT needed for single operations.
Explicit Transaction
You use BEGIN to group multiple statements. Autocommit is temporarily suspended until COMMIT or ROLLBACK.

Data Before and After

BEFORE Acct 1: $1000 Acct 2: $500 Total: $1500 BEGIN DURING Acct 1: $500 Acct 2: $500 Pending... Not yet visible to other users COMMIT AFTER Acct 1: $500 Acct 2: $1000 Total: $1500 ✓ ROLLBACK

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

✕ Forgetting COMMIT
You write BEGIN and your SQL, but never COMMIT. Changes remain pending and may be lost when the session ends.
✕ No Error Handling
You COMMIT without checking if any statement failed. Partial or corrupted data gets saved permanently.
✕ Nesting Confusion
Assuming you can nest transactions inside each other. Most databases do not support true nested transactions.

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

What most likely happens to the changes?