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?
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.
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.
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With