SQLSTATE 40002 ERROR Class 40: Transaction Rollback

transaction_integrity_constraint_violation Transaction Integrity Constraint Violation — SQLSTATE 40002

SQLSTATE 40002 (transaction_integrity_constraint_violation): The transaction was rolled back due to a serialization or deadlock conflict.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

Symptoms

The server reports SQLSTATE 40002 (transaction_integrity_constraint_violation), a condition in the Transaction Rollback class.

  • The error is written to the server log and returned to the client carrying SQLSTATE 40002.
  • Any driver (libpq, JDBC, psycopg, npgsql, pgx) surfaces this code in its error object so you can branch on it programmatically.
  • PL/pgSQL can trap it by name: EXCEPTION WHEN transaction_integrity_constraint_violation THEN.

Environment

Severity: ERROR  |  PostgreSQL versions: 12, 13, 14, 15, 16, 17

Reproduce with the exact statement and read the full message in the server log (raise log_min_messages / set log_min_error_statement for more context).

Root Cause

40002 belongs to Class 40 — Transaction Rollback. In this class, the transaction was rolled back due to a serialization or deadlock conflict.

The first two characters (40) identify the error class, so application code can match the whole class via 40000 when the specific code is not needed.

Diagnostic Queries

Recovery

Retry the whole transaction with exponential backoff (this is expected under concurrency), keep transactions short, and reduce contention with consistent lock ordering and indexes on foreign keys.

Reference: PostgreSQL error codes — Class 40 (Transaction Rollback).

Was this helpful?