PRIMARY KEY must be unique
This error occurs when you try to insert a duplicate primary key value. Learn about auto-increment, composite keys, and handling duplicates.
The PRIMARY KEY must be unique error occurs when inserting a row with a primary key that already exists.
Understanding the Error
SQLITE_CONSTRAINT: PRIMARY KEY must be unique
Every row must have a unique primary key value.
Common Causes
1. Manual ID Already Exists
SQL
2. Reusing Deleted IDs
SQL
3. Import/Sync Conflicts
Importing data that overlaps with existing records.
4. Composite Key Violation
SQL
How to Fix It
Solution 1: Use AUTOINCREMENT
Let SQLite handle ID generation:
SQL
Solution 2: Omit ID for Auto-Assignment
SQL
Note: Without AUTOINCREMENT, deleted IDs may be reused.
Solution 3: Use INSERT OR REPLACE
SQL
Solution 4: Use INSERT OR IGNORE
SQL
Solution 5: Use ON CONFLICT
SQL
Solution 6: Check Before Insert
JAVASCRIPT
Solution 7: Use UUIDs
JAVASCRIPT
AUTOINCREMENT vs INTEGER PRIMARY KEY
SQL
Best Practices
- Use AUTOINCREMENT for most cases
- Let database assign IDs when possible
- Use UUIDs for distributed systems
- Handle conflicts with ON CONFLICT
- Validate data before bulk imports