11

I've ran a simple insert command:

INSERT INTO names (name) VALUES ('john')

As a response I get a PG::Result object. I've been digging through those docs but I can't squeeze out of that object the info I need: what is the ID of the row I've just inserted?

dsp_099
  • 5,801
  • 17
  • 72
  • 128

1 Answers1

33
res  = conn.exec("INSERT INTO names (name) VALUES ('john') returning *")
res[0]
res[0]['id']

I used returning * just to show you can return everything not just the id. But obviously if you only need the id or the id and some other column use the explicit form just as you would in a select list

returning id, name
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
  • No idea why you got the random downvote. It's better to use `RETURNING id`, but otherwise this makes perfect sense. – Craig Ringer Jul 26 '13 at 00:06
  • 1
    @Craig Yes you are correct and I should never forget to turn on the explanation mode. Updated. – Clodoaldo Neto Jul 26 '13 at 09:28
  • 1
    The down vote may have been because "… RETURNING" is a Postgres extension, and not standard SQL. Which might be a fair criticism, but the question specifically referred to Postgres so this is definitely the best answer. – cvkline Jul 11 '15 at 02:25