Adding a New Column with a Default Value to an Existing SQL Server Table
Modifying existing SQL Server tables frequently involves adding new columns. This process can be easily enhanced by assigning a default value to the new column. This ensures data consistency and simplifies the insertion of new rows.
SQL Syntax:
<code class="language-sql">ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL | NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} WITH VALUES;</code>
Explanation of Parameters:
Practical Example:
Let's add a "IsActive" column (BIT data type) to a table named "Products," allowing NULLs and setting the default to 1 (true):
<code class="language-sql">ALTER TABLE Products ADD IsActive BIT NULL CONSTRAINT DF_Products_IsActive DEFAULT (1) WITH VALUES;</code>
Important Considerations:
WITH VALUES
judiciously. It's only needed when you want pre-existing rows to inherit the default value. Otherwise, existing rows will have NULL
in the new column.NULL
, the default value is ignored.This detailed explanation and example should make adding columns with default values in SQL Server a straightforward process.
The above is the detailed content of How to Add a New Column with a Default Value to an Existing SQL Server Table?. For more information, please follow other related articles on the PHP Chinese website!