Skip to main content

What is a transaction in SQL?

A transaction in SQL is a set of operations executed as a single unit: either all of them succeed, or none of them apply.

It exists to preserve data integrity, especially when changes span several tables.

Example

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

Both transfers run as one operation. If one step fails, everything rolls back.

The main commands

  • BEGIN / START TRANSACTION, starts the transaction;
  • COMMIT, commits the changes (saves them);
  • ROLLBACK, undoes the changes (rolls them back).

The properties of a transaction (ACID)

  1. Atomicity, all or nothing;
  2. Consistency, data stays valid;
  3. Isolation, concurrent transactions don't interfere with each other;
  4. Durability, after COMMIT, data is saved permanently.

Summary: A transaction is a guaranteed way to run several SQL operations safely and in sequence, so the database never ends up in a "half-updated" state.

Short Answer

Interview ready
Premium

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