SQL NOT NULL Constraint
The NOT NULL constraint in SQL ensures that a column cannot have a NULL value. It enforces that every row must have a value for the specified column, ensuring data integrity.
Key Points
Mandatory Values:
- Prevents inserting or updating rows with a
NULLvalue for the column.
- Prevents inserting or updating rows with a
Column-Level Constraint:
- Applied to individual columns when creating or altering a table.
Default Behavior:
- If not explicitly set, columns can be accepted
NULLby default in most databases.
- If not explicitly set, columns can be accepted
Syntax
1. Define NOT NULL During Table Creation
2. Add NOT NULL to an Existing Column
3. Remove NOT NULL Constraint
Examples
1. Create a Table with NOT NULL Constraint
EmployeeIDandNamemust have a value in every row.DepartmentIDcan acceptNULL.
2. Insert Values into a NOT NULL Column
3. Adding NOT NULL to an Existing Column
If a column is already created without a NOT NULL constraint, it can be added later:
Use Cases
Mandatory Fields:
- For columns like
ID,Name, orEmail, which must always have a value.
- For columns like
Data Consistency:
- Prevents accidental null values that could cause errors in queries or applications.
Primary Key Columns:
- Primary keys inherently have the
NOT NULLconstraint since they must uniquely identify rows.
- Primary keys inherently have the
Best Practices
Identify Critical Columns:
- Apply
NOT NULLto columns where null values would be illogical (e.g., identifiers, dates, or names).
- Apply
Default Values:
- Consider combining
NOT NULLwith aDEFAULTvalue to avoidNULLerrors during inserts.
- Consider combining
Check for Existing NULLs:
- Before adding a
NOT NULLconstraint to an existing column, ensure no rows currently containNULL.
- Before adding a
Test Updates and Inserts:
- Validate changes to avoid conflicts with existing queries or applications.
Comparison with DEFAULT and NULL Constraints
| Feature | NOT NULL | DEFAULT | NULL |
|---|---|---|---|
| Prevents NULL Values | Yes | No | No |
| Requires Value | Yes | No (uses default) | No (accepts NULL) |
| Suitable for Primary Keys | Yes | No | No |
Conclusion
The NOT NULL constraint is an essential tool for enforcing data integrity in SQL. By ensuring that certain columns cannot have NULL values, it helps prevent incomplete or invalid data from being stored in the database.

