Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a not null column without DEFAULT value

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.

like image 996
Saubhagya Avatar asked Oct 22 '10 14:10

Saubhagya


People also ask

Can we add a NOT NULL column to an existing table?

You can add a not null column at the time of table creation or you can use it for an existing table. In the above table, we have declared Id as int type that does not take NULL value. If you insert NULL value, you will get an error.

How do you insert a NOT NULL column?

To enforce NOT NULL for a column in SQL Server, use the ALTER TABLE .. ALTER COLUMN command and restate the column definition, adding the NOT NULL attribute.

How do I add a NOT NULL column to an existing table in Oracle?

How to add not null column to the existing table? explain. alter table your_table add(new_column_name NUMBER default 0 not null);

Is default NULL necessary?

No, it isn't necessary because without adding DEFAULT NULL, it gives NULL value. For example, let's say you haven't added DEFAULT NULL and inserted a record with no value, then the result would display the NULL value as the inserted value.


2 Answers

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.

like image 145
Gimly Avatar answered Sep 30 '22 02:09

Gimly


Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.

like image 39
Paul Tomblin Avatar answered Sep 30 '22 03:09

Paul Tomblin