Whats the standard way of getting the last insert id?

后端 未结 4 1277
刺人心
刺人心 2021-01-05 05:32

What\'s the sql standard to get the last inserted id? If there is such a thing.

mysql: LAST_INSERT_ID()
postgresql: ... RETURNING f_id
mssql: SCOPE_IDENTIT

4条回答
  •  Happy的楠姐
    2021-01-05 05:58

    This is more a clarification to a few comments than a real new answer, but it fits better here. select max(id) works fine as long as the client is in a serializable transaction. In pgsql, you can prove it to yourself. Open two psql sessions, and run this, first in the default read committed and then in serializable:

    p1: create table test (id serial);
    p1 and p2: begin;
    p1 and p2: set transaction isolation level serializable;
    p1: insert into test values (DEFAULT);
    p2: insert into test values (DEFAULT);
    p1: select max(id) from test;
     1
    p2: select max(id) from test;
     2
    p2: commit;
    p1: select max(id) from test;
     2
    

    However, with read committed:

    p1: create table test (id serial);
    p1 and p2: begin;
    p1 and p2: set transaction isolation level read committed;
    p1: insert into test values (DEFAULT);
    p2: insert into test values (DEFAULT);
    p1: select max(id) from test;
     1
    p2: select max(id) from test;
     2
    p2: commit;
    p1: select max(id) from test;
     1
    

    Performance wise serializable transactions can have negative impacts or result in transactions that fail and must be rolled back and tried again, etc.

    Returning or currval() are much better ideas. However, to say that max(id) just can't be trusted is wrong, if the transaction doing it is serializable.

提交回复
热议问题