Received: from localhost (unknown [200.46.204.183]) by developer.postgresql.org (Postfix) with ESMTP id B8E7A2E002D for ; Wed, 2 Apr 2008 00:24:37 -0300 (ADT) Received: from developer.postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 34169-07 for ; Wed, 2 Apr 2008 00:24:33 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from www.postnewspapers.com.au (www.postnewspapers.com.au [202.61.230.242]) by developer.postgresql.org (Postfix) with ESMTP id 57DDB2E0039 for ; Wed, 2 Apr 2008 00:24:32 -0300 (ADT) Received: from mail.postnewspapers.com.au (202-89-185-120.static.dsl.amnet.net.au [202.89.185.120]) by www.postnewspapers.com.au (Postfix) with ESMTP id 72D9E2E5A; Wed, 2 Apr 2008 11:24:28 +0800 (WST) Received: from [10.0.0.53] (wallace.localnet [10.0.0.53]) by mail.postnewspapers.com.au (Postfix) with ESMTP id 74FDF1E0435; Wed, 2 Apr 2008 11:24:30 +0800 (WST) Message-ID: <47F30A70.3090507@postnewspapers.com.au> Date: Wed, 02 Apr 2008 12:24:16 +0800 From: Craig Ringer User-Agent: Icedove 1.5.0.12 (X11/20070607) MIME-Version: 1.0 To: John Reeve Cc: pgsql-sql@postgresql.org Subject: Re: Sequential non unique IDs References: In-Reply-To: X-Enigmail-Version: 0.94.2.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200804/6 X-Sequence-Number: 30545 John Reeve wrote: > I've already considered: > 1. I can't lock the table, because there are too many inserts happening > and it will slow down the app. In a locking approach you may not need to lock the whole table. You should only need to lock the entry for the customer being altered, eg: BEGIN; SELECT 1 FROM task WHERE customerid = 92 FOR UPDATE; INSERT INTO task (id, customerid, localid) VALUES (nextval('task_id'), 92, (SELECT MAX(localid) + 1 FROM task WHERE customerid = 92)); If I'm not mistaken, that should ensure that for any given customer ID there's only one transaction holding the locks on that customer. It won't prevent SELECTs from reading the customer's records, but you don't mind that so long as they're not using the customer's records to determine the least free localid. That'll help reduce the hit on your app's performance, too. If you do mind the , use SELECT ... FOR SHARE and you'll wait on the FOR UPDATE lock if one is active (however, it might prove hard to obtain a FOR UPDATE lock if there are lots of FOR SHARE operations active). I *think* that'll work, but you should of course test and investigate before doing anything as crazy as taking my word for it. > Anyone know a solution for this? This can't be the first time anyone has > ever tried to do this. Thanks! If I'm not mistaken about the similarity, you might want to search the archives for the thread "Primary Key with serial". It might be informative. -- Craig Ringer