Re: mysql's last_insert_id

From: Dennis Björklund <db(at)zigo(dot)dhs(dot)org>
To: Bo Lorentsen <bl(at)netgroup(dot)dk>
Cc: Martijn van Oosterhout <kleptog(at)svana(dot)org>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: mysql's last_insert_id
Date: 2003-08-29 07:05:52
Message-ID: Pine.LNX.4.44.0308290900130.4053-100000@zigo.dhs.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 29 Aug 2003, Bo Lorentsen wrote:

> > There are various solutions. Some people use functions to do inserts,
> > I just use the string "currval(whatever)" in the application layer
> > which the database replaces with the appropriate value.
>
> Hmm, but what happends if more than one connection does this at the same
> time ? Then, only one of the concurrent connections will have a insert
> on the returned value, and the rest will get a wrong row reference
> returned.

That is not a problem, it's perfectly safe. It's all described in

http://www.postgresql.org/docs/7.3/static/functions-sequence.html

Basicly, currval() gives the last id for that sequence in that session. So
other sessions does not break anything.

> The only safe methode would be to do a "select nextval(whatever)", and
> aply this number by "hand" to the insert, but that remove the
> possibility to make general code even more, but it will be safe.

It's not needed. The following works fine (if the tables exists of course)
and has no problems with concurrency:

INSERT INTO foo(id,x) VALUES (DEFAULT, 'value');
INSERT INTO bar(id,foo_ref) VALUES (DEFAULT, currval('foo_id_seq'));

--
/Dennis

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Martijn van Oosterhout 2003-08-29 07:25:19 Re: mysql's last_insert_id
Previous Message David Shadovitz 2003-08-29 06:47:39 Re: CHAR vs TEXT args