Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the last 10 records

Tags:

postgresql

I have a db with +- 60000 records in, I need to obtain the last 10 records entered, can this be done via postgres? I was thinking off maybe setting the offset to 50 990 and the limit to 10 or something similar, but not sure if this will be efficient?

like image 321
Elitmiar Avatar asked Nov 09 '10 08:11

Elitmiar


2 Answers

Something like the following perhaps:

SELECT * FROM your_table
ORDER BY your_timestamp DESC
LIMIT 10

If you want the result sorted by the timestamp, you can wrap this in another query and sort again. You might want to take a look at the execution plan but this shouldn't be too inefficient.

like image 92
musiKk Avatar answered Nov 15 '22 07:11

musiKk


ORDER BY id DESC LIMIT 10

If id is indexed, this will be very efficient. Could naturally also be a timestamp.

like image 44
Yodan Tauber Avatar answered Nov 15 '22 07:11

Yodan Tauber