SQL NOT NULL constraint
The NOT NULL constraint in SQL is used to ensure that a column cannot contain a NULL value. This constraint is used to enforce data integrity and accuracy in a database.
A NULL value in a database means that the value is unknown or does not exist. By using the NOT NULL constraint, you can ensure that a value must be entered for a specific column. This makes it easier to maintain data consistency and avoid errors in the database.
To create a table with the NOT NULL constraint, you can use the following syntax:
1CREATE TABLE table_name ( 2 column1 data_type NOT NULL, 3 column2 data_type NOT NULL, 4 ... 5);
Alternatively, you can also add the NOT NULL constraint to an existing table using the ALTER TABLE statement:
1ALTER TABLE table_name 2MODIFY COLUMN column_name data_type NOT NULL;
Here is an example of how to create a table with the NOT NULL constraint:
1CREATE TABLE Customers ( 2 CustomerID int NOT NULL, 3 CustomerName varchar(255) NOT NULL, 4 ContactName varchar(255), 5 Country varchar(255) NOT NULL 6);
In this example, the CustomerID
, CustomerName
, and Country
columns are defined with the NOT NULL constraint, meaning that a value must be entered for these columns when inserting data into the table. The ContactName
column does not have the NOT NULL constraint, so it can contain a NULL value.
It is important to note that the NOT NULL constraint is applied only during data insertion and does not enforce the constraint during updates or deletions. To enforce the NOT NULL constraint during updates, you can use the CHECK constraint or a trigger.