T-SQL Tutorial

NOT NULL constraint T-SQL

The NOT NULL integrity constraint in SQL Server is used to ensure that a column in a table cannot contain a null value. This means that when a new row is inserted into the table or an existing row is updated, a value must be provided for the column that has the NOT NULL constraint.

The NOT NULL constraint is useful for ensuring that important data is not missing and also can be used to enforce business rules. It can also improve query performance by reducing the number of null values that need to be processed.

The NOT NULL constraint can be specified when a table is created, or it can be added or removed later on using the ALTER TABLE statement. When a NOT NULL constraint is added to an existing table, all existing rows in the table must contain a value for the column. If not, the ALTER TABLE statement will fail.

Example of NOT NULL constraint

The example below shows how to define a column with NOT NULL constraint when creating a table in SQL Server.

USE model;
CREATE TABLE employee (
employee_id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100)

Add NOT NULL constraint

This SQL statement adds a NOT NULL constraint on the "Email" column of the "Employee" table.

ALTER TABLE employee

It is important to note that SQL Server allows to add NOT NULL constraint to a column that already has data, but in that case the ALTER TABLE statement will fail if there are any NULL values in the column.