cannot drop table: foreign key constraint
This error occurs when you try to drop a table that other tables reference via foreign keys. Learn how to safely drop tables with dependencies.
The cannot drop table error occurs when foreign key constraints prevent dropping a referenced table.
Understanding the Error
Error: FOREIGN KEY constraint failed (when dropping table)
Another table has foreign keys pointing to the table you're trying to drop.
Common Causes
1. Referenced Table
SQL
2. Hidden References
You might not realize a table is referenced.
How to Fix It
Solution 1: Drop Dependent Tables First
SQL
Solution 2: Find All References
SQL
Solution 3: Disable Foreign Keys
SQL
Warning: This leaves orphaned references in dependent tables.
Solution 4: Use CASCADE (Recreate Tables)
SQLite doesn't support DROP TABLE CASCADE, but you can recreate:
SQL
Solution 5: Delete Referencing Data First
SQL
Solution 6: Drop and Recreate Schema
For complete reset:
SQL
Checking Foreign Key Dependencies
SQL
JAVASCRIPT
Best Practices
- Document table dependencies in your schema
- Create a drop order for teardown scripts
- Use migrations that handle dependencies
- Check dependencies before dropping
- Consider soft deletes instead of drops