How to retrieve last MySQL INSERT ID from db_merge() I am using db_merge for inserting or updating new records in my table.
I want to get the last inserted record id from this table, Thank you.
While there is RETURN_INSERT_ID which can be used with db_query(), I could not find a way to use with db_merge().

&lt;?php
  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' =&gt; $val1, ':arg2' =&gt; $val2);
  $last_id = db_query($query, $args, array('return' =&gt; Database::RETURN_INSERT_ID));
?


I think you will have to retrieve the last ID with another query, but you would need to check with MergeQuery::STATUS_INSERT.

$status = db_merge('example')
  -&gt;key(array('name' =&gt; $name))
  -&gt;fields(array(
      'field1' =&gt; $value1,
      'field2' =&gt; $value2,
  ))
  -&gt;execute()

if( $status == MergeQuery::STATUS_INSERT ) {
      $last_id = db_query("SELECT LAST_INSERT_ID()")-&gt;fetchField();
}