NOT NULL constraint failed
This error occurs when you try to insert or update a row with a NULL value in a column that requires a value. Learn how to fix it and handle nullable data.
The NOT NULL constraint failed error occurs when you try to insert NULL into a column that's marked as NOT NULL. SQLite is protecting your data integrity.
Understanding the Error
SQLITE_CONSTRAINT: NOT NULL constraint failed: users.email
This tells you:
- The
userstable has a NOT NULL constraint onemail - You tried to insert a row without providing an email value
- The operation was rejected
Common Causes
1. Missing Required Field
Not providing a value for a required column:
2. Explicitly Inserting NULL
Directly inserting NULL into a NOT NULL column:
3. Application Sending Null Values
Your application code might be sending null:
4. Update Setting Column to NULL
Updates can also trigger this:
How to Fix It
Solution 1: Provide the Required Value
Simply include the required field:
Solution 2: Set a Default Value
Modify the table to have a default:
Solution 3: Remove the NOT NULL Constraint
If the column should allow NULL values:
Solution 4: Handle Nulls in Application Code
Validate and provide defaults before inserting:
Solution 5: Use COALESCE in SQL
Provide a fallback value in your query:
Checking NOT NULL Columns
Find which columns have NOT NULL constraints:
Output shows notnull column (1 = NOT NULL, 0 = nullable):
cid name type notnull dflt_value pk
--- ----- ------- ------- ---------- --
0 id INTEGER 0 NULL 1
1 name TEXT 0 NULL 0
2 email TEXT 1 NULL 0
Best Practices
- Design schemas carefully - Only use NOT NULL when truly required
- Use DEFAULT values for NOT NULL columns when sensible
- Validate in application code before database operations
- Document required fields in your API/schema documentation
- Handle edge cases - What if user doesn't provide email?
Common Patterns
Optional Fields with NOT NULL
Use empty string instead of NULL for optional text:
Timestamps with Defaults
Related Errors
- UNIQUE constraint failed - Duplicate value in unique column
- FOREIGN KEY constraint failed - Referenced row doesn't exist
- CHECK constraint failed - Value doesn't meet validation rule