Re: The best option to insert data with primary id

Поиск
Список
Период
Сортировка
От Jasen Betts
Тема Re: The best option to insert data with primary id
Дата
Msg-id idvj4m$8e4$1@reversiblemaps.ath.cx
обсуждение исходный текст
Ответ на The best option to insert data with primary id  (- <grandebuzon@gmail.com>)
Список pgsql-sql
On 2010-12-06, - <grandebuzon@gmail.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


В списке pgsql-sql по дате отправления:

Предыдущее
От: Samuel Gendler
Дата:
Сообщение: Re: sqlplus reporting equivalent in postgres?
Следующее
От: Edgardo Portal
Дата:
Сообщение: Re: concatenate question