Re: libpq-fe: how to determine unique collision ? - Mailing list pgsql-general

From Tom Lane
Subject Re: libpq-fe: how to determine unique collision ?
Date
Msg-id 22003.978627865@sss.pgh.pa.us
Whole thread Raw
In response to Re: libpq-fe: how to determine unique collision ?  (Marc SCHAEFER <schaefer@alphanet.ch>)
List pgsql-general
Marc SCHAEFER <schaefer@alphanet.ch> writes:
> No, that right, but do you have a better way of doing the following ? :)

> INSERT INTO some_table(name, surname) VALUES('marc', 'moua');
> -> creates OID 37492374
> SELECT id FROM some_table WHERE oid = 37492374;

This select will get pretty slow as the table gets large, unless you
make an index on its OID.  Which you could do, but why pay the price
of maintaining an index just for this?

> Of course you could do:
>    BEGIN TRANSACTION
>    SELECT next_val('some_table_id_sequence');
>    INSERT INTO some_table(id, name, surname)
>       VALUES(current_val('some_table_id_sequence'), 'marc', 'moua');
>    END TRANSACTION

This is the Right Way To Do It.  You do not need the transaction
(because currval() is backend-private anyway).  I'd not bother with
currval() at all, but just do

   SELECT nextval('some_table_id_sequence');

   -- this returns 4242, say

   INSERT INTO some_table(id, name, surname)
      VALUES(4242, 'marc', 'moua');

Simple, reliable, fast.

            regards, tom lane

pgsql-general by date:

Previous
From: Dave Smith
Date:
Subject: Re: Doesn't use index, why?
Next
From: Tom Lane
Date:
Subject: Re: Time Zone Query