Search code examples
sqlitesql-order-by

SQLite3 output in reverse order latest 10 records


I need the last 10 records. The issue is the way it outputs, since starts from latest to oldest and I need oldest to new ones. See below

sqlite> SELECT * FROM raw_all_sensors order by timestamp desc LIMIT 10;
2022-03-10 16:43:58|26.43|19.19|1014|56.81|0|0|813|0
2022-03-10 16:38:57|26.49|19.19|1014|55.22|0|0|813|0
2022-03-10 16:33:56|26.58|19.19|1014|55.67|0|0|813|0
2022-03-10 16:28:55|26.68|19.19|1014|56.08|0|0|813|0
2022-03-10 16:23:54|26.77|19.19|1014|55.72|0|0|813|0
2022-03-10 16:18:52|26.88|19.19|1014|56.49|0|0|813|0
2022-03-10 16:13:51|26.99|19.19|1014|56.47|0|0|813|0
2022-03-10 16:08:50|27.07|19.19|1014|56.04|0|0|813|0
2022-03-10 16:03:49|27.14|19.19|1014|55.98|0|0|813|0
2022-03-10 15:58:48|27.3|19.19|1014|56.37|0|0|813|0

But I need

2022-03-10 15:58:48|27.3|19.19|1014|56.37|0|0|813|0
2022-03-10 16:03:49|27.14|19.19|1014|55.98|0|0|813|0
2022-03-10 16:08:50|27.07|19.19|1014|56.04|0|0|813|0
...

How can I do this?

If I do asc (instead of desc), it starts from oldest records and is not what I want.


Solution

  • I believe what you want is:

    SELECT *
    FROM   (SELECT *
            FROM   raw_all_sensors
            ORDER  BY timestamp DESC
            LIMIT  10) t
    ORDER  BY timestamp; 
    

    Basically getting the 10 rows you want in a derived table, then ordering them in an ascending way in the outer query.