3

I am trying to alter an existing column and adding an integer column. While adding integer column i am setting DEFAULT as 10 but default is not setting while adding the column

ALTER TABLE dbo.Contacts ADD Col1 INT DEFAULT 10

I require to do explicit update script to set all past records as default values

Whereas if the column is 'not null' then it is defaulting to 10 for all the records.

ALTER TABLE dbo.Contacts ADD Col2 INT NOT NULL DEFAULT 10

Why nullable column is not setting with default value? In my actual table I have close to 850 mil records and my new column is nullable column and I am trying to avoid one more update after my ALTER table script. What is the way?

I am thinking of creating not nullable column with default as 10 and alter again the constraint to NULL. Is this fine approach? Any other ways?

Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38

2 Answers2

6

You have to use WITH VALUES to get the value and not the null. Using WideWorldImporters on 2016:

ALTER TABLE sales.orders 
ADD c1 INT DEFAULT 10 WITH VALUES
GO 
dfundako
  • 8,022
  • 3
  • 18
  • 34
0

The Default column value is applied to new rows inserted into the table after the default column value is defined. To test this, try an INSERT command like this.

INSERT INTO TableName col1 VALUES (col1_value)

After this INSERT, the col2 value should get the Default value of 10 for the inserted row.

However, existing rows in the table do not automatically get assigned the new Default column value

JohnH
  • 1,920
  • 4
  • 25
  • 32