Skip to content

SA0249 : Specify default value for columns added with NOT NULL constraint

When adding a new NOT NULL column to a table using ALTER TABLE , ensure a default value is provided to avoid errors in SQL Server.

When you modify a table using an ALTER TABLE statement to add a new column that is specified as NOT NULL , it must include a default value to avoid operational errors.

For example:

-- Example of problematic query
ALTER TABLE TableName
ADD NewColumn INT NOT NULL;

The above T-SQL command attempts to add a new column NewColumn to the existing table TableName without defining a default value. If TableName already has data, this operation will fail because SQL Server would not know what value to insert into NewColumn for the existing rows.

  • Operation failure due to missing values for existing records.

  • Potential downtime and data inconsistency issues.

`

Ensure that any new column added with a NOT NULL constraint includes a default value to maintain data integrity and avoid operation failures in SQL Server.

Follow these steps to address the issue:

1.Identify the table where a new column needs to be added with a NOT NULL constraint.

2.Determine the appropriate default value for the new column that aligns with the existing data schema and business rules.

3.Modify the ALTER TABLE statement to include the DEFAULT clause with the chosen default value. For example:

4.Execute the revised ALTER TABLE command to ensure the new column is added without causing errors due to existing records. This step automatically populates the new column for existing rows with the specified default value.

For example:

-- Example of corrected query with default value
ALTER TABLE TableName
ADD NewColumn INT NOT NULL DEFAULT 0;

The rule has a Batch scope and is applied only on the SQL script.

Rule has no parameters.

The rule does not need Analysis Context or SQL Connection.

8 minutes per issue.

Design Rules, Code Smells

There is no additional info for this rule.

CREATE TABLE Test.Greeting
(
GreetingId INT IDENTITY (1,1) PRIMARY KEY,
Message nvarchar(255)
)
ALTER TABLE Test.Greeting ADD Kind int NOT NULL DEFAULT (5)
ALTER TABLE Test.Greeting ADD Kind2 int NOT NULL
 MessageLineColumn
1SA0249 : The column Kind2 is added as NOT NULL, but without a default value.730

Analysis Rules