Search code examples
sql-servert-sqlconstraintsdefault-value

Add DEFAULT constraint with a generated name


In SQL Server I have an existing table. Now I want to add a DEFAULT constraint to one of the columns - without having to define a name for it.

-- generated name works fine when creating new column
ALTER TABLE [xyz]
ADD [newColumn] int NOT NULL DEFAULT 0

-- when adding a default value afterwards I seem to have to provide a name
ALTER TABLE [xyz]
ADD CONSTRAINT [iDontWantToPutANameHere] DEFAULT 0 FOR [existingColumn]

Solution

  • You can create default constraint for an existing column, without specifying its name, e.g.:

    create table test
    (
        existing_column int
    )
    
    alter table test
        add default 0 for existing_column
    

    However, there are plenty articles, suggesting that it is better to name constraints explicitly. Because of it is harder to drop or other way alter system-named constraint. Also if you have multiple instances of the same database, the default name will no be the same across them.