Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Postgres 25P02: current transaction is aborted

25P02 means an earlier statement failed and PostgreSQL refuses the rest. Find the first error, roll back, and wrap optional work in a savepoint.

~5 min readSQL
#postgresql#transactions#savepoints#25p02
Bold white headline reading TRANSACTION ABORTED with a Postgres transaction crate sealed behind an amber rollback gate on the right.

Introduction & Quick Summary

Every statement after a failed one returns the same error:

code
ERROR: current transaction is aborted, commands ignored until end of transaction block

The first error is the real one, and it has already scrolled past. PostgreSQL does not silently continue after a statement fails inside an explicit transaction: it marks the whole transaction aborted, refuses all further statements, and waits for ROLLBACK or COMMIT. COMMIT in that state performs a rollback and reports ROLLBACK, which is a second surprise.

Quick answer: end the transaction, then fix the statement that actually failed.

sql
ROLLBACK; -- always allowed, always clears the aborted state BEGIN; -- start again when you are ready

When the failure is expected and you want to keep the surrounding work, wrap only the risky part in a savepoint:

BEGIN; INSERT INTO orders (id) VALUES (1); SAVEPOINT before_optional; INSERT INTO audit_log (order_id, note) VALUES (999, 'orphan'); -- FK error ROLLBACK TO SAVEPOINT before_optional; UPDATE orders SET status = 'open' WHERE id = 1; -- still in the transaction COMMIT;

In application code the same pattern is what makes a "try this, ignore the error" path safe: a connection in autocommit-off mode enters the aborted state on any error, and every later query on that connection fails until it is rolled back.

Core Mechanics, Signatures & Reproducible Setup

PostgreSQL's transaction state machine has four states, and 25P02 is the third:

StateEntered byAllowed statementsCOMMIT does
idleconnection start, COMMIT, ROLLBACKeverythingn/a
in transactionBEGINeverythingcommits
failedany statement error inside a transactionROLLBACK, ROLLBACK TO SAVEPOINT, COMMIT (as rollback)rolls back
aborted subtransactionerror inside a savepointsame as failed, scopedn/a

Reproduce it in psql, including a savepoint escape that keeps the first insert:

BEGIN; CREATE TEMP TABLE t (id int PRIMARY KEY); INSERT INTO t VALUES (1); INSERT INTO t VALUES (1); -- ERROR: duplicate key ... 23505 SELECT * FROM t; -- ERROR: current transaction is aborted ... ROLLBACK; -- clears the state BEGIN; INSERT INTO t VALUES (1); SAVEPOINT s1; INSERT INTO t VALUES (1); -- fails ROLLBACK TO SAVEPOINT s1; SELECT count(*) FROM t; -- 1: the first insert survived COMMIT;

psql has a convenience for the interactive case: \set ON_ERROR_ROLLBACK on wraps each statement in an implicit savepoint, so a failed statement does not poison the session. It is a psql feature, not a server one.

Key Comparison Table

Recovery options, and what each preserves:

ActionClears the stateKeeps earlier workUse when
ROLLBACKyesnothe whole transaction is invalid
ROLLBACK TO SAVEPOINT syesyes, up to sone statement was optional
COMMITyes, as a rollbacknonever; use ROLLBACK
disconnectingyesnothe connection is unusable
\set ON_ERROR_ROLLBACK onautomatically per statementyesinteractive psql only

Error codes that look related and mean something else:

SQLSTATEConditionRelationship to 25P02
25P02in_failed_sql_transactionthe state this article is about
25P03idle_in_transaction_session_timeoutthe server terminated a stuck transaction
40001serialization_failurea retry is correct; the transaction rolled back itself
40P01deadlock_detectedsame: retry the whole transaction
23505unique_violationoften the first error behind a 25P02
23503foreign_key_violationsame

Which layer produces the message:

LayerTypical causeFix
psql interactivea typo in statement two\set ON_ERROR_ROLLBACK on
psycopg 2/3, autocommit offexception caught, connection reusedconn.rollback() in the handler
SQLAlchemy Sessionsession not rolled back after an errorsession.rollback() before reuse
Django atomic blockIntegrityError caught inside the atomic blockcatch it outside, or use a nested atomic
PL/pgSQLexception block without a handlerthe BEGIN ... EXCEPTION block is itself a subtransaction

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. psycopg: roll back in the exception handler

