Skip site navigation (1) Skip section navigation (2)

Re: MySQL LAST_INSERT_ID() to Postgres

From: "Scott Marlowe" <scott(dot)marlowe(at)gmail(dot)com>
To: "Steve Atkins" <steve(at)blighty(dot)com>
Cc: "pgsql-general General" <pgsql-general(at)postgresql(dot)org>
Subject: Re: MySQL LAST_INSERT_ID() to Postgres
Date: 2008-08-28 21:17:07
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-general
On Thu, Aug 28, 2008 at 1:56 PM, Steve Atkins <steve(at)blighty(dot)com> wrote:
> Or lastval() if you want something bug-compatible with MySQL.

Not exactly.  LAST_INSERT_ID is transactionally safe in that one
connection doesn't see another connections.  However, it has it's own
special brand of bug that to me, is much worse.

create table test (id int auto_increment primary key);
insert into test values (DEFAULT);
select LAST_INSERT_ID();

In two sessions:
S1: insert into test values (DEFAULT);
S1: select LAST_INSERT_ID();
S2: insert into test values (DEFAULT);
S2: select LAST_INSERT_ID();
S1: select LAST_INSERT_ID();

So that seems reasonable.  But here's the part that makes me go huh?

insert into test values (DEFAULT),(DEFAULT),(DEFAULT);
select * from test;
| id |
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
 select LAST_INSERT_ID();
|                3 |

uh, what?  It returns not the LAST insert from a multicolumn insert
but the first.  Correct me if I'm wrong, but 3 is most certainly NOT
the last id inserted by our session.

Try the same thing in postgresql and you get the much less
pathological and more understandable set returned:

insert into test values (DEFAULT),(DEFAULT),(DEFAULT) returning i;

And if it was a BIG insert, and interleaved with another big insert so
it got every other ID, you'd get something back like 6,8,10,11,14
etc... so you'd know again, exactly which records you'd created.

In response to

pgsql-general by date

Next:From: BillDate: 2008-08-28 21:26:16
Subject: Re: MySQL LAST_INSERT_ID() to Postgres
Previous:From: Tino WildenhainDate: 2008-08-28 20:56:02
Subject: Re: SQL optimization - WHERE SomeField STARTING WITH ...

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group