In this article, we will learn how to use the NOT NULL constraint in SQL.
A column can hold NULL values by default. The NOT NULL constraint is used to enforce a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value, which means that without adding a value to this field we cannot insert a new record, or update a record.
NOT NULL – CREATE TABLE:
Please check How To Create Table Using Query In SQL, to get a brief description of the CREATE TABLE statement.
The subsequent statement would ensure that the “ID” and “Title” columns will NOT accept NULL values when the “Article” table is created:
CREATE TABLE Article ( ID int NOT NULL, Title varchar(100) NOT NULL, Author varchar(100), Views int );
NOT NULL – ALTER TABLE:
Please check How To Alter Table Using Query In SQL, to get a brief description of the ALTER TABLE statement.
The subsequent statement would add a NOT NULL constraint on the “Views” column using ALTER TABLE statement:
ALTER TABLE Article ALTER COLUMN Views bigint NOT NULL;
Also, check How To Use TRUNCATE TABLE Statement In SQL