Re: arbitrary number of values from a sequence - Mailing list pgsql-general

From Tom Lane
Subject Re: arbitrary number of values from a sequence
Date
Msg-id 25770.988995276@sss.pgh.pa.us
Whole thread Raw
In response to arbitrary number of values from a sequence  ("Gyozo Papp" <pgerzson@freestart.hu>)
List pgsql-general
"Gyozo Papp" <pgerzson@freestart.hu> writes:
> and I need 5 five subsequent values (from 1234 to 1238), - in other
> words - a range with a length of 5 from the current value. I thought
> this simple trick could do the job :

> =#select setval('seq', (select nextval('seq')) + 5);

No good, because there's no interlock being held between the nextval()
and the setval().  So, while process A is busy adding 5 to the nextval()
result it got, process B could sneak in and do a nextval().  It will
then be allocated one of the values that A thinks it's reserved.  After
the setval() occurs, there's not even any way to see anything's wrong.

I do not think you can avoid calling nextval() 5 times, in the current
implementation; nor can you assume you will get 5 consecutive values.
However, you might be able to improve efficiency by setting the 'cache'
value of the sequence to be more than one.  Read the caution about
'cache' on the CREATE SEQUENCE manual page first...

            regards, tom lane

pgsql-general by date:

Previous
From: "Mihai Gheorghiu"
Date:
Subject: Varchar vs. text
Next
From: Tom Lane
Date:
Subject: Re: VACUUM is hanging