SQL Server Error 339: Default or Null Not Allowed Fix
In this article
SQL Server Error 339 occurs when you attempt to create or alter a table column to be NOT NULL without providing a default value for existing rows, or when a constraint is improperly defined. To fix this, you must either provide a default value for the column using a DEFAULT constraint or ensure that the table is empty before applying the NOT NULL restriction.
What You'll Need
- SQL Server Management Studio (SSMS) or another SQL query editor.
- Administrative permissions (sysadmin or db_owner) to alter table schemas.
- A backup of the database (recommended before performing schema changes).
- Knowledge of the specific data type required for the column in question.
Step-by-Step
- Identify the Problematic Column: Review the error message to determine which table and column are triggering the error. This usually happens during an
ALTER TABLEstatement where you are changing a column fromNULLtoNOT NULL. - Analyze Existing Data: Run a query to check if there are any existing NULL values in that column. Use a command like
SELECT COUNT(*) FROM TableName WHERE ColumnName IS NULL;. If the count is greater than zero, SQL Server cannot apply the NOT NULL constraint because it doesn't know what to put in those empty slots. - Cleanse the Data (Manual Method): If you prefer not to use a permanent default value, manually update all NULL entries to a valid value. For example, if it is a numeric column, use
UPDATE TableName SET ColumnName = 0 WHERE ColumnName IS NULL;. For a string column, useUPDATE TableName SET ColumnName = 'Unknown' WHERE ColumnName IS NULL;. - Apply the NOT NULL Constraint: Once all NULLs are gone, execute the alter command:
ALTER TABLE TableName ALTER COLUMN ColumnName DataType NOT NULL;. (Note: Replace DataType with the actual type, such as INT or VARCHAR(50)). - Alternative Method: Adding a Default Constraint: If you want SQL Server to handle future NULLs automatically, add a default constraint first. Use the syntax:
ALTER TABLE TableName ADD CONSTRAINT DF_ColumnName DEFAULT 'YourDefaultValue' FOR ColumnName;. - Handle Existing NULLs via Default: Adding a constraint does not always retroactively fill existing NULLs. You must still perform the update step mentioned in step 3 before you can successfully change the column to NOT NULL.
- Verify the Change: Right-click the table in SSMS, select Design, and verify that the "Allow Nulls" checkbox is unchecked for the specific column. Alternatively, query the
sys.columnssystem view to confirm theis_nullableproperty is set to 0.
Common Mistakes
One of the most frequent mistakes is attempting to add a NOT NULL constraint to a column that already contains data without first addressing the existing NULL values. SQL Server will not guess what the data should be; it requires an explicit instruction. Another common error is forgetting that changing a column's nullability often requires redefining the entire column definition, including its length and precision. For example, if you have a VARCHAR(100) NULL and you run ALTER COLUMN ColumnName NOT NULL without specifying VARCHAR(100), the command may fail or inadvertently change the data type.
Users also frequently confuse the DEFAULT constraint with the NOT NULL property. A default value only applies when a new row is inserted without a value for that column; it does not automatically convert existing NULLs to that default value. You must run a separate UPDATE statement to synchronize existing data with your intended default before the schema change will be accepted.
Finally, attempting to change a column to NOT NULL while it is part of an index or a primary key can lead to secondary errors. You may need to drop the index, alter the column, and then recreate the index.
Tips
When working in a production environment, always wrap your schema changes in a transaction. This allows you to roll back the changes if the ALTER TABLE statement causes unexpected locking or errors. Use BEGIN TRANSACTION; followed by your SQL commands, and then COMMIT; only after you have verified the results.
For very large tables, running a massive UPDATE statement to remove NULLs can bloat the transaction log and lock the table for a long time. In these cases, perform the update in smaller batches using a WHILE loop with TOP (1000) to prevent the log from filling up and to avoid escalating to a full table lock, which would block other users.
Consider using a temporary column if the data migration is complex. Create a new column with the desired NOT NULL and DEFAULT properties, copy the data from the old column to the new one (handling the NULLs during the copy), drop the old column, and rename the new column to the original name.
Troubleshooting
If you have updated all NULL values and are still receiving Error 339, check for triggers. Some INSTEAD OF triggers can interfere with how the engine perceives column updates and constraints. Try disabling the trigger temporarily, applying the change, and then re-enabling it.
If the error persists during a table creation script, ensure that you haven't defined a column as NOT NULL while simultaneously providing a DEFAULT value that is itself NULL. For example, ColumnName INT NOT NULL DEFAULT NULL is a contradiction that will trigger this error immediately.
Check for dependent objects. If the column is used in a computed column or a check constraint, SQL Server might block the modification. You will need to drop the dependent constraint, modify the column, and then recreate the constraint. If you are using SSMS and the "Save" button is greyed out or gives a "Saving changes is not permitted" error, go to Tools > Options > Designers and uncheck "Prevent saving changes that require table re-creation".
Frequently Asked Questions
Why does SQL Server not just use the default value for existing NULLs?
SQL Server treats the DEFAULT constraint as a rule for future insertions, not a data migration tool. To maintain data integrity, it requires the administrator to explicitly define how existing empty cells should be filled before enforcing a NOT NULL rule.
Can I use a function as a default value to fix this?
Yes, you can use built-in functions like GETDATE() for datetime columns or NEWID() for unique identifiers. However, you must still ensure that existing NULLs are updated to a value (perhaps the current date) before applying the NOT NULL constraint.
Does this error happen during table creation or only during alteration?
It can happen during both. During creation, it occurs if you define a column as NOT NULL but provide a default value of NULL. During alteration, it occurs when you try to forbid NULLs in a column that already contains them.
Will changing a column to NOT NULL affect query performance?
Generally, NOT NULL columns can be slightly more efficient for the SQL Server query optimizer because it doesn't have to account for the possibility of NULL values during join operations or aggregations. It can also lead to slightly better storage efficiency in some data types.
Is there a way to fix this without writing SQL queries?
You can use the SSMS Table Designer. Right-click the table, select Design, uncheck "Allow Nulls", and provide a value in the "Default Value or Binding" column. However, if the table already contains NULLs, SSMS will likely throw the same error until you manually update the data in the table view.