I would like to changes my existing column as Auto Identity in a Postgres Database.
I used below script to set auto identity column and set default start with 1.
But here i would like to reset identity column value to table's last value.
Let me know if you have any solutions.
ALTER TABLE patient
ALTER patientid SET NOT NULL,
ALTER patientid ADD GENERATED ALWAYS AS IDENTITY (START WITH 1);
Here I'm setting up something like this:
ALTER TABLE Patient
ALTER COLUMN PatientId RESTART WITH (select Max(patientId) + 1 from patient);
Here, to reset the Identity column in SQL Server you can use DBCC CHECKIDENT method. Syntax : DBCC CHECKIDENT ('table_name', RESEED, new_value); Note : If we reset the existing records in the table and insert new records, then it will show an error.
An identity columns is also backed by a sequence, and pg_get_serial_sequence()
will return that sequence name. That can be used together with setval()
.
After running the add generated always
part you can adjust the sequence using this statement:
SELECT setval(pg_get_serial_sequence('patient', 'patientid'),
(select max(patientid) from patient));
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