Last Updated: February 25, 2016
·
322
· rsludge

Solve sequence value problem

Sometimes (for example when restoring dump), Postgres sets invalid number to sequence, which may cause insertion errors:
duplicate key value violates unique constraint

To solve this first check max value of primary key in your table:

SELECT MAX(id) FROM table_name;

Then compare it with sequnce value:

SELECT nextval('table_name_id_seq');

Sequence value should be higher, if not run this:

SELECT setval('table_name_id_seq', (SELECT MAX(id) +1 FROM table_name));