Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to select the last n rows in a table without changing the table's structure?

Tags:

sql

mysql

What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.

like image 308
thegad Avatar asked Sep 22 '08 23:09

thegad


People also ask

How do you select last n records from a table?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

How do I select n rows in MySQL?

Select Top N Rows in MySQL Using the LIMIT Clause Use of Top N query means you want to limit the results to a certain number of rows. These are used to get the best or most recent rows from a result set.


3 Answers

SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n
like image 122
Eran Galperin Avatar answered Sep 23 '22 03:09

Eran Galperin


Actually the right way to get last n rows in order is to use a subquery:

(SELECT id, title, description FROM my_table ORDER BY id DESC LIMIT 5) 
ORDER BY tbl.id ASC

As this way is the only I know that will return them in right order. The accepted answer is actually a solution for "Select first 5 rows from a set ordered by descending ID", but that is most probably what you need.

like image 43
Sergey Telshevsky Avatar answered Sep 19 '22 03:09

Sergey Telshevsky


(Similar to "marco"s answer,)
my fav is the max()-function of MySQL too, in a simple one-liner, but there are other ways of sure:

SELECT whatever FROM mytable WHERE id > (SELECT max(id)-10 FROM mytable);

... and you get "last id minus 10", normally the last 10 entries of that table.

It's a short way, to avoid the a error 1111 ("Invalid use of group function") not only if there is a auto_increment-row (here id).
The max()-function can be used many ways.

like image 21
tron5 Avatar answered Sep 23 '22 03:09

tron5