PostgreSQL function for last inserted ID

后端 未结 11 1402

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:21

    Postgres has an inbuilt mechanism for the same, which in the same query returns the id or whatever you want the query to return. here is an example. Consider you have a table created which has 2 columns column1 and column2 and you want column1 to be returned after every insert.

    # create table users_table(id serial not null primary key, name character varying);
    CREATE TABLE
    #insert into users_table(name) VALUES ('Jon Snow') RETURNING id;
     id 
    ----
      1
    (1 row)
    
    # insert into users_table(name) VALUES ('Arya Stark') RETURNING id;
     id 
    ----
      2
    (1 row)
    

提交回复
热议问题