Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 40002: Fix Transaction Integrity Violations

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 40002 (transaction integrity constraint violation) means a CHECK, NOT NULL, UNIQUE, or foreign key constraint failed during an INSERT, UPDATE, or DELETE. The transaction is rolled back automatically. To fix it, find the exact constraint that failed, correct the data, and re-run the statement. This guide walks you through diagnosing and resolving the error step by step.

What You'll Need

  • Access to the PostgreSQL database (psql, pgAdmin, or any SQL client).
  • Read permission on the table's schema (to view constraints).
  • The SQL statement that triggered the error, or the application logs showing it.
  • If the error comes from an application, the ability to modify that application's code or configuration.

Step-by-Step

  1. Read the full error message. PostgreSQL usually includes the constraint name and the table. For example: ERROR: new row for relation "orders" violates check constraint "orders_quantity_check". Write down the constraint name and table name. If the message is truncated, run the failing statement again in a terminal that shows the full error.
  2. Find the constraint definition. Run this query, replacing your_table with the actual table name:
    SELECT conname, pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = 'your_table'::regclass;
    This shows all constraints on the table and their definitions. Look for the one named in the error.
  3. Identify the violating data. If the constraint is a CHECK (e.g., CHECK (quantity > 0)), your data fails that condition. If it's UNIQUE, you're inserting a duplicate. If it's a foreign key, the referenced row doesn't exist. For NOT NULL, a required column is empty.
  4. Fix the data in the statement. Modify the INSERT or UPDATE to satisfy the constraint. For a CHECK constraint, change the value. For UNIQUE, pick a different value or remove the duplicate. For foreign keys, ensure the parent row exists first.
  5. If the data is already in the table and you're updating it: run a SELECT to view the current rows and identify which one violates the constraint. For example, if the constraint is CHECK (price >= 0), run SELECT * FROM your_table WHERE price < 0; to find bad rows.
  6. Correct the bad rows. Use an UPDATE to set the column to a valid value. For example: UPDATE your_table SET price = 0 WHERE price < 0; This fixes existing data without dropping the constraint.
  7. Re-run your original statement. After fixing the data, execute the original INSERT, UPDATE, or DELETE again. It should now succeed.
  8. If the error comes from an application: check the application's input validation. The app may be sending invalid data. Look at the form fields or API payload that map to the constrained columns. Add client-side validation to prevent invalid values from reaching the database.
  9. If the constraint itself is wrong: you may need to alter it. For example, a CHECK constraint that's too strict. Use ALTER TABLE your_table DROP CONSTRAINT constraint_name; then re-add it with corrected logic. Only do this if you're certain the constraint is incorrect, not the data.

Common Mistakes

  • Ignoring the constraint name. The error message always includes it. Skipping this step makes debugging much harder.
  • Dropping the constraint to make the error go away. This removes data integrity protection. Only drop a constraint if you're replacing it with a corrected version.
  • Forgetting that foreign key checks go both ways. If you delete a parent row that has children, you'll get a foreign key violation. You must delete or re-assign child rows first.
  • Assuming the error is in the current statement. In a transaction with multiple statements, the error may come from an earlier statement that was deferred. Use SET CONSTRAINTS ALL IMMEDIATE; to check earlier.
  • Not checking for NULL values. A NOT NULL constraint fails silently if you insert an empty string instead of NULL. Empty string is not NULL, so it passes—but a NULL column fails.

Tips

  • Use a transaction for multi-step fixes. Wrap your UPDATE statements in BEGIN; ... COMMIT; so you can roll back if something else fails.
  • Test with a SELECT first. Before running an UPDATE, run a SELECT with the same WHERE clause to see exactly which rows will change.
  • Use ON CONFLICT for upserts. If you're inserting data that might already exist, use INSERT ... ON CONFLICT (unique_column) DO UPDATE SET ... to handle duplicates gracefully.
  • Check the application's error handling. Many frameworks wrap database errors. The underlying PostgreSQL error is usually in the logs. Look for the SQLSTATE code 40002 in application logs.
  • Keep constraints simple. Complex CHECK constraints with multiple conditions are harder to debug. Split them into separate constraints so the error message names the exact failing one.

Troubleshooting

If the error persists after fixing the data:

  1. Re-check the constraint definition. You may have fixed the wrong column. Run the pg_get_constraintdef query again and verify the condition matches what you think.
  2. Check for deferred constraints. If a constraint is DEFERRABLE and set to DEFERRED, it's checked at COMMIT, not at statement end. Your statement may succeed, but the commit fails. Run SHOW constraint_exclusion; and check your transaction's isolation level.
  3. Look for triggers. A BEFORE INSERT or UPDATE trigger can modify data in a way that violates a constraint. Check SELECT tgname FROM pg_trigger WHERE tgrelid = 'your_table'::regclass; to list triggers.
  4. Verify the table's collation and data types. A UNIQUE constraint on a text column is case-sensitive by default. 'ABC' and 'abc' are different. If you need case-insensitive uniqueness, use citext or an expression index.

If the error occurs during a bulk load (COPY or pg_restore):

  1. Use COPY ... WITH (ON_ERROR_STOP false) to skip bad rows and see a summary at the end.
  2. For pg_restore, use --exit-on-error to stop at the first failure, then fix that row and re-run.
  3. Pre-validate the data using a staging table with no constraints, then run a query to find violations before inserting into the real table.

If you cannot identify the violating row:

  • For UNIQUE violations, run SELECT column_list, COUNT(*) FROM your_table GROUP BY column_list HAVING COUNT(*) > 1; to find duplicates.
  • For foreign key violations, check if the referenced table has the expected parent row. Sometimes the parent was deleted by another process.
  • Enable log_min_error_statement = on in postgresql.conf to log the full statement that failed, which may give more context.

Frequently Asked Questions

Can I bypass a constraint temporarily?

Yes, but only with superuser privileges and only for the session. Use SET session_replication_role = replica; to disable foreign key triggers, or ALTER TABLE ... DISABLE TRIGGER ALL; for specific tables. Re-enable them immediately after. This is risky and should not be used in production without a very good reason.

Does error 40002 roll back the entire transaction?

Yes. PostgreSQL aborts the current transaction when a constraint fails. Any prior statements in the same transaction are rolled back. You must issue ROLLBACK; or COMMIT; (which will fail) to end the aborted transaction before running new statements.

Why does my CHECK constraint fail on an empty string?

An empty string is a valid value in PostgreSQL. If your CHECK constraint is something like CHECK (name <> ''), it will reject empty strings. But if you have a NOT NULL constraint, an empty string passes because it's not NULL. You need both constraints or a CHECK that explicitly rejects empty strings.

Is error 40002 the same as a unique violation?

Not exactly. Unique violations have SQLSTATE 23505, which is a subset of integrity constraint violations. Error 40002 is the general class that includes CHECK (23514), NOT NULL (23502), foreign key (23503), and unique (23505) violations. The full SQLSTATE code in the error message tells you which one you have.

Can a constraint violation happen during a SELECT?

No. Constraints are only checked during INSERT, UPDATE, DELETE, or MERGE operations. A SELECT never triggers a constraint violation. If you see this error during a SELECT, it's likely coming from a trigger or a function called within the SELECT that modifies data.

How do I find all constraints on a table quickly?

Run \d your_table in psql. This shows all columns, indexes, and constraints. For a more detailed view, use SELECT conname, contype FROM pg_constraint WHERE conrelid = 'your_table'::regclass; where contype is 'c' for CHECK, 'f' for foreign key, 'p' for primary key, 'u' for unique.