DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

ATOMICITY

In this task I am checking atomicity. That means a transaction should either fully complete or not happen at all.

First I check the initial data.

Query
select * from accounts;

Here I see Alice has 1000 and Bob has 500.

Now I perform a correct transfer.

Query
begin;

update accounts
set balance = balance - 300
where name = 'Alice';

update accounts
set balance = balance + 300
where name = 'Bob';

commit;

Here I deducted 300 from Alice and added 300 to Bob in the same transaction.

Now I check the data.

Query
select * from accounts;

Now Alice has 700 and Bob has 800. So both operations happened successfully.

Now I test what happens if something goes wrong after deducting money.

Query
begin;

update accounts
set balance = balance - 200
where name = 'Alice';

Now I introduce an error. I write a wrong column name.

update accounts
set bal = balance + 200
where name = 'Bob';

commit;

Here the second query fails because column bal does not exist.

Now I check the data again.

Query
select * from accounts;

I can see that Alice balance is still 700 and not reduced to 500.

This means even though the first update worked, it was not saved because the transaction failed.

The database automatically rolled back everything.

Now I try another case where I manually rollback.

Query
begin;

update accounts
set balance = balance - 100
where name = 'Alice';

rollback;

Now I check again.

Query
select * from accounts;

Alice balance is still 700. So rollback cancelled the change.

From this I understand atomicity clearly.

If all queries succeed and commit is given, changes are saved.
If any query fails, the entire transaction is cancelled.
No partial update will happen.

So in a wallet system, this is very important.

If money is deducted but not added to the receiver, it will cause loss.
Atomicity makes sure both actions happen together or not at all.

Finally what I understood is

Transaction works like one unit
Either everything inside it is saved
Or nothing is saved

This ensures safe money transfer without inconsistency.

Top comments (0)