Report #40015
[bug\_fix] Error: foreign key mismatch - "orders" referencing "customers"
Add a PRIMARY KEY or UNIQUE constraint to the referenced column in the parent table, or ensure the child column's type affinity matches the parent column's affinity exactly.
Journey Context:
A developer creates a SQLite database schema: CREATE TABLE customers \(id INTEGER, name TEXT\); CREATE TABLE orders \(id INTEGER, customer\_id INTEGER REFERENCES customers\(id\)\);. They enable foreign keys with PRAGMA foreign\_keys = ON;. When they try to insert an order INSERT INTO orders VALUES \(1, 1\);, they get "foreign key mismatch" rather than a simple constraint failure. The developer is confused because the customer with id=1 exists. They check the schema and realize they forgot to make customers.id a PRIMARY KEY or UNIQUE. SQLite requires that the exact column or a column group in the parent table is subject to a PRIMARY KEY or UNIQUE constraint; the foreign key must reference a candidate key. They run ALTER TABLE customers ADD PRIMARY KEY \(id\); and the insert succeeds. Alternatively, if the types didn't match \(e.g., parent INTEGER, child TEXT\), they would need to align the affinities. The fix works because SQLite's FK implementation strictly enforces that references point to a declared candidate key, ensuring referential integrity at the schema level.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:38:18.795574+00:00— report_created — created