Re: How to create "auto-increment" field WITHOUT a sequence object?

From: Scott Marlowe <scott(dot)marlowe(at)gmail(dot)com>
To: dmitry(at)koterov(dot)ru
Cc: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: How to create "auto-increment" field WITHOUT a sequence object?
Date: 2011-06-30 19:34:50
Message-ID: BANLkTinQo-5gQqQQEj1-PO_iYNm1AKWwsg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Jun 30, 2011 at 12:40 PM, Dmitry Koterov <dmitry(at)koterov(dot)ru> wrote:
> Hello.
> I need to create an auto-increment field on a table WITHOUT using sequences:
> CREATE TABLE tbl(
>   name TEXT,
>   uniq_id INTEGER
> );
> Each INSERT to this table must generate a new uniq_id which is distinct from
> all others.

Do they need to be in order? It looks like you only need a few since
the range you mention is 1 to 100000. you could put those numbers in
another table. Then in a transaction you grab a number from the
table, try to delete it. If it's not there you lost a race condition,
exit and try it again. If you can delete it then you try the insert
transaction. If it fails things roll back and the lock on the row is
released. If the transaction works you commit the whole thing.

Are the transactions really long running?

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Dmitry Koterov 2011-06-30 20:34:15 Re: How to create "auto-increment" field WITHOUT a sequence object?
Previous Message Dmitriy Igrishin 2011-06-30 19:30:50 Re: How to create "auto-increment" field WITHOUT a sequence object?