COMMIT keeps the changes of a transaction. ROLLBACK throws them away.
| End the transaction with | Changes since BEGIN | Other sessions |
|---|---|---|
COMMIT; | kept | see the changes |
ROLLBACK; | undone | never see them |
ROLLBACK ends the transaction. Every row is the same as before BEGIN. Other sessions never saw the changes.
A safety net for risky changes
Chapter 6 showed what an UPDATE without WHERE does: it changes every row. Inside a transaction, you can still undo it:
BEGIN;
UPDATE accounts SET balance = 0; -- the WHERE is missing
SELECT * FROM accounts; -- every balance is 0
ROLLBACK; -- every balance is backUse this order for any change that you are not sure about:
BEGIN;- The change.
- A
SELECTto check the rows. COMMIT;if the rows are correct,ROLLBACK;if they are not.
After COMMIT, it is too late
ROLLBACK undoes only the open transaction. After COMMIT, there is no open transaction:
WARNING: there is no transaction in progressThe committed change stays. To undo it, you must write a new statement that changes the rows back.
Tables too
In PostgreSQL, CREATE TABLE, ALTER TABLE and DROP TABLE are also part of the transaction. ROLLBACK undoes them too.