Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select/display last inserted serial id in postgres

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 this with postgres ?

like image 564
Omu Avatar asked Sep 10 '10 19:09

Omu


1 Answers

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;
like image 78
Frank Heikens Avatar answered Sep 24 '22 07:09

Frank Heikens