tags:

views:

124

answers:

4

I can do SELECT TOP (200) ... but why not BOTTOM (200)?

Well not to get into philosophy what I mean is, how can I do the equivalent of TOP (200) but in reverse (from the bottom, like you'd expect BOTTOM to do...)?

+11  A: 

It is unnecessary. You can use an ORDER BY and just change the sort to DESC to get the same effect.

Justin Ethier
google said the same thing and now 9 of you agree, good enough for me, thanks :D
shogun
Using DESC will return the last N rows, but the returned rows will also be in reverse order from the first N rows.
RickNZ
+2  A: 

All you need to do is reverse your ORDER BY. Add or remove DESC to it.

Justin Swartsel
+7  A: 
SELECT
    columns
FROM
(
     SELECT TOP 200
          columns
     FROM
          My_Table
     ORDER BY
          a_column DESC
) SQ
ORDER BY
     a_column ASC
Tom H.
Why are you using a derived table?
RichardOD
If you want to return rows in A->Z order, but select the top 200 in Z->A order this is one way to do it. The other answers, suggesting just changing the ORDER BY will not return the same results described in the question, as they will be out of order (unless order doesn't matter, which the OP did not say).
Tom H.
@Tom H. Had to think for a few seconds as to what you meant (I've been up 14 hours). At first I couldn't see the difference between yours and the order by answers, but now I can. So +1.
RichardOD
A: 

The problem with ordering the other way is that it often does not make good use of indices. It is also not very extendable if you ever need to select a number of rows that are not at the start or the end. An alternative way is as follows.

DECLARE @NumberOfRows int;
SET @NumberOfRows = (SELECT COUNT(*) FROM TheTable);

SELECT col1, col2,...
FROM (
    SELECT col1, col2,..., ROW_NUMBER() OVER (ORDER BY col1) AS intRow
    FROM TheTable
) AS T
WHERE intRow > @NumberOfRows - 20;
Paul
1) If changing the direction of your ORDER BY clause "does not make good use of indices", then get a decent RDBMS! The RDBMS should never care whether it navigates the index forwards or backwards. 2) You're concerned about use of indexes, yet your solution attaches a sequence to every row in the table... That's one way to guarantee an appropriate index will NOT be used.
Craig Young