For the third time it has happened to me that a sequence has been set to an initial value (zero or one, not sure) while in the table, there are around 1500 records. When it happens, new rows cannot be inserted from my application. So I would like to know possible causes for the sequence to be out of sync like that. Because I have no idea why this problem is occurring.

  • There are three different possibilities: You are running a drop sequence ..; create sequence ...;, you are calling setval(..) or you use truncate table restart identity somewhere. Also, please show us the output of select version() – a_horse_with_no_name Aug 29 '13 at 13:48

There are a few possible cases where things can get out of sync.

  1. Very old versions (unsupported) used to sometimes fail to set sequences on backup restore. If you have manual backup and restore routines, this is somewhere to look.

  2. setval('sequence_name', 1) will set to to 1.

Those are your only two possibilities unless you have a short cycle, and are cycling.

  • it was my stupid mistake. The sequence has never been used because It was specified in the import file which I didn't notice. – clime Aug 29 '13 at 14:03

Was your sequence created with the "CYCLE" option? You can check by querying the sequence directly

select * from your_seq;

Look at the "max_value" and "is_cycled" columns. What those attributes mean is covered in more detail at http://www.postgresql.org/docs/current/static/sql-createsequence.html

  • thx, is_cycled is false and max_value is huge. – clime Aug 7 '13 at 14:31
  • 1
    Do you have anywhere in your application (or external jobs/crons/etc) that might be issuing a "setval()" on the sequence to reset it? – bma Aug 7 '13 at 14:34
  • The sequence has never been used because It was specified in the import file which I didn't notice. – clime Aug 29 '13 at 14:15
  • This should be the accepted answer... THANK YOU – emmdee Nov 20 '19 at 22:23

This happened to me, when I first started using a PostgreSQL variant (Greenplum). I renamed a table, created a new table under the original name, and ran an INSERT to copy the data across. I did not know that PostgreSQL implemented SERIAL columns with an associated sequence, and when the new table got a new sequence that started at 1, I got duplicates in the table when I started inserting new records.

So this is probably not what is happening to you, if the sequence is being reset to 1. What I had was a new sequence being created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.