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 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 NULL prevents NULL but not empty strings (''), unless you enforce that separately.
✔ Most engines treat PRIMARY KEY as implicitly NOT NULL.
✔ Columns without an explicit constraint default to NULL unless changed.
✔ For mandatory columns, combine with CHECK or DEFAULT when helpful.
🏎 Best Practices
✔ Apply NOT NULL to 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
