ilhan
ilhan

Reputation: 8995

How to get latest ID number in a table?

How can I get the latest ID in a table?

Upvotes: 3

Views: 23334

Answers (7)

Alan Christopher Thomas
Alan Christopher Thomas

Reputation: 4550

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

$mysqli->insert_id

http://php.net/manual/en/mysqli.insert-id.php

Upvotes: 0

Adrian J. Moreno
Adrian J. Moreno

Reputation: 14859

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().

http://www.iknowkungfoo.com/blog/index.cfm/2008/6/1/Please-stop-using-SELECT-MAX-id

Upvotes: 0

OMG Ponies
OMG Ponies

Reputation: 332681

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:

mysql_insert_id

Otherwise, you have these options:

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

Upvotes: 1

Matt S
Matt S

Reputation: 1757

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

Upvotes: 2

user375700
user375700

Reputation: 179

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

Upvotes: 7

Dan Heberden
Dan Heberden

Reputation: 11068

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

Upvotes: 15

grateful.dev
grateful.dev

Reputation: 1437

SELECT max(id) FROM table

Upvotes: 13

Related Questions