Adding a NOT NULL column to a Redshift table - sql

I'd like to add a NOT NULL column to a Redshift table that has records, an IDENTITY field, and that other tables have foreign keys to.
In PostgreSQL, you can add the column as NULL, fill it in, then ALTER it to be NOT NULL.
In Redshift, the best I've found so far is:
ALTER TABLE my_table ADD COLUMN new_column INTEGER;
-- Fill that column
CREATE TABLE my_table2 (
id INTEGER IDENTITY NOT NULL SORTKEY,
(... all the fields ... )
new_column INTEGER NOT NULL,
PRIMARY KEY(id)
) DISTSTYLE all;
UNLOAD ('select * from my_table')
to 's3://blah' credentials '<aws-auth-args>' ;
COPY my_table2
from 's3://blah' credentials '<aws-auth-args>'
EXPLICIT_IDS;
DROP table my_table;
ALTER TABLE my_table2 RENAME TO my_table;
-- For each table that had a foreign key to my_table:
ALTER TABLE another_table ADD FOREIGN KEY(my_table_id) REFERENCES my_table(id)
Is this the best way of achieving this?

You can achieve this w/o having to load to S3.
modify the existing table to create the desired column w/ a default value
update that column in some way (in my case it was copying from another column)
create a new table with the column w/o a default value
insert into the new table (you must list out the columns rather than using (*) since the order may be the same (say if you want the new column in position 2)
drop the old table
rename the table
alter table to give correct owner (if appropriate)
ex:
-- first add the column w/ a default value
alter table my_table_xyz
add visit_id bigint NOT NULL default 0; -- not null but default value
-- now populate the new column with whatever is appropriate (the key in my case)
update my_table_xyz
set visit_id = key;
-- now create the new table with the proper constraints
create table my_table_xzy_new
(
key bigint not null,
visit_id bigint NOT NULL, -- here it is not null and no default value
adt_id bigint not null
);
-- select all from old into new
insert into my_table_xyz_new
select key, visit_id, adt_id
from my_table_xyz;
-- remove the orig table
DROP table my_table_xzy_events;
-- rename the newly created table to the desired table
alter table my_table_xyz_new rename to my_table_xyz;
-- adjust any views, foreign keys or permissions as required

Related

Missing Keyword Error in Oracle SQL Database [duplicate]

I was wondering how can I add an identity column to existing oracle table? I am using oracle 11g. Suppose I have a table named DEGREE and I am going to add an identity column to that.
FYI table is not empty.
You can not do it in one step. Instead,
Alter the table and add the column (without primary key constraint)
ALTER TABLE DEGREE ADD (Ident NUMBER(10));
Fill the new column with data which will fulfill the primary key constraint (unique/not null), e.g. like
UPDATE DEGREE SET Ident=ROWNUM;
Alter the table and add the constraint to the column
ALTER TABLE DEGREE MODIFY (Ident PRIMARY KEY);
After that is done, you can set up a SEQUENCE and a BEFORE INSERT trigger to automatically set the id value for new records.
From Oracle 12c you would use an identity column.
For example, say your table is called demo and has 3 columns and 100 rows:
create table demo (col1, col2, col3)
as
select dbms_random.value(1,10), dbms_random.value(1,10), dbms_random.value(1,10)
from dual connect by rownum <= 100;
You could add an identity column using:
alter table demo add demo_id integer generated by default on null as identity;
update demo set demo_id = rownum;
Then reset the internal sequence to match the data and prevent manual inserts:
alter table demo modify demo_id generated always as identity start with limit value;
and define it as the primary key:
alter table demo add constraint demo_pk primary key (demo_id);
This leaves the new column at the end of the column list, which shouldn’t normally matter (except for tables with a large number of columns and row chaining issues), but it looks odd when you describe the table. However, we can at least tidy up the dictionary order using the invisible/visible hack:
SQL> desc demo
Name Null? Type
-------------------------------- -------- ----------------------
COL1 NUMBER
COL2 NUMBER
COL3 NUMBER
DEMO_ID NOT NULL NUMBER(38)
begin
for r in (
select column_name from user_tab_columns c
where c.table_name = 'DEMO'
and c.column_name <> 'DEMO_ID'
order by c.column_id
)
loop
execute immediate 'alter table demo modify '||r.column_name||' invisible';
execute immediate 'alter table demo modify '||r.column_name||' visible';
end loop;
end;
/
SQL> desc demo
Name Null? Type
-------------------------------- -------- ----------------------
DEMO_ID NOT NULL NUMBER(38)
COL1 NUMBER
COL2 NUMBER
COL3 NUMBER
One thing you can't do (as of Oracle 18.0) is alter an existing column to make it into an identity column, so you have to either go through a process like the one above but copying the existing values and finally dropping the old column, or else define a new table explicitly with the identity column in place and copy the data across in a separate step. Otherwise you'll get:
-- DEMO_ID column exists but is currently not an identity column:
alter table demo modify demo_id generated by default on null as identity start with limit value;
-- Fails with:
ORA-30673: column to be modified is not an identity column
add the column
alter table table_name add (id INTEGER);
create a sequence table_name_id_seq with start with clause, using number of rows in the table + 1 or another safe value(we don't want duplicate ids);
lock the table (no inserts)
alter table table_name lock exclusive mode;
fill the column
update table_name set id = rownum; --or another logic
add a trigger to automaticaly put the id on insert using the sequence(you can find examples on internet, for example this answer)
When you'll fire the create trigger the lock will be released. (it automatically commits).
Also, you may add unique constraint on the id column, it is best to do so.
For Oracle :
CREATE TABLE new_table AS (SELECT ROWNUM AS id, ta.* FROM old_table ta)
remember this id column is not auto incremented

Delete and Copy Big Table with Autoincrement

I want to delete many rows (More than a million) from a big table.
My table is like this:
Create table MY_TABLE (
MY_ID NUMBER GENERATED BY DEFAULT AS IDENTITY (Start with 1) primary key,
PROCESS NUMBER,
INFORMATION VARCHAR2(100)
);
Instead of using "delete from MY_TABLE where PROCESS = 3"
I do:
CREATE TABLE BCK_MY_TABLE AS (SELECT * FROM MY_TABLE WHERE PROCESS <> 3);
DROP TABLE MY_TABLE;
RENAME BCK_MY_TABLE to MY_TABLE;
Problem is: When i create another table (BCK_MY_TABLE) i lose the autoincrement on the column MY_ID. What can i do?
There isn't a straightforward way to do this with 'create table as select' (CTAS), because my_id in the new table won't be an identity column, and you can't make existing columns into identity columns.
One way would be to create the table explicitly with an identity column, copy the data and reset the identity value:
create table bck_my_table
( my_id number generated by default as identity primary key
, process number
, information varchar2(100) );
insert into bck_my_table (my_id, process, information)
select my_id, process, information from my_table;
alter table bck_my_table
modify my_id generated always as identity start with limit value;
(We have to use generated by default so the column is updatable, then change it to generated always to prevent further changes.)
Another way would be to copy the table using CTAS then add a new identity column, update it from the old my_id, reset it using start with limit value, drop the old column and rename the new one.

DB2 add auto increment column to an existing table

I have a table with following schema in my DB2 database.
CREATE TABLE IDN_OAUTH_CONSUMER_APPS (
CONSUMER_KEY VARCHAR (255) NOT NULL,
CONSUMER_SECRET VARCHAR (512),
USERNAME VARCHAR (255),
TENANT_ID INTEGER DEFAULT 0,
APP_NAME VARCHAR (255),
OAUTH_VERSION VARCHAR (128),
CALLBACK_URL VARCHAR (1024),
GRANT_TYPES VARCHAR (1024)
/
I need to add a new column ID of Type integer not null auto increment, and make it the primary key. How can I do that without deleting the table?
I could do this successfully using following set of queries.
ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ID INTEGER NOT NULL DEFAULT 0
CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE
CREATE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIGGER NO CASCADE BEFORE INSERT ON IDN_OAUTH_CONSUMER_APPS REFERENCING NEW AS NEW FOR EACH ROW MODE DB2SQL BEGIN ATOMIC SET (NEW.ID) = (NEXTVAL FOR IDN_OAUTH_CONSUMER_APPS_SEQUENCE); END
REORG TABLE IDN_OAUTH_CONSUMER_APPS
UPDATE IDN_OAUTH_CONSUMER_APPS SET ID = IDN_OAUTH_CONSUMER_APPS_SEQUENCE.NEXTVAL
And then add primary key using alter table.
Use a multi-step approach:
add the column ALTER TABLE ADD... with just the integer data type and as nullable
update the table to set the intended identity values for that column
alter the table to add the auto-generation
alter the table to add the primary key on that column
You need to have multiple steps because the identity values need to be added manually. Syntax and examples for ALTER TABLE can be found here.
There is an easy way to do it. Just run the alters above:
ALTER TABLE idn_oauth_consumer_apps ADD COLUMN id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE idn_oauth_consumer_apps ALTER COLUMN id SET GENERATED ALWAYS AS IDENTITY;
It is simple and fast even on big tables. Tested and working on DB2 for i V7R2.
I recommend using this approach. It does not require creating any satellite objects - no triggers, sequences, etc...
alter table test.test2 add column id integer not null default 0;
alter table test.test2 alter column id drop default;
alter table test.test2 alter column id set generated always as identity;
call sysproc.admin_cmd ('reorg table test.test2');
update test.test2 set id = default;
commit;
If using "db2" cli then the reorg command may be run directly without the "call sysproc.admin_cmd" wrapper.
Create a new table with the primary key field. Insert the records from the old table. Drop the old table and if you can, rename the new one. If you can't rename it, recreate it and populate from the one that now has the records.
Building on Chamila Wijayarathna's answer, I used the following:
ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD COLUMN ID INTEGER NOT NULL DEFAULT 0
CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE
CREATE TRIGGER IDN_OAUTH_CONSUMER_APPS_ID_TRIGGER NO CASCADE BEFORE INSERT ON
IDN_OAUTH_CONSUMER_APPS REFERENCING NEW AS NEW
FOR EACH ROW MODE DB2SQL BEGIN ATOMIC SET (NEW.ID) = (NEXTVAL FOR
IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE); END
REORG TABLE IDN_OAUTH_CONSUMER_APPS
UPDATE IDN_OAUTH_CONSUMER_APPS SET ID = IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE.NEXTVAL
ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD PRIMARY KEY (ID)
REORG TABLE IDN_OAUTH_CONSUMER_APPS
Then to reverse:
REORG TABLE IDN_OAUTH_CONSUMER_APPS
ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP PRIMARY KEY
DROP TRIGGER IDN_OAUTH_CONSUMER_APPS_ID_TRIGGER
DROP SEQUENCE IDN_OAUTH_CONSUMER_APPS_ID_SEQUENCE
ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP COLUMN ID
REORG TABLE IDN_OAUTH_CONSUMER_APPS
Tried this on DB2 for z/OS v12 and it worked:
alter table TABLE_NAME add column id integer generated always as identity

SQL Server Database unique number generation on any record insertion

I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column.
Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate Sequence
Create SEQUENCE RandomSeq
start with 1001
increment by 1
Go
Insert into YourTable(Id,col1...)
Select NEXT VALUE FOR RandomSeq,col1....
or else you can use Identity
Identity(seed,increment)
You can start the seed from 1101 and increment the sequence by 1
Create table YourTable
(
id INT IDENTITY(1101,1),
Col varchar(10)
)
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value.
If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want.
Alternatively you can use table script like,
CREATE TABLE Persons
(
ID int IDENTITY(12,1) PRIMARY KEY,
FName varchar(255) NOT NULL,
)
here the primary key will start seeding from 12 and seed value will be 1.
If you have your table definition already in place you can alter the column and add Computed column marked as persisted as:
ALTER TABLE tablename drop column column11;
ALTER TABLE tablename add column11 as '11'
+right('000000'+cast(ID as varchar(10)), 2) PERSISTED ;
--You can change the right operator value from 2 to any as per the requirements.
--Also replace ID with the identity column in your table.
create table inc
(
id int identity(1100,1),
somec char
)

Add a column with a default value to an existing table in SQL Server

How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?
Syntax:
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
Example:
ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
Notes:
Optional Constraint Name:
If you leave out CONSTRAINT D_SomeTable_SomeCol then SQL Server will autogenerate
a Default-Contraint with a funny Name like: DF__SomeTa__SomeC__4FB7FEF6
Optional With-Values Statement:
The WITH VALUES is only needed when your Column is Nullable
and you want the Default Value used for Existing Records.
If your Column is NOT NULL, then it will automatically use the Default Value
for all Existing Records, whether you specify WITH VALUES or not.
How Inserts work with a Default-Constraint:
If you insert a Record into SomeTable and do not Specify SomeCol's value, then it will Default to 0.
If you insert a Record and Specify SomeCol's value as NULL (and your column allows nulls),
then the Default-Constraint will not be used and NULL will be inserted as the Value.
Notes were based on everyone's great feedback below.
Special Thanks to:
#Yatrix, #WalterStabosz, #YahooSerious, and #StackMan for their Comments.
ALTER TABLE Protocols
ADD ProtocolTypeID int NOT NULL DEFAULT(1)
GO
The inclusion of the DEFAULT fills the column in existing rows with the default value, so the NOT NULL constraint is not violated.
When adding a nullable column, WITH VALUES will ensure that the specific DEFAULT value is applied to existing rows:
ALTER TABLE table
ADD column BIT -- Demonstration with NULL-able column added
CONSTRAINT Constraint_name DEFAULT 0 WITH VALUES
ALTER TABLE <table name>
ADD <new column name> <data type> NOT NULL
GO
ALTER TABLE <table name>
ADD CONSTRAINT <constraint name> DEFAULT <default value> FOR <new column name>
GO
ALTER TABLE MYTABLE ADD MYNEWCOLUMN VARCHAR(200) DEFAULT 'SNUGGLES'
The most basic version with two lines only
ALTER TABLE MyTable
ADD MyNewColumn INT NOT NULL DEFAULT 0
Beware when the column you are adding has a NOT NULL constraint, yet does not have a DEFAULT constraint (value). The ALTER TABLE statement will fail in that case if the table has any rows in it. The solution is to either remove the NOT NULL constraint from the new column, or provide a DEFAULT constraint for it.
Use:
-- Add a column with a default DateTime
-- to capture when each record is added.
ALTER TABLE myTableName
ADD RecordAddedDate SMALLDATETIME NULL DEFAULT (GETDATE())
GO
If you want to add multiple columns you can do it this way for example:
ALTER TABLE YourTable
ADD Column1 INT NOT NULL DEFAULT 0,
Column2 INT NOT NULL DEFAULT 1,
Column3 VARCHAR(50) DEFAULT 'Hello'
GO
To add a column to an existing database table with a default value, we can use:
ALTER TABLE [dbo.table_name]
ADD [Column_Name] BIT NOT NULL
Default ( 0 )
Here is another way to add a column to an existing database table with a default value.
A much more thorough SQL script to add a column with a default value is below including checking if the column exists before adding it also checkin the constraint and dropping it if there is one. This script also names the constraint so we can have a nice naming convention (I like DF_) and if not SQL will give us a constraint with a name which has a randomly generated number; so it's nice to be able to name the constraint too.
-------------------------------------------------------------------------
-- Drop COLUMN
-- Name of Column: Column_EmployeeName
-- Name of Table: table_Emplyee
--------------------------------------------------------------------------
IF EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table_Emplyee'
AND COLUMN_NAME = 'Column_EmployeeName'
)
BEGIN
IF EXISTS ( SELECT 1
FROM sys.default_constraints
WHERE object_id = OBJECT_ID('[dbo].[DF_table_Emplyee_Column_EmployeeName]')
AND parent_object_id = OBJECT_ID('[dbo].[table_Emplyee]')
)
BEGIN
------ DROP Contraint
ALTER TABLE [dbo].[table_Emplyee] DROP CONSTRAINT [DF_table_Emplyee_Column_EmployeeName]
PRINT '[DF_table_Emplyee_Column_EmployeeName] was dropped'
END
-- ----- DROP Column -----------------------------------------------------------------
ALTER TABLE [dbo].table_Emplyee
DROP COLUMN Column_EmployeeName
PRINT 'Column Column_EmployeeName in images table was dropped'
END
--------------------------------------------------------------------------
-- ADD COLUMN Column_EmployeeName IN table_Emplyee table
--------------------------------------------------------------------------
IF NOT EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table_Emplyee'
AND COLUMN_NAME = 'Column_EmployeeName'
)
BEGIN
----- ADD Column & Contraint
ALTER TABLE dbo.table_Emplyee
ADD Column_EmployeeName BIT NOT NULL
CONSTRAINT [DF_table_Emplyee_Column_EmployeeName] DEFAULT (0)
PRINT 'Column [DF_table_Emplyee_Column_EmployeeName] in table_Emplyee table was Added'
PRINT 'Contraint [DF_table_Emplyee_Column_EmployeeName] was Added'
END
GO
These are two ways to add a column to an existing database table with a default value.
Use:
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
Reference: ALTER TABLE (Transact-SQL) (MSDN)
You can do the thing with T-SQL in the following way.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
As well as you can use SQL Server Management Studio also by right clicking table in the Design menu, setting the default value to table.
And furthermore, if you want to add the same column (if it does not exists) to all tables in database, then use:
USE AdventureWorks;
EXEC sp_msforeachtable
'PRINT ''ALTER TABLE ? ADD Date_Created DATETIME DEFAULT GETDATE();''' ;
In SQL Server 2008-R2, I go to the design mode - in a test database - and add my two columns using the designer and made the settings with the GUI, and then the infamous Right-Click gives the option "Generate Change Script"!
Bang up pops a little window with, you guessed it, the properly formatted guaranteed-to-work change script. Hit the easy button.
Alternatively, you can add a default without having to explicitly name the constraint:
ALTER TABLE [schema].[tablename] ADD DEFAULT ((0)) FOR [columnname]
If you have an issue with existing default constraints when creating this constraint then they can be removed by:
alter table [schema].[tablename] drop constraint [constraintname]
This can be done in the SSMS GUI as well. I show a default date below but the default value can be whatever, of course.
Put your table in design view (Right click on the table in object
explorer->Design)
Add a column to the table (or click on the column you want to update if
it already exists)
In Column Properties below, enter (getdate()) or 'abc' or 0 or whatever value you want in Default Value or Binding field as pictured below:
ALTER TABLE ADD ColumnName {Column_Type} Constraint
The MSDN article ALTER TABLE (Transact-SQL) has all of the alter table syntax.
Example:
ALTER TABLE [Employees] ADD Seniority int not null default 0 GO
Example:
ALTER TABLE tes
ADD ssd NUMBER DEFAULT '0';
First create a table with name student:
CREATE TABLE STUDENT (STUDENT_ID INT NOT NULL)
Add one column to it:
ALTER TABLE STUDENT
ADD STUDENT_NAME INT NOT NULL DEFAULT(0)
SELECT *
FROM STUDENT
The table is created and a column is added to an existing table with a default value.
This is for SQL Server:
ALTER TABLE TableName
ADD ColumnName (type) -- NULL OR NOT NULL
DEFAULT (default value)
WITH VALUES
Example:
ALTER TABLE Activities
ADD status int NOT NULL DEFAULT (0)
WITH VALUES
If you want to add constraints then:
ALTER TABLE Table_1
ADD row3 int NOT NULL
CONSTRAINT CONSTRAINT_NAME DEFAULT (0)
WITH VALUES
This has a lot of answers, but I feel the need to add this extended method. This seems a lot longer, but it is extremely useful if you're adding a NOT NULL field to a table with millions of rows in an active database.
ALTER TABLE {schemaName}.{tableName}
ADD {columnName} {datatype} NULL
CONSTRAINT {constraintName} DEFAULT {DefaultValue}
UPDATE {schemaName}.{tableName}
SET {columnName} = {DefaultValue}
WHERE {columName} IS NULL
ALTER TABLE {schemaName}.{tableName}
ALTER COLUMN {columnName} {datatype} NOT NULL
What this will do is add the column as a nullable field and with the default value, update all fields to the default value (or you can assign more meaningful values), and finally it will change the column to be NOT NULL.
The reason for this is if you update a large scale table and add a new not null field it has to write to every single row and hereby will lock out the entire table as it adds the column and then writes all the values.
This method will add the nullable column which operates a lot faster by itself, then fills the data before setting the not null status.
I've found that doing the entire thing in one statement will lock out one of our more active tables for 4-8 minutes and quite often I have killed the process. This method each part usually takes only a few seconds and causes minimal locking.
Additionally, if you have a table in the area of billions of rows it may be worth batching the update like so:
WHILE 1=1
BEGIN
UPDATE TOP (1000000) {schemaName}.{tableName}
SET {columnName} = {DefaultValue}
WHERE {columName} IS NULL
IF ##ROWCOUNT < 1000000
BREAK;
END
Try this
ALTER TABLE Product
ADD ProductID INT NOT NULL DEFAULT(1)
GO
SQL Server + Alter Table + Add Column + Default Value uniqueidentifier
ALTER TABLE Product
ADD ReferenceID uniqueidentifier not null
default (cast(cast(0 as binary) as uniqueidentifier))
--Adding Value with Default Value
ALTER TABLE TestTable
ADD ThirdCol INT NOT NULL DEFAULT(0)
GO
IF NOT EXISTS (
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME ='TABLENAME' AND COLUMN_NAME = 'COLUMNNAME'
)
BEGIN
ALTER TABLE TABLENAME ADD COLUMNNAME Nvarchar(MAX) Not Null default
END
Add a new column to a table:
ALTER TABLE [table]
ADD Column1 Datatype
For example,
ALTER TABLE [test]
ADD ID Int
If the user wants to make it auto incremented then:
ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL
Try with the below query:
ALTER TABLE MyTable
ADD MyNewColumn DataType DEFAULT DefaultValue
This will add a new column into the Table.
This can be done by the below code.
CREATE TABLE TestTable
(FirstCol INT NOT NULL)
GO
------------------------------
-- Option 1
------------------------------
-- Adding New Column
ALTER TABLE TestTable
ADD SecondCol INT
GO
-- Updating it with Default
UPDATE TestTable
SET SecondCol = 0
GO
-- Alter
ALTER TABLE TestTable
ALTER COLUMN SecondCol INT NOT NULL
GO
There are 2 different ways to address this problem.
Both adds a default value but adds a totally different meaning to the problem statement here.
Lets start with creating some sample data.
Create Sample Data
CREATE TABLE ExistingTable (ID INT)
GO
INSERT INTO ExistingTable (ID)
VALUES (1), (2), (3)
GO
SELECT *
FROM ExistingTable
1.Add Columns with Default Value for Future Inserts
ALTER TABLE ExistingTable
ADD ColWithDefault VARCHAR(10) DEFAULT 'Hi'
GO
So now as we have added a default column when we are inserting a new record it will default it's value to 'Hi' if value not provided
INSERT INTO ExistingTable(ID)
VALUES (4)
GO
Select * from ExistingTable
GO
Well this addresses our problem to have default value but here is a catch to the problem.
What if we want to have default value in all the columns not just the future inserts???
For this we have Method 2.
2.Add Column with Default Value for ALL Inserts
ALTER TABLE ExistingTable
ADD DefaultColWithVal VARCHAR(10) DEFAULT 'DefaultAll'
WITH VALUES
GO
Select * from ExistingTable
GO
The following script will add a new column with a default value in every possible scenario.
Hope it adds value to the question asked.
Thanks.
Well, I now have some modification to my previous answer. I have noticed that none of the answers mentioned IF NOT EXISTS. So I am going to provide a new solution of it as I have faced some problems altering the table.
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'TaskSheet' AND column_name = 'IsBilledToClient')
BEGIN
ALTER TABLE dbo.TaskSheet ADD
IsBilledToClient bit NOT NULL DEFAULT ((1))
END
GO
Here TaskSheet is the particular table name and IsBilledToClient is the new column which you are going to insert and 1 the default value. That means in the new column what will be the value of the existing rows, therefore one will be set automatically there. However, you can change as you wish with the respect of the column type like I have used BIT, so I put in default value 1.
I suggest the above system, because I have faced a problem. So what is the problem? The problem is, if the IsBilledToClient column does exists in the table table then if you execute only the portion of the code given below you will see an error in the SQL server Query builder. But if it does not exist then for the first time there will be no error when executing.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[WITH VALUES]