DEV Community

Mohith
Mohith

Posted on

Atomicity

Atomicity means a transaction is treated as one complete action, not as separate steps. All operations inside the transaction must succeed together. If any step fails, the entire transaction is cancelled, and the database returns to its original state. This prevents partial updates and keeps the data consistent.

A simple real-world example is a wallet transfer. When I transfer money, I expect it to behave as one single action. Either the full amount is deducted from the sender and added to the receiver, or nothing happens at all. If something fails in the middle, the system rolls everything back so no money is lost and no partial update occurs.

BEGIN;

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

-- Intentional error (Charlie does not exist)
UPDATE accounts
SET balance = balance + 200
WHERE name = 'Charlie';

COMMIT;

In this case, the second update fails because the user Charlie does not exist. Since one step in the transaction fails, the entire transaction is cancelled. The database performs a rollback, and the commit does not take effect.

ROLLBACK;

After the rollback, Alice’s balance remains unchanged, and no partial deduction occurs. This behavior demonstrates Atomicity — either all operations succeed, or none of them are applied.

Top comments (0)