question

Raja M avatar image
Raja M asked

how to select Bottom( N) rows in a table through single query.

I have a table with two columns. First name,second name. There are 100 rows in that. No keys on this table.

I want last 30 rows . I can do this by cursors. How it can be solved through normal query.

t-sqlsql-server
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Bob Hovious avatar image Bob Hovious commented ·
I second Phil's point. It is a mistake to assume a table possesses any "natural" order other than that which is established with an ORDER BY clause. For example, if you wanted the last 30 based on their order of insertion into the table, you must have a timestamp or identity column already in the table which preserves that order.
2 Likes 2 ·
Phil Factor avatar image Phil Factor commented ·
You don't specify the order that you want the rows in.
1 Like 1 ·
Rob Farley avatar image
Rob Farley answered

Use TOP, with the reverse order.

SELECT TOP (30) *
FROM Table
ORDER BY LastName DESC, FirstName DESC;
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

AlexS avatar image
AlexS answered

Overall I agree with Rob Farley, but in case you want to preserve original order, you might want to use the following version:

SELECT *
FROM
(
     SELECT TOP (30) *
     FROM YourTable
     ORDER BY LastName DESC, FirstName Desc
)
ORDER BY LastName ASC, FirstName Asc

or if you don't like subqueries:

SELECT TOP (30)
  *,
  ROW_NUMBER() OVER (ORDER BY LastName DESC, FirstName DESC) as RowNum
FROM YourTable
ORDER BY RowNum DESC
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Jim_Mitten avatar image
Jim_Mitten answered
The subquery shown above works correctly. However, in SQL 2012 and maybe other versions, you need to add an Alias name to the subquery to make the syntax correct. An " A" after the ) works. The Row-Number example didn't work for me, the row numbers were inversely ordered, but it returned the first block, not the last block. I think a subquery is required.
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Kev Riley avatar image Kev Riley ♦♦ commented ·
+1 Yes a table alias is required
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.