PostgreSQL function for last inserted ID

后端 未结 11 1351

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

    Try this:

    select nextval('my_seq_name');  // Returns next value
    

    If this return 1 (or whatever is the start_value for your sequence), then reset the sequence back to the original value, passing the false flag:

    select setval('my_seq_name', 1, false);
    

    Otherwise,

    select setval('my_seq_name', nextValue - 1, true);
    

    This will restore the sequence value to the original state and "setval" will return with the sequence value you are looking for.

提交回复
热议问题