select/display last inserted serial id in postgres

后端 未结 3 1184
被撕碎了的回忆
被撕碎了的回忆 2021-02-09 06:21

in sql server I do like this:

insert into foo(name) values(\'bob\')
select @@identity;

so I get a query/scalar result displayed

how to

3条回答
  •  清歌不尽
    2021-02-09 07:05

    Get a specific sequence:

    SELECT currval('name_of_your_sequence');
    

    Get the last value from the last sequence used:

    SELECT lastval();
    

    Check the manual as well: http://www.postgresql.org/docs/current/static/functions-sequence.html

    Edit: You could also use RETURNING in your INSERT:

    INSERT INTO foo(id, name) VALUES(DEFAULT, 'bob') RETURNING id;
    

提交回复
热议问题