MySQL NOT NULL Constraint
MySQL NOT NULL Constraint
The NOT NULL constraint in MySQL ensures that a column cannot have a NULL value.
It is used to enforce data integrity, ensuring that a value must be provided when inserting or updating a record.
🔹 Syntax (During Table Creation)
-
NOT NULLis placed after the datatype of the column.
🔹 Syntax (Using ALTER TABLE)
-
Adds the
NOT NULLconstraint to an existing column.
🔹 Example 1: Creating Table with NOT NULL
-
namemust have a value; NULL is not allowed. -
deptandmarkscan be NULL.
🔹 Example 2: Adding NOT NULL to Existing Column
-
Now
deptcannot be NULL.
🔹 Example 3: Inserting Data
-
Second query will fail because
namecannot be NULL.
🔹 Key Points
-
NOT NULLensures mandatory values in a column. -
Helps maintain data integrity and prevents missing data.
-
Can be used during table creation or altering existing tables.
-
Often used with PRIMARY KEY, as primary key columns are automatically NOT NULL.
