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)
- Atomicity, all or nothing;
- Consistency, data stays valid;
- Isolation, concurrent transactions don't interfere with each other;
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.