Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of the row inserted from PG::Result

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?

like image 708
dsp_099 Avatar asked Jul 25 '13 22:07

dsp_099


People also ask

How do I get the last row inserted id in SQL?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do I find the table ID in PostgreSQL?

To get a table OID, cast to the object identifier type regclass (while connected to the same DB): SELECT 'mytbl'::regclass::oid; This finds the first table (or view, etc.) with the given name along the search_path or raises an exception if not found.

How do I find the last inserted ID in a database?

Get ID of The Last Inserted Record If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.


1 Answers

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
like image 155
Clodoaldo Neto Avatar answered Oct 19 '22 03:10

Clodoaldo Neto