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.

Introduction & Quick Summary
Every statement after a failed one returns the same error:
ERROR: current transaction is aborted, commands ignored until end of
transaction blockThe 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.
ROLLBACK; -- always allowed, always clears the aborted state
BEGIN; -- start again when you are readyWhen 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:
| State | Entered by | Allowed statements | COMMIT does |
|---|---|---|---|
| idle | connection start, COMMIT, ROLLBACK | everything | n/a |
| in transaction | BEGIN | everything | commits |
| failed | any statement error inside a transaction | ROLLBACK, ROLLBACK TO SAVEPOINT, COMMIT (as rollback) | rolls back |
| aborted subtransaction | error inside a savepoint | same as failed, scoped | n/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:
| Action | Clears the state | Keeps earlier work | Use when |
|---|---|---|---|
ROLLBACK | yes | no | the whole transaction is invalid |
ROLLBACK TO SAVEPOINT s | yes | yes, up to s | one statement was optional |
COMMIT | yes, as a rollback | no | never; use ROLLBACK |
| disconnecting | yes | no | the connection is unusable |
\set ON_ERROR_ROLLBACK on | automatically per statement | yes | interactive psql only |
Error codes that look related and mean something else:
| SQLSTATE | Condition | Relationship to 25P02 |
|---|---|---|
| 25P02 | in_failed_sql_transaction | the state this article is about |
| 25P03 | idle_in_transaction_session_timeout | the server terminated a stuck transaction |
| 40001 | serialization_failure | a retry is correct; the transaction rolled back itself |
| 40P01 | deadlock_detected | same: retry the whole transaction |
| 23505 | unique_violation | often the first error behind a 25P02 |
| 23503 | foreign_key_violation | same |
Which layer produces the message:
| Layer | Typical cause | Fix |
|---|---|---|
psql interactive | a typo in statement two | \set ON_ERROR_ROLLBACK on |
| psycopg 2/3, autocommit off | exception caught, connection reused | conn.rollback() in the handler |
SQLAlchemy Session | session not rolled back after an error | session.rollback() before reuse |
Django atomic block | IntegrityError caught inside the atomic block | catch it outside, or use a nested atomic |
| PL/pgSQL | exception block without a handler | the BEGIN ... EXCEPTION block is itself a subtransaction |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. psycopg: roll back in the exception handler
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
raiseThe 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
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 rollbackWithout 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
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:
passDjango 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
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 harmlessRetrying 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 documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
pg_dump: server version mismatch, aborting because of server version
pg_dump refuses to read a newer server. Install a matching client, run it from a container or the server host, and match pg_restore too.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.