Re: The best option to insert data with primary id

From: Jasen Betts <jasen(at)xnet(dot)co(dot)nz>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: The best option to insert data with primary id
Date: 2010-12-11 10:17:58
Message-ID: idvj4m$8e4$1@reversiblemaps.ath.cx
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 2010-12-06, - <grandebuzon(at)gmail(dot)com> wrote:
> --0016364d26cf7fa4970496bf2224
> Content-Type: text/plain; charset=ISO-8859-1
>
> Hi everyone,
> I have a question about how best to insert and manipulate the table with
> primary key id for better productivity. I need to insert data into the table
> and get last id.
>
> 1. First option to take counter Postgres SEQUENCE:
> INSERT INTO table (id, ...) VALUES ((SELECT nextval ('seq_table')), ...)
> RETURNING (SELECT currval ('seq_table')) AS id
>
> Only thing I see, that if the row is not inserted, the counter is
> incremented every time when called. Then they will have empty unused id in
> the table and ID number will grow much. There will be many records. This id
> int8 type declared with length 64.
> Is there any option to occupy empty sequence records. I have to worry about
> this?

(assuming the default for id is nextval ('seq_table'))

INSERT INTO table ( id, ...) VALUES ( default, ...) RETURNING id;

or you can leave id and default out of the left half:

INSERT INTO table ( ...) VALUES ( ...) RETURNING id;

> 2. Second option is to take control of id and
> INSERT INTO table (id, ...) VALUES ((SELECT MAX (id) +1 FROM table), ...)
> RETURNING (SELECT MAX (id) +1 FROM table) AS id

you run into concurrency issues that way. (two concurrent inserts
could pick the same ID, one will fail with an error)

> Quero your opinions on how best to insert data to have less maintenance and
> better productivity with concurrent users.
> Thank you very much.

INSERT INTO table ( ...) VALUES ( ...) RETURNING id;

Use the sequence, that's what they were designed for.
Let id get the default value and pull that from the returning.
you will get gaps in the serquence due to failed or cancelled
transactions but there will probably not be many gaps.

--
⚂⚃ 100% natural

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Dmitriy Igrishin 2010-12-11 10:32:10 Re: Correct usage of FOR UPDATE?
Previous Message Samuel Gendler 2010-12-11 03:44:12 Re: sqlplus reporting equivalent in postgres?