'Get Last Entry in a MySQL table

I'm basically trying to make a "goal" bar. The goal is determined by getting the last entry I made in a MySQL table. I want to get the ID of the last entry therefore.

How do I get the last entry in the table and then get the id from that last entry?

(Using PHP)



Solution 1:[1]

To get the greatest id:

SELECT MAX(id) FROM mytable

Then to get the row:

SELECT * FROM mytable WHERE id = ???

Or, you could do it all in one query:

SELECT * FROM mytable ORDER BY id DESC LIMIT 1

Solution 2:[2]

you can use LAST_INSERT_ID() function. example:

$sql = "SELECT * FROM mytable WHERE id = LAST_INSERT_ID()";

Solution 3:[3]

you can use this query to get the results you want with this sql query as used in this example:

$sql = "SELECT user_id FROM my_users_table ORDER BY user_id DESC LIMIT 0,1";

Solution 4:[4]

To do this reliably, you must have some field in the table that you can examine to determine which is last. This could be a time stamp of when you added the record, a sequence number that continually increases (especially an auto-incrementing sequence number), etc.

Then, let's suppose it's a sequence number called "rec_seq". You'd write something like:

select * from my_table
where rec_seq=(select max(rec_seq) from my_table)

Solution 5:[5]

select all fields from table in reverse order and set limit 0,1 This will give you last result of table field data

Solution 6:[6]

Get the latest entry of a user

'SELECT user_id FROM table_name WHERE user_id = '.$userid.' ORDER BY user_id DESC LIMIT 1';

Solution 7:[7]

if the field is auto-incremented then you can use LAST_INSERT_ID

Solution 8:[8]

The above answers show how to get the latest entry by id. If one uses non-incrementing ids such as UUIDs as keys, this does not work. In that case one could use a created_at column instead.

-- highest id
SELECT * FROM some_table ORDER BY id DESC LIMIT 1;

-- latest created at date
SELECT * FROM some_table ORDER BY created_at DESC LIMIT 1;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Petroelje
Solution 2 laltin
Solution 3 Rasmus Søborg
Solution 4 Jay
Solution 5 Puzzled Boy
Solution 6 user3917039
Solution 7 Sevle
Solution 8 swift-lynx