Database query with WHERE and ORDER BY
Try This

$nid = db_query('SELECT id FROM {stats} WHERE type = :type ORDER BY id DESC LIMIT 1', array(':type' =&gt; $param))-&gt;fetchField();


Refer db_query for more information...