Re: 1 Sequence per Row i.e. each customer's first order starts at 1

From: Greg Stark <gsstark(at)mit(dot)edu>
To: Merrick <merrick(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: 1 Sequence per Row i.e. each customer's first order starts at 1
Date: 2009-07-02 00:32:40
Message-ID: 407d949e0907011732hf3e2b01raa41f62b43b1a3f1@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Jul 2, 2009 at 1:04 AM, Merrick<merrick(at)gmail(dot)com> wrote:
> I would like for each customer
> to have orders that start at 1 and move up sequentially. I realize
> it's probably not efficient to create a new sequence for each
> customer, so am looking for alternate ways to accomplish the same
> thing.

You could have a last_order_num in the customer's main record and when you
issue a new order do something like

UPDATE customer
SET last_order_num = last_order_num+1
WHERE customer_id = :1
RETURNING last_order_num

Then use that value in a subsequent insert -- preferrably in the same
transaction so if it rolls back you restore the old last_order_num.

You should realize this will lock the customer record so if there are
other queries in the transaction which use the customer record you have to
be careful about deadlock risks. The other downside is it could create
a lot of update traffic on the customer table so it could require a lot of
careful vacuuming there.

--
greg
http://mit.edu/~gsstark/resume.pdf

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Marlowe 2009-07-02 01:01:40 Re: 1 Sequence per Row i.e. each customer's first order starts at 1
Previous Message John Cheng 2009-07-02 00:07:15 Problem search on text arrays, using the overlaps (&&) operator