# sqlite3.IntegrityError: FOREIGN KEY constraint failed

- **ID:** `python/sqlalchemy-sqlite-foreign-key-off`
- **Domain:** python
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

SQLite by default does not enforce foreign key constraints unless PRAGMA foreign_keys=ON is set; but if it's off, referential integrity can be violated, and when turned on, existing bad data causes errors.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 1.4.x | active | — | — |
| 2.0.x | active | — | — |

## Workarounds

1. **** (90% success)
   ```
   Enable foreign key enforcement per connection: from sqlalchemy import event; @event.listens_for(engine, 'connect') def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor(); cursor.execute('PRAGMA foreign_keys=ON'); cursor.close()
   ```
2. **** (80% success)
   ```
   Clean up orphaned records before enabling FK constraints.
   ```

## Dead Ends

- **** — Data inconsistency persists. (90% fail)
- **** — May lose data and doesn't fix the root cause. (60% fail)
