Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1T3c2n-0000Xd-My for pgsql-performance@postgresql.org; Tue, 21 Aug 2012 00:10:05 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1T3c2k-0008AV-4F for pgsql-performance@postgresql.org; Tue, 21 Aug 2012 00:10:05 +0000 Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.5/8.14.5) with ESMTP id q7L0A0ji013193; Mon, 20 Aug 2012 20:10:00 -0400 (EDT) From: Tom Lane To: Craig James cc: pgsql-performance@postgresql.org Subject: Re: Does setval(nextval()+N) generate unique blocks of IDs? In-reply-to: References: Comments: In-reply-to Craig James message dated "Mon, 20 Aug 2012 16:32:27 -0700" Date: Mon, 20 Aug 2012 20:10:00 -0400 Message-ID: <13192.1345507800@sss.pgh.pa.us> X-Pg-Spam-Score: -2.1 (--) X-Archive-Number: 201208/129 X-Sequence-Number: 47667 Craig James writes: > I want to do this: > select setval('object_id_seq', nextval('object_id_seq') + 1000, false); > Now suppose two processes do this simultaneously. Maybe they're in > transactions, maybe they're not. Are they guaranteed to get distinct > blocks of IDs? No, because the setval and the nextval are not indivisible. > Or is it possible that each will execute nextval() and > get N and N+1 respectively, and then do setval() to N+1000 and N+1001, > resulting in two overlapping blocks. Exactly. > If the answer is, "This won't work," then what's a better way to do this? AFAIK the only way at the moment is * acquire some advisory lock that by convention you use for this sequence * advance the sequence * release advisory lock There have been previous discussions of this type of problem, eg http://archives.postgresql.org/pgsql-hackers/2011-09/msg01031.php but the topic doesn't seem to have come up quite often enough to motivate anybody to do anything about it. Your particular case could be handled by a variant of nextval() with a number-of-times-to-advance argument, but I'm not sure if that's enough for other scenarios. regards, tom lane