The NOT NULL constraint in a column declaration in SQL indicates that the column must contain a value; it cannot be left empty or set to NULL. This constraint ensures that every record in the table has a valid value for that particular column.
Key Points:
- Mandatory Value: A column defined with
NOT NULLmust have a value for every row in the table. - Data Integrity: It helps maintain data integrity by preventing the insertion of records with missing values in critical fields.
- Error on Insertion: If an attempt is made to insert a row without providing a value for a
NOT NULLcolumn, the database will return an error.
Example:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
In this example, both the username and email columns are defined with the NOT NULL constraint, meaning every user must have a username and an email address when a new record is inserted.
