PostgreSQL function for last inserted ID

后端 未结 11 1233

In PostgreSQL, how do I get the last id inserted into a table?

In MS SQL there is SCOPE_IDENTITY().

Please do not advise me to use something like this:

11条回答
  •  太阳男子
    2020-11-22 14:25

    you can use RETURNING clause in INSERT statement,just like the following

    wgzhao=# create table foo(id int,name text);
    CREATE TABLE
    wgzhao=# insert into foo values(1,'wgzhao') returning id;
     id 
    ----
      1
    (1 row)
    
    INSERT 0 1
    wgzhao=# insert into foo values(3,'wgzhao') returning id;
     id 
    ----
      3
    (1 row)
    
    INSERT 0 1
    
    wgzhao=# create table bar(id serial,name text);
    CREATE TABLE
    wgzhao=# insert into bar(name) values('wgzhao') returning id;
     id 
    ----
      1
    (1 row)
    
    INSERT 0 1
    wgzhao=# insert into bar(name) values('wgzhao') returning id;
     id 
    ----
      2
    (1 row)
    
    INSERT 0 
    

提交回复
热议问题