Part 12 / Topic 2 of 9
BEGIN, COMMIT, ROLLBACK, SAVEPOINT
Without BEGIN, every statement is its own tiny transaction (autocommit). BEGIN opens a grouping; COMMIT lands it; ROLLBACK discards it. New here: SAVEPOINT — a bookmark inside a transaction, so one failed step needn't cost the whole batch:
BEGIN;
CREATE TABLE import_log (note text);
INSERT INTO import_log VALUES ('step 1: header checked');
SAVEPOINT before_risky_step;
INSERT INTO import_log VALUES ('step 2: exploded'::integer::text);
ROLLBACK TO SAVEPOINT before_risky_step;
INSERT INTO import_log VALUES ('step 2 skipped, continuing');
COMMIT;
SELECT * FROM import_log;
BEGIN
CREATE TABLE
INSERT 0 1
SAVEPOINT
ERROR: invalid input syntax for type integer: "step 2: exploded"
LINE 1: INSERT INTO import_log VALUES ('step 2: exploded'::integer::...
^
ROLLBACK
INSERT 0 1
COMMIT
note
----------------------------
step 1: header checked
step 2 skipped, continuing
(2 rows)
The cast blew up, ROLLBACK TO SAVEPOINT unwound only step 2, and the transaction carried on to a successful COMMIT. This matters doubly because of a Postgres rule worth knowing early: after any error, a transaction is aborted — every further statement fails with current transaction is aborted until you ROLLBACK (entirely, or to a savepoint). Batch jobs that must survive bad rows wrap each risky step in a savepoint.
🧪 Quick quiz — answer from memory, then check.
- After an error mid-transaction, what do further statements do?
- What does
ROLLBACK TO SAVEPOINT skeep, and what does it discard?
Show the answers
- They all fail ("current transaction is aborted") until a ROLLBACK — full or to a savepoint.
- Keeps everything before the savepoint (transaction still open); discards everything after it.
Done here? The practice set for Part 12 — 6 exercises with solutions — is on the part page.