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 NULL is placed after the datatype of the column.


🔹 Syntax (Using ALTER TABLE)

  • Adds the NOT NULL constraint to an existing column.


🔹 Example 1: Creating Table with NOT NULL

  • name must have a value; NULL is not allowed.

  • dept and marks can be NULL.


🔹 Example 2: Adding NOT NULL to Existing Column

  • Now dept cannot be NULL.


🔹 Example 3: Inserting Data


 

  • Second query will fail because name cannot be NULL.


🔹 Key Points

  1. NOT NULL ensures mandatory values in a column.

  2. Helps maintain data integrity and prevents missing data.

  3. Can be used during table creation or altering existing tables.

  4. Often used with PRIMARY KEY, as primary key columns are automatically NOT NULL.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *