I need to select the last 5 rows from a table except the last record in MS SQL Server.
In other words:
SELECT TOP 5 *
FROM table
ORDER BY column DESC
but not considering the table last record in this select.
How can I do that?
I need to select the last 5 rows from a table except the last record in MS SQL Server.
In other words:
SELECT TOP 5 *
FROM table
ORDER BY column DESC
but not considering the table last record in this select.
How can I do that?
It can be easily achieved in MS SQL Server 2012 using the following code:
BEGIN
DECLARE
@OFFSET int = 1,
@LIMIT int = 5
-- SQL Server 2012+
SELECT id, name
FROM t
ORDER BY name DESC -- DESC because you want the list upside down
OFFSET @OFFSET ROWS -- skipped rows
FETCH NEXT @LIMIT ROWS ONLY -- number of rows
END;
For an older SQL Server version, use:
BEGIN
DECLARE
@OFFSET int = 1,
@LIMIT int = 5
-- SQL Server 2008
;WITH cte AS
(
SELECT
id,
name,
ROW_NUMBER() OVER (ORDER BY name DESC) AS RowNum -- DESC because you want the list upside down
FROM t
)
SELECT id, name
FROM cte
WHERE RowNum > @OFFSET
AND RowNum <= @OFFSET + @Limit
END