NOT NULL constraints in Microsoft SQL Server allow you to specify that a column may not contain NULL values
. When you create a new NOT NULL constraint on a database column
, SQL Server checks the column’s current contents for any NULL values. If the column currently contains NULL values, the constraint creation fails. Otherwise, SQL Server adds the NOT NULL constraint and any future INSERT
commands that would cause the existence of a NULL value fail.
Creating a NOT NULL Constraint
There are many ways you can create a UNIQUE constraint in SQL Server. If you wish to use Transact-SQL to add a UNIQUE constraint on an existing table, you may use the ALTER TABLE statement, as illustrated below:
ALTER TABLE <table_name>
ALTER COLUMN <column_name> <data_type> NOT NULL
If you prefer to interact with SQL Server using GUI tools, you may also create a NOT NULL constraint using SQL Server Management Studio. Here’s how:
- Open SQL Server Management Studio.
- Expand the Tables folder of the database where you wish to create the constraint.
- Right-click the table where you wish to add the constraint and click Design.
- Check the NOT NULL checkbox for the column(s) that you wish to have NOT NULL constraint(s).
That’s all there is to creating NOT NULL constraints in Microsoft SQL Server!