Sub topic 10
Wrapping changes in a transaction
This chapter assumes you can write basic SELECT queries with WHERE. It also assumes you know the customers and orders tables from earlier chapters, with their primary keys, foreign key, and defaults. You do not need prior experience with transactions.
What a transaction is
A transaction is a group of statements that the database treats as one unit of work. Either all of its changes become permanent, or none of them do. Until you finish the transaction, other sessions generally do not see your uncommitted changes. Your own session sees them immediately.
Two commands end a transaction:
COMMITmakes every change in the transaction permanent.ROLLBACKdiscards every change made since the transaction began.
Transactions give you two practical benefits when you change data:
- A safety net. You can run a risky UPDATE or DELETE, inspect the result, and undo it if it looks wrong.
- Atomicity. Several related changes succeed or fail together, so the data is never left half-updated.
Starting a transaction
The command that starts a transaction depends on the dialect.
| Dialect | Start | End |
|---|---|---|
| PostgreSQL | `BEGIN;` or `START TRANSACTION;` | `COMMIT;` or `ROLLBACK;` |
| MySQL (InnoDB) | `START TRANSACTION;` or `BEGIN;` | `COMMIT;` or `ROLLBACK;` |
| SQL Server | `BEGIN TRANSACTION;` | `COMMIT;` or `ROLLBACK;` |
| SQLite | `BEGIN;` | `COMMIT;` or `ROLLBACK;` |
If you do not start a transaction yourself, most databases run in autocommit mode. In autocommit mode each statement is its own transaction and is committed as soon as it succeeds. That is why a mistaken DELETE typed at a plain prompt cannot be undone: it was already committed.
Two dialect notes apply here:
- In MySQL, the transactional behavior described here needs a transactional storage engine such as InnoDB, which is the default in current versions.
- In PostgreSQL, SQLite, and SQL Server, DDL such as CREATE TABLE can usually be rolled back. In MySQL, most DDL statements cause an implicit commit, so do not count on rolling them back.
Preview, change, inspect, decide
A safe workflow for a risky change has four steps:
- Preview the rows with a SELECT that uses the same WHERE condition.
- Begin a transaction and run the change.
- Inspect the result with another SELECT.
- Run
COMMITif the result is right, orROLLBACKif it is not.
BEGIN;
DELETE FROM orders WHERE status = 'cancelled';
SELECT COUNT(*) FROM orders;
ROLLBACK; -- use COMMIT; instead to keep the deletionIn SQL Server, replace the first line with BEGIN TRANSACTION;.
The SELECT COUNT(*) runs inside the transaction, so it shows the table as it would look after the DELETE. After ROLLBACK, the cancelled orders are back exactly as they were.
Grouping related changes
Atomicity matters most when one business action needs more than one statement. Suppose a customer is closed and their open orders must be cancelled. If the first statement succeeds and the second fails, you would have inconsistent data.
BEGIN;
UPDATE orders
SET status = 'cancelled'
WHERE customer_id = 3
AND status = 'new';
UPDATE customers
SET status = 'inactive'
WHERE id = 3;
COMMIT;If anything goes wrong before COMMIT, a ROLLBACK leaves both tables unchanged. Readers in other sessions never see the state in which the orders are cancelled but the customer is still active, because they see either the data from before the transaction or the data after the commit.
What happens when a statement fails
A constraint violation, such as a foreign key error, makes one statement fail. What happens to the rest of the transaction depends on the database.
- PostgreSQL marks the whole transaction as aborted. Every later statement fails with an error such as "current transaction is aborted" until you issue
ROLLBACK. - MySQL and SQLite roll back only the failed statement by default. The transaction stays open, and earlier changes are still pending.
- SQL Server behavior depends on the error and on the
XACT_ABORTsetting. WithSET XACT_ABORT ON, most runtime errors roll back the entire transaction.
Because of these differences, the safe habit is to check for errors yourself. When any statement in a transaction fails, run ROLLBACK and start again, instead of committing whatever is left.
Savepoints
A savepoint is a named marker inside a transaction. You can roll back to the marker and keep the work done before it.
BEGIN;
UPDATE orders
SET status = 'shipped'
WHERE id = 100;
SAVEPOINT before_repricing;
UPDATE orders
SET total = total * 1.10
WHERE status = 'new';
-- The repricing looks wrong, so undo only that step.
ROLLBACK TO SAVEPOINT before_repricing;
COMMIT; -- order 100 is still marked 'shipped'SAVEPOINT and ROLLBACK TO SAVEPOINT work in PostgreSQL, MySQL, and SQLite. SQL Server uses SAVE TRANSACTION before_repricing; and ROLLBACK TRANSACTION before_repricing;. In PostgreSQL, rolling back to a savepoint also recovers a transaction that was aborted by an error after that savepoint.
Common errors and gotchas
- Forgetting to end the transaction. A transaction that stays open can hold locks on the rows you changed. Other sessions that try to change those rows will wait. Always finish with
COMMITorROLLBACK. - Closing the connection without committing. If a session disconnects with a transaction still open, the database rolls it back. Your changes are lost.
- Assuming autocommit is off. Many tools and drivers differ. Some begin a transaction implicitly, and others commit every statement. Check the setting in your client before relying on
ROLLBACK. - Keeping transactions long. Long transactions hold locks longer, block other work, and make conflicts more likely. Keep them short: run the preview first, then begin, change, check, and finish.
- Rolling back things that cannot be undone. A rollback undoes data changes in the database. It does not unsend an email or reverse a call to an external service made by your application.
- Sequence values. In PostgreSQL, a rollback does not give back values taken from a sequence, so a rolled-back INSERT can leave a gap in generated ids.
Locks and isolation in brief
While a transaction holds uncommitted changes, the database protects those rows with locks. If two sessions try to UPDATE the same row, the second waits until the first commits or rolls back. The isolation level controls what a session can see of other sessions' uncommitted and recently committed work. The default differs by product: PostgreSQL and SQL Server default to READ COMMITTED, and MySQL InnoDB defaults to REPEATABLE READ. For the statements in this tutorial, the practical rule is the same everywhere: keep transactions short and finish them promptly.
Exercises
Exercise
You run BEGIN;, then UPDATE orders SET status = 'shipped'; with no WHERE clause, and then notice the mistake. Which single command restores the data, and what must be true for it to work?
Show answer
Run ROLLBACK;. It works only because the UPDATE ran inside an open transaction that has not been committed. In autocommit mode, or after a COMMIT, the change is already permanent and ROLLBACK cannot undo it.
Exercise
Inside a transaction in MySQL, the second of three INSERT statements fails with a foreign key error. You then run the third INSERT and COMMIT;. Which inserts are saved? How would the result differ in PostgreSQL?
Show answer
In MySQL, only the failed statement is rolled back, so the first and third inserts are saved. In PostgreSQL, the failure aborts the whole transaction, the third INSERT is rejected, and the COMMIT ends up rolling the transaction back, so no inserts are saved.