MySQL Last Insert ID

Kevin FOO
Jun 24, 2021

--

Ruby mysql2 gem does not return the primary key of the last inserted row if the table runs on auto increment primary key. To get the primary key you’ll need to run

SELECT LAST_INSERT_ID()

This statement is dangerous if you are using multiple DB connections from a pool. It will return you the wrong value if you happened to use a different connection from the pool than the one you used to insert the new row.

It is still safe to use if you are in control of the DB connections from the pool. I usually have a queue of DB connections and pull a connection to use and later push it back once I’m done.

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet