Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get last row value in mysql database

Tags:

mysql

I have a MySQL table with following data (sample);

UserId  -   DeviceId    -   StartDate   -   EndDate
------------------------------------------------------
1001        D119822         11/27/2011      12/02/2011
1001        D198726         11/27/2011      12/02/2011
1001        D552833         11/27/2011      12/02/2011
1001        D980993         11/27/2011      12/02/2011

I have searched for some kind of row_num or ordinal_position thing, but found nothing. How could I get the latest record from the above table without adding a serial/auto increment number column?

like image 777
Sanjay Patel Avatar asked Nov 29 '11 12:11

Sanjay Patel


People also ask

How do I get the last row of data in SQL?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table.

How can I see last 10 rows in SQL?

SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records.

How do I get the last 5 rows of a SQL table?

METHOD 1 : Using LIMIT clause in descending order As we know that LIMIT clause gives the no. of specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending.

How do I get the first row and last row in SQL?

To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.


3 Answers

Try this query, i have tested it and it works for me.

select s.*, @rownum:=@rownum+1 as rank
from your_table s, (SELECT @rownum:=0) r
order by rank DESC
LIMIT 1;
like image 102
Fred Avatar answered Sep 29 '22 15:09

Fred


"last" can be alphabetical, time, value etc. You need to define that in a simply query:

SELECT *
FROM Mytable
ORDER BY (some criteria that defines "last") DESC
LIMIT 1;
like image 35
gbn Avatar answered Sep 29 '22 16:09

gbn


Ok, so the answer to this question is simply NO. MySQL does not provide you with a built in feature that let you keep track of the order in which data has been inserted.

You could add a column that auto increments (unique id) when a row is inserted, or you could add a time stamp column to keep track of the time at which the row was inserted.

If you're not allowed to manipulate the table then maybe you could add a new table to store the latest added row of data (but this is just a bad solution really).

like image 45
Niklas Avatar answered Sep 29 '22 16:09

Niklas