Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Redshift - Add IDENTITY column to existing table

In AWS Redshift, when attempting to add an IDENTITY column to an existing table using the command

ALTER TABLE table_name ADD COLUMN id bigint IDENTITY(1,1);

I get the following error

ERROR: ALTER TABLE ADD COLUMN does not support columns with type IDENTITY

Which obviously implies that this simply isn't allowed in Redshift. Will I need to drop and recreate the table? Or is there some workaround solution to get this done in Redshift?

like image 848
MJ. Avatar asked May 21 '15 14:05

MJ.


People also ask

Can we add identity to existing column?

There is no straightforward way to add IDENTITY to an existing column. We need to follow a series of steps to achieve this. There are two ways to do this. We need to convert the 'student_id' column of the table below to an IDENTITY column.

How do you set identity in an existing table?

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.

How do you create an identity column in Redshift?

INSERT INTO tablename ( identity-column-name ) VALUES (DEFAULT); Overriding values of a default identity column doesn't affect the next generated value. You can't add a default identity column with the ALTER TABLE ADD COLUMN statement. You can append a default identity column with the ALTER TABLE APPEND statement.


2 Answers

While you can't do it directly, you can accomplish this in a few steps. If we have existing table t1 defined as:

CREATE TABLE t1 (
c1 vachar(MAX),
c2 int
);

First, create a new table that has the same columns as t1, but with the addition of the identity column that you want to add:

CREATE TABLE t2 (
id bigint IDENTITY(1,1),
c1 varchar(MAX),
c2 int
);

Then, insert all of the rows of t1 into t2, filling every column other than the identity column:

INSERT INTO t2 (c1, c2)
(SELECT * FROM t1);

Now we can drop the original table:

DROP TABLE t1

And finally rename the new table to original table:

ALTER TABLE t2
RENAME TO t1;
like image 95
gnelson Avatar answered Oct 13 '22 20:10

gnelson


You must add IDENTITY column during table declaration. And you can't add it later.

Docs: You cannot use an ALTER TABLE ADD COLUMN command to modify the following table and column attributes:

    UNIQUE

    PRIMARY KEY

    REFERENCES (foreign key)

    IDENTITY
like image 32
Vor Avatar answered Oct 13 '22 20:10

Vor