Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select Bottom Records

I have a query where I wish to retrieve the oldest X records. At present my query is something like the following:

SELECT Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate DESC

I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.

So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005.

like image 872
Richard McGuire Avatar asked Sep 13 '08 21:09

Richard McGuire


People also ask

How do I get bottom 10 records in SQL?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

How do I SELECT the last 3 rows in SQL Server?

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.

How do I SELECT the last 5 columns in SQL?

Just press "End" key when you are in the Results tab. After that you will be at end of columns.


2 Answers

Why not just use a subquery?

SELECT T1.* 
FROM
(SELECT TOP X Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate) T1
ORDER BY CreatedDate DESC
like image 140
Jason Punyon Avatar answered Sep 19 '22 21:09

Jason Punyon


Embed the query. You take the top x when sorted in ascending order (i.e. the oldest) and then re-sort those in descending order ...

select * 
from 
(
    SELECT top X Id, Title, Comments, CreatedDate
    FROM MyTable
    WHERE CreatedDate > @OlderThanDate
    ORDER BY CreatedDate 
) a
order by createddate desc 
like image 27
Unsliced Avatar answered Sep 18 '22 21:09

Unsliced