Skip to main content

Why do we need transactions?

Transactions exist to guarantee data integrity and reliability, especially when several related operations run together.

Without transactions, part of the changes might get saved while another part doesn't, leaving the data in an inconsistent state.

What transactions are for

  1. Safety for changes. If one operation in a series fails, every earlier one rolls back (ROLLBACK).
  2. Data integrity. They prevent "half-done" actions (e.g. money leaving one account but never arriving at another).
  3. Isolation. Concurrent users don't interfere with each other, and each one only sees completed changes.
  4. Error control. A failure can be caught and the data restored to its pre-change state.

Example:

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

If one row fails to update, the transaction gets cancelled, and the balance stays as it was.

Summary: Transactions exist so the database always stays in a correct state, even when an error, failure, or several concurrent users are involved.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.