06. Importance Of Undo Log

 

Importance Of Undo Log



Question:

In MySQL (InnoDB), when a row is updated inside a transaction, it is loaded into memory (RAM), and undo/redo logs are used.

Suppose we update a row's value but later roll back the transaction — why do we still need the undo log if the change wasn't committed to the database?

Also, how does MySQL use memory (RAM) to avoid reading from disk again?

 

Example:

 Initially, the name in the `Student` table is `"A"`.

 Transaction 1: Updates name to `"B"` but then rolls back.

 Transaction 2: Updates name to `"B"` again and commits.

 

How does MySQL handle undo logs, in-memory changes, and rollback? Why do we need to roll back in-memory data if it’s not yet committed?

 

 

Answer:

  • When you run a query in MySQL (InnoDB), the row is loaded into RAM (called the buffer pool) to speed up access. MySQL prefers working from memory rather than reading from disk repeatedly — even for SELECT queries. 
  • When you update a row inside a transaction, that change is only visible to your transaction unless it's committed. The original version of the row is saved in the undo log. 
  • If you roll back, MySQL uses the undo log to revert the in-memory row back to its original state. This is very important — because if memory wasn’t rolled back and still showed `"B"`, future SELECTs might return the wrong value, even though it was never committed.

 

In your example: 

1. Name starts as `"A"`.

2. Transaction 1 updates to `"B"`, then rolls back.

    Undo log restores name back to `"A"` in memory.

3. Transaction 2 updates name to `"B"` again and commits.

    Now `"B"` is saved to disk and kept in memory.

 

This is why undo logs are essential — not just for rollbacks, but to keep the in-memory view consistent with the actual database state.

 

Why in-memory matters:

  • MySQL tries to avoid disk I/O for performance.
  • When we SELECT a row, it’s usually fetched from RAM, not disk.
  • That’s why it's important that in-memory data always reflects the correct state — especially after rollbacks.

Comments

Popular posts from this blog

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.

01. Steps in SQL Query Execution (MySQL)