violates foreign key constraint
This error occurs when you try to insert a row with a foreign key value that doesn't exist in the referenced table, or delete a row that is referenced by other tables.
The violates foreign key constraint error occurs when a foreign key relationship is broken.
Understanding the Error
ERROR: insert or update on table "orders" violates foreign key constraint "orders_user_id_fkey"
DETAIL: Key (user_id)=(999) is not present in table "users".
Or when deleting:
ERROR: update or delete on table "users" violates foreign key constraint "orders_user_id_fkey" on table "orders"
DETAIL: Key (id)=(1) is still referenced from table "orders".
Common Causes
1. Referencing Non-Existent Parent
SQL
2. Deleting Referenced Parent
SQL
3. Wrong Insert Order
SQL
How to Fix It
Solution 1: Insert Parent First
SQL
Solution 2: Use CASCADE on Delete
SQL
Solution 3: Use SET NULL on Delete
SQL
Solution 4: Delete Children First
SQL
Solution 5: Validate Before Insert
SQL
Solution 6: Defer Constraint Check
SQL
Best Practices
- Plan insert order - parent tables first
- Use CASCADE for tight parent-child relationships
- Use SET NULL when children can exist independently
- Validate references in application code
- Use transactions for multi-table operations