问题
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.
Thanks !!!
回答1:
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 http://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html :
You cannot use an ALTER TABLE ADD COLUMN command to modify the following table and column attributes:
UNIQUE
PRIMARY KEY
REFERENCES (foreign key)
IDENTITY
回答2:
Use CREATE TABLE to add a new table with identity column and then use ALTER TABLE APPEND with FILLTARGET modifier, and then drop the original table and rename the new table it is extremely fast and simple.
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.
It moves the columns from one table to another, extremely fast, took me 4s for 1GB table in dc1.large node.
Appends rows to a target table by moving data from an existing source table.
...
ALTER TABLE APPEND is usually much faster than a similar CREATE TABLE AS or INSERT INTO operation because data is moved, not duplicated.
/* 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)
来源:https://stackoverflow.com/questions/29385916/adding-a-auto-incremental-column-into-existing-redshift-table