MySQL : NOT NULL Constraint

In MySQL, the NOT NULL constraint is used to specify that a column must contain a value and cannot be NULL. It ensures that every row must have a value for that column, and NULL values are not allowed.

Here's how you can use the NOT NULL constraint while creating a table:


CREATE TABLE table_name (
    column_name data_type NOT NULL,
    ...
);

 

For example, suppose you have a table named employees and you want to ensure that the name and age columns cannot be NULL:


CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    age INT NOT NULL
);

 

In this example, the name and age columns are defined with the NOT NULL constraint. This means that when inserting data into the employees table, values must be provided for both name and age columns, and NULL values will be rejected.

Using the NOT NULL constraint is crucial for maintaining data integrity and ensuring that your database contains valid and consistent data. It helps prevent the insertion of incomplete or missing information into the database.