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?
The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With