How can i change existing column as Identity in PostgreSQL 11.1

前端 未结 2 1342
北海茫月
北海茫月 2020-12-20 19:28

I would like to changes my existing column as Auto Identity in a Postgres Database.
I tried with below script but it won\'t worked.
Let me know if you have solution

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 19:38

    Suppose you have a table patient previously created as

    CREATE TABLE patient( patientid int, col1 int );
    

    and a row inserted as

    INSERT INTO patient VALUES(1,5);
    

    Firstly create a sequence starting +1 iterated from the max value of ID and make it default for your column

    CREATE SEQUENCE mySeq START WITH 2;
    ALTER TABLE patient ALTER COLUMN patientid SET DEFAULT nextval('mySeq');
    

    and convert your column to a primary key

    ALTER TABLE patient ALTER COLUMN patientid SET NOT NULL;
    ALTER TABLE patient ADD CONSTRAINT uk_patientid UNIQUE (patientid);
    

    whenever you insert new rows such as

    INSERT INTO patient(col1) VALUES(10);
    INSERT INTO patient(col1) VALUES(15);
    

    you'll observe that you sucessfully made your column as an identity column

    SELECT * FROM patient
    
    patientid  col1
    ---------  ----
    1          5
    2          10
    3          15
    

提交回复
热议问题