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;
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With