SQL Error Guide

SQL Error: Foreign Key Constraint (Fix + Examples)

Fix the SQL "insert or update on table violates foreign key constraint" error. Learn what causes it and see examples of how to resolve it.

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

  1. Insert parent records before child records.
  2. Use ON DELETE CASCADE or ON DELETE SET NULL in FK definition.
  3. Check that referenced value exists before inserting.
  4. 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:

Related Content

From Our Blog

Still stuck?

Practice SQL in our sandbox environment with instant error feedback.