Why it happens: FOREIGN KEY blocks an insert or delete
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
INSERT INTO customers (id, name)
VALUES (1, 'Amy');
INSERT INTO orders (id, customer_id)
VALUES (101, 99);The order tries to store customer_id = 99, but the table customers does not contain that key. The fix is not to drop the constraint: first decide whether the customer is missing, the identifier is wrong or the relationship should be optional.
How to fix it in SQL
Fix the data or the order of the operations
INSERT INTO customers (id, name)
VALUES (99, 'Liam');
INSERT INTO orders (id, customer_id)
VALUES (101, 99);| order_id | customer_id | customer |
|---|---|---|
| 101 | 99 | Liam |
If DELETE fails, look for the child rows first
Before deleting a parent row, check which tables reference it. With the usual default action, the database will not let child rows point to a key that no longer exists. Actions such as CASCADE, SET NULL or SET DEFAULT change that behaviour and should be chosen because they fit the data model, not to dodge a one-off error.
Do not disable foreign keys as your first fix. You may turn a visible error into inconsistent data that is much harder to repair.
How to check it
Look up the key in the parent table and all its child references before trying the change again.
How to avoid it next time
Do not switch off integrity checks to accept a wrong reference.
Related cases worth checking
PostgreSQL enforces the foreign key constraints defined in the schema. SQLite also supports foreign keys, but its documentation states that the application must enable enforcement for each connection where it is not on by default. If you try the examples in SQLite, confirm that setting before concluding that an invalid insert “works”.