Skip to content

Foreign Key Constraint Violation

Error message

                violates foreign key constraint
              

Quick summary

You tried to insert or update a row with a foreign key value that does not match any primary key in the referenced table.

Why this happens

  • Inserting a child record before the parent record exists

  • Deleting a parent record that still has child records referencing it

  • Setting a foreign key to a value that does not exist in the parent table

  • Typo in the foreign key value

Minimal example

✗ Broken code
INSERT INTO orders (id, user_id, total) VALUES (1, 999, 50.00);
-- But user 999 does not exist
✓ Fixed code
-- Create the user first
INSERT INTO users (id, name) VALUES (999, 'Ada');
INSERT INTO orders (id, user_id, total) VALUES (1, 999, 50.00);

The order referenced a non-existent user. Creating the user first satisfies the foreign key constraint.

How to diagnose

  • Read the error to identify which foreign key constraint was violated

  • Check if the referenced parent record exists: SELECT * FROM parent_table WHERE id = value

  • Check if child records exist before deleting a parent

How to fix

  • Create the parent record first, then the child record

  • Delete or reassign child records before deleting the parent

  • Use ON DELETE CASCADE if child records should be removed automatically

  • Correct the foreign key value to reference an existing record

How to prevent

  • Always create parent records before child records

  • Use cascading deletes or updates where appropriate

  • Validate foreign key references in your application before inserting

Related Resources

Related Glossary

Related Lessons

← Back to language