SQL NOT NULL constraint

Here is a clear, practical, and complete guide to the SQL NOT NULL constraint, including behavior, examples, and engine differences.
What the SQL NOT NULL constraint Does
NOT NULL ensures that a column cannot contain NULL values.
Prevents missing or unknown data
Enforces data integrity at the database level
Often used for required fields (email, username, timestamps, etc.)
Basic Syntax
In CREATE TABLE:
In ALTER TABLE:
Example: Ensure a required column
- Prevents inserting a product without name or price.
Inserting Rows With NOT NULL Columns
Valid:
Invalid (missing required field):
Add NOT NULL to an Existing Column (with data present)
PostgreSQL:
MySQL:
SQL Server:
- Must remove NULLs first or the ALTER will fail.
Remove NOT NULL Constraint
PostgreSQL:
MySQL:
SQL Server:
Important Behavior Notes
NOT NULLprevents NULL but not empty strings (''), unless you enforce that separately.- Most engines treat
PRIMARY KEYas implicitlyNOT NULL. - Columns without an explicit constraint default to
NULLunless changed. - For mandatory columns, combine with
CHECKorDEFAULTwhen helpful.
Best Practices
- Apply
NOT NULLto all required fields - Add sensible defaults (e.g.,
DEFAULT CURRENT_TIMESTAMP) - Clean existing NULL data before adding constraints
- Avoid allowing NULL on foreign key columns unless logically required
- Use migrations to apply changes safely in production
