Getting last record from mysql

Almost done.
You succeed in getting the insert order.
So:

select myId, @rowid:=@rowid+1 as myrow from maxID, (SELECT @rowid:=0) as init ORDER BY myrow desc LIMIT 1;

In my console I get the following:

mysql> select myId, @rowid:=@rowid+1 as myrow from maxID, (SELECT @rowid:=0) as
init ORDER BY myrow desc LIMIT 1;
+------+-------+
| myId | myrow |
+------+-------+
| A003 |     4 |
+------+-------+
1 row in set (0.00 sec)

Demo

UPDATE

Yak is right. My solution is not deterministic. Maybe it works for small amount of records. I found tons of post abount unreliability of default sorting of a SELECT statement (here for example).
Next steps:

  • Under which conditions the default SELECT sorting matches the insertion order?
  • Is it possible to obtain the last inserted record in a table without an incremental id or an insertion timestamp?

I know it’s not an answer, but stating the problem limit the problem.

Leave a Comment