Diagnostic Queries
Symptoms
An ALTER TABLE … ADD CONSTRAINT tried to add a constraint whose name already exists on the relation. PostgreSQL raises SQLSTATE 42710 (duplicate_object).
- A constraint with that name already exists on the table.
- Constraint names are unique per relation.
- Common in re-run migrations.
What the server log shows
ERROR: constraint "orders_amount_check" for relation "orders" already exists
Why PostgreSQL raises this — what the manual says
the ALTER TABLE reference (ADD CONSTRAINT):
“This form adds a new constraint to a table using the same constraint syntax as CREATE TABLE, plus the option NOT VALID, which is currently only allowed for foreign-key, CHECK, and not-null constraints.”
Each relation’s constraint names must be unique. Adding one whose name is already present collides with the existing constraint, so PostgreSQL reports 42710.
Common causes
- Re-running a migration that adds the constraint.
- Two constraints sharing a name on the same table.
- An auto-generated name colliding with an explicit one.
How to fix it
- Drop the existing constraint first if you intend to redefine it.
- Use a unique constraint name.
- Guard the migration so it adds the constraint only when absent.
Related & next steps
Reference: PostgreSQL 18 — ALTER TABLE.
Thanks — noted. This helps keep the database accurate.