python
import psycopg with psycopg.connect("...", autocommit=False) as conn: with conn.cursor() as cur: cur.execute("INSERT INTO orders (id) VALUES (%s)", (1,)) try: cur.execute("INSERT INTO orders (id) VALUES (%s)", (1,)) except psycopg.errors.UniqueViolation: conn.rollback() # without this, every later query fails with 25P02 raise

The context manager rolls back on an exception that escapes it, but a caught exception does not roll back anything — the connection is still in the failed state when the next query runs. conn.rollback() is the missing line in most reports of this error from Python services.

2. SQLAlchemy sessions and the "pending rollback" state

python
from sqlalchemy import text with Session(engine) as session: try: session.execute(text("INSERT INTO t (id) VALUES (1)")) except IntegrityError: session.rollback() # clears the failed transaction session.execute(text("SELECT 1")) # works only after the rollback

Without it SQLAlchemy raises PendingRollbackError before the driver ever sees a statement, which is the ORM's way of saying the same thing.

3. Django: atomic swallows the recovery point

python
from django.db import IntegrityError, transaction # broken: the exception is caught inside the atomic block with transaction.atomic(): Order.objects.create(id=1) try: Order.objects.create(id=1) except IntegrityError: pass # transaction is now broken; next query raises 25P02 # fixed: inner atomic creates a savepoint with transaction.atomic(): Order.objects.create(id=1) try: with transaction.atomic(): # savepoint Order.objects.create(id=1) except IntegrityError: pass

Django documents this exact caveat: catching a database exception inside atomic without an inner block leaves the transaction unusable, and TransactionManagementError or the raw PostgreSQL message follows.

4. PL/pgSQL exception blocks are subtransactions

CREATE OR REPLACE FUNCTION try_insert() RETURNS void AS $$ BEGIN INSERT INTO t VALUES (1); EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'duplicate ignored'; END; $$ LANGUAGE plpgsql;

A BEGIN ... EXCEPTION block in PL/pgSQL wraps the body in a subtransaction, so an error inside it rolls back only that block and the caller's transaction survives. That is why the same statement is fatal in a client-side transaction and harmless inside a function — and why functions that swallow errors hide the aborted-state problem from the caller entirely.

5. Poolers and idle in transaction

SELECT pid, state, now() - state_change AS idle_for, query FROM pg_stat_activity WHERE state LIKE 'idle in transaction%' ORDER BY idle_for DESC;

A pooled connection left in the failed state is returned to PgBouncer in transaction mode and handed to the next request, which then gets 25P02 without having done anything wrong. idle_in_transaction_session_timeout (since 9.6) bounds the damage:

ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s'; SELECT pg_reload_conf();

PostgreSQL 17 adds transaction_timeout, which bounds the total duration of a transaction rather than the idle period; both are worth setting for an application server that is not careful.

6. Retrying correctly

python
for attempt in range(3): try: with conn.transaction(): do_work(conn) break except (psycopg.errors.SerializationFailure, psycopg.errors.DeadlockDetected): continue # the transaction was rolled back by the server except psycopg.errors.InFailedSqlTransaction: conn.rollback() # should not happen with the block above, but harmless

Retrying 25P02 itself is never right: the state is cleared by a rollback, not by re-running the statement. Retrying 40001 or 40P01 is right, because the server has already rolled back.

Common Compilation/Runtime Mistakes & Version Gotchas

Retrying the failed statement. The transaction is dead; only ROLLBACK revives the connection. A retry loop that does not roll back first produces the same error three times and looks like a connection failure.

Reading the wrong error. The 25P02 is a consequence. Search the server log for the statement that preceded it in the same pid.

Assuming the connection is broken. It is not. After ROLLBACK the same connection serves queries normally, which is why reconnecting hides the real problem and adds churn.

Version differences. idle_in_transaction_session_timeout exists since 9.6 and transaction_timeout since 17; on older servers an idle connection stays in the failed state indefinitely. Savepoints cost a subtransaction ID, and before PostgreSQL 17 an excessive number of subtransactions in one transaction could overflow the 64-bit pg_subtrans cache and slow the whole cluster — a reason to avoid putting a savepoint around every loop iteration. psql gained ON_ERROR_ROLLBACK long ago and it is still client-side only, so it never appears in a driver-based test.

Confirming the state instead of guessing. SELECT txid_current_if_assigned() and pg_stat_activity.state tell you whether a session is inside a transaction and whether it is failing, and \echo :AUTOCOMMIT in psql shows the client mode. When a long psql session is involved, the SQL formatter makes the statement that failed easier to read, and the schema designer helps verify that the constraint being violated is the one you expect.

Reference material: PostgreSQL error codes and SAVEPOINT.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.