duplicate key value violates unique constraint on type/function
This error occurs when you try to create a type, function, or other database object that already exists.
The already exists error for types and functions means the object name is taken.
Understanding the Error
ERROR: type "user_status" already exists
Or:
ERROR: function "calculate_total" already exists with same argument types
Common Causes
1. Creating Type Twice
SQL
2. Creating Function Twice
SQL
3. Migration Run Multiple Times
Schema migration script executed repeatedly.
How to Fix It
Solution 1: Use CREATE OR REPLACE for Functions
SQL
Solution 2: Drop Before Create for Types
SQL
Solution 3: Check Before Creating
SQL
Solution 4: Use DO Block for Conditional Creation
SQL
Solution 5: Alter Existing Type
SQL
Solution 6: Different Function Signature
SQL
Listing Existing Objects
SQL
Best Practices
- Use CREATE OR REPLACE for functions
- Check existence before creating types
- Use migrations that track what's been applied
- Drop carefully - types can't be dropped if used
- Version your objects if major changes needed