35

I have a table that I want to add a bit column, which I wish to default to false for all existing data.

How do I alter my table in such a way that it allows me to specify NOT NULL before I have inserted false for my existing rows?

Should I create it as nullable, do an insert than switch it non-nullable?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
KingNestor
  • 65,976
  • 51
  • 121
  • 152

6 Answers6

79

You could add the column and provide the default value to be used for all existing rows.

ALTER TABLE foo 
ADD bar bit 
DEFAULT 0 NOT NULL;
Robert Christie
  • 20,177
  • 8
  • 42
  • 37
  • 7
    I typically like to NAME my constraint - even default constraints - in case I need to drop them later on. The default "DF__TimeZones__IsUsa__3D5E1FD2" names are a bit hard to remember..... – marc_s Dec 22 '09 at 17:08
5

As an alternative to the answers listed there is another syntax available which may suit some people better, for example if you use tools like 'ReadyRoll'.

ALTER TABLE [dbo].[FOO] ADD BAR bit NOT NULL CONSTRAINT [df_Bar] DEFAULT 0

Check out this SO answer to see why naming your constraints (the df_Bar above) is nice.

Community
  • 1
  • 1
gingerbreadboy
  • 7,386
  • 5
  • 36
  • 62
4
ALTER TABLE foo ADD bar bit DEFAULT 0 NOT NULL WITH VALUES;

The "with values" clause propigates the default value into existing rows.

Cylon Cat
  • 7,111
  • 2
  • 25
  • 33
  • 1
    @marc_s, I just ran it without the "WITH VALUES" for my bit column and it worked. Are you sure? – KingNestor Dec 22 '09 at 16:55
  • 1
    @KingNestor, try it with a default value of 1, or something that's not all binary zeros. – Cylon Cat Dec 22 '09 at 16:58
  • 6
    WITH VALUES is used in the case of a NULLABLE column and you want the default value to be used instead of NULL. – Bryan Batchelder Dec 22 '09 at 16:59
  • 1
    @KingNestor: you're absolutely right - if the column is defined as NOT NULL, it will be filled with the default value even without the "WITH VALUES" clause. Thanks for pointing that out! But the WITH VALUES is needed if the column is defined as NULLable – marc_s Dec 22 '09 at 17:07
1
ALTER TABLE dbo.MyTable ADD MyColumn bit NOT NULL DEFAULT 0

For what it is worth, you can fire up Enterprise Manager, make the changes in the UI, and then have it generate a Change Script - and you can see how it would accomplish these kinds of tasks.

Bryan Batchelder
  • 3,627
  • 21
  • 17
0

I have also done it as you say "create it as nullable, do an insert than switch it non-nullable". I've not had a problem doing it this way.

I've not yet needed to find a better way, however I'm intrigued if there is another way....

MrEdmundo
  • 5,105
  • 13
  • 46
  • 58
0

I usually create the field as nullable with a default as false in your case update all the fields that were in the database prior then switch it to null

Josh Mein
  • 28,107
  • 15
  • 76
  • 87