Getting the "insert or update on table violates foreign key constraint" error in SQL? This guide explains what causes this error and how to fix it with practical examples.
What Causes This Error?
The foreign key constraint error (23503) occurs when:
- Inserting row with non-existent foreign key value
- Deleting parent row that has child records
- Updating primary key that is referenced elsewhere
- Order of insert operations incorrect
How to Fix It
- Insert parent records before child records.
- Use ON DELETE CASCADE or ON DELETE SET NULL in FK definition.
- Check that referenced value exists before inserting.
- Use deferred constraints for complex transactions.
Example: Wrong vs Correct
❌ Code That Causes the Error
INSERT INTO orders (customer_id, product_id) VALUES (999, 1); -- Error: customer_id 999 does not exist in customers table
✅ Corrected Code
-- First verify customer exists: INSERT INTO customers (id, name) VALUES (999, 'New Customer'); INSERT INTO orders (customer_id, product_id) VALUES (999, 1); -- Correct: parent record exists
Quick Checklist
- [ ] Verify column/table names are spelled correctly
- [ ] Check data types match expected values
- [ ] Review query syntax for missing keywords
- [ ] Ensure referenced tables/columns exist
Related SQL Errors
If you're troubleshooting SQL errors, you might also encounter: