October 30, 2013 by Kenneth Fisher
There are lots of ways to learn new things, or be reminded of old things. One of my favorites is the QotD on sql server central. Recently there was an interesting question on defaults. It pointed out that there is a difference between adding a column with a default that allows NULLs and one that does not.
-- Setup CREATE TABLE DefaultTest (Id INT NOT NULL IDENTITY(1,1)) GO INSERT INTO DefaultTest DEFAULT VALUES INSERT INTO DefaultTest DEFAULT VALUES INSERT INTO DefaultTest DEFAULT VALUES GO
-- Test adding one NULL column and one NOT NULL column ALTER TABLE DefaultTest ADD Nullable char(1) NULL CONSTRAINT df_DefaultTest_Nullable DEFAULT 'x', NotNull char(1) NOT NULL CONSTRAINT df_DefaultTest_NotNull DEFAULT 'x' GO
Note that the nullable column is all NULLs and the other was filled in with x’s. This makes sense when you think about it. If you add a column with a default that allows NULLs it can just have NULL in any existing rows. However when you add a column that doesn’t allow NULLs then you have to have a value to put in it. In fact that brings up the point that you can’t add a NOT NULL column without a default if there are any rows in the table.
-- Trying to add a NOT NULL column without a default ALTER TABLE DefaultTest ADD NotNull2 char(1) NOT NULL GO
Returns an error of
Msg 4901, Level 16, State 1, Line 1 ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'NotNull2' cannot be added to non-empty table 'DefaultTest' because it does not satisfy these conditions.
This is one of those simple things that can bite you in the ____ occasionally. It certainly catches me every now and again.