A Transaction is a logical unit of work that contains one or more SQL statements.
All statements inside a transaction must either:
This ensures data accuracy, safety, and reliability.
Bank Transfer Scenario
Both operations must succeed together.
If one fails, the transaction must roll back.
Transactions follow ACID, which guarantees reliability.
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
If second update fails → first update is undone.
Example:
Prevents:
START TRANSACTION;
-- or
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;
START TRANSACTION begins the transactionCOMMIT permanently saves changesSTART TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
-- Something went wrong
ROLLBACK;
ROLLBACK cancels all changes in the transactionSTART TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
SAVEPOINT step1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
-- Undo only second update
ROLLBACK TO step1;
COMMIT;
| Command | Purpose |
|---|---|
| START TRANSACTION / BEGIN | Start transaction |
| COMMIT | Save changes |
| ROLLBACK | Undo changes |
| SAVEPOINT | Create rollback point |
| ROLLBACK TO | Rollback to savepoint |
| RELEASE SAVEPOINT | Remove savepoint |
By default, many databases run in auto-commit mode.
SET autocommit = 0; -- Disable
SET autocommit = 1; -- Enable
Isolation level defines how much one transaction can see of another.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
Reading data that is not committed yet.
Same query returns different results in same transaction.
New rows appear in repeated queries.
| Operation | Transaction Support |
|---|---|
| INSERT | Yes |
| UPDATE | Yes |
| DELETE | Yes |
| SELECT | No |
| CREATE TABLE | Often auto-commit |
| DROP TABLE | Often auto-commit |
⚠️ Many DDL commands implicitly commit.