How can I get the latest ID in a table?

+11  A: 

SELECT max(id) FROM table

Saggi Malachi
+12  A: 

If you mean the latest generated ID from an insert statement with an auto-increment column, then mysql_insert_id() should help ya out

Dan Heberden
+4  A: 

SELECT id FROM table ORDER BY id DESC LIMIT 1 should work as well

This solution would be preferred, if of course the id column is the primary key. MySQL will only access the index to return this value, and not have to resort to the data.
Dave Rix
+2  A: 

IF you've just inserted into a table with auto_increment you can run right after your query.

SELECT last_insert_id();

Otherwise the max(id) FROM table

Matt S
+1  A: 

If the table has an auto_increment column defined - you can check by looking for "auto_increment" in the output from DESC your_table, use:


Otherwise, you have these options:

SELECT MAX(id) FROM your_table
SELECT id FROM your_table ORDER BY id LIMIT 1
OMG Ponies

If there are no inserts being done on a table, then SELECT MAX(ID) should be fine. However, every database has a built-in function to return the most recently created primary key of a table after an insert has been performed. If that's what you're after, don't use MAX().



Also, for the id of the last record inserted, if you're using MySQLi, it would look like this:



Alan Christopher Thomas