Received: from localhost (unknown [200.46.204.184]) by developer.postgresql.org (Postfix) with ESMTP id 19E872E0039 for ; Wed, 2 Apr 2008 02:44:31 -0300 (ADT) Received: from developer.postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 86581-05 for ; Wed, 2 Apr 2008 02:44:22 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from mailserver.ttmail.com (unknown [88.255.235.9]) by developer.postgresql.org (Postfix) with ESMTP id B66EB2E002C for ; Wed, 2 Apr 2008 02:44:23 -0300 (ADT) Received: from STT1EXF01.TTHMC.LOCAL ([192.168.19.136]) by mailserver.ttmail.com with Microsoft SMTPSVC(6.0.3790.1830); Wed, 2 Apr 2008 08:44:10 +0300 Received: from alamut.mobiliz.com.tr ([213.139.194.86]) by STT1EXF01.TTHMC.LOCAL with Microsoft SMTPSVC(6.0.3790.1830); Wed, 2 Apr 2008 08:44:09 +0300 Received: from (ip-86.213-139-194.reverse.meteksan.net.tr [213.139.194.86]) by AVGW-TTMAIL-5.ttmail.com with smtp id 79d7_cf45e054_0077_11dd_b767_0011433771ac; Wed, 02 Apr 2008 08:44:08 +0300 From: Volkan YAZICI To: "John Reeve" Cc: Subject: Re: Sequential non unique IDs References: Date: Wed, 02 Apr 2008 08:48:03 +0300 In-Reply-To: (John Reeve's message of "Tue, 1 Apr 2008 15:49:46 -0700") Message-ID: <87k5jgyfho.fsf@alamut.mobiliz.com.tr> User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.0.60 (gnu/linux) MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-NAI-Spam-Rules: 1 Rules triggered BAYES_10=-0.7 X-OriginalArrivalTime: 02 Apr 2008 05:44:09.0531 (UTC) FILETIME=[928C20B0:01C89484] X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200804/7 X-Sequence-Number: 30546 On Tue, 1 Apr 2008, "John Reeve" writes: > I have the following scenario: > > A 'task' table that has the fields: > id => primary key, updated on each insert using a sequence > customerid => integer > localid => integer > > I need the localid to be sequential and unique per unique customerid. The data needs to look like this: > 1, 92, 1 > 2, 92, 2 > 3, 93, 1 > 4, 93, 2 > 5, 93, 3 > 6, 92, 3 > and so on > > I am presently doing this on the INSERT using an INNER SELECT, like this: > > INSERT INTO task (id, customerid, localid) VALUES (nextval('task_id'), > 92, (SELECT MAX(localid) + 1 FROM task WHERE customerid = 92)); Why not creating a separate serial for localid field? It won't contradict with your making localid to be sequential and unique per unique customerid restriction. CREATE TABLE task ( id serial PRIMARY KEY, customerid integer, localid serial ); CREATE UNIQUE INDEX task_customerid_localid_idx ON task (customerid, localid); INSERT INTO task (customerid) VALUES (92); If I didn't get you wrong, this should solve your problem. Regards.