Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

In PostgreSQL an insert in the middle of a transaction fails with a unique violation, and every following statement fails with 'current transaction is aborted, commands ignored until end of transaction block'. Show with SQL and with plain JDBC how a savepoint lets you continue the transaction.

PostgreSQL marks the whole transaction as failed after any error, and from then on it refuses every statement until we roll back. A savepoint is a named point inside the transaction that we can roll back to: we set it before the risky INSERT, and if the INSERT fails we run ROLLBACK TO SAVEPOINT, which undoes only that INSERT and clears the failed state, so the rest of the transaction continues and can commit. In JDBC the same steps are setSavepoint, rollback(savepoint) and releaseSavepoint.

Why this question is asked

Developers who come from MySQL or Oracle are often surprised by this PostgreSQL behaviour: one failed insert, caught and logged in Java, and suddenly every later statement fails too. Interviewers ask it to see whether we know why PostgreSQL does this and how to recover properly, in SQL and in plain JDBC, and whether we know a simpler alternative for the common case. In this answer, we will reproduce the error, fix it with a savepoint in SQL and then in JDBC, look at ON CONFLICT as a way to avoid the error altogether, and finish with the performance cost of savepoints.

1Reproducing the Aborted Transaction

A transaction groups statements so they commit or roll back together. In PostgreSQL, when any statement inside a transaction fails, the transaction enters an aborted state. The reason is safety: PostgreSQL cannot know which of our later statements depended on the failed one, so it refuses all of them until we decide what to do.

SQL
CREATE TABLE customer (id int PRIMARY KEY, name text);
INSERT INTO customer VALUES (1, 'Ana');
BEGIN;
INSERT INTO customer VALUES (2, 'Ben'); -- INSERT 0 1
INSERT INTO customer VALUES (1, 'Ana again');
-- ERROR: duplicate key value violates unique constraint "customer_pkey"
INSERT INTO customer VALUES (3, 'Cleo');
-- ERROR: current transaction is aborted, commands ignored until end of transaction block
COMMIT; -- ROLLBACK: Ben is gone too

Notice the last line. COMMIT on an aborted transaction does not commit; PostgreSQL answers ROLLBACK, and even the successful insert of Ben is lost. Only two things clear the aborted state: ROLLBACK of the whole transaction, or ROLLBACK TO SAVEPOINT to a savepoint set before the error.

2Fixing It With a Savepoint in SQL

A savepoint marks a point inside the transaction. Rolling back to it undoes everything after it and returns the transaction to a healthy state, while everything before it is kept.

SQL
BEGIN;
INSERT INTO customer VALUES (2, 'Ben'); -- INSERT 0 1
SAVEPOINT before_insert;
INSERT INTO customer VALUES (1, 'Ana again'); -- ERROR: duplicate key value ...
ROLLBACK TO SAVEPOINT before_insert; -- undoes only the failed insert
INSERT INTO customer VALUES (3, 'Cleo'); -- INSERT 0 1, the transaction is healthy again
COMMIT; -- Ben and Cleo are saved
-- on the success path we release the savepoint instead:
SAVEPOINT before_insert;
INSERT INTO customer VALUES (4, 'Dev'); -- INSERT 0 1
RELEASE SAVEPOINT before_insert; -- keeps the insert, forgets the savepoint
Step throughInserting one row safely inside a transaction
  1. SAVEPOINT before_insert
  2. INSERT the row
  3. Did it fail?
    YesROLLBACK TO SAVEPOINT before_insertNoRELEASE SAVEPOINT before_insert
  4. Continue with the next statementsthe transaction is healthy
  5. COMMITeverything not rolled back is saved

5 steps in order. Play them, or step through them one at a time.

RELEASE SAVEPOINT does not commit anything; the insert is still part of the outer transaction and becomes permanent only at COMMIT. Releasing simply frees the savepoint's resources once we no longer need to roll back to it.

3The Same Thing in Plain JDBC

JDBC exposes savepoints on the Connection. Autocommit must be off, because with autocommit on each statement is its own transaction and there is nothing to save a point in.

Java
try (Connection conn = dataSource.getConnection()) {
conn.setAutoCommit(false);
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO customer VALUES (?, ?)")) {
ps.setInt(1, 2); ps.setString(2, "Ben"); ps.executeUpdate(); // 1
Savepoint sp = conn.setSavepoint("before_insert");
try {
ps.setInt(1, 1); ps.setString(2, "Ana again"); ps.executeUpdate();
} catch (SQLException e) {
if (!"23505".equals(e.getSQLState())) throw e; // only swallow unique violations
conn.rollback(sp); // transaction usable again
}
conn.releaseSavepoint(sp);
ps.setInt(1, 3); ps.setString(2, "Cleo"); ps.executeUpdate(); // 1
conn.commit(); // Ben and Cleo saved
} catch (SQLException e) {
conn.rollback();
throw e;
}
}

