Android SQLite Query – Getting latest 10 records

Change the DESC to ASC and you will get the records that you want, but if you need them ordered, then you will need to reverse the order that they come in. You can either do that in your own code or simply extend your query like so:

select * from (
    select *
    from tblmessage
    order by sortfield ASC
    limit 10
) order by sortfield DESC;

You really should always specify an order by clause, not just ASC or DESC.

on large databases, the ORDER BY DESC statement really might slow down the system, e.g. raspberry pi. A nice approach to avoid ORDER BY is the OFFSET command. And you even keep the stored order:

SELECT * FROM mytable LIMIT 10 OFFSET (SELECT COUNT(*) FROM mytable)-10;

see: http://www.sqlite.org/lang_select.html

check out your performance with:

.timer ON

Slightly improved answer:

select * from (select * from tblmessage order by sortfield DESC limit 10) order by sortfield ASC;

Michael Dillon had the right idea in his answer, but the example gives the first few rows, inverted order:

select * ... (select * ... ASC limit 10) ... DESC

He wanted the last, it should be:

select * ... (select * ... DESC limit 10) ... ASC

Leave a Comment