Let\'s say I have the following data in the Customers table: (nothing more)
ID FirstName LastName
-------------------------------
20 John Macken
select max(id) from Customers
select max(id) from customers
If you want to just select the id use select max(id) from customer.
If you want to select the entire row then use a query like this:
select c1.*
from customer c1, (select max(id) as max_id from customer )c2
where c1.id=c2.max_id
c2 is an alias for the new temporary table which contains max id. Then its cross product is taken with customer table to get the entire row.
Here we are writing a query in the from clause, which can often be quite useful.
You can do
SELECT MAX(ID) FROM Customers;
If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.
select IDENT_CURRENT('TableName') as LastIdentity
Using MAX(id) is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id). IDENT_CURRENT is nearly instantaneous...
To find the next (still not used) auto-increment, I am using this function for somewhat years now.
public function getNewAI($table)
{
$newAI = false;
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SHOW TABLE STATUS LIKE '".$table."'";
$result = $mysqli->query($sql);
if($result) {
$row = $result->fetch_assoc();
$newAI = $row['Auto_increment'];
}
$mysqli->close();
return $newAI;
}