Back to all questions

ACID - Atomicity

Devs Hive

Devs Hive

Seen on interview: 2 users

Atomicity means that a transaction either completes in full or does not execute at all. If an error occurs during execution after the transaction has already changed something in the database, those changes НЕ be applied, and the state returns to the original one - this is called a ROLLBACK. If the transaction succeeds, a COMMIT is performed and the changes are applied to the database.

Let's look at an example

Here we deduct funds from the balance of user id=1 and credit them to the balance of user id=2. These are two separate operations, but if even one of them fails, it will break data integrity.

Since we wrapped these operations in a single transaction, according to Atomicity all of them must complete successfully. If the funds were withdrawn from id=1, but an error occurred while crediting them to id=2, a ROLLBACK will occur and the database state will be returned to BEGIN(the initial one).

BEGIN;

UPDATE accounts
SET balance = balance - 100
WHERE id = 1;

UPDATE accounts
SET balance = balance + 100
WHERE id = 2;

COMMIT;

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!