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 purposetext
Error: CHECK constraint failed: balance >= 0The 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;| id | owner | balance |
|---|---|---|
| 1 | Ana | 100 |
| 2 | Bilal | 50 |
| 3 | Chloe | 40 |
| 5 | Eli | 20 |
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