Sql-server – TSQL change column constraint between null and not null

nullsql server

I am doing a exercise to change a column's constraint between null to not null.
Table name: Production.categoriesTest. Please review my question and give me suggestion
on what I did wrong and how to fix the issue. Thanks!

  1. when table was created, the description column is set to NOT NULL
  2. I used the update clause to set description column to NULL
  3. When using alter table command to set the column description back to NOT NULL, I received an error message.

Error message:

Msg 515, Level 16, State 2, Line 98
Cannot insert the value NULL into column 'description', table 'TSQL2012.Production.categoriesTest'; column does not allow nulls. UPDATE fails.

Create table command:

 create table Production.categoriesTest
    categoryid INT not null identity,
    categoryname nvarchar(15) not null,
    description nvarchar(200) not null,
    constraint PK_Categories1 Primary Key (categoryid)

--update clause make all description column becomes 'NULL"
  update Production.categoriesTest
  set description = NULL
  where categoryid = 8;

The description column became 'NULL'

I did insert a value for description column in the able after the column set to Null.

Best Answer

When trying to return the column back to NOT NULL SQL Server immediately checks the constraint, which fails because the rows for that column were set to NULL.

For an existing column, you have to update the table to remove any NULL values before you can set it as NOT NULL.