I have a column 'name' in student table. I need to add NOT NULL constraint on this column. But I get SQL error saying cannot add null constraint since the existing rows in the table has null values in the column. How would I add a null constraint along with default value in a single alter statement. Below is my query.
alter table Student alter column name nvarchar NOT NULL;
SQL Server does not make this easy. I think the only way is to set the existing values to the default that you want. Then change the column to have a default value and not null:
-- Get rid of the existing `NULL` values
update students set name = '' where name is null;
-- Add the NOT NULL constraint
alter table students
alter column name varchar(255) not null;
-- Add a default value
alter table students
add constraint df_t_name default '' for name ;
Here is what it looks like in practice.
But I get SQL error saying cannot add null constraint since the existing rows in the table has null values in the column.
Have you tried overwriting the existing NULL values?
You can't have a constraint on a column when existing values would violate that constraint. You need to make your table compliant first.
SQL> ALTER TABLE CUSTOMERS MODIFY AGE INT DEFAULT 10;
Table altered.
SQL > ALTER TABLE CUSTOMERS ALTER COLUMN AGE DROP DEFAULT;
ERROR at line 2:
ORA - 01735 : invalid ALTER TABLE OPTION.
Your ALTER statement is wrong and you cannot use two ALTER commands in one statement. And we never drop default value instead we set it to NULL.
If a column has a default value, then you can use the DEFAULT clause to change the default to NULL, but you cannot remove the default value completely. If a column has ever had a default value assigned to it, then the DATA_DEFAULT column of the USER_TAB_COLUMNS data dictionary view will always display either a default value or NULL.
ALTER TABLE
Use the following SQL command to drop the default.
ALTER TABLE constomers MODIFY age DEFAULT NULL;
Use MODIFY [COL_NAME] DEFAULT NULL instead of ALTER COLUMN [COL_NAME] DROP DEFAULT so far oracle does not accept the latter version.
I have a Product table in which I want to create a new columns Modified_By and Modified_Date_Time. These columns do not allow nulls.
However, as the database already has data, in order to create this column, I had to defined as "allowing nulls". Then, I run a process which updated the new column. The last step was to uncheck the "Allow nulls" property, but when I tried to save the table changes, I got the following error:
'Product_Details' table
- Unable to modify table.
Cannot insert the value NULL into column 'Modified_Date_Time', table 'Vendor Products.dbo.Tmp_Product_Details'; column does not allow nulls. INSERT fails.
The statement has been terminated.
All the rows were succesfully updated with the correct value in the "Modified_By" and "Modified_Date_Time" column, so I don't know why I get this error...Anyway, it seems like a new "temporary" table was created by SQL Server 2008, because I don't have any table with the name "Tmp_Orders"
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
You have to set a default value.
ALTER TABLE Product ADD Modified_By datetime DEFAULT (GETDATE())
The default value will be set to today.
I find the interactive design is not very good at this sort of thing. It's better to simply add the constraint manually
ALTER TABLE Table_Name ALTER COLUMN Column_Name DataType NOT NULL
E.g.
ALTER TABLE MyTable ALTER COLUMN A_Column Int NOT NULL;
I want to add a new column "CreatedBy" to a table PerformanceData. I want this new column to be nnon-nullable, and I want existing NULLs to be populated as 'NA'. This is how I am doing this right now. Do we have a better way?
ALTER TABLE PerformanceData ADD CreatedBy VARCHAR(50) NOT NULL
CONSTRAINT DF1 DEFAULT('NA')
ALTER TABLE PerformanceData DROP CONSTRAINT DF1
I create a DEFAULT constraint and drop it later, because I don't want values to be inserted by default in future.
It looks good for me. If you want another way, you can do it in three steps:
ALTER TABLE PerformanceData ADD CreatedBy VARCHAR(50) NULL
UPDATE PerformanceData SET CreatedBy = 'NA'
ALTER TABLE PerformanceData ALTER COLUMN CreatedBy VARCHAR(50) NOT NULL
I'd do it your way in 2 steps with a default constraint.
Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'test' cannot be added to non-empty table 'shiplist' because it does not satisfy these conditions.
If YES, please let me know the syntax, if No please specify the reason.
No, you can't.
Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.
The simplest way to do this is create the column with a default and then remove the default.
ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn
Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.
Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.
No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have
It's easy to create a DEFAULT at the same time, and then immediately drop it.
I use this approach to insert NOT NULL column without default value
ALTER TABLE [Table] ADD [Column] INT NULL
GO
UPDATE [Table] SET [Column] = <default_value>
ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
No.
Just use empty string '' (in case of character type) or 0 (if numeric), etc as DEFAULT value
No you cannot. But you can consider to specify the default value to ('')
No, you can't, as SQL Server, or any other database engines will force this new column to be null for existing rows into your data table. But since you do not allow a NULL, you are required to provide a default value in order to respect your own constraint. This falls under great sense! The DBE will not extrapolate a value for non-null values for the existing rows.
#Damien_The_Unbeliever's comment ,
Is it adding computed column? Neither question nor answer implied anything like that. In case of computed column the error states:
"Only UNIQUE or PRIMARY KEY constraints can be created on computed columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require that computed columns be persisted"
OK, if to continue this guessing game, here is my script illustrating the adding of "NOT NULL" column in one "ALTER TABLE" step:
CREATE TABLE TestInsertComputedColumn
(
FirstName VARCHAR(100),
LastName CHAR(50)
);
insert into TestInsertComputedColumn(FirstName,LastName)
select 'v', 'gv8';
select * from TestInsertComputedColumn;
ALTER TABLE TestInsertComputedColumn
ADD FullName As FirstName + LastName PERSISTED NOT NULL;
select * from TestInsertComputedColumn;
--drop TABLE TestInsertComputedColumn;
I used below approach it worked for me
Syntax:
ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Example:
ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO