Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: select N “most recent” rows in ascending order

For example, if my data look like this:

timestamp | message
100 | hello
101 | world
102 | foo
103 | bar
104 | baz

How can I select the three most recent rows — 102, 103, 104 — in ascending order?

The obvious (to me) … LIMIT 3 ORDER BY timestamp DESC will return the correct rows but the order is incorrect.

like image 683
David Wolever Avatar asked Oct 12 '11 04:10

David Wolever


People also ask

How do I get most recent rows in SQL?

Use the aggregate MAX(signin) grouped by id. This will list the most recent signin for each id . To get the whole single record, perform an INNER JOIN against a subquery which returns only the MAX(signin) per id.

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 sort SQL from newest to oldest?

If you'd like to see the latest date first and the earliest date last, you need to sort in descending order. Use the DESC keyword in this case. ORDER BY ExamDate DESC ; Note that in T-SQL, NULL s are displayed first when sorting in ascending order and last when sorting in descending order.

How do I select the last 3 rows in SQL?

This one-liner is the simplest query in the list, to get the last 3 number of records in a table. The TOP clause in SQL Server returns the first N number of records or rows from a table. Applying the ORDER BY clause with DESC, will return rows in descending order. Hence, we get the last 3 rows.


1 Answers

Use an inner select to select the correct rows, and an outer select to order them correctly:

SELECT timestamp, message
FROM
(
     SELECT *
     FROM your_table
     ORDER BY timestamp DESC
     LIMIT 3 
) T1
ORDER BY timestamp
like image 183
Mark Byers Avatar answered Oct 15 '22 23:10

Mark Byers