Cannot add a PRIMARY KEY column
This error occurs when you try to add a PRIMARY KEY column to an existing table using ALTER TABLE. SQLite has limited ALTER TABLE support.
The Cannot add a PRIMARY KEY column error occurs because SQLite's ALTER TABLE is limited.
Understanding the Error
SQLite's ALTER TABLE only supports adding columns with certain constraints, not PRIMARY KEY.
What ALTER TABLE Supports
SQLite's ALTER TABLE can:
- Rename table
- Rename column
- Add column (with restrictions)
Cannot:
- Add PRIMARY KEY
- Add UNIQUE constraint
- Add FOREIGN KEY
- Remove column (before 3.35.0)
- Modify column type
How to Fix It
Solution 1: Recreate Table
The standard approach:
SQL
Solution 2: With Foreign Keys
Handle foreign key references:
SQL
Solution 3: Preserve Indexes and Triggers
SQL
Solution 4: Use a Migration Helper
JAVASCRIPT
Preserve Row Order (if needed)
SQL
Best Practices
- Plan schema upfront to minimize migrations
- Use transactions for safety
- Backup before major schema changes
- Test migrations on copy of production data
- Disable foreign keys during migration
- Recreate indexes after table swap