DEV Community

Ashiq Omar
Ashiq Omar

Posted on

ATOMICITY

Let me explain the transaction working using accounts table
First we have an accounts table with balance for each user
Alice = 1000
Bob = 500
since we are doing money transfer we need to deduct from one and add to another. Now we start transaction to transfer 200 from Alice to Bob.

Lets see the commands:

BEGIN;

UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';

UPDATE accounts
SET balance = balance + 200
WHERE name = 'Bob';

COMMIT; 
Enter fullscreen mode Exit fullscreen mode

As we see there are no issues and the transaction is committed.
Now: the values will be
Alice → 800
Bob → 700

Now we try with an error in between:

BEGIN;

UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
UPDATE accounts
SET balance = balance + 2000o
WHERE name = 'Bob';

ROLLBACK;
Enter fullscreen mode Exit fullscreen mode


sql
since second query has error.so transaction fails.After this failed transaction:
Alice = 1000
Bob = 500
even though money was deducted first rollback will undo it so no change happens.

Now we try another error case.

BEGIN;

UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';

 wrong table
SELECT * FROM wrong_table;

ROLLBACK;
Enter fullscreen mode Exit fullscreen mode

Final result:
Alice = 1000
Bob = 500
database does not allow partial updates.

The main concept is:
Transaction will happen fully or fail fully but there is no partial process of success or fail but we can achieve this by using savepoints

Top comments (0)