Search code examples
postgresqldatabase-sequence

Reset postgres sequence to take un-used primary key ids


I am using postgres 9.5. As part of application initialization I make some inserts in database at application startup with random ids. Something like insert into student values(1,'abc') , insert into student values(10,'xyz'). Then I have some rest APIs developed which insert new rows programatically. Is there any way we can tell postgres to skip already taken ids?

It tried to take up already used ids. I noticed it does not have the sequence updated accounting for the initial inserts

Here is how I create the table

CREATE TABLE student(
    id                  SERIAL PRIMARY KEY,
    name                VARCHAR(64) NOT NULL UNIQUE     
);

Solution

  • You can advance the sequence that is populating the id column to the highest value:

    insert into student (id, name) 
    values 
      (1, 'abc'),
      (2, 'xyz');
    
    select setval(pg_get_serial_sequence('student', 'id'), (select max(id) from student));