← Database & SQL
MODULE 05 · DATABASE & SQL

Transaction

A transaction groups multiple database operations into one logical unit so they can succeed or fail together.

01 · What is it?

A transaction is a group of database operations treated as one complete unit.

The database commits the unit when every required operation succeeds. If an operation fails, the transaction can roll back the earlier changes.

02 · Think of it like…

Think of moving money between two bank accounts.

One account must be debited and the other must be credited. You do not want only one side to change, so both steps belong to the same all-or-nothing unit.

Debit Account ARemove the money.
Credit Account BAdd the money.
CommitKeep both changes.

03 · What does it do?

A transaction helps a database:

Group operationsKeep related changes together.
Commit changesMake successful work permanent.
Roll back changesUndo partial work after failure.
Protect consistencyPrevent incomplete business results.

04 · Where is it used?

Transactions are useful whenever one business action changes more than one piece of data.

Bank transfersDebit one account and credit another.
Order checkoutCreate an order and reserve inventory.
PaymentsRecord payment and update order status.
ReservationsBook a resource and mark it unavailable.
Account changesUpdate related user records together.
Batch updatesApply a set of changes as one unit.

05 · Example

Transfer 100 from one account to another

BEGIN;

UPDATE accounts
SET balance = balance - 100
WHERE id = 1;

UPDATE accounts
SET balance = balance + 100
WHERE id = 2;

COMMIT;

If either update fails, the application can roll back the transaction so the transfer does not leave the accounts in an incomplete state.

06 · How it connects

Request Backend Begin Transaction SQL Operations Commit or Rollback Response

The backend decides which operations belong together and reports whether the unit completed successfully.

07 · Do Not Confuse

Transaction

A unit that groups related database operations.

Query

One request to read or change database data.

Commit

Make a successful transaction permanent.

Rollback

Undo the changes made by a transaction.

09 · What to Remember

A transaction groups related database operations into one logical unit.

Commit makes the whole unit permanent; rollback undoes its changes after failure.

Use transactions when a business action must not leave partial data behind.

↑