Upgrade a Database table to add a new column - sql

I need to convert an existing db table to a new db table which adds a new column.
I have the following sql code which set the default value of this column to be -1.
// Insert new column for holding appWidgetIds
db.execSQL("ALTER TABLE favorites " +
"ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
But how can i set the default value of the column to increment one by one for each row?

It depends on your DBMS. MySQL uses AUTO_INCREMENT:
ALTER TABLE favorites ADD COLUMN appWidgetId INTEGER
NOT NULL DEFAULT -1 AUTO_INCREMENT
PostgreSQL uses CREATE SEQUENCE:
CREATE SEQUENCE favorites_seq;
ALTER TABLE favorites ADD COLUMN appWidgetId INTEGER
NOT NULL DEFAULT -1 nextval('favorites_seq')
SQL Server uses IDENTITY:
ALTER TABLE favorites ADD COLUMN appWidgetId INTEGER
IDENTITY(1,1) NOT NULL DEFAULT -1
As a side note, I don't know why you're setting your default as -1. Why would you make your integers signed if they will always be positive? You should make the default 0 for efficiency.

This depends on which DBMS you're using. For MySQL, you can use:
ALTER TABLE x ADD COLUMN y INTEGER NOT NULL DEFAULT -1 AUTO_INCREMENT
See http://dev.mysql.com/doc/refman/5.0/en/alter-table.html

Are values auto-incremented for new rows AFTER your conversion too? If not, you could do 3 steps:
ALTER the table with NULLable column
UPDATE the new column with whatever rules you have
ALTER again to set NOT NULL.

Related

New Column With Default Value not setting for old records

I created a new Column S_TEST and set its default value to 2 and save the table, but unfortunately the old records were not set automatically, instead they have NULL values. See my screenshots.
If you add a new column which is not null then the default constraint will automatically populate the column with the default value for existing rows.
If you add a new column which is nullable the DDL statement should have WITH VALUES option to force setting of the default values for existing rows.
ALTER TABLE dbo.tab ADD Col int NULL DEFAULT 10 WITH VALUES ;
Think this way, DBs add new columns with NULL values, even it has a default assigned.
To avoid that, make it not NULL:
This works for me on SQL 2016:
ALTER TABLE [DB].[MY_TABLE] ADD MyText VARCHAR(255) NOT NULL DEFAULT 'yes'
Another way of reaching the same, is creating a VIEW on the top of our table.

Alter column set default unsupported feature

I want to alter the table and set the default sequence of a column which is identity. When I try to run
ALTER TABLE report.test_table MODIFY id set default test_table_seq.NEXTVAL;
it shows following error:
[0A000][2] Unsupported feature 'Alter Column Set Default'.
Here's create table sql:
create table report.test_table(
id int identity,
txt text
);
Considering snowflake documentation a column must have a sequence to use alter column set default and trusting snowflake docs too identity or autoincrement are synonyms and snowflake use sequence to autoincrement that column.
https://docs.snowflake.net/manuals/sql-reference/sql/create-table.html
Sadly, there's no other way. Snowflake uses a sequence in backend but doesn't allow applying another sequence on that. You can only alter the column to add a new sequence if it was added as default while table creation.

How DB2(v10.5.0.5) add auto increment column to an exists table

I'm trying to add an auto increment column in an existing table of DB2.
DB2 version is v10.5.0.5.
Following is my query:
alter table DB2INST1.AAA_BJ_BOND
ADD COLUMN id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE DB2INST1.AAA_BJ_BOND ALTER COLUMN id
set generated always as identity (start with 1);
but I got following error:
"com.ibm.db2.jcc.am.SqlSyntaxErrorException: ALTER TABLE "DB2INST1.AAA_BJ_BOND"
specified attributes for column "ID" that are not compatible with the existing
column.. SQLCODE=-190, SQLSTATE=42837, DRIVER=4.13.127"
What can I do to solve this problem?
You must drop the column DEFAULT value first.
This is mentioned in the description of SQL0190N:
If SET GENERATED ALWAYS AS (expression) is specified, but the column
is already defined with a form of generation (default, identity, or
expression) and there is no corresponding DROP in the same statement.
ALTER TABLE DB2INST1.AAA_BJ_BOND
ALTER COLUMN id drop default;
ALTER TABLE DB2INST1.AAA_BJ_BOND ALTER COLUMN id
set generated always as identity (start with 1);
Now I have successfully added auto-increasing ID to the table through the following three steps:
ALTER TABLE DB2INST1.AAA_SEAT ADD COLUMN ID INTEGER NOT NULL DEFAULT 0;
ALTER TABLE DB2INST1.AAA_SEAT ALTER COLUMN ID DROP DEFAULT;
ALTER TABLE DB2INST1.AAA_SEAT ALTER COLUMN ID SET GENERATED ALWAYS AS IDENTITY (START WITH 1);

MS Access - sql expression for allow null?

I use MS Access (2003) database. Once I create a column I set NOT NULL using sql statement:
ALTER TABLE Table1
ALTER column myColumn INTEGER not null
Is there a way to change it back to allow null values? I already tried:
ALTER TABLE Table1
ALTER column myColumn INTEGER null
but nothing...
You cant specify null in ALTER TABLE (although not null is allowed)
See the below documentation and also this discussion on this toppic
Syntax
ALTER TABLE table {ADD {COLUMN field type[(size)] [NOT NULL] [CONSTRAINT index] | ALTER COLUMN field type[(size)] | CONSTRAINT multifieldindex} | DROP {COLUMN field I CONSTRAINT indexname} }
Old School Solution:-
create a new temporray field as null with the same datatype
update the new temporary field to the existing NOT NULL field
drop the old NOT NULL field
create the droped column with the same datatype again without NOT NULL
update the existing field to the temporary field
if there have been indices on the existing field, recreate these
drop the temporary field
Try something like this using MODIFY :-
ALTER TABLE Table1 MODIFY myColumn INT NULL;
The only way I've found is to use DAO directly on the table.
Set db.TableDefs(strTable1).Fields(strFieldName).Required = false

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.
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