Re: Strategy for Primary Key Generation When Populating Table

From: Chris Travers <chris(dot)travers(at)gmail(dot)com>
To: Vincent Veyron <vv(dot)lists(at)wanadoo(dot)fr>
Cc: Merlin Moncure <mmoncure(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Strategy for Primary Key Generation When Populating Table
Date: 2012-02-10 23:32:36
Message-ID: CAKt_Zfsxz9ovneid-Z41ynZSwMqWfhmfK89aq4sh2OYqzLqC5Q@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, Feb 10, 2012 at 7:49 AM, Vincent Veyron <vv(dot)lists(at)wanadoo(dot)fr> wrote:

> Le jeudi 09 février 2012 à 16:30 -0600, Merlin Moncure a écrit :
>
> > natural/surrogate is a performance/usability debate with various
> > tradeoffs. but using surrogate to 'create' uniqueness is a logical
> > design error; maybe a very forgivable one for various reasons, but the
> > point stands.
>
> Please consider the following case :
>
> I record insurance claims in the table below, where id_evenement,
> id_agent and date_origine define a unique event.
>
> However, records sometimes have to be canceled (set annule=true), and
> re-recorded the same way. They're normally canceled once, but
> occasionnally twice, or more (for various reasons).
>
> What would you use for a primary key?
>
> CREATE TABLE tbldossier (
> id_evenement text NOT NULL,
> id_agent integer NOT NULL,
> date_origine date NOT NULL,
> annule boolean DEFAULT false NOT NULL);
>
> First, a surrogate key will make joins more robust and so it should be
there. Also a partial unique index could be used.

We've had a similar issue with LedgerSMB and while our solution might not
apply to you it's worth mentioning.

We had an issue of storing sales tax rates which may change or expire at
some point, so something like:

CREATE TABLE tax (
id serial not null unique,
account_id int not null,
rate numeric not null,
valid_to date,
unique (valid_to, account_id)
);

Initially we created a partial unique index on account_id where valid_to is
null.

Later we changed valid_to to a timestamp and defaulted it to infinity.
This allowed us to declare account_id, valid_to as the primary key.

Best Wishes,
Chris Travers

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Bruce Momjian 2012-02-11 00:25:40 Re: psql latex and newlines
Previous Message Merlin Moncure 2012-02-10 22:30:27 Re: " " around fields with psql