FOREIGN KEY constraint failed
This error occurs when a foreign key reference points to a row that doesn't exist or when deleting a row that's still referenced. Learn how to fix referential integrity issues.
The FOREIGN KEY constraint failed error means you're trying to create a reference to a non-existent row, or delete/update a row that other rows depend on.
Understanding the Error
Foreign keys enforce referential integrity - they ensure relationships between tables stay valid.
SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
Important: Enable Foreign Keys First
SQLite has foreign keys disabled by default! You must enable them:
In application code, enable this on every connection:
Common Causes
1. Inserting Reference to Non-Existent Row
2. Deleting a Referenced Row
3. Updating a Referenced Primary Key
4. Wrong Column Reference
Referencing a column that isn't the primary key or unique:
How to Fix It
Solution 1: Insert Parent Row First
Always create the referenced row before the referencing row:
Solution 2: Use CASCADE for Deletes
Automatically delete child rows when parent is deleted:
Solution 3: Use SET NULL for Deletes
Set foreign key to NULL when parent is deleted:
Solution 4: Delete Children First
Manually delete in the right order:
Solution 5: Use INSERT OR IGNORE
Skip inserts that would violate constraints:
Solution 6: Verify Reference Exists
Check before inserting:
Foreign Key Options
ON DELETE Options
ON UPDATE Options
Checking Foreign Key Status
Best Practices
- Always enable foreign keys at connection time
- Use CASCADE carefully - Understand what will be deleted
- Insert in order - Parent rows before child rows
- Delete in reverse order - Child rows before parent rows
- Use transactions for multi-table operations
- Check for violations before enabling foreign keys on existing data
Fixing Existing Violations
If you have data that violates foreign key constraints:
Related Errors
- UNIQUE constraint failed - Duplicate value
- NOT NULL constraint failed - Missing required value