Transactions

Draft

A transaction groups statements into one unit of work. You either commit the whole change or roll it back.

Commit a transfer

COMMIT makes every statement in the transaction durable together.

BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 1000 WHERE name = 'Ada';
UPDATE accounts SET balance_cents = balance_cents + 1000 WHERE name = 'Grace';
COMMIT;
SELECT name, balance_cents FROM accounts ORDER BY name;
Loading plan...

Rollback a transfer

ROLLBACK throws away the changes made inside the transaction.

BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 1000 WHERE name = 'Ada';
UPDATE accounts SET balance_cents = balance_cents + 1000 WHERE name = 'Grace';
ROLLBACK;
SELECT name, balance_cents FROM accounts ORDER BY name;
Loading plan...

Try Yourself

Loaded Database:transactions.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 1 DONE
1.In a transaction, add 500 cents to both accounts, commit, then select balances.

What We Learned

  • BEGINstarts a transaction.
  • COMMITkeeps the transaction's changes.
  • ROLLBACKdiscards the transaction's changes.
  • Atomicitymeans related changes succeed or fail as a unit.