MySQL NOT NULL Constraint (original) (raw)

Last Updated : 16 Apr, 2026

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 (
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);

Screenshot-2026-04-15-172409

**Query :

INSERT INTO users (user_id, username, email, age) VALUES
(3, 'emma_w', 'emma.williams@gmail.com',NULL);

**Output:

Screenshot-2026-04-15-173425

Output after insertion

**Adding a NOT NULL Constraint to an Existing Column

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:

Screenshot-2026-04-15-184017

Output after insertion