Add a column with a default value to an existing table in SQL Server
Here's the magic command to Add a column with a default value
to a SQL Server table:
Swap YourTable
with your table name, NewColumn
for the new column, DataType
with the type you desire, and 'DefaultValue'
with your default value. SQL Server takes the wheel from there!
Using Non-NULL columns
When you're adding non-null columns, SQL Server is your best mate! It automatically fills them up with the default value. For any nullable column needing the default value, don't forget to tack on the WITH VALUES
toolkit:
Named constraints for your sanity
Maintain your sanity by giving your constraints descriptive names. This will help you modify or remove them in the future:
The DF_
is a legacy from naming convention of ye olden times - feel free to replace it with a prefix of your liking.
Insert action after adding new column
Doing an insert operation after adding a new column doesn't require its mention; SQL Server's default values have your back:
In case the new column is nullable and you insert NULL
, SQL Server will understand that you like to live dangerously and override the default.
Considerations during "Table Surgery"
Certain generations of SQL Server (2000 and 2005 to be exact) need the GO
statement to split up operations:
Entering a non-nullable column? You might need to plan a strategy to fill your existing rows:
Your data type needs to be spot on, like VARCHAR(200)
or INT
, depending on the room your data needs.
Was this article helpful?