Category: java
what is rolback
Published on 04 May 2026
Explanation
Rollback in a database is a transaction
control operation that undoes
all changes made
during the current transaction. It
restores the
database to its previous
consistent state before
the transaction began.
Code:
-- Example BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; ROLLBACK; -- Cancels the update
Explanation
Rollback is needed to maintain
data integrity
when an error occurs
during a transaction.
If any step fails,
rollback ensures that
partial changes are not saved.
Code:
-- Transfer example BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; -- Suppose error happens here ROLLBACK;
Explanation
It is also used to handle system
failures, application crashes, or
unexpected issues, ensuring
the database remains consistent.
Code:
-- If system crashes before commit, DB automatically rolls back incomplete transactions
Explanation
Rollback is a key part of ACID
properties (Atomicity),
which ensures that a transaction
is either fully completed or not applied
at all.
Code:
-- Atomic transaction BEGIN; INSERT INTO orders VALUES (1, 'item'); ROLLBACK; -- No data inserted
Explanation
Real-time usage: Rollback is commonly
used in
banking systems, e-commerce
transactions, and financial operations
where partial updates can lead to incorrect
data.
Code:
-- Safe transaction BEGIN; UPDATE wallet SET amount = amount - 500 WHERE user_id = 10; UPDATE wallet SET amount = amount + 500 WHERE user_id = 20; -- If any issue ROLLBACK; -- Else COMMIT;