Lesson 55 of 60 – MySQL Transactions
92%

MySQL Transactions

A transaction is a group of SQL operations that are treated as one logical unit of work. A transaction is useful when several related operations must succeed together.

Note: Transaction behavior depends on the storage engine and statement type. In MySQL, transactional applications commonly use the InnoDB storage engine.

1. What is a Transaction?

A transaction is a sequence of SQL statements that MySQL handles as one logical operation.

For example, transferring money between two accounts may require:

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 2;

Both operations belong to the same logical transaction.

2. Why Use Transactions?

Transactions help maintain data consistency when multiple related operations are performed.

  • Keep related operations together.
  • Allow changes to be committed together.
  • Allow changes to be rolled back when appropriate.
  • Help maintain consistency.
  • Are important for banking, payments, orders, inventory, and similar systems.

3. ACID Properties

Transactions are commonly described using four ACID properties:

  • Atomicity – the transaction is treated as one unit.
  • Consistency – valid transactions take the database from one valid state to another.
  • Isolation – concurrent transactions are controlled so their intermediate effects do not improperly interfere.
  • Durability – committed changes are intended to survive failures according to the storage engine's guarantees.

4. Atomicity

Atomicity means a transaction is treated as one logical unit of work.

Suppose a payment system performs two operations:

UPDATE accounts
SET balance = balance - 500
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 500
WHERE account_id = 2;

If the transaction is rolled back before commit, the changes made by the transaction can be undone.

5. Consistency

Consistency means a completed transaction should preserve the database rules and constraints that apply to it.

For example, if an order and its payment are required to follow certain application rules, the transaction should leave the database in a valid state.

6. Isolation

Isolation controls how concurrent transactions interact with each other.

MySQL provides transaction isolation levels such as:

  • READ UNCOMMITTED
  • READ COMMITTED
  • REPEATABLE READ
  • SERIALIZABLE

InnoDB uses REPEATABLE READ as its default isolation level.

7. Durability

Durability means that once a transaction has been successfully committed, its changes are intended to remain stored even if a failure occurs, subject to the storage engine and server configuration.

COMMIT;

COMMIT permanently completes the transaction from the application's transaction perspective.

8. START TRANSACTION

You can explicitly start a transaction using:

START TRANSACTION;

You can then execute one or more SQL statements before using COMMIT or ROLLBACK.

9. BEGIN

BEGIN can also be used to start a transaction.

BEGIN;

UPDATE students
SET status = 'Active'
WHERE student_id = 10;

COMMIT;

For normal transaction control, BEGIN and START TRANSACTION are commonly used to begin an explicit transaction.

10. COMMIT

COMMIT successfully completes the current transaction and makes its changes permanent.

START TRANSACTION;

UPDATE students
SET status = 'Active'
WHERE student_id = 10;

COMMIT;

After COMMIT, the transaction's changes are no longer available for rollback through that transaction.

11. ROLLBACK

ROLLBACK cancels changes made by the current transaction that have not yet been committed.

START TRANSACTION;

UPDATE students
SET status = 'Inactive'
WHERE student_id = 10;

ROLLBACK;

The UPDATE made within the transaction is undone.

12. Basic Transaction Example

START TRANSACTION;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 2;

COMMIT;

Both UPDATE statements are part of the same transaction.

13. Transaction with ROLLBACK

START TRANSACTION;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 2;

ROLLBACK;

If the transaction has not been committed, ROLLBACK can undo the transaction's changes.

14. Autocommit

MySQL normally operates with autocommit enabled for individual statements.

You can check its value using:

SELECT @@autocommit;

A value of 1 means autocommit is enabled, while 0 means it is disabled for the session.

15. Disabling Autocommit

You can disable autocommit for the current session:

SET autocommit = 0;

Now changes to transactional tables can remain part of an ongoing transaction until COMMIT or ROLLBACK is issued.

Tip: Transaction handling should be deliberate in application code. Remember to commit successful work or roll back when appropriate.

16. Enabling Autocommit

Autocommit can be enabled again:

SET autocommit = 1;

When autocommit is enabled, each statement that is transactional and completes successfully is generally committed automatically unless it is inside an explicit transaction.

17. SAVEPOINT

A SAVEPOINT creates a named point inside a transaction.

START TRANSACTION;

UPDATE students
SET status = 'Active'
WHERE student_id = 1;

SAVEPOINT student_update;

UPDATE students
SET status = 'Inactive'
WHERE student_id = 2;

You can later roll back to the savepoint instead of rolling back the entire transaction.

18. ROLLBACK TO SAVEPOINT

Use ROLLBACK TO SAVEPOINT to undo changes made after a savepoint.

START TRANSACTION;

UPDATE students
SET status = 'Active'
WHERE student_id = 1;

SAVEPOINT student_update;

UPDATE students
SET status = 'Inactive'
WHERE student_id = 2;

ROLLBACK TO SAVEPOINT student_update;

COMMIT;

The second UPDATE is undone, while the first UPDATE can remain part of the transaction.

