Inserting, updating, or deleting a row that would break a referential integrity rule.
A foreign key constraint violation occurs when a database operation would break the referential integrity between two tables. This can happen in two ways: inserting a row with a foreign key value that doesn't exist in the referenced table, or deleting/updating a referenced row that still has dependent rows in child tables.
Causes: inserting a child record before the parent exists, deleting a parent record that still has related child records, referencing a wrong ID (typo), loading data in the wrong order during imports, or cascading updates not being set up properly.
1CREATE TABLE departments (2 id INT PRIMARY KEY,3 name VARCHAR(100) NOT NULL4);5 6CREATE TABLE employees (7 id INT PRIMARY KEY,8 name VARCHAR(100),9 department_id INT REFERENCES departments(id)10);11 12-- INSERT with non-existent department_id fails13INSERT INTO employees (id, name, department_id)14VALUES (1, 'Alice', 99); -- department_id=99 doesn't exist!15-- ERROR: insert or update on table "employees" violates foreign key constraint1-- Fix 1: Insert parent record first2INSERT INTO departments (id, name) VALUES (99, 'Engineering');3INSERT INTO employees (id, name, department_id) VALUES (1, 'Alice', 99); -- Now OK4 5-- Fix 2: For deletes, set up CASCADE or SET NULL behavior6CREATE TABLE employees (7 id INT PRIMARY KEY,8 name VARCHAR(100),9 department_id INT REFERENCES departments(id)10 ON DELETE SET NULL -- Set to NULL when dept is deleted11 ON UPDATE CASCADE -- Update automatically when dept ID changes12);13 14-- Fix 3: Delete child records before parent15DELETE FROM employees WHERE department_id = 99;16DELETE FROM departments WHERE id = 99;Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The `employees.department_id` column references `departments.id`. Department `99` doesn't exist in the `departments` table. The database enforces referential integrity and rejects the insert. You must always insert the referenced (parent) row before inserting the referencing (child) row.