SQLCriticalRuntime ErrorJune 15, 2026

Runtime Error

Cannot execute query: Cannot add or update a child row: a foreign key constraint fails

What This Error Means

This error occurs when attempting to insert, update, or delete a record in a table that has a foreign key constraint, but the referenced record does not exist in the referenced table.

Why It Happens

This error typically happens when there's a mismatch in the data between the parent table and the child table, such as inserting a record with a foreign key that does not exist in the referenced table, or deleting a record from the parent table that still has related records in the child table.

How to Fix It

  1. 1To fix this error, you need to either update the child table to reference a valid record in the parent table, or delete the record from the child table that's causing the constraint to fail. Additionally, you can also consider adding a trigger to automatically update the child table when the parent record is updated or deleted.

Example Code Solution

❌ Before (problematic code)
SQL
INSERT INTO orders (order_id, customer_id) VALUES (1, 10);
✅ After (fixed code)
SQL
INSERT INTO orders (order_id, customer_id) VALUES (1, 10);
UPDATE customers SET customer_id = 10 WHERE customer_name = 'John Doe';

Fix for Cannot execute query: Cannot add or update a child row: a foreign key constraint fails

Related SQL Errors

Related SQL Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error