Reading history

SQL Transactions: COMMIT, ROLLBACK, SAVEPOINT and ACID

4 min read 0 views

Learn SQL transactions: BEGIN, COMMIT, ROLLBACK and SAVEPOINT, the ACID properties, autocommit, and isolation levels with dirty, non-repeatable and phantom reads.

A transaction groups several SQL statements into one unit of work that either succeeds completely or has no effect at all. The classic example is a bank transfer: taking money from one account and adding it to another must happen together, because a crash between the two steps would make money disappear. This lesson covers BEGIN, COMMIT, ROLLBACK, savepoints and the ACID properties that databases guarantee.

In this lesson you will learn

  • Starting and finishing a transaction
  • Undoing changes with ROLLBACK
  • Partial undo with SAVEPOINT
  • What Atomicity, Consistency, Isolation and Durability mean
  • Isolation levels and when locks matter

COMMIT and ROLLBACK

-- Move 5000 taka of budget from one salary to another as one unit
BEGIN;
UPDATE employees SET salary = salary - 5000 WHERE name = 'Faisal';
UPDATE employees SET salary = salary + 5000 WHERE name = 'Rubel';
COMMIT;
SELECT name, salary FROM employees WHERE name IN ('Faisal', 'Rubel');

-- A change that is undone
BEGIN;
DELETE FROM employees WHERE title = 'Engineer';
SELECT COUNT(*) AS engineers_inside_transaction FROM employees WHERE title = 'Engineer';
ROLLBACK;
SELECT COUNT(*) AS engineers_after_rollback FROM employees WHERE title = 'Engineer';

Output

+--------+--------+
| name   | salary |
+--------+--------+
| Faisal | 175000 |
| Rubel  | 95000  |
+--------+--------+
(2 rows)

+------------------------------+
| engineers_inside_transaction |
+------------------------------+
| 0                            |
+------------------------------+
(1 row)

+--------------------------+
| engineers_after_rollback |
+--------------------------+
| 2                        |
+--------------------------+
(1 row)
  • BEGIN (or START TRANSACTION in MySQL, BEGIN TRANSACTION in SQL Server) starts a transaction.
  • COMMIT makes every change since BEGIN permanent. The two salary updates are saved together.
  • Inside the second transaction the engineers really are deleted: the count is 0. ROLLBACK then cancels the delete, and the count is back to 2.
  • Without an explicit BEGIN, most databases run in autocommit mode, where each statement is its own transaction and is saved immediately.

Savepoints

-- Savepoints: undo part of a transaction
BEGIN;
INSERT INTO orders (id, customer, order_date, amount, status) VALUES (9, 'Mina', '2026-04-02', 900, 'pending');
SAVEPOINT before_second;
INSERT INTO orders (id, customer, order_date, amount, status) VALUES (10, 'Mina', '2026-04-03', 99999, 'pending');
ROLLBACK TO before_second;
COMMIT;
SELECT id, customer, amount FROM orders WHERE customer = 'Mina';

Output

+----+----------+--------+
| id | customer | amount |
+----+----------+--------+
| 9  | Mina     | 900    |
+----+----------+--------+
(1 row)
  • SAVEPOINT name marks a point inside a transaction.
  • ROLLBACK TO name undoes only the work done after that point; the transaction stays open. Here the order with the wrong amount (99999) is removed while order 9 survives.
  • COMMIT then saves what is left.

ACID Properties

PropertyMeaningBank transfer example
AtomicityAll statements succeed or none doDebit and credit both happen, or neither does
ConsistencyData moves from one valid state to another, respecting constraintsA CHECK (balance >= 0) rule is never broken
IsolationConcurrent transactions do not see each other’s unfinished workAnother user never sees the money “in flight”
DurabilityCommitted data survives crashes and power lossAfter COMMIT, a server restart does not lose the transfer

Isolation Levels

Full isolation is expensive, so databases let you choose a level. Lower levels allow more concurrency but permit certain anomalies.

LevelDirty readNon-repeatable readPhantom read
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDPreventedPossiblePossible
REPEATABLE READPreventedPreventedPossible
SERIALIZABLEPreventedPreventedPrevented
  • A dirty read sees another transaction’s uncommitted change.
  • A non-repeatable read reads the same row twice and gets different values.
  • A phantom read runs the same query twice and finds new rows.
  • PostgreSQL and SQL Server default to READ COMMITTED; MySQL’s InnoDB defaults to REPEATABLE READ. SQLite transactions are serializable.

Common Mistakes

  1. Forgetting to COMMIT, so changes vanish when the connection closes, or locks are held for a long time.
  2. Keeping transactions open while waiting for user input, which blocks other users.
  3. Assuming DDL can be rolled back: in MySQL and Oracle, CREATE, ALTER and DROP commit automatically.
  4. Running related updates without a transaction and leaving half-finished data after an error.

Practice Exercises

Exercise 1. Write a transaction that marks order 5 as delivered and inserts a new order 11 for Rina, saving both together.

Show answer
BEGIN;
UPDATE orders SET status = 'delivered' WHERE id = 5;
INSERT INTO orders (id, customer, order_date, amount, status)
VALUES (11, 'Rina', '2026-04-05', 700, 'pending');
COMMIT;

Exercise 2. After BEGIN; DELETE FROM orders; ROLLBACK;, how many rows does orders have?

Show answer

The same number as before (8 in the sample data). ROLLBACK cancels the delete completely.

Frequently Asked Questions

What happens if the server crashes in the middle of a transaction?

On restart, the database uses its log to undo any transaction that had not committed. Committed transactions are kept. This is atomicity and durability working together.

What is a deadlock?

Two transactions each wait for a lock the other holds, so neither can continue. The database detects this and rolls one back. Accessing tables in a consistent order and keeping transactions short reduces deadlocks.

Summary

  • A transaction runs several statements as one all-or-nothing unit.
  • COMMIT saves; ROLLBACK undoes; SAVEPOINT allows partial undo.
  • ACID: atomicity, consistency, isolation and durability.
  • Isolation levels trade safety against concurrency.

Next: SQL ALTER TABLE and DROP.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *