In MySQL, The NOT NULL constraint is used to specify that a column in a table cannot contain NULL values.
This constraint enforces that every row in the table must have a non-null value for that column.
When we declare a column as NOT NULL, it means that the column must have a value during the INSERT operation, and the absence of a value (i.e., NULL) is not allowed.
Here's an example of using the NOT NULL constraint:
CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(50) NOT NULL, product_category VARCHAR(100) NOT NULL );
the `products` table is created with columns product_id, product_name, and product_category.
Both product_name and product_category columns have the NOT NULL constraint, indicating that these columns cannot contain NULL values.
The PRIMARY KEY constraint is also applied to the product_id column, ensuring that each product_id is unique.
Attempting to insert a row into the `products` table without providing values for the `product_name` and `product_category` columns will result in an error due to the NOT NULL constraint.
-- it will fail due to NOT NULL constraint INSERT INTO products (product_id) VALUES (1);
To insert a row into a table with NOT NULL columns, we need to provide values for those columns during the INSERT operation:
-- This will get succeed INSERT INTO products (product_id, product_name, product_category) VALUES (1, 'iPad', 'GADGETS');
The NOT NULL constraint is useful when we want to ensure that certain columns always contain valid data, and it helps maintain data integrity within our database.