SQL Topics
NOT NULL
title: NOT NULL
The NOT NULL constraint prevents a column from storing NULL values.
In other words, the database requires a real value. Omitting the column in an INSERT or explicitly passing NULL will both trigger an error.
Why NOT NULL Matters
Many fields are critical to business logic. A missing Name, Email, or OrderDate can break downstream calculations.
NOT NULL protects these fields at the schema level.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(255) NOT NULL,
Phone VARCHAR(20)
);Inserting without Name or Email fails:
INSERT INTO Customers (CustomerID, Phone)
VALUES (1, '9999999999'); -- ERROR: Name/Email cannot be NULLDefining NOT NULL
Set it during table creation:
Name VARCHAR(100) NOT NULLAdd it later:
ALTER TABLE Customers
MODIFY Name VARCHAR(100) NOT NULL;Note: Modifying an existing column to NOT NULL requires that all current rows already contain non-NULL values.
NOT NULL with DEFAULT
NOT NULL works well with DEFAULT to guarantee a value when the user supplies none.
Status VARCHAR(20) NOT NULL DEFAULT 'Active'Even if the INSERT statement omits Status, the database fills 'Active'.
Real-World Uses
| Column | Reason |
|---|---|
Name | Users must have a display name |
Email | Needed for account login |
City | Required for shipping addresses |
OrderDate | Needed for billing and reporting |
Amount | Transaction value must exist |
Pseudocode example:
Frequently Asked Questions
Q: What is the difference between NULL and an empty string? A: NULL means unknown or missing data. An empty string '' is a known value. NOT NULL blocks NULL, but not ''.
Q: Can a PRIMARY KEY column still be NULL? A: No. A PRIMARY KEY automatically implies NOT NULL.
Q: Can I change a nullable column to NOT NULL later? A: Yes, as long as existing rows have values for that column. Otherwise the operation fails.
Summary
NOT NULLrequires a value in a column.- It prevents incomplete records at the database level.
- Combine it with
DEFAULTfor safe automatic values. - Critical fields like names, emails, and dates are common candidates.
Next Step
See UNIQUE to prevent duplicate values, or return to the SQL Constraints overview.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for NOT NULL.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this SQL topic.
Search Terms
sql, sql complete guide, sql tutorial, sql notes, complete, guide, constraints, not
Related SQL Topics