SQL Server SELECT LAST N Rows SQL Server SELECT LAST N Rows sql-server sql-server

SQL Server SELECT LAST N Rows


You can make SQL server to select last N rows using this SQL:

select * from tbl_name order by id desc limit N;


I tested JonVD's code, but found it was very slow, 6s.

This code took 0s.

SELECT TOP(5) ORDERID, CUSTOMERID, OrderDate    FROM Orders where EmployeeID=5    Order By OrderDate DESC


You can do it by using the ROW NUMBER BY PARTITION Feature also. A great example can be found here:

I am using the Orders table of the Northwind database... Now let us retrieve the Last 5 orders placed by Employee 5:

SELECT ORDERID, CUSTOMERID, OrderDateFROM(    SELECT ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY OrderDate DESC) AS OrderedDate,*    FROM Orders) as ordlistWHERE ordlist.EmployeeID = 5AND ordlist.OrderedDate <= 5