How can i change existing column as Identity in PostgreSQL 11.1

前端 未结 2 1328
北海茫月
北海茫月 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

    Following the documentation

    ALTER TABLE patient 
        ALTER patientid SET NOT NULL,  -- optional
        ALTER patientid ADD GENERATED ALWAYS AS IDENTITY 
            (START WITH 2);  -- optional
    

    Add NOT NULL constraint if the column does not have the constraint yet. The optional clause START WITH start changes the recorded start value of the sequence.

    Test it in DB<>Fiddle.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题