← Back to SQL, page 12

sql-0234 · Medium mid

What is a savepoint, and how would you use one to keep a batch going when one row fails?

A savepoint marks a point inside a transaction. ROLLBACK TO name undoes only the work after that point, and the outer transaction continues. In a batch import, set a savepoint before each row, roll back to it when the row fails, log the failure, and commit the good rows at the end.

Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
sql
BEGIN;
SAVEPOINT row1;
INSERT INTO accounts VALUES (3, 'Chloe', 40);
RELEASE row1;
SAVEPOINT row2;
INSERT INTO accounts VALUES (4, 'Dev', -5);
-- error on purpose
text
Error: CHECK constraint failed: balance >= 0

The second row breaks the CHECK. The program rolls back to its savepoint (shown as the next step here) and moves on:

sql
ROLLBACK TO row2;
RELEASE row2;
SAVEPOINT row3;
INSERT INTO accounts VALUES (5, 'Eli', 20);
RELEASE row3;
COMMIT;
SELECT 'committed' AS status;
status
committed
sql
SELECT id, owner, balance FROM accounts ORDER BY id;
idownerbalance
1Ana100
2Bilal50
3Chloe40
5Eli20

Both good rows were committed, and the bad one left nothing behind. In PostgreSQL this pattern is the standard way to continue after an error, since otherwise the whole transaction is aborted. RELEASE name discards a savepoint without undoing anything.

Savepoints have a cost per use; for very large imports, validating rows first or loading into a staging table is faster.

sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);

-- error on purpose
BEGIN;
SAVEPOINT row1;
INSERT INTO accounts VALUES (3, 'Chloe', 40);
RELEASE row1;
SAVEPOINT row2;
INSERT INTO accounts VALUES (4, 'Dev', -5);

ROLLBACK TO row2;
RELEASE row2;
SAVEPOINT row3;
INSERT INTO accounts VALUES (5, 'Eli', 20);
RELEASE row3;
COMMIT;
SELECT 'committed' AS status;

SELECT id, owner, balance FROM accounts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SAVEPOINT marks a point inside a transaction
  • ROLLBACK TO undoes work after that point only
  • RELEASE removes the savepoint and keeps the work
  • Lets a batch skip bad rows and commit the rest

Common mistakes

  • Rolling back the whole batch because of one bad row
  • Forgetting that ROLLBACK TO keeps the transaction open

Follow-ups

  • How would you report which rows failed?
  • When is a staging table better?

Tips

  • Describe the per-row savepoint loop