Shanraq.org Shanraq.org
Transactions and UPDATE: change everything or nothing
IT

SQL: a family budget without guesswork Lesson 2 of 4

Transactions and UPDATE: change everything or nothing

Make safe corrections and treat a transfer as one atomic database operation.

Why this matters

A transfer needs at least two related records. If debit succeeds and credit fails, the database invents or loses money.

Image. A transaction is a lock with two gates: either the boat passes completely or boat and water return to their initial state.

See the whole thing first

BEGIN IMMEDIATE;

UPDATE transactions
SET note = 'Utilities and rent'
WHERE id = 2;

SELECT changes() AS changed_rows;
COMMIT;

Explanation

ACID summarises atomicity, consistency, isolation, and durability; exact guarantees vary by DBMS. Before UPDATE or DELETE, run SELECT with the same WHERE and then check the affected-row count. COMMIT makes changes durable; ROLLBACK cancels unfinished work; SAVEPOINT rolls back part. A transfer between your accounts is not household spending.

Lesson map

Transactions and UPDATE

Say it in your own words

  1. What is atomicity?
  2. How do you test WHERE before changing data?
  3. Why is an internal transfer not spending?

Exercise

Inside a transaction set Transport’s limit to 40,000 tenge, read it, ROLLBACK, and confirm the old value returned.

Where this fits in the project

Every related budget change is atomic and can be cancelled before commit.

Answers

Show the answers
BEGIN;
UPDATE categories SET monthly_limit_tiyn=4000000 WHERE name='Transport';
SELECT monthly_limit_tiyn FROM categories WHERE name='Transport';
ROLLBACK;
SELECT monthly_limit_tiyn FROM categories WHERE name='Transport';

Sources

If you have found a mistake or a typo in this article, tell us about it

Check your exercise

Solve it and run it in VS Code first — the editor shows the mistake where you made it. Paste the finished solution here. A model reads it: it will point at the mistake but will not hand you the answer.

Sign in to have it checked. Sign in

Comments (0)

No comments yet. Be the first.