Take the 2-minute tour ×

How can I fetch the last row that was inserted using DBI (DBD::mysql)?

Code sample:

my $sth = $dbh->prepare('INSERT INTO a ( x, y, z ) VALUES ( ?, ?, ? )');
$sth->execute( $x, $y, $z );

How can I get access to the data that was inserted by the above prepare statement? I need to get the primary ID (AUTOINCREMENT) value.


From DBD::mysql documentation:


Thank you Manni and n0rd for your answers. :-)

share|improve this question

3 Answers 3

up vote 15 down vote accepted

This is a property of the statement handle. You should be able to access the ID like that:

share|improve this answer
$dbh->{mysql_insertid} returns the same. –  eugene y Mar 29 '13 at 12:48
Couldn't you get a different answer, if there was an insert between your insert and this call? –  Sam Selikoff Sep 9 '13 at 18:57
Of course. Your supposed to query $sth->{ mysql_insertid } immediately after the INSERT statement your interested in. –  innaM Sep 10 '13 at 12:51

SELECT LAST_INSERT_ID() query will also return what you want.

share|improve this answer

A database agnostic approach is to use the DBI's last_insert_id method. This approach helps to reduce dependency on a specific database:


$rv = $dbh->last_insert_id($catalog, $schema, $table, $field);

Returns a value 'identifying' the row just inserted, if possible. Typically this would be a value assigned by the database server to a column with an auto_increment or serial type. Returns undef if the driver does not support the method or can't determine the value.

share|improve this answer

Your Answer


