Re: Serial and triggers

From: Sean Davis <sdavis2(at)mail(dot)nih(dot)gov>
To: Lan Barnes <lan(at)falleagle(dot)net>
Cc: Postgres Newbie <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Serial and triggers
Date: 2006-09-09 11:17:07
Message-ID: 4502A2B3.9020202@mail.nih.gov
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Lan Barnes wrote:
> I have come to the conclusion that the serial data type is inadequate
> for providing a reliable unique record number on inserts. The final
> sticking point is that after restoring (or replicating) a data base from
> a pg_dump, the seed number for the serial value isn't updated and I get
> dupe numbers.
>
> To compensate for this, I want to add a code snippet on inserts that
> checks for the high number in the unique number field, increments it,
> and inserts. However, it seems to me that this snippet should be an
> insert trigger so that I don't have to promulgate it to all clients,
> present and future.
>
> Because this is NOVICE I have no trouble admitting I have no trigger
> experience. However, before I get into it, I want to ask if this is
> already available on some contrib forum.
>
Lan,

It is great to hear that you want to get into using triggers. However,
the problem you are trying to solve has already been solved in postgres,
and that solution is the "serial" data type. You can add a unique
constraint to the column to guarantee uniqueness. You DO NOT want to do
what you are proposing, as it will kill performance for any moderately
large table and does not guarantee that you get a unique number.
Imagine I do some insert while inside a long-running transaction and
while the transaction is running, you do a quick insert. You insert the
same value that I was just given if you use your method. Serial types
do not allow this to happen.

As for your dump/restore problem, perhaps you should tell us how you did
the dump and restore. Generally, if you dump a whole database, you will
not have this problem. If you dump only the table and not the
associated sequence, you will need to reset the sequence, I think.

In any case, the serial datatype is the best way to go here. Save
learning triggers for another day.

Sean

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message barbara figueirido 2006-09-09 13:18:01 no more problems with mailing list addresses
Previous Message James Schiiller 2006-09-09 04:38:33 Getting Started with PostgreSQL for Windows