Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in SQL by (20.3k points)

This is a known question but the best solution I've found is something like:

SELECT TOP N *

FROM MyTable

ORDER BY Id DESC

I have a table with lots of rows. It is not a possibility to use that query because it takes a lot of time. So how can I do to select last N rows without using ORDER BY?

EDIT

Sorry duplicated question of this one

1 Answer

0 votes
by (40.7k points)

You can select last N rows without using ORDER BY, by using the ROW NUMBER BY PARTITION Feature as well. For example, you can use the Orders table of the Northwind database. Try to retrieve the Last 5 orders placed by Employee 5 like this:

SELECT ORDERID, CUSTOMERID, OrderDate

FROM

(

    SELECT ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY OrderDate DESC) AS OrderedDate,*

    FROM Orders

) as ordlist

WHERE ordlist.EmployeeID = 5

AND ordlist.OrderedDate <= 5

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...