The NOT NULL constraint in MySQL ensures that a column cannot store NULL values. It is commonly used on important fields like IDs, names, and other required data.
✅ Use for mandatory fields
NULL (or omit the value) for a NOT NULL column, MySQL will raise an error.PRIMARY KEY, UNIQUE, and default values.Basic syntax to define a column with the NOT NULL constraint while creating a table:
-- Defining a column with NOT NULL constraint
CREATE TABLE table_name (
column1 datatype NOT NULL
);
Here is an example showing how to use NOT NULL on multiple columns in an Employees table:
-- Creating a table with NOT NULL columns
CREATE TABLE Employees (
ID INT NOT NULL,
Name VARCHAR(100) NOT NULL,
Age INT,
Salary DECIMAL(10,2)
);
ID and Name must always have values when inserting a row.Age and Salary are optional and can be NULL.ID or Name will cause an error.Let’s see valid and invalid insert statements for this table:
-- ✅ Valid insert: all NOT NULL columns have values
INSERT INTO Employees (ID, Name, Age, Salary)
VALUES (1, 'Alice', 28, 55000.00);
-- ✅ Valid insert: optional columns can be NULL
INSERT INTO Employees (ID, Name, Age, Salary)
VALUES (2, 'Bob', NULL, NULL);
-- ❌ Invalid insert: Name is NOT NULL but omitted
INSERT INTO Employees (ID, Age, Salary)
VALUES (3, 30, 60000.00);
INSERT statements succeed because ID and Name have values.INSERT fails because Name is defined as NOT NULL but no value is supplied.You can add or remove the NOT NULL constraint using ALTER TABLE:
-- Adding NOT NULL to an existing column
ALTER TABLE Employees
MODIFY COLUMN Age INT NOT NULL;
-- Removing NOT NULL from an existing column
ALTER TABLE Employees
MODIFY COLUMN Age INT NULL;
NOT NULL, existing rows must not contain NULL in that column.NULL in Age, the first ALTER will fail until you update those rows.NOT NULL for columns where a value is required for every record, such as identifiers, usernames, or mandatory fields.PRIMARY KEY, MySQL will automatically treat it as NOT NULL.NOT NULL with DEFAULT values to avoid errors when no value is provided explicitly.NOT NULL on that column.Students table with columns: StudentID (INT, NOT NULL), FullName (VARCHAR, NOT NULL), Email (VARCHAR, optional), and Age (INT, optional).Students table and try omitting StudentID or FullName to observe the NOT NULL error.ALTER TABLE to add a NOT NULL constraint to the Email column, then try inserting a row without an email.NOT NULL from a column and verify that it now accepts NULL values.