Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset identity column with last value of table's identity in postgres

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);
like image 258
Nayan Rudani Avatar asked Apr 13 '19 10:04

Nayan Rudani


People also ask

How do I reset my identity column?

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.


1 Answers

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));
like image 165
a_horse_with_no_name Avatar answered Sep 28 '22 14:09

a_horse_with_no_name