We use cookies to enhance your experience on the site
CodeWorlds

Transactions - all or nothing

A transaction is a group of operations that the database treats as one indivisible whole. Either all of them run, or - if something goes wrong - none of them do.

The Keeper's three spells

  • START TRANSACTION (or
    BEGIN
    ) - opens a transaction. From this moment the changes are "on hold".
  • COMMIT - confirms. All changes become permanent and visible to others.
  • ROLLBACK - undoes. The database returns to the state before
    START TRANSACTION
    , as if nothing happened.

Example: a safe loan

1START TRANSACTION;
2
3INSERT INTO wypozyczenia (ksiazka_id, czytelnik_id, data_wypozyczenia)
4VALUES (1, 1, '2026-06-22');
5
6UPDATE ksiazki SET dostepna = 0 WHERE id = 1;
7
8COMMIT;

These two operations will happen together. If the second one fails, the Keeper gives the order:

1ROLLBACK;

and even the first

INSERT
is wiped out. The book will never hang in an in-between state.

When to use transactions?

Whenever several changes must be consistent together: a transfer (take from one account, add to another), a loan, deleting a reader together with their history. This is your shield against inconsistency.

Go to CodeWorlds