I have a table in Redshift.
I want to add a column which should have incremental values. I dont want to drop the table and create a new one.
Please suggest the command to add a column having auto incremental values in redshift table.
It is not possible to add an IDENTITY column to an existing table.
It might be easiest to create a new table with the new IDENTITY column, and copy the data into it. Note that the values aren't guaranteed to increase monotonically - i.e. there may be gaps.
From <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html" rel="nofollow">http://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html</a> :<blockquote>
You cannot use an ALTER TABLE ADD COLUMN command to modify the following table and column attributes:
REFERENCES (foreign key)
Use CREATE TABLE to add a new table with identity column and then use <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE_APPEND.html" rel="nofollow">ALTER TABLE APPEND</a> with FILLTARGET modifier, and then drop the original table and rename the new table it is extremely fast and simple.<blockquote>
If the target table contains columns that don't exist in the source table, include FILLTARGET. The command fills the extra columns in the source table with either the default column value or IDENTITY value, if one was defined, or NULL.</blockquote>
It moves the columns from one table to another, extremely fast, took me 4s for 1GB table in dc1.large node.<blockquote>
Appends rows to a target table by moving data from an existing source table.<br /> ...<br /> ALTER TABLE APPEND is usually much faster than a similar CREATE TABLE AS or INSERT INTO operation because data is moved, not duplicated.</blockquote>
/* This is your table to be modified */ CREATE TABLE t_original (a varchar); INSERT INTO t_original VALUES ('v1'), ('v2'); /* Here are the steps to add IDENTITY column */ CREATE TABLE t_new (id BIGINT IDENTITY(0,1), a varchar); ALTER TABLE t_new APPEND FROM t_original FILLTARGET; DROP TABLE t_original; ALTER TABLE t_new RENAME TO t_original; /* Show the result */ SELECT * FROM t_original; id | a ----+---- 1 | v2 0 | v1 (2 rows)