What is a Database transaction?

A database transaction is a sequence of one or more operations executed as a single, indivisible unit of work -- either every operation in it succeeds and is committed, or if any part fails, the entire transaction is rolled back and the database is left unchanged. Transactions are what give databases their ACID guarantees: Atomicity, Consistency, Isolation, and Durability.

Key Points: • Atomicity ensures all operations in the transaction succeed together or none do. • Consistency guarantees the database moves from one valid state to another, respecting all constraints. • Isolation controls how concurrent transactions see each other's uncommitted changes. • Durability guarantees that once a transaction commits, its changes survive even a system crash. • Transactions are started, committed, or rolled back explicitly, often via BEGIN/START TRANSACTION, COMMIT, and ROLLBACK.

Example: When a Spring Boot banking application transfers money, it debits the sender and credits the receiver inside one transaction; if the credit step fails after the debit succeeds, the whole transaction rolls back so no money simply disappears.

Code Example:

START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

Interview Tip: A concise interview answer is:

"A transaction groups multiple operations into one atomic unit that either fully commits or fully rolls back, which is what gives us the ACID guarantees. The classic example is a money transfer -- debiting one account and crediting another must succeed or fail together, otherwise you'd risk money vanishing if the second step failed after the first one committed."