Re: MySQL LAST_INSERT_ID() to Postgres - Mailing list pgsql-general

From Bill
Subject Re: MySQL LAST_INSERT_ID() to Postgres
Date
Msg-id 48B71AEE.6030404@dbginc.com
Whole thread Raw
In response to Re: MySQL LAST_INSERT_ID() to Postgres  (Steve Atkins <steve@blighty.com>)
Responses Re: MySQL LAST_INSERT_ID() to Postgres  ("Scott Marlowe" <scott.marlowe@gmail.com>)
List pgsql-general
Steve Atkins wrote:
>
> On Aug 28, 2008, at 12:09 PM, Scott Marlowe wrote:
>
>> On Thu, Aug 28, 2008 at 10:14 AM, Masis, Alexander (US SSA)
>> <alexander.masis@baesystems.com> wrote:
>>> I was mapping C++ application code that works with mySQL to work with
>>> Postgres.
>>> There were a number of articles on line regarding the conversion from
>>> mySQL to Postgres like:
>> SNIP
>>> Well, in MySQL it's easy you just do:
>>> "SELECT LAST_INSERT_ID();"
>>>       In Postgres, however it is not that simple. You have to know the
>>> name of so called "insert sequence". Postgres has a system function for
>>> that( SQL line below ).
>>> In Postgres you will have to provide the table and column name(
>>> "auto_increment" type in MySQL or "serial or bigserial" in Postgres).
>>>
>>> Here is that SQL query that returns the last inserted ID:
>>>
>>>  "SELECT CURRVAL(
>>> pg_get_serial_sequence('my_tbl_name','id_col_name'));"
>>
>> That's the hard way.  Starting with pgsql 8.2 you can do it much more
>> easily:
>>
>> create table tester (id serial primary key, info text);
>> insert into tester (info) values ('this is a text string') returning id;
>>
>> tada!  All done, that insert will return the id for you.
>
> Or lastval() if you want something bug-compatible with MySQL.
>
> Cheers,
>   Steve
>
>
I am new to PostgreSQL but it seems to me that lastval() will only work
if the insert does not produce side effects that call nextval().
Consider the case where a row is inserted into a table that has an after
insert trigger and the after insert trigger inserts a row into another
table which has a serial primary key. In that case I assume that
lastval() will  return the value from the serial column in the second table.

Bill

pgsql-general by date:

Previous
From: Raymond O'Donnell
Date:
Subject: Re: MySQL LAST_INSERT_ID() to Postgres
Next
From: Raymond O'Donnell
Date:
Subject: Re: ERROR: relation . . . does not exist