How can i change existing column as Identity in PostgreSQL 11.1

[亡魂溺海] 提交于 2020-07-09 09:53:08

问题


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 for the same
I don't want to use postgres SEQUENCE. I would like to use GENERATED ALWAYS AS IDENTITY.

ALTER TABLE public.patient ALTER COLUMN patientid Type int4 
USING patientid::int4 GENERATED ALWAYS AS IDENTITY;

回答1:


Following the documentation

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

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.




回答2:


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


来源:https://stackoverflow.com/questions/55555547/how-can-i-change-existing-column-as-identity-in-postgresql-11-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!