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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With