19. RELEASE SAVEPOINT

You can remove a savepoint when it is no longer needed.

RELEASE SAVEPOINT student_update;

After releasing a savepoint, you cannot roll back to that savepoint.

20. Transaction with INSERT

Transactions can contain INSERT statements when the table uses a transactional storage engine such as InnoDB.

START TRANSACTION;

INSERT INTO students
(name, email, city)
VALUES
('Amit Kumar', 'amit@example.com', 'Patna');

COMMIT;

The INSERT becomes part of the transaction and is committed when COMMIT is executed.

21. Transaction with DELETE

DELETE operations can also be included in a transaction.

START TRANSACTION;

DELETE FROM students
WHERE student_id = 10;

ROLLBACK;

For a transactional table, the DELETE can be undone before the transaction is committed.

22. Transaction Isolation Levels

MySQL supports four standard transaction isolation levels:

READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE

Isolation level controls how one transaction can see data changed by other concurrent transactions.

23. READ UNCOMMITTED

READ UNCOMMITTED is the least restrictive standard isolation level.

A transaction may be able to read changes made by another transaction before those changes are committed. This can result in phenomena such as dirty reads.

It is generally used only when the application can tolerate very weak read consistency.

24. READ COMMITTED

With READ COMMITTED, a transaction reads committed data from other transactions rather than uncommitted changes.

The same query executed at different times within a transaction can potentially see newly committed changes from other transactions.

25. REPEATABLE READ

REPEATABLE READ is the default isolation level for InnoDB.

It provides consistent reads within a transaction using InnoDB's transaction model.

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

The exact behavior also depends on the type of read and locking used.

26. SERIALIZABLE

SERIALIZABLE is the most restrictive standard isolation level.

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

It provides stronger isolation by making concurrent access more restrictive, which can reduce concurrency.

27. Checking the Isolation Level

You can inspect the current transaction isolation level with:

SELECT @@transaction_isolation;

This helps you understand which isolation level is currently configured for the session.

28. Important Transaction Mistakes

  • Forgetting to COMMIT a successful transaction.
  • Forgetting to ROLLBACK after an application error.
  • Assuming every MySQL table supports transactional rollback.
  • Ignoring autocommit behavior.
  • Keeping transactions open unnecessarily long.
  • Using an isolation level without understanding its effects.
  • Assuming DDL statements behave exactly like ordinary DML statements inside transactions.
Important: Statements such as CREATE, ALTER, DROP, and TRUNCATE have different transaction behavior from ordinary INSERT, UPDATE, and DELETE statements. Always check the specific statement and storage engine behavior.

29. Practical Bank Transfer Example

Consider two accounts:

CREATE TABLE accounts (
    account_id INT PRIMARY KEY,
    account_name VARCHAR(100),
    balance DECIMAL(12,2)
) ENGINE=InnoDB;

Transfer ₹1,000 from account 1 to account 2:

START TRANSACTION;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 2;

COMMIT;

If the application detects a problem before COMMIT, it can use:

ROLLBACK;

This is a common example of why transactions are important: multiple related changes should be handled as one logical unit.

30. Complete MySQL Transaction Example

CREATE TABLE accounts (
    account_id INT PRIMARY KEY,
    account_name VARCHAR(100),
    balance DECIMAL(12,2)
) ENGINE=InnoDB;

INSERT INTO accounts
(account_id, account_name, balance)
VALUES
(1, 'Amit', 10000.00),
(2, 'Rahul', 5000.00);

START TRANSACTION;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 2;

COMMIT;

SELECT *
FROM accounts;

If an error occurs before COMMIT, the application can instead execute:

ROLLBACK;

You can also use a savepoint:

START TRANSACTION;

UPDATE accounts
SET balance = balance - 500
WHERE account_id = 1;

SAVEPOINT transfer_step;

UPDATE accounts
SET balance = balance + 500
WHERE account_id = 2;

ROLLBACK TO SAVEPOINT transfer_step;

COMMIT;

This example demonstrates transactions, COMMIT, ROLLBACK, SAVEPOINT, and InnoDB.

📌 Key Points

  • A transaction is a group of related SQL operations treated as one logical unit.
  • Transactions are commonly associated with the ACID properties.
  • START TRANSACTION begins an explicit transaction.
  • BEGIN can also begin a transaction.
  • COMMIT completes the transaction and saves its changes.
  • ROLLBACK undoes uncommitted transactional changes.
  • SAVEPOINT creates a point within a transaction.
  • ROLLBACK TO SAVEPOINT partially rolls back a transaction.
  • RELEASE SAVEPOINT removes a savepoint.
  • InnoDB supports transactions.
  • MySQL commonly uses autocommit by default.
  • InnoDB's default isolation level is REPEATABLE READ.
  • MySQL supports READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.
  • Transaction behavior is not identical for every MySQL statement or storage engine.
  • Transactions are especially useful for payments, banking, orders, inventory, and other multi-step operations.

🧠 Quick Quiz

Question: Which MySQL command is used to permanently complete the current transaction?