Smart Systems for Home

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

PostgreSQL Error 23505: Unique Violation Fix

· 5 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 23505 means a unique constraint was violated: you tried to insert or update a row with a value that already exists in a column (or set of columns) that must be unique. The fix is to find the conflicting row, decide whether to update it, skip the insert, or change the incoming value, and then rerun your statement. This guide walks through diagnosing and resolving the error step by step, with practical SQL you can run in psql or any PostgreSQL client.

What You'll Need

  • Access to a PostgreSQL database with permission to run SELECT queries and, if needed, INSERT/UPDATE.
  • A SQL client such as psql, pgAdmin, DBeaver, or your application's database console.
  • The exact error message, which usually names the constraint (for example, duplicate key value violates unique constraint "users_email_key").
  • Basic familiarity with SELECT, INSERT, and UPDATE statements.

Step-by-Step

  1. Read the full error message. PostgreSQL includes the constraint name and often the key value. For example: ERROR: duplicate key value violates unique constraint "users_email_key" DETAIL: Key (email)=(alice@example.com) already exists. Note both the constraint and the value.
  2. Identify the table and columns. If the constraint name is not obvious, query the catalog: SELECT conname, pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = 'users_email_key'; This shows the table and the exact columns covered by the unique constraint.
  3. Find the existing row. Run a SELECT using the value from the error: SELECT * FROM users WHERE email = 'alice@example.com'; If the constraint covers multiple columns, include all of them in the WHERE clause.
  4. Decide the correct action. If the existing row is the one you meant to update, use UPDATE instead of INSERT. If the incoming row is a duplicate you want to ignore, use INSERT ... ON CONFLICT DO NOTHING. If you want to merge changes, use INSERT ... ON CONFLICT (email) DO UPDATE SET ....
  5. Apply the fix. For example, to update an existing record: UPDATE users SET name = 'Alice' WHERE email = 'alice@example.com'; To insert only if absent: INSERT INTO users (email, name) VALUES ('alice@example.com', 'Alice') ON CONFLICT (email) DO NOTHING;
  6. Verify. Re-run the original statement or check the row with SELECT to confirm the data is correct and no duplicate remains.

Common Mistakes

  • Assuming the error is about the primary key. Error 23505 can come from any unique constraint or unique index, not just the primary key. Always check the constraint name.
  • Ignoring multi-column constraints. A unique constraint on (tenant_id, email) will not conflict if the same email appears under a different tenant_id. Include all columns in your lookup.
  • Using ON CONFLICT without a conflict target. For a multi-column constraint, specify the columns: ON CONFLICT (tenant_id, email) DO NOTHING. Omitting the target only works for a single-column unique constraint or primary key.
  • Forgetting that NULLs are distinct. In PostgreSQL, multiple NULLs do not violate a unique constraint by default. If you need NULLs to be treated as equal, use a partial unique index or a CHECK constraint instead.
  • Editing data manually without a transaction. Wrap risky changes in BEGIN/COMMIT so you can roll back if something goes wrong.

Tips

  • Name your constraints clearly (for example, users_email_key) so error messages are self-explanatory.
  • Use ON CONFLICT for idempotent inserts in application code; it avoids race conditions between SELECT and INSERT.
  • When debugging, run SELECT * FROM table WHERE column = value; before attempting the insert to see what already exists.
  • Check for unique indexes as well as constraints: SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'users';
  • In application logs, capture the constraint name and key value; they are the fastest path to the conflicting row.

Troubleshooting

If the error persists after you think you have fixed it, work through these checks:

  • The constraint name is missing from the error. Some drivers truncate the message. Enable verbose error logging or run the statement directly in psql to see the full detail.
  • You cannot find the conflicting row. The value may contain trailing spaces or different case. Try SELECT * FROM users WHERE lower(email) = lower('alice@example.com'); or use LIKE with wildcards.
  • The insert still fails after ON CONFLICT. Confirm the conflict target matches the actual unique constraint columns. If the constraint is on an expression (for example, lower(email)), you must use the same expression in the conflict target.
  • You need to remove the duplicate but cannot delete. Check for foreign key references before deleting; you may need to update child rows first.
  • Permission errors. Ensure your role has INSERT/UPDATE privileges on the table and USAGE on the sequence if using serial columns.

Frequently Asked Questions

What does PostgreSQL error 23505 mean exactly?

It is the SQLSTATE code for unique_violation: a unique constraint or unique index was violated by an INSERT or UPDATE.

How do I find which constraint caused the error?

The error message usually names it. If not, query pg_constraint or pg_indexes for the table to list unique constraints and indexes.

Can I ignore the error and continue?

Yes, use INSERT ... ON CONFLICT DO NOTHING to skip the insert when a duplicate exists, or catch the error in your application code.

Why does ON CONFLICT not work for my multi-column constraint?

You must specify the conflict target columns exactly as defined in the constraint, for example ON CONFLICT (col1, col2) DO NOTHING.

Does a unique constraint allow multiple NULL values?

Yes, by default PostgreSQL treats NULLs as distinct, so multiple NULLs are allowed. Use a partial unique index if you need different behavior.

How can I prevent 23505 errors in application code?

Use upsert patterns (ON CONFLICT) or check for existence within a transaction, and handle the error gracefully by retrying or updating.