I have a table "MY_TABLE" in Snowflake that I would like to add an identity column to. I tried
ALTER TABLE "MY_TABLE"
ADD COLUMN primary_key int IDENTITY(1,1);
But this returns
SQL compilation error: Cannot add column 'PRIMARY_KEY' with non-constant default to non-empty table 'MY_TABLE'.
Is this just not possible in snowflake?
To try to get around this limitation, I tried to create a temp version of the table
CREATE OR REPLACE TABLE "MY_TABLE_TEMP" LIKE "MY_TABLE"
ALTER TABLE "MY_TABLE_TEMP" ADD COLUMN primary_key int IDENTITY(1,1)
INSERT INTO "MY_TABLE_TEMP"
SELECT * FROM "MY_TABLE";
But now I get the error
SQL compilation error: Insert value list does not match column list expecting <x+1> but got <x>
Which sort of makes sense, since I am not passing the primary key. At this point it seems like I may have to manually enter the list of x (which is a very high number) of column names into the sql query, so I am wondering if I am just doing this all wrong. Has anyone else run into a similar issue?
You can just specify columns in the insert: CREATE TABLE TEST_TABLE_TEMP LIKE TEST_TABLE; ALTER TABLE TEST_TABLE_TEMP ADD COLUMN primary_key int IDENTITY(1,1); INSERT INTO TEST_TABLE_TEMP (col1,col2,...) SELECT col1,col2,...
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.
In Snowflake, you can set the default value for a column, which is typically used to set an autoincrement or identity as the default value, so that each time a new row is inserted a unique id for that row is generated and stored and can be used as a primary key.
One option to add an identity to the table is to add a new column to the table and set it as an identity. This is possible through the Alter statement. However, if we want to set the identity to an already existing column in the table, we cannot use this DDL command.
Can you try this
CREATE TABLE TEST_TABLE_TEMP LIKE TEST_TABLE;
ALTER TABLE TEST_TABLE_TEMP ADD COLUMN primary_key int IDENTITY(1,1);
create or replace sequence seq_01 start = 1 increment = 1;
INSERT INTO TEST_TABLE_TEMP
SELECT *,seq_01.NEXTVAL FROM TEST_TABLE;
SELECT * FROM TEST_TABLE_TEMP;
Instead of using IDENTITY
, you could use your own SEQUENCE
to create a unique id for each row.
Fixing the example in the question with a sequence:
CREATE OR REPLACE SEQUENCE seq1;
CREATE OR REPLACE TABLE "MY_TABLE_TEMP" LIKE "MY_TABLE";
ALTER TABLE "MY_TABLE_TEMP"
ADD COLUMN primary_key int DEFAULT seq1.nextval;
INSERT INTO "MY_TABLE_TEMP"
SELECT *, seq1.nextval
FROM "MY_TABLE";
(after posting this answer, I noticed it's very similar to Rajib's)
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