How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

后端 未结 4 1903
野的像风
野的像风 2020-11-29 15:26

I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?

4条回答
  •  天命终不由人
    2020-11-29 15:59

    I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.

    ALTER TABLE target ADD COLUMN some_column SERIAL;
    INSERT INTO target SELECT * from source;
    

提交回复
热议问题