MYSQL Tutorial



MySQL NOT NULL


MySQL NOT NULL Constraint

The NOT NULL constraint ensures that a column cannot contain NULL values. Use it for fields that must always have meaningful data.

Syntax

column_name data_type NOT NULL
  

Defining NOT NULL in CREATE TABLE

CREATE TABLE users (
  user_id   INT AUTO_INCREMENT PRIMARY KEY,
  name      VARCHAR(100) NOT NULL,
  email     VARCHAR(150) NOT NULL,
  age       INT
);
  

Adding NOT NULL to Existing Column

ALTER TABLE users
MODIFY COLUMN age INT NOT NULL;
  

Removing NOT NULL Constraint

ALTER TABLE users
MODIFY COLUMN email VARCHAR(150) NULL;
  
Tip: Before making an existing column NOT NULL, ensure there are no NULL values presentβ€”use SELECT * FROM table WHERE column IS NULL; to check.

Common Use Cases

  • Usernames, emails, or passwords that must always be provided.
  • Order dates, product IDs, or any mandatory business fields.
  • Foreign key columns when you require strict referential integrity.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review