Home > Net >  How can I change current value for identity type primary key column in table in PostgreSQL database?
How can I change current value for identity type primary key column in table in PostgreSQL database?

Time:11-26

I had an application and PostgreSQL database with EF Core orm. There was a table Cars and Id column had a sequence, where I could change current value for next record. Now I created a new app and moved records from old table to new table in new database. First record has an Id=12000 for example. New records started from 1 and when it reached record with Id 12000 I started get following error:

Npgsql.PostgresException (0x80004005): 23505: duplicate key value violates unique constraint "PK_Cars"

In new table Id coloumn not using sequence anymore, it has an Identity type and i can not change current value in pgAdmin. How can I make my Id coloumn change current id value?

CodePudding user response:

First, find out the actual maximum in the table:

SELECT max(id) FROM tab;

  max 
════════
 123000
(1 row)

Then, set the underlying sequence to a higher value:

ALTER TABLE tab ALTER id RESTART 200000;
  • Related