![]() |
VOOZH | about |
MySQL provides the NOT NULL constraint to ensure that a column cannot store NULL values. It helps maintain data accuracy and reliability by enforcing mandatory values in specific columns.
Syntax:
CREATE TABLE table_name (
column_name datatype NOT NULL
);
We can add a NOT NULL constraint to an existing column using the ALTER TABLE statement
Syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name data_type(size) NOT NULL;
Example:
Letβs create a users table without a NOT NULL constraint.
CREATE TABLE users (π Screenshot-2026-04-15-172409
user_id INT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100),
age INT NOT NULL
);
INSERT INTO users (user_id, username, email, age) VALUES
(1, 'john_doe', 'john.doe@gmail.com', 30),
(3, 'robert264', 'robert.johnson@yahoo.com', 35);
Query :
INSERT INTO users (user_id, username, email, age) VALUES
(3, 'emma_w', 'emma.williams@gmail.com',NULL);
Output:
Use the ALTER TABLE command to modify the column and set it as NOT NULL. This ensures the column cannot contain NULL values and helps maintain data consistency.
ALTER TABLE users
MODIFY COLUMN email VARCHAR(100) NOT NULL;
Query:
INSERT INTO users (user_id, username, email, age) VALUES
(5, 'bob_miller',NULL, 25);
Output: