Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i change existing column as Identity in PostgreSQL 11.1

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;
like image 904
Nayan Rudani Avatar asked Apr 07 '19 04:04

Nayan Rudani


People also ask

How do I change a column to an identity?

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.

Can we modify an existing table column to add the identity property?

You can add and drop the generated or identity property of a column in a table using the ALTER COLUMN clause in the ALTER TABLE statement.

How do I change the datatype of a column in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.


1 Answers

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.

like image 57
klin Avatar answered Sep 24 '22 19:09

klin