Notice that we check the SQLSTATE, 23505 for a unique violation, before swallowing the error. Any other failure still rolls back the whole transaction. After rollback(sp) the savepoint still exists in PostgreSQL, so releasing it afterwards is valid on both paths.

4The Simpler Fix for Unique Violations: ON CONFLICT

When the error we expect is a duplicate key, the cleanest solution is not to cause an error at all. PostgreSQL's INSERT ... ON CONFLICT handles the conflict inside the statement.

SQL
INSERT INTO customer VALUES (1, 'Ana again') ON CONFLICT (id) DO NOTHING; -- INSERT 0 0
INSERT INTO customer VALUES (1, 'Ana B.') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name; -- INSERT 0 1

No error means no aborted transaction and no savepoint. The row count, 0 or 1, tells us whether the row was inserted, and DO UPDATE turns it into an upsert. Savepoints remain the tool for errors that ON CONFLICT cannot cover, such as check constraint or foreign key violations.

5The Cost of Savepoints

Each savepoint that writes data starts a subtransaction with its own transaction id. PostgreSQL caches up to 64 subtransaction ids per backend in shared memory; beyond that, the cache overflows and visibility checks by every session must consult the pg_subtrans structure on disk-backed pages, which has caused serious slowdowns on busy systems. So a batch of 100,000 rows with a savepoint per row inside one transaction is a bad idea. For large batches, prefer ON CONFLICT, validating data before inserting, or committing in smaller chunks.

6Follow-up questions

What does the PostgreSQL JDBC driver option autosave do?

With autosave=always, pgjdbc sets a savepoint before each statement and rolls back to it automatically if the statement fails, so the transaction never enters the aborted state; our code sees the exception and can carry on. With autosave=conservative it does this only for specific recoverable errors, such as a cached statement plan becoming invalid after a schema change. The default is never. It is convenient for code ported from other databases, but it adds a savepoint round trip per statement and the subtransaction costs described above, so I would not turn on always for heavy batch work.

Does MySQL need savepoints for this?

Not for most errors. In InnoDB a failed statement such as a duplicate key is rolled back by itself and the transaction continues, although a deadlock rolls back the whole transaction.

Is ROLLBACK TO SAVEPOINT the same as a nested transaction?

It behaves like one for rollback, but there is still only one real transaction: nothing after the savepoint is permanent until the outer COMMIT.

7Conclusion

In this answer, we saw that PostgreSQL aborts the whole transaction after any error and only ROLLBACK or ROLLBACK TO SAVEPOINT clears it. Setting a savepoint before the risky insert, rolling back to it on error and releasing it on success lets the transaction continue, in SQL and in JDBC with setSavepoint, rollback(sp) and releaseSavepoint. For duplicate keys, INSERT ... ON CONFLICT avoids the error entirely, and savepoints should not be created per row in large batches because of subtransaction overhead.

What to say in the interviewAbout 80 seconds aloud

Open with

PostgreSQL treats any error inside a transaction as making the whole transaction invalid, because it can't know which later statements depended on the failed one. So after the unique violation, every statement fails with current transaction is aborted, and even COMMIT just rolls back.

Then, if they want more

Only ROLLBACK or ROLLBACK TO SAVEPOINT clears that state. The fix is to set a savepoint before the risky insert. In SQL that's SAVEPOINT before_insert, then the INSERT; if it fails, ROLLBACK TO SAVEPOINT before_insert, which undoes only the insert and makes the transaction healthy again; if it succeeds, RELEASE SAVEPOINT. Then I continue and COMMIT.

In JDBC, I turn autocommit off, call conn.setSavepoint before the insert, catch the SQLException, check the SQL state is 23505 so I only swallow unique violations, call conn.rollback with the savepoint, release it, and commit at the end. For a duplicate key specifically, I'd rather use INSERT ... ON CONFLICT DO NOTHING, which avoids the error and the savepoint completely.

And I'd be careful with savepoints in big batches: each one is a subtransaction, and more than 64 in one transaction overflows PostgreSQL's subtransaction cache, which can slow down the whole server. So no savepoint per row for a large batch.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In PostgreSQL an insert in the middle of a transaction fails with a unique violation...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/8a1741973f/